sha
string | github
string | commit_message
string | git_diff
string | is_security
int64 |
|---|---|---|---|---|
33405d5b753d8c3992adb51926638e4ddaa1f531
|
https://github.com/domoticz/domoticz/commit/33405d5b753d8c3992adb51926638e4ddaa1f531
|
Changing package folder and disabling default debug to SSH feature
|
diff --git a/.github/workflows/development.yml b/.github/workflows/development.yml
index e2c80c2698..d5a14c8962 100644
--- a/.github/workflows/development.yml
+++ b/.github/workflows/development.yml
@@ -83,7 +83,7 @@ jobs:
username: ${{ secrets.FTP_USERNAME }}
password: ${{ secrets.FTP_PASSWORD }}
protocol: ftp
- local-dir: ../dev-domoticz/package/
+ local-dir: ./package/
server-dir: beta/
security: loose
@@ -96,7 +96,8 @@ jobs:
# Grok 2.tcp.ngrok.io DNS resolves to 52.14.18.129
- name: Start SSH debug Session
- if: ${{ failure() }}
+ #if: ${{ failure() }}
+ if: ${{ false }}
uses: luchihoratiu/debug-via-ssh@main
with:
NGROK_AUTH_TOKEN: ${{ secrets.NGROK_TOKEN }}
| 0
|
9d0023ba906f3a5eb930318609db5ec61e57f030
|
https://github.com/ceph/ceph/commit/9d0023ba906f3a5eb930318609db5ec61e57f030
|
pybind/mgr/dashboard: do not install enum34
enum was introduced by python 3.4, but we require python3.6 and up.
so drop it.
Signed-off-by: Kefu Chai <[email protected]>
|
diff --git a/src/pybind/mgr/dashboard/constraints.txt b/src/pybind/mgr/dashboard/constraints.txt
index 96cfdb99e4fbd..05dbdd869f122 100644
--- a/src/pybind/mgr/dashboard/constraints.txt
+++ b/src/pybind/mgr/dashboard/constraints.txt
@@ -1,5 +1,4 @@
CherryPy==13.1.0
-enum34==1.1.6
more-itertools==4.1.0
PyJWT==1.6.4
bcrypt==3.1.4
diff --git a/src/pybind/mgr/dashboard/requirements.txt b/src/pybind/mgr/dashboard/requirements.txt
index 282a07573cdf5..39ce5f9eae32f 100644
--- a/src/pybind/mgr/dashboard/requirements.txt
+++ b/src/pybind/mgr/dashboard/requirements.txt
@@ -1,6 +1,5 @@
bcrypt
CherryPy
-enum34; python_version<'3.4'
more-itertools
PyJWT
pyopenssl
| 0
|
b44341d7012b7e3f3d4a0ee414216ee90aedcec8
|
https://github.com/jenkinsci/tikal-multijob-plugin/commit/b44341d7012b7e3f3d4a0ee414216ee90aedcec8
|
[maven-release-plugin] prepare release jenkins-multijob-plugin-1.32
|
diff --git a/pom.xml b/pom.xml
index c4364bad..b3519a0b 100644
--- a/pom.xml
+++ b/pom.xml
@@ -10,7 +10,7 @@
<version>2.1.0</version> <relativePath>../pom.xml</relativePath> </parent -->
<artifactId>jenkins-multijob-plugin</artifactId>
- <version>1.32-SNAPSHOT</version>
+ <version>1.32</version>
<name>Jenkins Multijob plugin</name>
<description>Enabling full hierarchy of Jenkins jobs</description>
<url>http://wiki.jenkins-ci.org/display/JENKINS/Multijob+Plugin</url>
| 0
|
d73fc8367f2e193c62b06ae9b666dd09d48ae320
|
https://github.com/Matroska-Org/libmatroska/commit/d73fc8367f2e193c62b06ae9b666dd09d48ae320
|
KaxSeekHead: let IndexThis return pointer to newly created KaxSeek object
That way the caller can use it for whatever purpose.
|
diff --git a/matroska/KaxSeekHead.h b/matroska/KaxSeekHead.h
index bae3a3a..c6b6a4a 100644
--- a/matroska/KaxSeekHead.h
+++ b/matroska/KaxSeekHead.h
@@ -60,7 +60,7 @@ DECLARE_MKX_MASTER(KaxSeekHead)
\brief add an element to index in the Meta Seek data
\note the element should already be written in the file
*/
- void IndexThis(const EbmlElement & aElt, const KaxSegment & ParentSegment);
+ KaxSeek * IndexThis(const EbmlElement & aElt, const KaxSegment & ParentSegment);
KaxSeek * FindFirstOf(const EbmlCallbacks & Callbacks) const;
KaxSeek * FindNextOf(const KaxSeek &aPrev) const;
diff --git a/src/KaxSeekHead.cpp b/src/KaxSeekHead.cpp
index 6372fe3..8dfec06 100644
--- a/src/KaxSeekHead.cpp
+++ b/src/KaxSeekHead.cpp
@@ -46,7 +46,7 @@ START_LIBMATROSKA_NAMESPACE
/*!
\todo verify that the element is not already in the list
*/
-void KaxSeekHead::IndexThis(const EbmlElement & aElt, const KaxSegment & ParentSegment)
+KaxSeek * KaxSeekHead::IndexThis(const EbmlElement & aElt, const KaxSegment & ParentSegment)
{
// create a new point
auto & aNewPoint = AddNewChild<KaxSeek>(*this);
@@ -59,6 +59,8 @@ void KaxSeekHead::IndexThis(const EbmlElement & aElt, const KaxSegment & ParentS
binary ID[4];
((const EbmlId&)aElt).Fill(ID);
aNewID.CopyBuffer(ID, EBML_ID_LENGTH((const EbmlId&)aElt));
+
+ return &aNewPoint;
}
KaxSeek * KaxSeekHead::FindFirstOf(const EbmlCallbacks & Callbacks) const
| 0
|
3a6dd6b44cef2fa3f96f403e1cb971d8d0d694b5
|
https://github.com/LimeSurvey/LimeSurvey/commit/3a6dd6b44cef2fa3f96f403e1cb971d8d0d694b5
|
Fixed issue: Vulnerable parameter on survey resume
|
diff --git a/application/helpers/common_helper.php b/application/helpers/common_helper.php
index 3439011e951..00e646c7a42 100644
--- a/application/helpers/common_helper.php
+++ b/application/helpers/common_helper.php
@@ -3799,7 +3799,6 @@ function questionAttributes($returnByName=false)
'category'=>$clang->gT('Other'),
'sortorder'=>130,
"inputtype"=>"text",
- 'default'=>'1',
"help"=>$clang->gT("Maximum number of files that the participant can upload for this question"),
"caption"=>$clang->gT("Max number of files"));
@@ -3883,14 +3882,6 @@ function categorySort($a, $b)
return $result;
}
-// make sure the given string (which comes from a POST or GET variable)
-// is safe to use in MySQL. This does nothing if gpc_magic_quotes is on.
-function autoEscape($str) {
- if (!get_magic_quotes_gpc()) {
- return addslashes ($str);
- }
- return $str;
-}
// the opposite of the above: takes a POST or GET variable which may or
// may not have been 'auto-quoted', and return the *unquoted* version.
diff --git a/application/helpers/frontend_helper.php b/application/helpers/frontend_helper.php
index 3a49373e4c3..c808282712d 100644
--- a/application/helpers/frontend_helper.php
+++ b/application/helpers/frontend_helper.php
@@ -29,7 +29,7 @@ function loadanswers()
{
$query .= "AND {{saved_control}}.scid={$scid}\n";
}
- $query .="AND {{saved_control}}.identifier = '".autoEscape($_SESSION['survey_'.$surveyid]['holdname'])."' ";
+ $query .="AND {{saved_control}}.identifier = '".Yii::app()->db->quoteValue($_SESSION['survey_'.$surveyid]['holdname'])."' ";
if (in_array(Yii::app()->db->getDriverName(), array('mssql', 'sqlsrv', 'dblib')))
{
| 1
|
a45241f4bc46aee1ab2cc0749f6444b043681edf#diff-94ec20582215bda9f55fadcefe68c168
|
https://github.com/gnuboard/gnuboard5/commit/a45241f4bc46aee1ab2cc0749f6444b043681edf#diff-94ec20582215bda9f55fadcefe68c168
|
XSS 취약점 수정
|
diff --git a/adm/board_form_update.php b/adm/board_form_update.php
index 912887760..2222baadb 100644
--- a/adm/board_form_update.php
+++ b/adm/board_form_update.php
@@ -72,6 +72,9 @@
//https://github.com/gnuboard/gnuboard5/commit/f5f4925d4eb28ba1af728e1065fc2bdd9ce1da58 에 따른 조치
$str_bo_category_list = isset($_POST['bo_category_list']) ? preg_replace("/[\<\>\'\"\\\'\\\"\%\=\(\)\/\^\*]/", "", $_POST['bo_category_list']) : '';
+$_POST['bo_subject'] = strip_tags($_POST['bo_subject']);
+$_POST['bo_mobile_subject'] = strip_tags($_POST['bo_mobile_subject']);
+
$sql_common = " gr_id = '{$_POST['gr_id']}',
bo_subject = '{$_POST['bo_subject']}',
bo_mobile_subject = '{$_POST['bo_mobile_subject']}',
diff --git a/adm/boardgroup_form.php b/adm/boardgroup_form.php
index 73e162d98..c9e8338bd 100644
--- a/adm/boardgroup_form.php
+++ b/adm/boardgroup_form.php
@@ -117,7 +117,7 @@
<label for="gr_<?php echo $i ?>_subj">여분필드 <?php echo $i ?> 제목</label>
<input type="text" name="gr_<?php echo $i ?>_subj" value="<?php echo get_text($group['gr_'.$i.'_subj']) ?>" id="gr_<?php echo $i ?>_subj" class="frm_input">
<label for="gr_<?php echo $i ?>">여분필드 <?php echo $i ?> 내용</label>
- <input type="text" name="gr_<?php echo $i ?>" value="<?php echo $gr['gr_'.$i] ?>" id="gr_<?php echo $i ?>" class="frm_input">
+ <input type="text" name="gr_<?php echo $i ?>" value="<?php echo get_sanitize_input($gr['gr_'.$i]); ?>" id="gr_<?php echo $i ?>" class="frm_input">
</td>
</tr>
<?php } ?>
diff --git a/adm/config_form.php b/adm/config_form.php
index 00915fe7d..e4daee961 100644
--- a/adm/config_form.php
+++ b/adm/config_form.php
@@ -1317,7 +1317,7 @@
<label for="cf_<?php echo $i ?>_subj">여분필드<?php echo $i ?> 제목</label>
<input type="text" name="cf_<?php echo $i ?>_subj" value="<?php echo get_text($config['cf_'.$i.'_subj']) ?>" id="cf_<?php echo $i ?>_subj" class="frm_input" size="30">
<label for="cf_<?php echo $i ?>">여분필드<?php echo $i ?> 값</label>
- <input type="text" name="cf_<?php echo $i ?>" value="<?php echo $config['cf_'.$i] ?>" id="cf_<?php echo $i ?>" class="frm_input" size="30">
+ <input type="text" name="cf_<?php echo $i ?>" value="<?php echo get_sanitize_input($config['cf_'.$i]); ?>" id="cf_<?php echo $i ?>" class="frm_input" size="30">
</td>
</tr>
<?php } ?>
diff --git a/adm/config_form_update.php b/adm/config_form_update.php
index 03179c345..126786382 100644
--- a/adm/config_form_update.php
+++ b/adm/config_form_update.php
@@ -26,6 +26,8 @@
$cf_social_servicelist = !empty($_POST['cf_social_servicelist']) ? implode(',', $_POST['cf_social_servicelist']) : '';
+$_POST['cf_title'] = strip_tags($_POST['cf_title']);
+
$sql = " update {$g5['config_table']}
set cf_title = '{$_POST['cf_title']}',
cf_admin = '{$_POST['cf_admin']}',
diff --git a/adm/menu_list.php b/adm/menu_list.php
index ffe88aee7..4a6c25127 100644
--- a/adm/menu_list.php
+++ b/adm/menu_list.php
@@ -196,6 +196,20 @@ function base_convert(number, frombase, tobase) {
function fmenulist_submit(f)
{
+
+ var me_links = document.getElementsByName('me_link[]');
+ var reg = /^javascript/;
+
+ for (i=0; i<me_links.length; i++){
+
+ if( reg.test(me_links[i].value) ){
+
+ alert('링크에 자바스크립트문을 입력할수 없습니다.');
+ me_links[i].focus();
+ return false;
+ }
+ }
+
return true;
}
</script>
diff --git a/adm/menu_list_update.php b/adm/menu_list_update.php
index f05e2ec22..4244d3343 100644
--- a/adm/menu_list_update.php
+++ b/adm/menu_list_update.php
@@ -23,8 +23,8 @@
$code = $_POST['code'][$i];
$me_name = $_POST['me_name'][$i];
- $me_link = $_POST['me_link'][$i];
-
+ $me_link = preg_match('/^javascript/', $_POST['me_link'][$i]) ? G5_URL : strip_tags($_POST['me_link'][$i]);
+
if(!$code || !$me_name || !$me_link)
continue;
diff --git a/bbs/board_head.php b/bbs/board_head.php
index 04b60450f..a62706a28 100644
--- a/bbs/board_head.php
+++ b/bbs/board_head.php
@@ -5,13 +5,13 @@
if (G5_IS_MOBILE) {
// 모바일의 경우 설정을 따르지 않는다.
include_once(G5_BBS_PATH.'/_head.php');
- echo stripslashes($board['bo_mobile_content_head']);
+ echo html_purifier(stripslashes($board['bo_mobile_content_head']));
} else {
if(is_include_path_check($board['bo_include_head'])) { //파일경로 체크
@include ($board['bo_include_head']);
} else { //파일경로가 올바르지 않으면 기본파일을 가져옴
include_once(G5_BBS_PATH.'/_head.php');
}
- echo stripslashes($board['bo_content_head']);
+ echo html_purifier(stripslashes($board['bo_content_head']));
}
?>
\ No newline at end of file
diff --git a/bbs/board_tail.php b/bbs/board_tail.php
index 57b81b46e..436e2cc3b 100644
--- a/bbs/board_tail.php
+++ b/bbs/board_tail.php
@@ -3,11 +3,11 @@
// 게시판 관리의 하단 파일 경로
if (G5_IS_MOBILE) {
- echo stripslashes($board['bo_mobile_content_tail']);
+ echo html_purifier(stripslashes($board['bo_mobile_content_tail']));
// 모바일의 경우 설정을 따르지 않는다.
include_once(G5_BBS_PATH.'/_tail.php');
} else {
- echo stripslashes($board['bo_content_tail']);
+ echo html_purifier(stripslashes($board['bo_content_tail']));
if(is_include_path_check($board['bo_include_tail'])) { //파일경로 체크
@include ($board['bo_include_tail']);
} else { //파일경로가 올바르지 않으면 기본파일을 가져옴
diff --git a/bbs/password.php b/bbs/password.php
index e5e0a4d4e..646f3b645 100644
--- a/bbs/password.php
+++ b/bbs/password.php
@@ -43,8 +43,8 @@
include_once(G5_PATH.'/head.sub.php');
-//if ($board['bo_include_head']) { @include ($board['bo_include_head']); }
-//if ($board['bo_content_head']) { echo stripslashes($board['bo_content_head']); }
+//if ($board['bo_include_head'] && is_include_path_check($board['bo_content_head'])) { @include ($board['bo_include_head']); }
+//if ($board['bo_content_head']) { echo html_purifier(stripslashes($board['bo_content_head'])); }
/* 비밀글의 제목을 가져옴 지운아빠 2013-01-29 */
$sql = " select wr_subject from {$write_table}
@@ -57,8 +57,8 @@
include_once($member_skin_path.'/password.skin.php');
-//if ($board['bo_content_tail']) { echo stripslashes($board['bo_content_tail']); }
-//if ($board['bo_include_tail']) { @include ($board['bo_include_tail']); }
+//if ($board['bo_content_tail']) { echo html_purifier(stripslashes($board['bo_content_tail'])); }
+//if ($board['bo_include_tail'] && is_include_path_check($board['bo_content_tail'])) { @include ($board['bo_include_tail']); }
include_once(G5_PATH.'/tail.sub.php');
?>
| 1
|
1fb829a935541bf37a6af6fda0a4a76e0c954207
|
https://github.com/mde/ejs/commit/1fb829a935541bf37a6af6fda0a4a76e0c954207
|
docs(includer): simple includer function reference on options
|
diff --git a/README.md b/README.md
index 74524ac3..23b291d7 100644
--- a/README.md
+++ b/README.md
@@ -90,6 +90,10 @@ Therefore, we do not recommend using this shortcut.
output inside scriptlet tags.
- `async` When `true`, EJS will use an async function for rendering. (Depends
on async/await support in the JS runtime.
+ - `includer` Custom function to handle EJS includes, receives `(url, prev)` parameters,
+ where `url` is the path in include as-is and `prev` is the previously resolved path. Should
+ return an object `{ filename, template }`, you may return only one of the properties,
+ where `filename` is the final parsed path and `template` is the included content.
This project uses [JSDoc](http://usejsdoc.org/). For the full public API
documentation, clone the repository and run `npm run doc`. This will run JSDoc
| 0
|
712930ea6b1cd523d29e5a57cb6ea4aed694d700
|
https://github.com/eclipse-vertx/vert.x/commit/712930ea6b1cd523d29e5a57cb6ea4aed694d700
|
Releasing 4.0.1
|
diff --git a/pom.xml b/pom.xml
index 457e0413946..d090a735471 100644
--- a/pom.xml
+++ b/pom.xml
@@ -20,7 +20,7 @@
</parent>
<artifactId>vertx-core</artifactId>
- <version>4.0.1-SNAPSHOT</version>
+ <version>4.0.1</version>
<name>Vert.x Core</name>
@@ -50,7 +50,7 @@
<assertj.version>3.4.1</assertj.version>
<apacheds-protocol-dns.version>1.5.7</apacheds-protocol-dns.version>
<generated.dir>${project.basedir}/src/main/generated</generated.dir>
- <stack.version>4.0.1-SNAPSHOT</stack.version>
+ <stack.version>4.0.1</stack.version>
<jetty.alpnAgent.argLine/>
<jmh.version>1.19</jmh.version>
<vertx.testNativeTransport>false</vertx.testNativeTransport>
| 0
|
18c8521bbbb9fbe6e1e689acbb487206275ca904
|
https://github.com/gosa-project/gosa-core/commit/18c8521bbbb9fbe6e1e689acbb487206275ca904
|
Updated LM hash to only gen if sambaHashHook set to LM
|
diff --git a/include/functions.inc b/include/functions.inc
index 40d16583a..287735992 100644
--- a/include/functions.inc
+++ b/include/functions.inc
@@ -3124,14 +3124,18 @@ function NThash($Input)
}
// Really Really should disable this and just output invalid junk
-// since this hashing method is very very broken...
+// since this hashing method is very very broken... disabled unless
+// config for sambaHashHook is set specifically to "LM"
function LMhash($Input)
{
- // return('abunchofinvalidjunk!');
- $Input = strtoupper(substr($Input,0,14));
- $p1 = LMhash_DESencrypt(substr($Input, 0, 7));
- $p2 = LMhash_DESencrypt(substr($Input, 7, 7));
- return strtoupper($p1.$p2);
+ $lmhash = 'abunchofinvalidjunk!';
+ if (trim($config->get_cfg_value('core','sambaHashHook')) == 'LM') {
+ $Input = strtoupper(substr($Input,0,14));
+ $p1 = LMhash_DESencrypt(substr($Input, 0, 7));
+ $p2 = LMhash_DESencrypt(substr($Input, 7, 7));
+ $lmhash = strtoupper($p1.$p2);
+ }
+ return $lmhash;
}
function LMhash_DESencrypt($Input)
| 0
|
d2282e63e1f22ef1445b767de18da52bef5f8740
|
https://github.com/mozilla-b2g/gaia/commit/d2282e63e1f22ef1445b767de18da52bef5f8740
|
Bug 1283578 - Remove artifact expiration from taskgraph.json r=aus
|
diff --git a/taskgraph.json b/taskgraph.json
index 7584c7a6a150..a247ebae6a0e 100644
--- a/taskgraph.json
+++ b/taskgraph.json
@@ -40,8 +40,7 @@
"artifacts": {
"public/package.json": {
"type": "file",
- "path": "/home/worker/git_checkout/package.json",
- "expires": "2016-03-30T11:59:00.000Z"
+ "path": "/home/worker/git_checkout/package.json"
}
},
"features": {
| 0
|
20fc85edccc80e7e7f162613542792380c44446a
|
https://github.com/LimeSurvey/LimeSurvey/commit/20fc85edccc80e7e7f162613542792380c44446a
|
[security] Fixed issue #13960: vulnerabilities in file upload functionality
|
diff --git a/application/helpers/common_helper.php b/application/helpers/common_helper.php
index d16c2b77d44..c7849ef4710 100644
--- a/application/helpers/common_helper.php
+++ b/application/helpers/common_helper.php
@@ -4960,3 +4960,40 @@ function isAssociativeArray($array){
}
return false;
}
+
+/**
+ * Test if a given zip file is Zip Bomb
+ * see comment here : http://php.net/manual/en/function.zip-entry-filesize.php
+ * @param string $zip_filename
+ * @return int
+ */
+function isZipBomb($zip_filename)
+{
+ return ( get_zip_originalsize($zip_filename) > getMaximumFileUploadSize() );
+}
+
+/**
+ * Get the original size of a zip archive to prevent Zip Bombing
+ * see comment here : http://php.net/manual/en/function.zip-entry-filesize.php
+ * @param string $filename
+ * @return int
+ */
+function get_zip_originalsize($filename) {
+
+ if ( function_exists ('zip_entry_filesize') ){
+ $size = 0;
+ $resource = zip_open($filename);
+ while ($dir_resource = zip_read($resource)) {
+ $size += zip_entry_filesize($dir_resource);
+ }
+ zip_close($resource);
+
+ return $size;
+ }else{
+ if ( YII_DEBUG ){
+ Yii::app()->setFlashMessage(gT("Warning! php zip extension is not installed on your server. You're not protected from Zip Bomb attaacks."), 'error');
+ }
+ }
+
+ return -1;
+}
diff --git a/application/third_party/pclzip/pclzip.lib.php b/application/third_party/pclzip/pclzip.lib.php
index 8c7cbc79395..1db8f983060 100644
--- a/application/third_party/pclzip/pclzip.lib.php
+++ b/application/third_party/pclzip/pclzip.lib.php
@@ -221,6 +221,13 @@ public function __construct($p_zipname)
die('Abort '.basename(__FILE__).' : Missing zlib extensions');
}
+
+ // Added by LS Team to prevent Zip Bombing
+ if (isZipBomb($p_zipname)){
+ die('Abort '.basename(__FILE__).' : Unzipped file is superior to upload_max_filesize or to post_max_size');
+ }
+
+
// ----- Set the attributes
$this->zipname = $p_zipname;
$this->zip_fd = 0;
@@ -3670,7 +3677,7 @@ function privExtractFile(&$p_entry, $p_path, $p_remove_path, $p_remove_all_path,
}
// Added by LS Team to check for invalid paths
- $p_entry['filename'] = get_absolute_path($p_entry['filename']);
+ $p_entry['filename'] = get_absolute_path($p_entry['filename']);
// ----- Add the path
if ($p_path != '') {
| 1
|
def012a74fa0da4cc6eb8c5f51d34ce500858fd2
|
https://github.com/twitter/finagle/commit/def012a74fa0da4cc6eb8c5f51d34ce500858fd2
|
finagle-netty: Fix resource leak in http proxy connect handler
Problem
As discussed on Github [1], it's not only a good idea to interrupt a handshake
(either SSL/TLS handshake or HTTP proxy handshake) on interrupted connect future
(eg: interrupted by `TimeoutFactory`) it's absolutely necessary to do in order to
prevent resource leaks from channels remaining open.
Imagine the following scenario:
1. A client sends an HTTP proxy handshake message `CONNECT /twitter.com`
2. A server accepts that but never sends a response back
3. A client stalls the connection waiting for a response from a server
4. `TimeoutFactory` kicks in and interrupts the connect promise
5. Finagle stack will create a new channel for a next request, but this will remain open
Solution
Close the channel and fail pending writes when a connect promise is interrupted.
Note that this RB also fixes the behavior when channel is closed by remote peer
so we no longer need to wait for a handshake to complete.
[1]: https://github.com/twitter/finagle/issues/345#issuecomment-210754044
RB_ID=823927
|
diff --git a/finagle-netty4/src/main/scala/com/twitter/finagle/netty4/proxy/HttpProxyConnectHandler.scala b/finagle-netty4/src/main/scala/com/twitter/finagle/netty4/proxy/HttpProxyConnectHandler.scala
index b74022cb36..cd0144ec23 100644
--- a/finagle-netty4/src/main/scala/com/twitter/finagle/netty4/proxy/HttpProxyConnectHandler.scala
+++ b/finagle-netty4/src/main/scala/com/twitter/finagle/netty4/proxy/HttpProxyConnectHandler.scala
@@ -1,6 +1,8 @@
package com.twitter.finagle.netty4.proxy
-import com.twitter.finagle.{Failure, ConnectionFailedException}
+import com.twitter.finagle.{
+ CancelledConnectionException, ChannelClosedException, Failure, ConnectionFailedException
+}
import com.twitter.finagle.client.Transporter
import com.twitter.finagle.client.Transporter.Credentials
import com.twitter.finagle.netty4.channel.BufferingChannelOutboundHandler
@@ -12,7 +14,7 @@ import io.netty.util.concurrent.{Future => NettyFuture, GenericFutureListener}
import java.net.SocketAddress
/**
- * An internal handler that upgrades the pipeline to delay connect-promise satisfaction, until the
+ * An internal handler that upgrades the pipeline to delay connect-promise satisfaction until the
* remote HTTP proxy server is ready to proxy traffic to an ultimate destination represented as
* `host` (i.e., HTTP proxy connect procedure is successful).
*
@@ -26,7 +28,7 @@ import java.net.SocketAddress
* don't want to bypass Finagle's load balancers while resolving the proxy endpoint.
*
* @note This mixes in a [[BufferingChannelOutboundHandler]] so we can protect ourselves from
- * channel handlers that write on `channelAdded`.
+ * channel handlers that write on `channelAdded` or `channelActive`.
*
* [1]: http://www.web-cache.com/Writings/Internet-Drafts/draft-luotonen-web-proxy-tunneling-01.txt
* [2]: http://wiki.squid-cache.org/Features/HTTPS
@@ -50,6 +52,11 @@ private[netty4] class HttpProxyConnectHandler(
"Basic " + Base64StringEncoder.encode(bytes)
}
+ private[this] def fail(ctx: ChannelHandlerContext, t: Throwable): Unit = {
+ connectPromise.tryFailure(t)
+ failPendingWrites(ctx, t)
+ }
+
override def connect(
ctx: ChannelHandlerContext,
remote: SocketAddress,
@@ -62,19 +69,20 @@ private[netty4] class HttpProxyConnectHandler(
promise.addListener(new GenericFutureListener[NettyFuture[Any]] {
override def operationComplete(f: NettyFuture[Any]): Unit =
if (f.isCancelled) {
- // The connect request was cancelled so the channel was never active. Since no writes
- // are expected from the previous handler, no need to fail the pending writes.
- proxyConnectPromise.cancel(true /*mayInterruptIfRunning*/)
+ if (!proxyConnectPromise.cancel(true) && proxyConnectPromise.isSuccess) {
+ // New connect promise wasn't cancelled because it was already satisfied (connected) so
+ // we need to close the channel to prevent resource leaks.
+ // See https://github.com/twitter/finagle/issues/345
+ failPendingWrites(ctx, new CancelledConnectionException())
+ ctx.close()
+ }
}
})
// Fail old promise if a new one is failed.
proxyConnectPromise.addListener(new GenericFutureListener[NettyFuture[Any]] {
override def operationComplete(f: NettyFuture[Any]): Unit =
- if (!f.isSuccess && !f.isCancelled) {
- promise.setFailure(f.cause())
- failPendingWrites(ctx, f.cause())
- } else if (f.isSuccess) {
+ if (f.isSuccess) {
// Add HTTP client codec so we can talk to an HTTP proxy.
ctx.pipeline().addBefore(ctx.name(), httpCodecKey, httpClientCodec)
@@ -91,9 +99,13 @@ private[netty4] class HttpProxyConnectHandler(
if (!ctx.channel().config().isAutoRead) {
ctx.read()
}
+ } else {
+ // The connect request was cancelled or failed so the channel was never active. Since no
+ // writes are expected from the previous handler, no need to fail the pending writes.
+ if (!f.isCancelled) {
+ promise.setFailure(f.cause())
+ }
}
- // We don't need to fail pending writes here (on `f.isCancelled`) since we expect that a
- // channel was never active and no handlers write into a non-active channel.
})
// We propagate the pipeline with a new promise thereby delaying the original connect's
@@ -108,8 +120,7 @@ private[netty4] class HttpProxyConnectHandler(
// need HTTP proxy pieces in the pipeline.
if (rep.status() == HttpResponseStatus.OK) {
ctx.pipeline().remove(httpCodecKey)
- // This handler drains pending writes when removed.
- ctx.pipeline().remove(self)
+ ctx.pipeline().remove(self) // drains pending writes when removed
connectPromise.trySuccess()
// We don't release `req` since by specs, we don't expect any payload sent back from a
@@ -120,19 +131,21 @@ private[netty4] class HttpProxyConnectHandler(
ctx.channel().remoteAddress()
)
- connectPromise.tryFailure(failure)
- failPendingWrites(ctx, failure)
-
+ fail(ctx, failure)
ctx.close()
}
case other => ctx.fireChannelRead(other)
}
override def exceptionCaught(ctx: ChannelHandlerContext, cause: Throwable): Unit = {
- // We don't call `super.exceptionCaught` here since we don't want `cause` be propagated to
- // the pipeline given that we already took an action (closed the channel).
- connectPromise.tryFailure(cause)
- failPendingWrites(ctx, cause)
- ctx.close()
+ fail(ctx, cause)
+ ctx.fireExceptionCaught(cause) // we don't call super.exceptionCaught since we've already filed
+ // both connect promise and pending writes in `fail`
+ ctx.close() // close a channel since we've failed to perform an HTTP proxy handshake
+ }
+
+ override def channelInactive(ctx: ChannelHandlerContext): Unit = {
+ fail(ctx, new ChannelClosedException(ctx.channel().remoteAddress()))
+ ctx.fireChannelInactive()
}
}
diff --git a/finagle-netty4/src/test/scala/com/twitter/finagle/netty4/proxy/HttpProxyConnectHandlerTest.scala b/finagle-netty4/src/test/scala/com/twitter/finagle/netty4/proxy/HttpProxyConnectHandlerTest.scala
index 7c52dc35c5..9c18cf3b1c 100644
--- a/finagle-netty4/src/test/scala/com/twitter/finagle/netty4/proxy/HttpProxyConnectHandlerTest.scala
+++ b/finagle-netty4/src/test/scala/com/twitter/finagle/netty4/proxy/HttpProxyConnectHandlerTest.scala
@@ -1,6 +1,6 @@
package com.twitter.finagle.netty4.proxy
-import com.twitter.finagle.ConnectionFailedException
+import com.twitter.finagle.{ChannelClosedException, ConnectionFailedException}
import io.netty.channel.{
ChannelHandlerAdapter, ChannelPromise, ChannelHandlerContext, ChannelOutboundHandlerAdapter
}
@@ -53,7 +53,7 @@ class HttpProxyConnectHandlerTest extends FunSuite with OneInstancePerTest {
channel.finishAndReleaseAll()
}
- test("connect to proxy (canceled)") {
+ test("connect to proxy (canceled before connected)") {
val channel = new EmbeddedChannel(
connectPromiseSnooper,
new HttpProxyConnectHandler("example.com", None, emptyCodec)
@@ -67,6 +67,20 @@ class HttpProxyConnectHandlerTest extends FunSuite with OneInstancePerTest {
channel.finishAndReleaseAll()
}
+ test("connect to proxy (canceled after connected)") {
+ val channel = new EmbeddedChannel(
+ new HttpProxyConnectHandler("example.com", None, emptyCodec)
+ )
+
+ val connectPromise = channel.connect(fakeAddress)
+ assert(!connectPromise.isDone)
+ assert(channel.isActive)
+ assert(connectPromise.cancel(false))
+ assert(!channel.isActive)
+
+ channel.finishAndReleaseAll()
+ }
+
test("connect to proxy (tcp connect failed)") {
val e = new Exception("not good")
val channel = new EmbeddedChannel(
@@ -77,12 +91,8 @@ class HttpProxyConnectHandlerTest extends FunSuite with OneInstancePerTest {
val connectPromise = channel.connect(fakeAddress)
assert(!connectPromise.isDone)
- channel.writeOutbound("pending write")
- assert(channel.outboundMessages().size() == 0)
connectPromiseSnooper.promise.setFailure(e)
-
assert(connectPromise.cause() == e)
- assert(intercept[Exception](channel.checkException()) == e)
channel.finishAndReleaseAll()
}
@@ -106,7 +116,7 @@ class HttpProxyConnectHandlerTest extends FunSuite with OneInstancePerTest {
channel.finishAndReleaseAll()
}
- test("connect to proxy (exception caught)") {
+ test("connect to proxy (exception caught after connected)") {
val channel = new EmbeddedChannel(
new HttpProxyConnectHandler("example.com", None, emptyCodec))
@@ -125,4 +135,19 @@ class HttpProxyConnectHandlerTest extends FunSuite with OneInstancePerTest {
channel.finishAndReleaseAll()
}
+
+ test("connect to proxy (channel closed after connected)") {
+ val channel = new EmbeddedChannel(
+ new HttpProxyConnectHandler("example.com", None, emptyCodec)
+ )
+
+ val connectPromise = channel.connect(fakeAddress)
+ assert(!connectPromise.isDone)
+ assert(channel.isActive)
+ channel.close().sync()
+ assert(!channel.isActive)
+ assert(connectPromise.cause().isInstanceOf[ChannelClosedException])
+
+ channel.finishAndReleaseAll()
+ }
}
| 1
|
dc7e21fb20fba14d59f80ad26c31a72030e6fd53
|
https://github.com/twigphp/Twig/commit/dc7e21fb20fba14d59f80ad26c31a72030e6fd53
|
Merge branch '2.x' into 3.x
* 2.x:
Remove some PHP in docs
|
diff --git a/doc/filters/format_datetime.rst b/doc/filters/format_datetime.rst
index ddbe35f93b..e08e6cdcaf 100644
--- a/doc/filters/format_datetime.rst
+++ b/doc/filters/format_datetime.rst
@@ -3,8 +3,6 @@
The ``format_datetime`` filter formats a date time:
- public function formatDateTime(Environment $env, $date, ?string $dateFormat = 'medium', ?string $timeFormat = 'medium', string $pattern = '', $timezone = null, string $calendar = 'gregorian', string $locale = null): string
-
.. code-block:: twig
{# Aug 7, 2019, 11:39:12 PM #}
| 0
|
8bea1458cf36e40a4bff1b9b351764ba2af85dbf
|
https://github.com/LawnGnome/php-radius/commit/8bea1458cf36e40a4bff1b9b351764ba2af85dbf
|
Add radius_get_tagged_attr_data() and radius_get_tagged_attr_tag() functions.
|
diff --git a/php_radius.h b/php_radius.h
index 074fa1d..ed5240f 100644
--- a/php_radius.h
+++ b/php_radius.h
@@ -79,6 +79,8 @@ PHP_FUNCTION(radius_put_vendor_attr);
PHP_FUNCTION(radius_put_vendor_addr);
PHP_FUNCTION(radius_send_request);
PHP_FUNCTION(radius_get_attr);
+PHP_FUNCTION(radius_get_tagged_attr_data);
+PHP_FUNCTION(radius_get_tagged_attr_tag);
PHP_FUNCTION(radius_get_vendor_attr);
PHP_FUNCTION(radius_cvt_addr);
PHP_FUNCTION(radius_cvt_int);
diff --git a/radius.c b/radius.c
index 7718206..94ba24c 100644
--- a/radius.c
+++ b/radius.c
@@ -80,6 +80,8 @@ zend_function_entry radius_functions[] = {
PHP_FE(radius_put_vendor_addr, NULL)
PHP_FE(radius_send_request, NULL)
PHP_FE(radius_get_attr, NULL)
+ PHP_FE(radius_get_tagged_attr_data, NULL)
+ PHP_FE(radius_get_tagged_attr_tag, NULL)
PHP_FE(radius_get_vendor_attr, NULL)
PHP_FE(radius_cvt_addr, NULL)
PHP_FE(radius_cvt_int, NULL)
@@ -610,6 +612,46 @@ PHP_FUNCTION(radius_get_attr)
}
/* }}} */
+/* {{{ proto string radius_get_tagged_attr_data(string attr) */
+PHP_FUNCTION(radius_get_tagged_attr_data)
+{
+ const char *attr;
+ int len;
+
+ if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "s", &attr, &len) == FAILURE) {
+ return;
+ }
+
+ if (len < 1) {
+ zend_error(E_NOTICE, "Empty attributes cannot have tags");
+ RETURN_FALSE;
+ } else if (len == 1) {
+ RETURN_EMPTY_STRING();
+ }
+
+ RETURN_STRINGL(attr + 1, len - 1, 1);
+}
+/* }}} */
+
+/* {{{ proto string radius_get_tagged_attr_tag(string attr) */
+PHP_FUNCTION(radius_get_tagged_attr_tag)
+{
+ const char *attr;
+ int len;
+
+ if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "s", &attr, &len) == FAILURE) {
+ return;
+ }
+
+ if (len < 1) {
+ zend_error(E_NOTICE, "Empty attributes cannot have tags");
+ RETURN_FALSE;
+ }
+
+ RETURN_LONG((long) *attr);
+}
+/* }}} */
+
/* {{{ proto string radius_get_vendor_attr(data) */
PHP_FUNCTION(radius_get_vendor_attr)
{
diff --git a/tests/radius_get_tagged_attr_data.phpt b/tests/radius_get_tagged_attr_data.phpt
new file mode 100644
index 0000000..f87717d
--- /dev/null
+++ b/tests/radius_get_tagged_attr_data.phpt
@@ -0,0 +1,20 @@
+--TEST--
+radius_get_tagged_attr_data()
+--INI--
+display_errors=1
+error_reporting=30719
+--SKIPIF--
+<?php
+if (!extension_loaded('radius')) echo 'SKIP: radius extension required';
+?>
+--FILE--
+<?php
+var_dump(radius_get_tagged_attr_data(''));
+var_dump(radius_get_tagged_attr_data(pack('C', 20)));
+var_dump(radius_get_tagged_attr_data(pack('C', 20).'foo'));
+?>
+--EXPECTF--
+Notice: Empty attributes cannot have tags in %s on line %d
+bool(false)
+string(0) ""
+string(3) "foo"
diff --git a/tests/radius_get_tagged_attr_tag.phpt b/tests/radius_get_tagged_attr_tag.phpt
new file mode 100644
index 0000000..c5199d6
--- /dev/null
+++ b/tests/radius_get_tagged_attr_tag.phpt
@@ -0,0 +1,20 @@
+--TEST--
+radius_get_tagged_attr_tag()
+--INI--
+display_errors=1
+error_reporting=30719
+--SKIPIF--
+<?php
+if (!extension_loaded('radius')) echo 'SKIP: radius extension required';
+?>
+--FILE--
+<?php
+var_dump(radius_get_tagged_attr_tag(''));
+var_dump(radius_get_tagged_attr_tag(pack('C', 20)));
+var_dump(radius_get_tagged_attr_tag(pack('C', 20).'foo'));
+?>
+--EXPECTF--
+Notice: Empty attributes cannot have tags in %s on line %d
+bool(false)
+int(20)
+int(20)
| 0
|
8c437e0e424db912135256b0738ada2b8d388d4a
|
https://github.com/google/voice-builder/commit/8c437e0e424db912135256b0738ada2b8d388d4a
|
Merge pull request #5 from google/develop
Created DataSets.md
|
diff --git a/DataSets.md b/DataSets.md
new file mode 100644
index 0000000..bd8b8ea
--- /dev/null
+++ b/DataSets.md
@@ -0,0 +1,82 @@
+# Datasets
+
+Following are some datasets that you can use to build TTS voices using Voice Builder.
+
+These data are taken from https://github.com/googlei18n/language-resources
+
+- [Javaneses](#javaneses)
+- [Sundanese](#sundanese)
+- [Khmer](#khmer)
+- [Bengali (bangladesh)](#bengali-bangladesh)
+- [Nepali](#nepali)
+
+## Javaneses
+
+- Lexicon: [gs://voice-builder-public-data/all_example_data/linguistics_data/jv/lexicon.scm](http://storage.googleapis.com/voice-builder-public-data/all_example_data/linguistics_data/jv/lexicon.scm)
+- Phonology: [gs://voice-builder-public-data/all_example_data/linguistics_data/jv/phonology.json](http://storage.googleapis.com/voice-builder-public-data/all_example_data/linguistics_data/jv/phonology.json)
+
+ ### Male (jvm)
+ - Wavs: [gs://voice-builder-public-data/all_example_data/data/jv_id_male/jv_id_male.tar.gz](http://storage.googleapis.com/voice-builder-public-data/all_example_data/data/jv_id_male/jv_id_male.tar.gz)
+ - Wavs info file: [gs://voice-builder-public-data/all_example_data/linguistics_data/jv/jvm.txt.done.data](http://voice-builder-public-data/all_example_data/linguistics_data/jv/jvm.txt.done.data)
+
+ ### Female (jvf)
+
+ - Wavs: [gs://voice-builder-public-data/all_example_data/data/jv_id_female/jv_id_female.tar.gz](http://storage.googleapis.com/voice-builder-public-data/all_example_data/data/jv_id_female/jv_id_female.tar.gz)
+ - Wavs info file: [gs://voice-builder-public-data/all_example_data/linguistics_data/jv/jvf.txt.done.data](http://storage.googleapis.com/voice-builder-public-data/all_example_data/linguistics_data/jv/jvf.txt.done.data)
+
+## Sundanese
+
+- Lexicon: [gs://voice-builder-public-data/all_example_data/linguistics_data/su/lexicon.scm](http://storage.googleapis.com/voice-builder-public-data/all_example_data/linguistics_data/su/lexicon.scm)
+- Phonology: [gs://voice-builder-public-data/all_example_data/linguistics_data/su/phonology.json](http://storage.googleapis.com/voice-builder-public-data/all_example_data/linguistics_data/su/phonology.json)
+
+
+ ### Male (sum)
+ - Wavs: [gs://voice-builder-public-data/all_example_data/data/su_id_male/su_id_male.tar.gz](http://storage.googleapis.com/voice-builder-public-data/all_example_data/data/su_id_male/su_id_male.tar.gz)
+ - Wavs info file: [gs://voice-builder-public-data/all_example_data/linguistics_data/su/sum.txt.done.data](http://storage.googleapis.com/voice-builder-public-data/all_example_data/linguistics_data/su/sum.txt.done.data)
+
+
+ ### Female (suf)
+
+ - Wavs: [gs://voice-builder-public-data/all_example_data/data/su_id_female/su_id_female.tar.gz](http://storage.googleapis.com/voice-builder-public-data/all_example_data/data/su_id_female/su_id_female.tar.gz)
+ - Wavs info file: [gs://voice-builder-public-data/all_example_data/linguistics_data/su/suf.txt.done.data](http://storage.googleapis.com/voice-builder-public-data/all_example_data/linguistics_data/su/suf.txt.done.data)
+
+
+## Khmer
+
+- Lexicon: [gs://voice-builder-public-data/all_example_data/linguistics_data/km/lexicon.scm](http://storage.googleapis.com/voice-builder-public-data/all_example_data/linguistics_data/km/lexicon.scm)
+- Phonology: [gs://voice-builder-public-data/all_example_data/linguistics_data/km/phonology.json](http://storage.googleapis.com/voice-builder-public-data/all_example_data/linguistics_data/km/phonology.json)
+
+ ### Female (khm)
+
+ - Wavs: [gs://voice-builder-public-data/all_example_data/data/km_kh_female/km_kh_female.tar.gz](http://storage.googleapis.com/voice-builder-public-data/all_example_data/data/km_kh_female/km_kh_female.tar.gz)
+ - Wavs info file: [gs://voice-builder-public-data/all_example_data/linguistics_data/km/txt.done.data](http://storage.googleapis.com/voice-builder-public-data/all_example_data/linguistics_data/km/txt.done.data)
+
+
+## Bengali (bangladesh)
+
+- Lexicon: [gs://voice-builder-public-data/all_example_data/linguistics_data/bn/lexicon.scm](http://storage.googleapis.com/voice-builder-public-data/all_example_data/linguistics_data/bn/lexicon.scm)
+- Phonology: [gs://voice-builder-public-data/all_example_data/linguistics_data/bn/phonology.json](http://storage.googleapis.com/voice-builder-public-data/all_example_data/linguistics_data/bn/phonology.json)
+
+ ### Male (ban)
+
+ - Wavs: [gs://voice-builder-public-data/all_example_data/data/bn_bd_male/bn_bd_male.tar.gz](http://storage.googleapis.com/voice-builder-public-data/all_example_data/data/bn_bd_male/bn_bd_male.tar.gz)
+ - Wavs info file: [gs://voice-builder-public-data/all_example_data/linguistics_data/bn/txt.done.data](http://storage.googleapis.com/voice-builder-public-data/all_example_data/linguistics_data/bn/txt.done.data)
+
+
+## Nepali
+
+- Lexicon: [gs://voice-builder-public-data/all_example_data/linguistics_data/su/lexicon.scm](http://storage.googleapis.com/voice-builder-public-data/all_example_data/linguistics_data/su/lexicon.scm)
+- Phonology: [gs://voice-builder-public-data/all_example_data/linguistics_data/su/phonology.json](http://storage.googleapis.com/voice-builder-public-data/all_example_data/linguistics_data/su/phonology.json)
+
+ ### Female (nep)
+
+ - Wavs: [gs://voice-builder-public-data/all_example_data/data/ne_np_female/ne_np_female.tar.gz](http://storage.googleapis.com/voice-builder-public-data/all_example_data/data/ne_np_female/ne_np_female.tar.gz)
+ - Wavs info file: [gs://voice-builder-public-data/all_example_data/linguistics_data/ne/txt.done.data](http://storage.googleapis.com/voice-builder-public-data/all_example_data/linguistics_data/ne/txt.done.data)
+
+
+
+
+
+
+
+
| 0
|
926a5a8226019665ec66d691276616a8f7335960
|
https://github.com/ImageMagick/ImageMagick/commit/926a5a8226019665ec66d691276616a8f7335960
|
Added methods to get the name and the module name of MagickInfo.
|
diff --git a/MagickCore/magick.c b/MagickCore/magick.c
index 376825807f..269106d6a6 100644
--- a/MagickCore/magick.c
+++ b/MagickCore/magick.c
@@ -870,6 +870,64 @@ MagickExport const char *GetMagickMimeType(const MagickInfo *magick_info)
% %
% %
% %
++ G e t M a g i c k M o d u l e N a m e %
+% %
+% %
+% %
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+%
+% GetMagickModuleName() returns the magick module name.
+%
+% The format of the GetMagickModuleName method is:
+%
+% const char *GetMagickModuleName(const MagickInfo *magick_info)
+%
+% A description of each parameter follows:
+%
+% o magick_info: The magick info.
+%
+*/
+MagickExport const char *GetMagickModuleName(const MagickInfo *magick_info)
+{
+ assert(magick_info != (MagickInfo *) NULL);
+ assert(magick_info->signature == MagickCoreSignature);
+ return(magick_info->magick_module);
+}
+
+/*
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% %
+% %
+% %
++ G e t M a g i c k N a m e %
+% %
+% %
+% %
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+%
+% GetMagickName() returns the magick name.
+%
+% The format of the GetMagickName method is:
+%
+% const char *GetMagickName(const MagickInfo *magick_info)
+%
+% A description of each parameter follows:
+%
+% o magick_info: The magick info.
+%
+*/
+MagickExport const char *GetMagickName(const MagickInfo *magick_info)
+{
+ assert(magick_info != (MagickInfo *) NULL);
+ assert(magick_info->signature == MagickCoreSignature);
+ return(magick_info->name);
+}
+
+/*
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% %
+% %
+% %
% G e t M a g i c k P r e c i s i o n %
% %
% %
diff --git a/MagickCore/magick.h b/MagickCore/magick.h
index 3129eff92e..9d5d59d3be 100644
--- a/MagickCore/magick.h
+++ b/MagickCore/magick.h
@@ -107,7 +107,9 @@ extern MagickExport char
extern MagickExport const char
*GetMagickDescription(const MagickInfo *),
- *GetMagickMimeType(const MagickInfo *);
+ *GetMagickMimeType(const MagickInfo *),
+ *GetMagickModuleName(const MagickInfo *),
+ *GetMagickName(const MagickInfo *);
extern MagickExport DecodeImageHandler
*GetImageDecoder(const MagickInfo *) magick_attribute((__pure__));
| 0
|
ceddd7462210fc15d1aec4f18bf47929f492930f
|
https://github.com/nothings/stb/commit/ceddd7462210fc15d1aec4f18bf47929f492930f
|
Update CONTRIBUTING.md
|
diff --git a/.github/CONTRIBUTING.md b/.github/CONTRIBUTING.md
index 0161659835..54e3543ff8 100644
--- a/.github/CONTRIBUTING.md
+++ b/.github/CONTRIBUTING.md
@@ -22,6 +22,7 @@ address things. Many issues have been around for a long time.
* Make sure you're using a special branch just for this pull request. (Sometimes people unknowingly use a default branch, then later update that branch, which updates the pull request with the other changes if it hasn't been merged yet.)
* Do NOT update the version number in the file. (This just causes conflicts.)
* Do add your name to the list of contributors. (Don't worry about the formatting.) I'll try to remember to add it if you don't, but I sometimes forget as it's an extra step.
+* Your change needs to compile as both C and C++. Pre-C99 compilers should be supported (e.g. declare at start of block)
# Specific libraries
| 0
|
b309d392d95a681953680115ccc2a8451a7b65c8
|
https://github.com/centreon/centreon/commit/b309d392d95a681953680115ccc2a8451a7b65c8
|
feat(api): add endpoints to API to add comment on resources (#9245)
|
diff --git a/config/json_validator/latest/Centreon/Comment/Comment.json b/config/json_validator/latest/Centreon/Comment/Comment.json
new file mode 100644
index 00000000000..c37e00b1258
--- /dev/null
+++ b/config/json_validator/latest/Centreon/Comment/Comment.json
@@ -0,0 +1,19 @@
+{
+ "$schema": "http://json-schema.org/draft-04/schema#",
+ "title": "Add comment to a host or a service",
+ "type": "object",
+ "required": ["comment"],
+ "additionalProperties": false,
+ "properties": {
+ "comment": {
+ "type": "string"
+ },
+ "date": {
+ "type": [
+ "string",
+ "null"
+ ],
+ "format": "date-time"
+ }
+ }
+}
diff --git a/config/json_validator/latest/Centreon/Comment/CommentResources.json b/config/json_validator/latest/Centreon/Comment/CommentResources.json
new file mode 100644
index 00000000000..bb114b18a26
--- /dev/null
+++ b/config/json_validator/latest/Centreon/Comment/CommentResources.json
@@ -0,0 +1,55 @@
+{
+ "$schema": "http://json-schema.org/draft-04/schema#",
+ "title": "Add comment on multiple resources",
+ "type": "object",
+ "required": ["resources"],
+ "additionalProperties": false,
+ "properties": {
+ "resources": {
+ "type": "array",
+ "items": {
+ "type": "object",
+ "required": [
+ "type",
+ "id",
+ "parent",
+ "comment"
+ ],
+ "additionalProperties": false,
+ "properties": {
+ "type": {
+ "type": "string",
+ "enum": [
+ "service",
+ "host"
+ ]
+ },
+ "id": {
+ "type": "integer"
+ },
+ "parent": {
+ "type": [
+ "object",
+ "null"
+ ],
+ "properties": {
+ "id": {
+ "type": "integer"
+ }
+ }
+ },
+ "comment": {
+ "type": "string"
+ },
+ "date": {
+ "type": [
+ "string",
+ "null"
+ ],
+ "format": "date-time"
+ }
+ }
+ }
+ }
+ }
+}
\ No newline at end of file
diff --git a/config/packages/validator/validation.yaml b/config/packages/validator/validation.yaml
index 8636581a001..849572044fe 100644
--- a/config/packages/validator/validation.yaml
+++ b/config/packages/validator/validation.yaml
@@ -41,6 +41,19 @@ Centreon\Domain\Acknowledgement\Acknowledgement:
type: boolean
groups: [add_host_acks, add_host_ack, ack_resource]
+# Used to validate the Comment entity
+Centreon\Domain\Monitoring\Comment:
+ properties:
+ date:
+ - Type:
+ type: DateTime
+ groups: [add_host_comment, add_service_comment]
+ comment:
+ - Type:
+ type: string
+ groups: [add_host_comment, add_service_comment]
+ - NotNull: ~
+
# Used to validate the Downtime entity
Centreon\Domain\Downtime\Downtime:
properties:
diff --git a/config/routes/Centreon/monitoring/comments.yaml b/config/routes/Centreon/monitoring/comments.yaml
new file mode 100644
index 00000000000..5f7ce361738
--- /dev/null
+++ b/config/routes/Centreon/monitoring/comments.yaml
@@ -0,0 +1,22 @@
+centreon_application_monitoring_commentresource:
+ methods: POST
+ path: /monitoring/resources/comments
+ controller: 'Centreon\Application\Controller\Monitoring\CommentController::addResourcesComment'
+ condition: "request.attributes.get('version') >= 2.0"
+
+centreon_application_monitoring_commenthost:
+ methods: POST
+ path: /monitoring/hosts/{hostId}/comments
+ requirements:
+ hostId: '\d+'
+ controller: 'Centreon\Application\Controller\Monitoring\CommentController::addHostComment'
+ condition: "request.attributes.get('version') >= 2.0"
+
+centreon_application_monitoring_commentservice:
+ methods: POST
+ path: /monitoring/hosts/{hostId}/services/{serviceId}/comments
+ requirements:
+ hostId: '\d+'
+ serviceId: '\d+'
+ controller: 'Centreon\Application\Controller\Monitoring\CommentController::addServiceComment'
+ condition: "request.attributes.get('version') >= 2.0"
diff --git a/doc/API/centreon-api-v2.yaml b/doc/API/centreon-api-v2.yaml
index 8d16309e324..53eda0e6def 100644
--- a/doc/API/centreon-api-v2.yaml
+++ b/doc/API/centreon-api-v2.yaml
@@ -1738,6 +1738,74 @@ paths:
description: 'Host or service not found'
'500':
$ref: '#/components/responses/InternalServerError'
+ /monitoring/hosts/{host_id}/comments:
+ post:
+ tags:
+ - Comment
+ summary: "Add a comment to a single host"
+ description: "Add a comment to a monitored host"
+ parameters:
+ - $ref: '#/components/parameters/HostId'
+ requestBody:
+ required: true
+ content:
+ application/json:
+ schema:
+ $ref: '#/components/schemas/Comment.Host'
+ responses:
+ '204':
+ description: 'Command Sent'
+ '401':
+ $ref: '#/components/responses/Unauthorized'
+ '404':
+ description: 'Host not found'
+ '500':
+ $ref: '#/components/responses/InternalServerError'
+ /monitoring/hosts/{host_id}/services/{service_id}/comments:
+ post:
+ tags:
+ - Comment
+ summary: "Add a comment to a single service"
+ description: "Add a comment to a monitored service"
+ parameters:
+ - $ref: '#/components/parameters/HostId'
+ - $ref: '#/components/parameters/ServiceId'
+ requestBody:
+ required: true
+ content:
+ application/json:
+ schema:
+ $ref: '#/components/schemas/Comment.Service'
+ responses:
+ '204':
+ description: 'Command Sent'
+ '401':
+ $ref: '#/components/responses/Unauthorized'
+ '404':
+ description: 'Host or service not found'
+ '500':
+ $ref: '#/components/responses/InternalServerError'
+ /monitoring/resources/comments:
+ post:
+ tags:
+ - Comment
+ summary: "Add comment to resources"
+ description: "Add at least one comment to a single or to multiple resources"
+ requestBody:
+ required: true
+ content:
+ application/json:
+ schema:
+ $ref: '#/components/schemas/Comment.Resources'
+ responses:
+ '204':
+ description: 'Command Sent'
+ '401':
+ $ref: '#/components/responses/Unauthorized'
+ '404':
+ description: 'Host or service not found'
+ '500':
+ $ref: '#/components/responses/InternalServerError'
/monitoring/hosts/{host_id}/services/{service_id}/metrics/start/{start}/end/{end}:
get:
tags:
@@ -3751,6 +3819,68 @@ components:
$ref: "#/components/schemas/Downtime.Host"
acknowledgement:
$ref: "#/components/schemas/Acknowledgement.Host"
+ Comment.Host:
+ type: object
+ required: [comment]
+ properties:
+ date:
+ type: string
+ format: date-time
+ nullable: true
+ description: "Date of the comment (ISO8601)"
+ comment:
+ type: string
+ description: "Comment to add to the monitored host"
+ example: "HOST is down because it has been powered off"
+ Comment.Service:
+ type: object
+ required: [comment]
+ properties:
+ date:
+ type: string
+ format: date-time
+ nullable: true
+ description: "Date of the comment (ISO8601)"
+ comment:
+ type: string
+ description: "Comment to add to the monitored service"
+ example: "SERVICE is critical because ntpd service if stopped"
+ Comment.Resources:
+ type: object
+ required: [resources]
+ properties:
+ resources:
+ type: array
+ items:
+ type: object
+ required: [comment,id]
+ properties:
+ type:
+ type: string
+ enum: [host, service]
+ description: "Type of resource"
+ example: "service"
+ id:
+ type: integer
+ description: "Resource ID"
+ example: 10
+ parent:
+ type: object
+ nullable: true
+ properties:
+ id:
+ type: integer
+ description: "Parent resource ID"
+ example: 17
+ date:
+ type: string
+ format: date-time
+ nullable: true
+ description: "Date of the comment (ISO8601)"
+ comment:
+ type: string
+ description: "Comment to add to the monitored resource"
+ example: "Resource is not-OK but it is expected"
Monitoring.Resource.Disacknowledge.Host:
type: object
properties:
diff --git a/lang/fr_FR.UTF-8/LC_MESSAGES/messages.po b/lang/fr_FR.UTF-8/LC_MESSAGES/messages.po
index dc1a94054a8..60f794d12d6 100644
--- a/lang/fr_FR.UTF-8/LC_MESSAGES/messages.po
+++ b/lang/fr_FR.UTF-8/LC_MESSAGES/messages.po
@@ -15860,3 +15860,9 @@ msgstr "[%s] La valeur \"%s\" est trop longue, elle ne devrait pas avoir plus de
msgid "[%s] The value \"%s\" is too short, it should have at least %d characters, but only has %d characters"
msgstr "[%s] La valeur \"%s\" est trop courte, elle devrait avoir au moins %d caractères, mais n'a que %d caractères"
+
+msgid "Error when searching for services"
+msgstr "Erreur lors de la recherche des services"
+
+msgid "Error when searching for hosts"
+msgstr "Erreur lors de la recherche des hôtes"
diff --git a/src/Centreon/Application/Controller/Monitoring/CommentController.php b/src/Centreon/Application/Controller/Monitoring/CommentController.php
new file mode 100644
index 00000000000..27f64fe3c08
--- /dev/null
+++ b/src/Centreon/Application/Controller/Monitoring/CommentController.php
@@ -0,0 +1,302 @@
+<?php
+
+/*
+ * Copyright 2005 - 2020 Centreon (https://www.centreon.com/)
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ *
+ * For more information : [email protected]
+ *
+ */
+declare(strict_types=1);
+
+namespace Centreon\Application\Controller\Monitoring;
+
+use Exception;
+use JsonSchema\Validator;
+use FOS\RestBundle\View\View;
+use Centreon\Domain\Contact\Contact;
+use Centreon\Domain\Monitoring\Host;
+use JsonSchema\Constraints\Constraint;
+use Centreon\Domain\Monitoring\Service;
+use Symfony\Component\HttpFoundation\Request;
+use Centreon\Domain\Monitoring\ResourceStatus;
+use Symfony\Component\HttpFoundation\Response;
+use Centreon\Domain\Monitoring\Comment\Comment;
+use Centreon\Domain\Exception\EntityNotFoundException;
+use Centreon\Application\Controller\AbstractController;
+use Centreon\Domain\Monitoring\Resource as ResourceEntity;
+use Centreon\Domain\Monitoring\Interfaces\MonitoringServiceInterface;
+use Centreon\Domain\Monitoring\Comment\Interfaces\CommentServiceInterface;
+
+class CommentController extends AbstractController
+{
+ /**
+ * comment
+ *
+ * @var CommentServiceInterface
+ */
+ private $commentService;
+
+ /**
+ * Monitoring
+ *
+ * @var MonitoringServiceInterface
+ */
+ private $monitoringService;
+
+ public function __construct(
+ CommentServiceInterface $commentService,
+ MonitoringServiceInterface $monitoringService
+ ) {
+ $this->commentService = $commentService;
+ $this->monitoringService = $monitoringService;
+ }
+
+ /**
+ * This function will ensure that the POST data is valid
+ * regarding validation constraints defined and will return
+ * the decoded JSON content
+ *
+ * @param Request $request
+ * @param string $jsonValidatorFile
+ * @return array $receivedData
+ * @throws InvalidArgumentException
+ */
+ private function validateAndRetrievePostData(Request $request, string $jsonValidatorFile): array
+ {
+ $receivedData = json_decode((string) $request->getContent(), true);
+ if (!is_array($receivedData)) {
+ throw new \InvalidArgumentException(_('Error when decoding sent data'));
+ }
+
+ /*
+ * Validate the content of the POST request against the JSON schema validator
+ */
+ $validator = new Validator();
+ $bodyContent = json_decode((string) $request->getContent());
+ $file = 'file://' . __DIR__ . '/../../../../../' . $jsonValidatorFile;
+ $validator->validate(
+ $bodyContent,
+ (object) ['$ref' => $file],
+ Constraint::CHECK_MODE_VALIDATE_SCHEMA
+ );
+
+ if (!$validator->isValid()) {
+ $message = '';
+ foreach ($validator->getErrors() as $error) {
+ $message .= sprintf("[%s] %s\n", $error['property'], $error['message']);
+ }
+ throw new \InvalidArgumentException($message);
+ }
+
+ return $receivedData;
+ }
+
+ /**
+ * This function will verify that the contact is authorized to add a comment
+ * on the selected resources
+ *
+ * @param Contact $contact
+ * @param array $resources
+ * @return boolean
+ */
+ private function hasCommentRightsForResources(Contact $contact, array $resources): bool
+ {
+ if ($contact->isAdmin()) {
+ return true;
+ }
+ /**
+ * Retrieving the current rights of the user for adding comments
+ */
+ $hasHostRights = $contact->hasRole(Contact::ROLE_HOST_ADD_COMMENT);
+ $hasServiceRights = $contact->hasRole(Contact::ROLE_SERVICE_ADD_COMMENT);
+
+ /**
+ * If the user has no rights at all, do not go further
+ */
+ if (!$hasHostRights && !$hasServiceRights) {
+ return false;
+ }
+
+ foreach ($resources as $resource) {
+ if (
+ ($resource['type'] === ResourceEntity::TYPE_HOST && $hasHostRights)
+ || ($resource['type'] === ResourceEntity::TYPE_SERVICE && $hasServiceRights)
+ ) {
+ continue;
+ }
+ return false;
+ }
+
+ return true;
+ }
+
+ /**
+ * Entry point to add comments to multiple resources
+ *
+ * @param Request $request
+ * @return View
+ * @throws \Exception
+ * @throws \InvalidArgumentException
+ */
+ public function addResourcesComment(
+ Request $request
+ ): View {
+ $this->denyAccessUnlessGrantedForApiRealtime();
+ /**
+ * @var Contact $contact
+ */
+ $contact = $this->getUser();
+ $this->commentService->filterByContact($contact);
+
+ /*
+ * Validate the content of the request against the JSON schema validator
+ */
+ $receivedData = $this->validateAndRetrievePostData(
+ $request,
+ 'config/json_validator/latest/Centreon/Comment/CommentResources.json'
+ );
+
+ /**
+ * If user has no rights to add a comment for host and/or service
+ * return view with unauthorized HTTP header response
+ */
+ if (!$this->hasCommentRightsForResources($contact, $receivedData['resources'])) {
+ return $this->view(null, Response::HTTP_UNAUTHORIZED);
+ }
+
+ /**
+ * Dissect the results to extract the hostids and serviceids from it
+ */
+ $resourceIds = [];
+ $comments = [];
+
+ $now = new \DateTime();
+
+ foreach ($receivedData['resources'] as $commentResource) {
+ $date = ($commentResource['date'] !== null) ? new \DateTime($commentResource['date']) : $now;
+ $comments[$commentResource['id']] = (new Comment($commentResource['id'], $commentResource['comment']))
+ ->setDate($date)
+ ->setParentResourceId($commentResource['parent']['id']);
+
+ if ($commentResource['type'] === ResourceEntity::TYPE_HOST) {
+ $resourceIds['host'][] = $commentResource['id'];
+ } elseif ($commentResource['type'] === ResourceEntity::TYPE_SERVICE) {
+ $resourceIds['service'][] = [
+ 'host_id' => $commentResource['parent']['id'],
+ 'service_id' => $commentResource['id']
+ ];
+ }
+ }
+
+ $this->commentService->addResourcesComment($comments, $resourceIds);
+
+ return $this->view(null, Response::HTTP_NO_CONTENT);
+ }
+
+ /**
+ * Entry point to add a comment on a host resource
+ *
+ * @param Request $request
+ * @param int $hostId ID of the host
+ * @return View
+ * @throws \Exception
+ * @throws \InvalidArgumentException
+ */
+ public function addHostComment(
+ Request $request,
+ int $hostId
+ ): View {
+ $this->denyAccessUnlessGrantedForApiRealtime();
+ /**
+ * @var Contact $contact
+ */
+ $contact = $this->getUser();
+ $this->commentService->filterByContact($contact);
+
+ /**
+ * Checking that user is allowed to add a comment for a host resource
+ */
+ if (!$contact->isAdmin() && !$contact->hasRole(Contact::ROLE_HOST_ADD_COMMENT)) {
+ return $this->view(null, Response::HTTP_UNAUTHORIZED);
+ }
+
+ $receivedData = $this->validateAndRetrievePostData(
+ $request,
+ 'config/json_validator/latest/Centreon/Comment/Comment.json'
+ );
+
+ /**
+ * At this point we validate the JSON sent with the JSON validator.
+ */
+ $date = ($receivedData['date'] !== null) ? new \DateTime($receivedData['date']) : new \DateTime();
+ $comment = (new Comment($hostId, $receivedData['comment']))
+ ->setDate($date);
+ $host = new Host();
+ $host->setId($hostId);
+ $this->commentService->addHostComment($comment, $host);
+
+ return $this->view(null, Response::HTTP_NO_CONTENT);
+ }
+
+ /**
+ * Entry point to add a comment on a service
+ *
+ * @param Request $request
+ * @param int $hostId ID of service parent (host)
+ * @param int $serviceId ID of the service
+ * @return View
+ * @throws \Exception
+ * @throws \InvalidArgumentException
+ */
+ public function addServiceComment(
+ Request $request,
+ int $hostId,
+ int $serviceId
+ ): View {
+ $this->denyAccessUnlessGrantedForApiRealtime();
+
+ /**
+ * @var Contact $contact
+ */
+ $contact = $this->getUser();
+ $this->commentService->filterByContact($contact);
+ if (!$contact->isAdmin() && !$contact->hasRole(Contact::ROLE_SERVICE_ADD_COMMENT)) {
+ return $this->view(null, Response::HTTP_UNAUTHORIZED);
+ }
+
+ $receivedData = $this->validateAndRetrievePostData(
+ $request,
+ 'config/json_validator/latest/Centreon/Comment/Comment.json'
+ );
+
+ /**
+ * At this point we validate the JSON sent with the JSON validator.
+ */
+ $date = ($receivedData['date'] !== null) ? new \DateTime($receivedData['date']) : new \DateTime();
+ $comment = (new Comment($serviceId, $receivedData['comment']))
+ ->setDate($date)
+ ->setParentResourceId($hostId);
+
+ $service = new Service();
+ $host = new Host();
+
+ $host->setId($hostId);
+ $service->setId($serviceId)->setHost($host);
+
+ $this->commentService->addServiceComment($comment, $service);
+
+ return $this->view(null, Response::HTTP_NO_CONTENT);
+ }
+}
diff --git a/src/Centreon/Application/Controller/UserController.php b/src/Centreon/Application/Controller/UserController.php
index 1a87810bd29..d5411464cfd 100644
--- a/src/Centreon/Application/Controller/UserController.php
+++ b/src/Centreon/Application/Controller/UserController.php
@@ -48,6 +48,7 @@ public function getActionsAuthorization(): View
'disacknowledgement' => $this->getAuthorizationForRole(Contact::ROLE_HOST_DISACKNOWLEDGEMENT),
'downtime' => $this->getAuthorizationForRole(Contact::ROLE_ADD_HOST_DOWNTIME),
'submit_status' => $this->getAuthorizationForRole(Contact::ROLE_HOST_SUBMIT_RESULT),
+ 'comment' => $this->getAuthorizationForRole(Contact::ROLE_HOST_ADD_COMMENT),
],
'service' => [
'check' => $this->getAuthorizationForRole(Contact::ROLE_SERVICE_CHECK),
@@ -55,6 +56,7 @@ public function getActionsAuthorization(): View
'disacknowledgement' => $this->getAuthorizationForRole(Contact::ROLE_SERVICE_DISACKNOWLEDGEMENT),
'downtime' => $this->getAuthorizationForRole(Contact::ROLE_ADD_SERVICE_DOWNTIME),
'submit_status' => $this->getAuthorizationForRole(Contact::ROLE_SERVICE_SUBMIT_RESULT),
+ 'comment' => $this->getAuthorizationForRole(Contact::ROLE_SERVICE_ADD_COMMENT),
],
];
diff --git a/src/Centreon/Domain/Contact/Contact.php b/src/Centreon/Domain/Contact/Contact.php
index d4399a035e1..767061ec2be 100644
--- a/src/Centreon/Domain/Contact/Contact.php
+++ b/src/Centreon/Domain/Contact/Contact.php
@@ -45,6 +45,8 @@ class Contact implements UserInterface, ContactInterface
public const ROLE_ADD_SERVICE_DOWNTIME = 'ROLE_ADD_SERVICE_DOWNTIME';
public const ROLE_SERVICE_SUBMIT_RESULT = 'ROLE_SERVICE_SUBMIT_RESULT';
public const ROLE_HOST_SUBMIT_RESULT = 'ROLE_HOST_SUBMIT_RESULT';
+ public const ROLE_HOST_ADD_COMMENT = 'ROLE_HOST_ADD_COMMENT';
+ public const ROLE_SERVICE_ADD_COMMENT = 'ROLE_SERVICE_ADD_COMMENT';
// user pages access
public const ROLE_CONFIGURATION_HOSTS_WRITE = 'ROLE_CONFIGURATION_HOSTS_HOSTS_RW';
diff --git a/src/Centreon/Domain/Engine/EngineService.php b/src/Centreon/Domain/Engine/EngineService.php
index f68ae900abe..5d6354b0524 100644
--- a/src/Centreon/Domain/Engine/EngineService.php
+++ b/src/Centreon/Domain/Engine/EngineService.php
@@ -38,6 +38,8 @@
use Centreon\Domain\Monitoring\SubmitResult\SubmitResultService;
use Centreon\Domain\Engine\Interfaces\EngineConfigurationServiceInterface;
use Centreon\Domain\Engine\Interfaces\EngineConfigurationRepositoryInterface;
+use Centreon\Domain\Monitoring\Comment\Comment;
+use Centreon\Domain\Monitoring\Comment\CommentService;
/**
* This class is designed to send external command for Engine
@@ -500,20 +502,106 @@ public function submitServiceResult(SubmitResult $result, Service $service): voi
$this->engineRepository->sendExternalCommand($commandFull);
}
+ /**
+ * @inheritDoc
+ */
+ public function addServiceComment(Comment $comment, Service $service): void
+ {
+ // We validate the comment instance
+ $errors = $this->validator->validate(
+ $comment,
+ null,
+ CommentService::VALIDATION_GROUPS_SERVICE_ADD_COMMENT
+ );
+
+ if ($errors->count() > 0) {
+ throw new ValidationFailedException($errors);
+ }
+
+ if (empty($this->contact->getAlias())) {
+ throw new EngineException(_('The contact alias is empty'));
+ }
+
+ if ($service->getHost() == null) {
+ throw new EngineException(
+ sprintf(_('The host of service (id: %d) is not defined'), $service->getId())
+ );
+ }
+ if (empty($service->getHost()->getName())) {
+ throw new EngineException(
+ sprintf(_('Host name of service (id: %d) can not be empty'), $service->getId())
+ );
+ }
+ if (empty($service->getDescription())) {
+ throw new EngineException(
+ sprintf(_('The description of service (id: %d) can not be empty'), $service->getId())
+ );
+ }
+ $preCommand = sprintf(
+ 'ADD_SVC_COMMENT;%s;%s;1;%s;%s',
+ $service->getHost()->getName(),
+ $service->getDescription(),
+ $this->contact->getAlias(),
+ $comment->getComment()
+ );
+ $commandToSend = str_replace(['"', "\n"], ['', '<br/>'], $preCommand);
+ $command = $this->createCommandHeader($service->getHost()->getPollerId(), $comment->getDate()) . $commandToSend;
+
+ $this->engineRepository->sendExternalCommand($command);
+ }
+
+ /**
+ * @inheritDoc
+ */
+ public function addHostComment(Comment $comment, Host $host): void
+ {
+ // We validate the comment instance
+ $errors = $this->validator->validate(
+ $comment,
+ null,
+ CommentService::VALIDATION_GROUPS_HOST_ADD_COMMENT
+ );
+
+ if ($errors->count() > 0) {
+ throw new ValidationFailedException($errors);
+ }
+
+ if (empty($this->contact->getAlias())) {
+ throw new EngineException(_('The contact alias is empty'));
+ }
+
+ if (empty($host->getName())) {
+ throw new EngineException(
+ sprintf(_('Host name can not be empty for host (id: %d)'), $host->getId())
+ );
+ }
+
+ $preCommand = sprintf(
+ 'ADD_HOST_COMMENT;%s;1;%s;%s',
+ $host->getName(),
+ $this->contact->getAlias(),
+ $comment->getComment()
+ );
+ $commandToSend = str_replace(['"', "\n"], ['', '<br/>'], $preCommand);
+ $command = $this->createCommandHeader($host->getPollerId(), $comment->getDate()) . $commandToSend;
+ $this->engineRepository->sendExternalCommand($command);
+ }
+
/**
* Create the command header for external commands
*
* @param int $pollerId Id of the poller
+ * @param \DateTime|null $date date of the command
* @return string Returns the new generated command header
* @throws \Exception
*/
- private function createCommandHeader(int $pollerId): string
+ private function createCommandHeader(int $pollerId, \DateTime $date = null): string
{
return sprintf(
"%s:%d:[%d] ",
'EXTERNALCMD',
$pollerId,
- (new \DateTime())->getTimestamp()
+ $date ? $date->getTimestamp() : (new \DateTime())->getTimestamp()
);
}
}
diff --git a/src/Centreon/Domain/Engine/Interfaces/EngineServiceInterface.php b/src/Centreon/Domain/Engine/Interfaces/EngineServiceInterface.php
index c3651f7c300..7b3cbaa0a2f 100644
--- a/src/Centreon/Domain/Engine/Interfaces/EngineServiceInterface.php
+++ b/src/Centreon/Domain/Engine/Interfaces/EngineServiceInterface.php
@@ -27,6 +27,7 @@
use Centreon\Domain\Downtime\Downtime;
use Centreon\Domain\Monitoring\Service;
use Centreon\Domain\Engine\EngineException;
+use Centreon\Domain\Monitoring\Comment\Comment;
use Centreon\Domain\Acknowledgement\Acknowledgement;
use JMS\Serializer\Exception\ValidationFailedException;
use Centreon\Domain\Monitoring\SubmitResult\SubmitResult;
@@ -145,4 +146,22 @@ public function submitHostResult(SubmitResult $result, Host $host): void;
* @throws \Exception
*/
public function submitServiceResult(SubmitResult $result, Service $service): void;
+
+ /**
+ * Add a comment to a monitored service
+ *
+ * @param Comment $comment
+ * @param Service $service
+ * @throws \Exception
+ */
+ public function addServiceComment(Comment $comment, Service $service): void;
+
+ /**
+ * Add a comment to a monitored host
+ *
+ * @param Comment $comment
+ * @param Host $host
+ * @throws \Exception
+ */
+ public function addHostComment(Comment $comment, Host $host): void;
}
diff --git a/src/Centreon/Domain/Monitoring/Comment/Comment.php b/src/Centreon/Domain/Monitoring/Comment/Comment.php
new file mode 100644
index 00000000000..3f431065422
--- /dev/null
+++ b/src/Centreon/Domain/Monitoring/Comment/Comment.php
@@ -0,0 +1,139 @@
+<?php
+
+/*
+ * Copyright 2005 - 2020 Centreon (https://www.centreon.com/)
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ *
+ * For more information : [email protected]
+ *
+ */
+declare(strict_types=1);
+
+namespace Centreon\Domain\Monitoring\Comment;
+
+class Comment
+{
+ /**
+ * @var int Resource ID
+ */
+ public $resourceId;
+
+ /**
+ * @var int|null Parent Resource ID
+ */
+ private $parentResourceId;
+
+ /**
+ * @var string added comment
+ */
+ public $comment;
+
+ /**
+ * Date of the comment
+ *
+ * @var \DateTime|null
+ */
+ public $date;
+
+ public function __construct(int $resourceId, string $comment)
+ {
+ $this->resourceId = $resourceId;
+ $this->setComment($comment);
+ }
+
+ /**
+ * @return int
+ */
+ public function getResourceId(): int
+ {
+ return $this->resourceId;
+ }
+
+ /**
+ * @param int $resourceId
+ * @return Comment
+ */
+ public function setResourceId(int $resourceId): Comment
+ {
+ $this->resourceId = $resourceId;
+ return $this;
+ }
+
+ /**
+ * @return int|null
+ */
+ public function getParentResourceId(): ?int
+ {
+ return $this->parentResourceId;
+ }
+
+ /**
+ * @param int|null $parentResourceId
+ * @return Comment
+ */
+ public function setParentResourceId(?int $parentResourceId): Comment
+ {
+ $this->parentResourceId = $parentResourceId;
+ return $this;
+ }
+
+ /**
+ * Get added comment
+ *
+ * @return string
+ */
+ public function getComment(): string
+ {
+ return $this->comment;
+ }
+
+ /**
+ * Set added comment
+ *
+ * @param string $comment added comment
+ * @return Comment
+ */
+ public function setComment(string $comment): Comment
+ {
+ if (empty($comment)) {
+ throw new \InvalidArgumentException(
+ "Comment can not be empty"
+ );
+ }
+ $this->comment = $comment;
+ return $this;
+ }
+
+ /**
+ * Get date of the comment
+ *
+ * @return \DateTime|null
+ */
+ public function getDate(): ?\DateTime
+ {
+ return $this->date;
+ }
+
+ /**
+ * Set date of the comment
+ *
+ * @param \DateTime $date Date of the comment
+ * @return Comment
+ */
+ public function setDate(\DateTime $date)
+ {
+ $this->date = $date;
+ return $this;
+ }
+}
diff --git a/src/Centreon/Domain/Monitoring/Comment/CommentException.php b/src/Centreon/Domain/Monitoring/Comment/CommentException.php
new file mode 100644
index 00000000000..d81a71b041a
--- /dev/null
+++ b/src/Centreon/Domain/Monitoring/Comment/CommentException.php
@@ -0,0 +1,27 @@
+<?php
+
+/*
+ * Copyright 2005 - 2020 Centreon (https://www.centreon.com/)
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ *
+ * For more information : [email protected]
+ *
+ */
+declare(strict_types=1);
+
+namespace Centreon\Domain\Monitoring\Comment;
+
+class CommentException extends \RuntimeException
+{
+}
diff --git a/src/Centreon/Domain/Monitoring/Comment/CommentService.php b/src/Centreon/Domain/Monitoring/Comment/CommentService.php
new file mode 100644
index 00000000000..669814f2e27
--- /dev/null
+++ b/src/Centreon/Domain/Monitoring/Comment/CommentService.php
@@ -0,0 +1,254 @@
+<?php
+
+/*
+ * Copyright 2005 - 2020 Centreon (https://www.centreon.com/)
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ *
+ * For more information : [email protected]
+ *
+ */
+declare(strict_types=1);
+
+namespace Centreon\Domain\Monitoring\Comment;
+
+use Centreon\Domain\Contact\Contact;
+use Centreon\Domain\Monitoring\Host;
+use Centreon\Domain\Monitoring\Service;
+use Centreon\Domain\Entity\EntityValidator;
+use Centreon\Domain\Monitoring\MonitoringService;
+use Centreon\Domain\Service\AbstractCentreonService;
+use Centreon\Domain\Exception\EntityNotFoundException;
+use JMS\Serializer\Exception\ValidationFailedException;
+use Centreon\Domain\Monitoring\Comment\CommentException;
+use Centreon\Domain\Engine\Interfaces\EngineServiceInterface;
+use Centreon\Domain\Monitoring\Interfaces\MonitoringServiceInterface;
+use Centreon\Domain\Security\Interfaces\AccessGroupRepositoryInterface;
+use Centreon\Domain\Monitoring\Interfaces\MonitoringRepositoryInterface;
+use Centreon\Domain\Monitoring\Comment\Interfaces\CommentServiceInterface;
+
+/**
+ * Monitoring class used to manage result submitting to services, hosts and resources
+ *
+ * @package Centreon\Domain\Monitoring\SubmitResult
+ */
+class CommentService extends AbstractCentreonService implements CommentServiceInterface
+{
+ public const VALIDATION_GROUPS_HOST_ADD_COMMENT = ['add_host_comment'];
+ public const VALIDATION_GROUPS_SERVICE_ADD_COMMENT = ['add_service_comment'];
+
+ /**
+ * @var EngineServiceInterface Used to send external commands to engine.
+ */
+ private $engineService;
+
+ /**
+ * @var EntityValidator
+ */
+ private $validator;
+
+ /**
+ * @var MonitoringRepositoryInterface
+ */
+ private $monitoringRepository;
+
+ /**
+ * @var AccessGroupRepositoryInterface
+ */
+ private $accessGroupRepository;
+
+ /**
+ * @var MonitoringServiceInterface
+ */
+ private $monitoringService;
+
+ /**
+ * CommentService constructor.
+ *
+ * @param AccessGroupRepositoryInterface $accessGroupRepository
+ * @param MonitoringRepositoryInterface $monitoringRepository
+ * @param EngineServiceInterface $engineService
+ * @param MonitoringServiceInterface $monitoringService
+ * @param EntityValidator $validator
+ */
+ public function __construct(
+ AccessGroupRepositoryInterface $accessGroupRepository,
+ MonitoringRepositoryInterface $monitoringRepository,
+ EngineServiceInterface $engineService,
+ MonitoringServiceInterface $monitoringService,
+ EntityValidator $validator
+ ) {
+ $this->accessGroupRepository = $accessGroupRepository;
+ $this->monitoringRepository = $monitoringRepository;
+ $this->engineService = $engineService;
+ $this->monitoringService = $monitoringService;
+ $this->validator = $validator;
+ }
+
+ /**
+ * {@inheritDoc}
+ * @param Contact $contact
+ * @return CommentServiceInterface
+ */
+ public function filterByContact($contact): CommentServiceInterface
+ {
+ parent::filterByContact($contact);
+ $this->engineService->filterByContact($contact);
+
+ $accessGroups = $this->accessGroupRepository->findByContact($contact);
+
+ $this->monitoringRepository
+ ->setContact($contact)
+ ->filterByAccessGroups($accessGroups);
+
+ return $this;
+ }
+
+ /**
+ * @inheritDoc
+ */
+ public function addServiceComment(Comment $comment, Service $service): void
+ {
+ // We validate the comment entity sent
+ $errors = $this->validator->validate(
+ $comment,
+ null,
+ self::VALIDATION_GROUPS_SERVICE_ADD_COMMENT
+ );
+
+ if ($errors->count() > 0) {
+ throw new ValidationFailedException($errors);
+ }
+
+ $hostComment = $this->monitoringService
+ ->filterByContact($this->contact)
+ ->findOneHost($service->getHost()->getId());
+
+ if (is_null($hostComment)) {
+ throw new EntityNotFoundException(
+ sprintf(
+ _('Host %d not found'),
+ $service->getHost()->getId()
+ )
+ );
+ }
+
+ $serviceComment = $this->monitoringService
+ ->filterByContact($this->contact)
+ ->findOneService($hostComment->getId(), $service->getId());
+
+ if (is_null($serviceComment)) {
+ throw new EntityNotFoundException(
+ sprintf(
+ _('Service %d not found'),
+ $service->getId()
+ )
+ );
+ }
+ $serviceComment->setHost($hostComment);
+
+ $this->engineService->addServiceComment($comment, $serviceComment);
+ }
+
+ /**
+ * @inheritDoc
+ */
+ public function addHostComment(Comment $comment, Host $host): void
+ {
+ // We validate the comment entity sent
+ $errors = $this->validator->validate(
+ $comment,
+ null,
+ self::VALIDATION_GROUPS_HOST_ADD_COMMENT
+ );
+
+ if ($errors->count() > 0) {
+ throw new ValidationFailedException($errors);
+ }
+
+ $hostComment = $this->monitoringService
+ ->filterByContact($this->contact)
+ ->findOneHost($host->getId());
+
+ if (is_null($hostComment)) {
+ throw new EntityNotFoundException(
+ sprintf(
+ _('Host %d not found'),
+ $host->getId()
+ )
+ );
+ }
+
+ $this->engineService->addHostComment($comment, $hostComment);
+ }
+
+ /**
+ * @inheritDoc
+ */
+ public function addResourcesComment(array $comments, array $resourceIds): void
+ {
+ $hosts = [];
+ $services = [];
+ /**
+ * Retrieving at this point all the host and services entities linked to
+ * the resource ids provided
+ */
+ if ($this->contact->isAdmin()) {
+ if (!empty($resourceIds['host'])) {
+ try {
+ $hosts = $this->monitoringRepository->findHostsByIdsForAdminUser($resourceIds['host']);
+ } catch (\Throwable $ex) {
+ throw new CommentException(_('Error when searching for hosts'), 0, $ex);
+ }
+ }
+
+ if (!empty($resourceIds['service'])) {
+ try {
+ $services = $this->monitoringRepository->findServicesByIdsForAdminUser($resourceIds['service']);
+ } catch (\Throwable $ex) {
+ throw new CommentException(_('Error when searching for services'), 0, $ex);
+ }
+ }
+ } else {
+ $accessGroups = $this->accessGroupRepository->findByContact($this->contact);
+
+ if (!empty($resourcesId['host'])) {
+ try {
+ $hosts = $this->monitoringRepository
+ ->filterByAccessGroups($accessGroups)
+ ->findHostsByIdsForNonAdminUser($resourceIds['host']);
+ } catch (\Throwable $ex) {
+ throw new CommentException(_('Error when searching for hosts'), 0, $ex);
+ }
+ }
+
+ if (!empty($resourcesIds['service'])) {
+ try {
+ $services = $this->monitoringRepository
+ ->filterByAccessGroups($accessGroups)
+ ->findServicesByIdsForNonAdminUser($resourceIds['service']);
+ } catch (\Throwable $ex) {
+ throw new CommentException(_('Error when searching for services'), 0, $ex);
+ }
+ }
+ }
+
+ foreach ($hosts as $host) {
+ $this->addHostComment($comments[$host->getId()], $host);
+ }
+
+ foreach ($services as $service) {
+ $this->addServiceComment($comments[$service->getId()], $service);
+ }
+ }
+}
diff --git a/src/Centreon/Domain/Monitoring/Comment/Interfaces/CommentServiceInterface.php b/src/Centreon/Domain/Monitoring/Comment/Interfaces/CommentServiceInterface.php
new file mode 100644
index 00000000000..4a76027e180
--- /dev/null
+++ b/src/Centreon/Domain/Monitoring/Comment/Interfaces/CommentServiceInterface.php
@@ -0,0 +1,57 @@
+<?php
+
+/*
+ * Copyright 2005 - 2020 Centreon (https://www.centreon.com/)
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ *
+ * For more information : [email protected]
+ *
+ */
+declare(strict_types=1);
+
+namespace Centreon\Domain\Monitoring\Comment\Interfaces;
+
+use Centreon\Domain\Monitoring\Host;
+use Centreon\Domain\Monitoring\Service;
+use Centreon\Domain\Monitoring\Comment\Comment;
+use Centreon\Domain\Contact\Interfaces\ContactFilterInterface;
+
+interface CommentServiceInterface extends ContactFilterInterface
+{
+ /**
+ * Function allowing contact to add a comment to a service
+ *
+ * @param Comment $comment Comment to add to the service
+ * @param Service $service Service that will receive the comment
+ */
+ public function addServiceComment(Comment $comment, Service $service): void;
+
+ /**
+ * Function allowing contact to add a comment to a host
+ *
+ * @param Comment $comment Comment to add to the host
+ * @param Host $host Host that will receive the comment
+ * @return void
+ */
+ public function addHostComment(Comment $comment, Host $host): void;
+
+ /**
+ * Function allowing contact to add multiple comments to multiple resources
+ *
+ * @param Comment[] $comments Comments added for each resources
+ * @param array $resourceIds IDs of the resources
+ * @return void
+ */
+ public function addResourcesComment(array $comments, array $resourceIds): void;
+}
diff --git a/src/Centreon/Domain/Monitoring/Interfaces/MonitoringRepositoryInterface.php b/src/Centreon/Domain/Monitoring/Interfaces/MonitoringRepositoryInterface.php
index 0bd20ec5ff7..b6a99d01948 100644
--- a/src/Centreon/Domain/Monitoring/Interfaces/MonitoringRepositoryInterface.php
+++ b/src/Centreon/Domain/Monitoring/Interfaces/MonitoringRepositoryInterface.php
@@ -84,6 +84,22 @@ public function findHostGroups(?int $hostId): array;
*/
public function findOneHost(int $hostId): ?Host;
+ /**
+ * Find all hosts from an array of hostIds for a non admin user
+ *
+ * @param array $hostIds
+ * @return Host[]
+ */
+ public function findHostsByIdsForNonAdminUser(array $hostIds): array;
+
+ /**
+ * Find all hosts from an array of hostIds for an admin user
+ *
+ * @param array $hostIds
+ * @return Host[]
+ */
+ public function findHostsByIdsForAdminUser(array $hostIds): array;
+
/**
* Find one service based on its id and according to ACL.
*
@@ -94,6 +110,22 @@ public function findOneHost(int $hostId): ?Host;
*/
public function findOneService(int $hostId, int $serviceId): ?Service;
+ /**
+ * Find all services from an array of serviceIds for a non admin user
+ *
+ * @param array $serviceIds
+ * @return Services[]
+ */
+ public function findServicesByIdsForNonAdminUser(array $serviceIds): array;
+
+ /**
+ * Find all services from an array of serviceIds for an admin user
+ *
+ * @param array $serviceIds
+ * @return Services[]
+ */
+ public function findServicesByIdsForAdminUser(array $serviceIds): array;
+
/**
* Find all services grouped by service groups
*
diff --git a/src/Centreon/Domain/Monitoring/Interfaces/MonitoringServiceInterface.php b/src/Centreon/Domain/Monitoring/Interfaces/MonitoringServiceInterface.php
index ab8261bcb53..b6fe3aa5022 100644
--- a/src/Centreon/Domain/Monitoring/Interfaces/MonitoringServiceInterface.php
+++ b/src/Centreon/Domain/Monitoring/Interfaces/MonitoringServiceInterface.php
@@ -22,15 +22,15 @@
namespace Centreon\Domain\Monitoring\Interfaces;
-use Centreon\Domain\Contact\Interfaces\ContactFilterInterface;
-use Centreon\Domain\HostConfiguration\HostConfigurationException;
-use Centreon\Domain\Monitoring\Exception\MonitoringServiceException;
use Centreon\Domain\Monitoring\Host;
-use Centreon\Domain\Monitoring\HostGroup;
use Centreon\Domain\Monitoring\Service;
+use Centreon\Domain\Monitoring\HostGroup;
use Centreon\Domain\Monitoring\ServiceGroup;
-use Centreon\Domain\MonitoringServer\MonitoringServerException;
use Centreon\Domain\Repository\RepositoryException;
+use Centreon\Domain\Contact\Interfaces\ContactFilterInterface;
+use Centreon\Domain\MonitoringServer\MonitoringServerException;
+use Centreon\Domain\HostConfiguration\HostConfigurationException;
+use Centreon\Domain\Monitoring\Exception\MonitoringServiceException;
use Centreon\Domain\ServiceConfiguration\ServiceConfigurationException;
interface MonitoringServiceInterface extends ContactFilterInterface
diff --git a/src/Centreon/Infrastructure/Contact/ContactRepositoryRDB.php b/src/Centreon/Infrastructure/Contact/ContactRepositoryRDB.php
index 339b1284932..cb78450ccac 100644
--- a/src/Centreon/Infrastructure/Contact/ContactRepositoryRDB.php
+++ b/src/Centreon/Infrastructure/Contact/ContactRepositoryRDB.php
@@ -374,6 +374,12 @@ private function addActionRule(Contact $contact, string $ruleName): void
case 'host_submit_result':
$contact->addRole(Contact::ROLE_HOST_SUBMIT_RESULT);
break;
+ case 'host_comment':
+ $contact->addRole(Contact::ROLE_HOST_ADD_COMMENT);
+ break;
+ case 'service_comment':
+ $contact->addRole(Contact::ROLE_SERVICE_ADD_COMMENT);
+ break;
}
}
diff --git a/src/Centreon/Infrastructure/Monitoring/MonitoringRepositoryRDB.php b/src/Centreon/Infrastructure/Monitoring/MonitoringRepositoryRDB.php
index 9935efc204b..bfad95c3d83 100644
--- a/src/Centreon/Infrastructure/Monitoring/MonitoringRepositoryRDB.php
+++ b/src/Centreon/Infrastructure/Monitoring/MonitoringRepositoryRDB.php
@@ -35,6 +35,7 @@
use Centreon\Domain\Monitoring\Service;
use Centreon\Domain\Monitoring\ResourceStatus;
use Centreon\Domain\Monitoring\Interfaces\MonitoringRepositoryInterface;
+use Centreon\Infrastructure\CentreonLegacyDB\StatementCollector;
use Centreon\Infrastructure\DatabaseConnection;
use Centreon\Infrastructure\RequestParameters\SqlRequestParametersTranslator;
@@ -540,6 +541,182 @@ public function findOneHost(int $hostId): ?Host
}
}
+ /**
+ * @inheritDoc
+ */
+ public function findServicesByIdsForAdminUser(array $serviceIds): array
+ {
+ $services = [];
+
+ $collector = new StatementCollector();
+
+ if (empty($serviceIds)) {
+ return $services;
+ }
+
+ $request =
+ 'SELECT DISTINCT srv.*,
+ h.host_id AS `host_host_id`, h.name AS `host_name`, h.alias AS `host_alias`,
+ h.instance_id AS `host_poller_id`, srv.state AS `status_code`,
+ CASE
+ WHEN srv.state = 0 THEN "' . ResourceStatus::STATUS_NAME_OK . '"
+ WHEN srv.state = 1 THEN "' . ResourceStatus::STATUS_NAME_WARNING . '"
+ WHEN srv.state = 2 THEN "' . ResourceStatus::STATUS_NAME_CRITICAL . '"
+ WHEN srv.state = 3 THEN "' . ResourceStatus::STATUS_NAME_UNKNOWN . '"
+ WHEN srv.state = 4 THEN "' . ResourceStatus::STATUS_NAME_PENDING . '"
+ END AS `status_name`,
+ CASE
+ WHEN srv.state = 0 THEN ' . ResourceStatus::SEVERITY_OK . '
+ WHEN srv.state = 1 THEN ' . ResourceStatus::SEVERITY_MEDIUM . '
+ WHEN srv.state = 2 THEN ' . ResourceStatus::SEVERITY_HIGH . '
+ WHEN srv.state = 3 THEN ' . ResourceStatus::SEVERITY_LOW . '
+ WHEN srv.state = 4 THEN ' . ResourceStatus::SEVERITY_PENDING . '
+ END AS `status_severity_code`
+ FROM `:dbstg`.services srv
+ LEFT JOIN `:dbstg`.hosts h
+ ON h.host_id = srv.host_id
+ WHERE srv.enabled = \'1\'
+ AND h.enabled = \'1\'';
+
+ $idsListKey = [];
+ foreach ($serviceIds as $index => $hostServiceIds) {
+ $hostKey = ":host_id{$index}";
+ $hostIdsListKey[] = $hostKey;
+ $serviceKey = ":service_id{$index}";
+ $serviceIdsListKey[] = $serviceKey;
+ $collector->addValue($serviceKey, $hostServiceIds['service_id'], \PDO::PARAM_INT);
+ $collector->addValue($hostKey, $hostServiceIds['host_id'], \PDO::PARAM_INT);
+ }
+ $request .= ' AND srv.service_id IN (' . implode(',', $serviceIdsListKey) . ')';
+ $request .= ' AND srv.host_id IN (' . implode(',', $hostIdsListKey) . ')';
+
+ $request .= ' GROUP BY srv.service_id';
+
+ $request = $this->translateDbName($request);
+
+ $statement = $this->db->prepare($request);
+ $collector->bind($statement);
+ $statement->execute();
+
+ while (false !== ($row = $statement->fetch(\PDO::FETCH_ASSOC))) {
+ $service = EntityCreator::createEntityByArray(
+ Service::class,
+ $row
+ );
+ $service->setHost(
+ EntityCreator::createEntityByArray(Host::class, $row, 'host_')
+ );
+ $services[] = $service;
+ }
+ return $services;
+ }
+
+ /**
+ * @inheritDoc
+ */
+ public function findHostsByIdsForAdminUser(array $hostIds): array
+ {
+ $hosts = [];
+
+ if (empty($hostIds)) {
+ return $hosts;
+ }
+
+ $collector = new StatementCollector();
+
+ $request =
+ 'SELECT h.*,
+ i.name AS poller_name,
+ IF (h.display_name LIKE \'_Module_Meta%\', \'Meta\', h.display_name) AS display_name,
+ IF (h.display_name LIKE \'_Module_Meta%\', \'0\', h.state) AS state
+ FROM `:dbstg`.`instances` i
+ INNER JOIN `:dbstg`.`hosts` h
+ ON h.instance_id = i.instance_id
+ AND h.enabled = \'1\'
+ AND h.name NOT LIKE \'_Module_BAM%\'';
+
+ $idsListKey = [];
+ foreach ($hostIds as $index => $id) {
+ $key = ":id{$index}";
+ $idsListKey[] = $key;
+ $collector->addValue($key, $id, \PDO::PARAM_INT);
+ }
+ $request .= ' WHERE h.host_id IN (' . implode(',', $idsListKey) . ')';
+
+ $request = $this->translateDbName($request);
+
+ $statement = $this->db->prepare($request);
+ $collector->bind($statement);
+ $statement->execute();
+
+ while (false !== ($row = $statement->fetch(\PDO::FETCH_ASSOC))) {
+ $hosts[] = EntityCreator::createEntityByArray(
+ Host::class,
+ $row
+ );
+ }
+
+ return $hosts;
+ }
+
+ /**
+ * @inheritDoc
+ */
+ public function findHostsByIdsForNonAdminUser(array $hostIds): array
+ {
+ $hosts = [];
+
+ if (empty($hostIds)) {
+ return $hosts;
+ }
+
+ $collector = new StatementCollector();
+
+ $accessGroupFilter =
+ ' INNER JOIN `:dbstg`.`centreon_acl` acl
+ ON acl.host_id = h.host_id
+ AND acl.service_id IS NULL
+ INNER JOIN `:db`.`acl_groups` acg
+ ON acg.acl_group_id = acl.group_id
+ AND acg.acl_group_activate = \'1\'
+ AND acg.acl_group_id IN (' . $this->accessGroupIdToString($this->accessGroups) . ') ';
+
+ $request =
+ 'SELECT h.*,
+ i.name AS poller_name,
+ IF (h.display_name LIKE \'_Module_Meta%\', \'Meta\', h.display_name) AS display_name,
+ IF (h.display_name LIKE \'_Module_Meta%\', \'0\', h.state) AS state
+ FROM `:dbstg`.`instances` i
+ INNER JOIN `:dbstg`.`hosts` h
+ ON h.instance_id = i.instance_id
+ AND h.enabled = \'1\'
+ AND h.name NOT LIKE \'_Module_BAM%\''
+ . $accessGroupFilter;
+
+ $idsListKey = [];
+ foreach ($hostIds as $index => $id) {
+ $key = ":id{$index}";
+ $idsListKey[] = $key;
+ $collector->addValue($key, $id, \PDO::PARAM_INT);
+ }
+
+ $request .= ' WHERE h.host_id IN (' . implode(',', $idsListKey) . ')';
+ $request = $this->translateDbName($request);
+
+ $statement = $this->db->prepare($request);
+ $collector->bind($statement);
+ $statement->execute();
+
+ while (false !== ($row = $statement->fetch(\PDO::FETCH_ASSOC))) {
+ $host[] = EntityCreator::createEntityByArray(
+ Host::class,
+ $row
+ );
+ }
+
+ return $hosts;
+ }
+
/**
* @inheritDoc
*/
@@ -629,6 +806,87 @@ public function findOneService(int $hostId, int $serviceId): ?Service
return $service;
}
+ /**
+ * @inheritDoc
+ */
+ public function findServicesByIdsForNonAdminUser(array $serviceIds): array
+ {
+ $services = [];
+
+ $collector = new StatementCollector();
+
+ if (empty($serviceIds)) {
+ return $services;
+ }
+
+ $accessGroupFilter =
+ ' INNER JOIN `:dbstg`.`centreon_acl` acl
+ ON acl.host_id = h.host_id
+ AND acl.service_id = srv.service_id
+ INNER JOIN `:db`.`acl_groups` acg
+ ON acg.acl_group_id = acl.group_id
+ AND acg.acl_group_activate = \'1\'
+ AND acg.acl_group_id IN (' . $this->accessGroupIdToString($this->accessGroups) . ') ';
+
+ $request =
+ 'SELECT DISTINCT srv.*,
+ h.host_id AS `host_host_id`, h.name AS `host_name`, h.alias AS `host_alias`,
+ h.instance_id AS `host_poller_id`, srv.state AS `status_code`,
+ CASE
+ WHEN srv.state = 0 THEN "' . ResourceStatus::STATUS_NAME_OK . '"
+ WHEN srv.state = 1 THEN "' . ResourceStatus::STATUS_NAME_WARNING . '"
+ WHEN srv.state = 2 THEN "' . ResourceStatus::STATUS_NAME_CRITICAL . '"
+ WHEN srv.state = 3 THEN "' . ResourceStatus::STATUS_NAME_UNKNOWN . '"
+ WHEN srv.state = 4 THEN "' . ResourceStatus::STATUS_NAME_PENDING . '"
+ END AS `status_name`,
+ CASE
+ WHEN srv.state = 0 THEN ' . ResourceStatus::SEVERITY_OK . '
+ WHEN srv.state = 1 THEN ' . ResourceStatus::SEVERITY_MEDIUM . '
+ WHEN srv.state = 2 THEN ' . ResourceStatus::SEVERITY_HIGH . '
+ WHEN srv.state = 3 THEN ' . ResourceStatus::SEVERITY_LOW . '
+ WHEN srv.state = 4 THEN ' . ResourceStatus::SEVERITY_PENDING . '
+ END AS `status_severity_code`
+ FROM `:dbstg`.services srv
+ LEFT JOIN `:dbstg`.hosts h
+ ON h.host_id = srv.host_id'
+ . $accessGroupFilter
+ . ' WHERE srv.enabled = \'1\'
+ AND h.enabled = \'1\'';
+
+ $idsListKey = [];
+ foreach ($serviceIds as $index => $hostServiceIds) {
+ $hostKey = ":host_id{$index}";
+ $hostIdsListKey[] = $hostKey;
+ $serviceKey = ":service_id{$index}";
+ $serviceIdsListKey[] = $serviceKey;
+ $collector->addValue($serviceKey, $hostServiceIds['service_id'], \PDO::PARAM_INT);
+ $collector->addValue($hostKey, $hostServiceIds['host_id'], \PDO::PARAM_INT);
+ }
+ $request .= ' AND srv.service_id IN (' . implode(',', $serviceIdsListKey) . ')';
+ $request .= ' AND srv.host_id IN (' . implode(',', $hostIdsListKey) . ')';
+
+ $request .= ' GROUP BY srv.service_id';
+
+ $request = $this->translateDbName($request);
+
+ $statement = $this->db->prepare($request);
+ $collector->bind($statement);
+ $statement->execute();
+
+ while (false !== ($row = $statement->fetch(\PDO::FETCH_ASSOC))) {
+ $service = EntityCreator::createEntityByArray(
+ Service::class,
+ $row
+ );
+ $service->setHost(
+ EntityCreator::createEntityByArray(Host::class, $row, 'host_')
+ );
+ $services[] = $service;
+ }
+
+ return $services;
+ }
+
/**
* @inheritDoc
*/
diff --git a/tests/api/Context/CommentContext.php b/tests/api/Context/CommentContext.php
new file mode 100644
index 00000000000..67149ae8269
--- /dev/null
+++ b/tests/api/Context/CommentContext.php
@@ -0,0 +1,28 @@
+<?php
+
+/*
+ * Copyright 2005 - 2020 Centreon (https://www.centreon.com/)
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ *
+ * For more information : [email protected]
+ *
+ */
+
+namespace Centreon\Test\Api\Context;
+
+use Centreon\Test\Behat\Api\Context\ApiContext;
+
+class CommentContext extends ApiContext
+{
+}
diff --git a/tests/api/behat.yml b/tests/api/behat.yml
index d1a2d70eae5..2b9deb2774a 100644
--- a/tests/api/behat.yml
+++ b/tests/api/behat.yml
@@ -36,6 +36,10 @@ default:
paths: [ "%paths.base%/features/SubmitResult.feature" ]
contexts:
- Centreon\Test\Api\Context\SubmitResultContext
+ comment:
+ paths: [ "%paths.base%/features/Comment.feature" ]
+ contexts:
+ - Centreon\Test\Api\Context\CommentContext
acknowledgement:
paths: [ "%paths.base%/features/Acknowledgement.feature" ]
contexts:
diff --git a/tests/api/features/Comment.feature b/tests/api/features/Comment.feature
new file mode 100644
index 00000000000..0062a2489a9
--- /dev/null
+++ b/tests/api/features/Comment.feature
@@ -0,0 +1,51 @@
+Feature:
+ In order to identify issues on resources
+ As a user
+ I want to add a comment on those resources
+
+ Background:
+ Given a running instance of Centreon Web API
+ And the endpoints are described in Centreon Web API documentation
+
+ Scenario: Add comment to resources
+ Given I am logged in
+ And the following CLAPI import data:
+ """
+ HOST;ADD;test;Test host;127.0.0.1;generic-host;central;
+ SERVICE;ADD;test;test_service_1;Ping-LAN;
+ """
+ And the configuration is generated and exported
+ And I wait until service "test_service_1" from host "test" is monitored
+ And I send a GET request to '/beta/monitoring/services?search={"$and":[{"host.name":"test"},{"service.description":"test_service_1"}]}'
+ And I store response values in:
+ | name | path |
+ | hostId | result[0].host.id |
+ | serviceId | result[0].id |
+
+ When I send a POST request to '/beta/monitoring/resources/comments' with body:
+ """
+ {
+ "resources": [
+ {
+ "type": "host",
+ "id": <hostId>,
+ "parent": null,
+ "comment": "This happened because wire has been unplugged",
+ "date": null
+ },
+ {
+ "type": "service",
+ "id": <serviceId>,
+ "parent": {
+ "id": <hostId>
+ },
+ "comment": "This happened because the ntpd service is stopped",
+ "date": null
+ }
+ ]
+ }
+ """
+
+ Then the response code should be 204
+ And the content of file "/var/log/centreon-engine/centengine.log" should match "/ADD_HOST_COMMENT;test/"
+ And the content of file "/var/log/centreon-engine/centengine.log" should match "/ADD_SVC_COMMENT;test;test_service_1/" (tries: 3)
diff --git a/tests/php/Centreon/Application/Controller/Monitoring/CommentControllerTest.php b/tests/php/Centreon/Application/Controller/Monitoring/CommentControllerTest.php
new file mode 100644
index 00000000000..722a8a8630c
--- /dev/null
+++ b/tests/php/Centreon/Application/Controller/Monitoring/CommentControllerTest.php
@@ -0,0 +1,330 @@
+<?php
+
+/*
+ * Copyright 2005 - 2020 Centreon (https://www.centreon.com/)
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ *
+ * For more information : [email protected]
+ *
+ */
+
+namespace Tests\Centreon\Application\Controller\Monitoring;
+
+use FOS\RestBundle\View\View;
+use PHPUnit\Framework\TestCase;
+use Centreon\Domain\Contact\Contact;
+use Psr\Container\ContainerInterface;
+use Centreon\Domain\Monitoring\Resource;
+use Symfony\Component\HttpFoundation\Request;
+use Symfony\Component\HttpFoundation\Response;
+use Centreon\Domain\Monitoring\Comment\CommentService;
+use Centreon\Application\Controller\Monitoring\CommentController;
+use Centreon\Domain\Monitoring\MonitoringService;
+use Centreon\Test\Api\Context\CommentContext;
+use Symfony\Component\Security\Core\Authentication\Token\TokenInterface;
+use Symfony\Component\Security\Core\Authorization\AuthorizationCheckerInterface;
+use Symfony\Component\Security\Core\Authentication\Token\Storage\TokenStorageInterface;
+
+class CommentControllerTest extends TestCase
+{
+ protected $adminContact;
+ protected $hostResource;
+ protected $serviceResource;
+ protected $correctJsonComment;
+ protected $wrongJsonComment;
+ protected $hostCommentJson;
+ protected $serviceCommentJson;
+ protected $serviceResult;
+ protected $commentService;
+ protected $monitoringService;
+
+ protected $container;
+
+ protected $request;
+
+ protected function setUp()
+ {
+ $timezone = new \DateTimeZone('Europe/Paris');
+ $dateTime = new \DateTime('now');
+ $date = $dateTime->format(\DateTime::ATOM);
+
+ $this->adminContact = (new Contact())
+ ->setId(1)
+ ->setName('admin')
+ ->setAdmin(true)
+ ->setTimezone($timezone);
+
+ $correctJsonComment = [
+ 'resources' => [
+ [
+ 'type' => 'host',
+ 'id' => 1,
+ 'parent' => null,
+ 'comment' => 'simple comment on a host resource',
+ 'date' => null
+ ],
+ [
+ 'type' => 'service',
+ 'id' => 1,
+ 'parent' => [
+ 'id' => 1,
+ ],
+ 'comment' => 'simple comment on a service resource',
+ 'date' => $date
+ ],
+ ],
+ ];
+
+ $hostCommentJson = [
+ 'comment' => 'single comment on a service',
+ 'date' => $date
+ ];
+
+ $serviceCommentJson = [
+ 'comment' => 'single comment on a host',
+ 'date' => $date
+ ];
+
+ $this->hostResource = (new Resource())
+ ->setType($correctJsonComment['resources'][0]['type'])
+ ->setId($correctJsonComment['resources'][0]['id']);
+ $this->serviceResource = (new Resource())
+ ->setType($correctJsonComment['resources'][1]['type'])
+ ->setId($correctJsonComment['resources'][1]['id'])
+ ->setParent($this->hostResource);
+
+ $this->correctJsonComment = json_encode($correctJsonComment);
+ $this->serviceCommentJson = json_encode($serviceCommentJson);
+ $this->hostCommentJson = json_encode($hostCommentJson);
+
+ $this->wrongJsonComment = json_encode([
+ 'unknown_property' => 'unknown',
+ ]);
+
+ $this->commentService = $this->createMock(CommentService::class);
+ $this->monitoringService = $this->createMock(MonitoringService::class);
+
+ $authorizationChecker = $this->createMock(AuthorizationCheckerInterface::class);
+ $authorizationChecker->expects($this->once())
+ ->method('isGranted')
+ ->willReturn(true);
+ $token = $this->createMock(TokenInterface::class);
+ $token->expects($this->any())
+ ->method('getUser')
+ ->willReturn($this->adminContact);
+ $tokenStorage = $this->createMock(TokenStorageInterface::class);
+ $tokenStorage->expects($this->any())
+ ->method('getToken')
+ ->willReturn($token);
+
+ $this->container = $this->createMock(ContainerInterface::class);
+ $this->container->expects($this->any())
+ ->method('has')
+ ->willReturn(true);
+ $this->container->expects($this->any())
+ ->method('get')
+ ->withConsecutive(
+ [$this->equalTo('security.authorization_checker')],
+ [$this->equalTo('security.token_storage')],
+ [$this->equalTo('parameter_bag')]
+ )
+ ->willReturnOnConsecutiveCalls(
+ $authorizationChecker,
+ $tokenStorage,
+ new class () {
+ public function get()
+ {
+ return __DIR__ . '/../../../../../';
+ }
+ }
+ );
+
+ $this->request = $this->createMock(Request::class);
+ }
+
+ /**
+ * Testing wrongly formatted JSON POST data for addResourcesComment
+ */
+ public function testaddResourcesCommentBadJsonFormat()
+ {
+ $commentController = new CommentController($this->commentService, $this->monitoringService);
+ $commentController->setContainer($this->container);
+
+ $this->request->expects($this->once())
+ ->method('getContent')
+ ->willReturn('[}');
+ $this->expectException(\InvalidArgumentException::class);
+ $this->expectExceptionMessage('Error when decoding sent data');
+ $commentController->addResourcesComment($this->request);
+ }
+
+ /**
+ * Testing with wrong property added to the POST JSON for addResourcesComment
+ */
+ public function testCommentResourcesBadJsonProperties()
+ {
+ $commentController = new CommentController($this->commentService, $this->monitoringService);
+ $commentController->setContainer($this->container);
+
+ $this->request->expects($this->any())
+ ->method('getContent')
+ ->willReturn($this->wrongJsonComment);
+ $this->expectException(\InvalidArgumentException::class);
+ $commentController->addResourcesComment($this->request);
+ }
+
+ /**
+ * Testing with a correct JSON POST data and successfully adding a comment to a resource
+ */
+ public function testAddResourcesCommentSuccess()
+ {
+ $this->commentService->expects($this->any())
+ ->method('filterByContact')
+ ->willReturn($this->commentService);
+
+ $commentController = new CommentController($this->commentService, $this->monitoringService);
+ $commentController->setContainer($this->container);
+
+ $this->request->expects($this->any())
+ ->method('getContent')
+ ->willReturn($this->correctJsonComment);
+ $view = $commentController->addResourcesComment($this->request);
+
+ $this->assertEquals($view, View::create(null, Response::HTTP_NO_CONTENT));
+ }
+
+ /**
+ * Testing with wrongly formatted JSON POST data for addHostComment
+ */
+ public function testAddHostCommentBadJsonFormat()
+ {
+ $commentController = new CommentController($this->commentService, $this->monitoringService);
+ $commentController->setContainer($this->container);
+
+ $this->request->expects($this->once())
+ ->method('getContent')
+ ->willReturn('[}');
+ $this->expectException(\InvalidArgumentException::class);
+ $this->expectExceptionMessage('Error when decoding sent data');
+ $commentController->addHostComment($this->request, $this->hostResource->getId());
+ }
+ /**
+ * Testing with wrong property added to the POST JSON for addHostComment
+ */
+ public function testAddHostCommentBadJsonProperties()
+ {
+ $commentController = new CommentController($this->commentService, $this->monitoringService);
+ $commentController->setContainer($this->container);
+
+ $this->request->expects($this->any())
+ ->method('getContent')
+ ->willReturn($this->wrongJsonComment);
+ $this->expectException(\InvalidArgumentException::class);
+ $commentController->addHostComment($this->request, $this->hostResource->getId());
+ }
+ /**
+ * Testing with a correct JSON POST data and successfully adding a comment for a host resource
+ */
+ public function testAddHostCommentSuccess()
+ {
+ $this->commentService->expects($this->any())
+ ->method('filterByContact')
+ ->willReturn($this->commentService);
+
+ $commentController = new CommentController($this->commentService, $this->monitoringService);
+ $commentController->setContainer($this->container);
+
+ $this->request->expects($this->any())
+ ->method('getContent')
+ ->willReturn($this->hostCommentJson);
+
+ $this->request->expects($this->any())
+ ->method('findOneHost')
+ ->willReturn($this->hostResource);
+
+ $view = $commentController->addHostComment($this->request, $this->hostResource->getId());
+
+ $this->assertEquals($view, View::create(null, Response::HTTP_NO_CONTENT));
+ }
+
+ /**
+ * Testing with wrongly formatted JSON POST data for addServiceComment
+ */
+ public function testAddServiceCommentBadJsonFormat()
+ {
+ $commentController = new CommentController($this->commentService, $this->monitoringService);
+ $commentController->setContainer($this->container);
+
+ $this->request->expects($this->once())
+ ->method('getContent')
+ ->willReturn('[}');
+ $this->expectException(\InvalidArgumentException::class);
+ $this->expectExceptionMessage('Error when decoding sent data');
+ $commentController->addServiceComment(
+ $this->request,
+ $this->serviceResource->getParent()->getId(),
+ $this->serviceResource->getId()
+ );
+ }
+ /**
+ * Testing with wrong property added to the POST JSON for addServiceComment
+ */
+ public function testAddServiceCommentBadJsonProperties()
+ {
+ $commentController = new CommentController($this->commentService, $this->monitoringService);
+ $commentController->setContainer($this->container);
+
+ $this->request->expects($this->any())
+ ->method('getContent')
+ ->willReturn($this->wrongJsonComment);
+ $this->expectException(\InvalidArgumentException::class);
+ $commentController->addServiceComment(
+ $this->request,
+ $this->serviceResource->getParent()->getId(),
+ $this->serviceResource->getId()
+ );
+ }
+ /**
+ * Testing with a correct JSON POST data and successfully adding comment for a service resource
+ */
+ public function testAddServiceCommentSuccess()
+ {
+ $this->commentService->expects($this->any())
+ ->method('filterByContact')
+ ->willReturn($this->commentService);
+
+ $commentController = new CommentController($this->commentService, $this->monitoringService);
+ $commentController->setContainer($this->container);
+
+ $this->request->expects($this->any())
+ ->method('getContent')
+ ->willReturn($this->serviceCommentJson);
+
+ $this->request->expects($this->any())
+ ->method('findOneHost')
+ ->willReturn($this->hostResource);
+
+ $this->request->expects($this->any())
+ ->method('findOneService')
+ ->willReturn($this->serviceResource);
+
+ $view = $commentController->addServiceComment(
+ $this->request,
+ $this->serviceResource->getParent()->getId(),
+ $this->serviceResource->getId()
+ );
+
+ $this->assertEquals($view, View::create(null, Response::HTTP_NO_CONTENT));
+ }
+}
diff --git a/tests/php/Centreon/Domain/Engine/EngineServiceTest.php b/tests/php/Centreon/Domain/Engine/EngineServiceTest.php
index ddecb27b699..1164713fd17 100644
--- a/tests/php/Centreon/Domain/Engine/EngineServiceTest.php
+++ b/tests/php/Centreon/Domain/Engine/EngineServiceTest.php
@@ -27,6 +27,7 @@
use Centreon\Domain\Monitoring\Service;
use Centreon\Domain\Engine\EngineService;
use Centreon\Domain\Entity\EntityValidator;
+use Centreon\Domain\Monitoring\Comment\Comment;
use Symfony\Component\Validator\ConstraintViolationList;
use Centreon\Domain\Monitoring\SubmitResult\SubmitResult;
use Centreon\Domain\Engine\Interfaces\EngineServiceInterface;
@@ -47,13 +48,16 @@ class EngineServiceTest extends TestCase
protected $commandHeaderRegex;
protected $monitoringRepository;
protected $engineConfigurationService;
+ protected $hostComment;
+ protected $serviceComment;
protected function setUp()
{
$this->adminContact = (new Contact())
->setId(1)
->setName('admin')
- ->setAdmin(true);
+ ->setAdmin(true)
+ ->setAlias('adminAlias');
$this->host = (new Host())
->setId(1)
@@ -73,6 +77,12 @@ protected function setUp()
->setParentResourceId($this->service->getHost()->getId())
->setOutput('Service went critical')
->setPerformanceData('ping: 0');
+
+ $this->hostComment = (new Comment($this->host->getID(), 'Simple host comment'))
+ ->setDate(new \DateTime('now'));
+
+ $this->serviceComment = (new Comment($this->service->getID(), 'Simple service comment'))
+ ->setDate(new \DateTime('now'));
/**
* commandHeader should look like 'EXTERNALCMD:<pollerid>:[timestamp] '
*/
@@ -86,6 +96,85 @@ protected function setUp()
$this->monitoringRepository = $this->createMock(MonitoringRepositoryInterface::class);
}
+ /**
+ * Testing the addHostComment EngineService function in a nominal case.
+ */
+ public function testAddHostComment()
+ {
+ $this->entityValidator->expects($this->once())
+ ->method('validate')
+ ->willReturn(new ConstraintViolationList());
+
+ /**
+ * Creating the command to check that the code
+ * will send the same to the sendExternalCommand
+ * repository function
+ */
+ $command = sprintf(
+ 'ADD_HOST_COMMENT;%s;1;%s;%s',
+ $this->host->getName(),
+ $this->adminContact->getAlias(),
+ $this->hostComment->getComment()
+ );
+
+ $this->engineRepository->expects($this->once())
+ ->method('sendExternalCommand')
+ ->with(
+ $this->matchesRegularExpression(
+ '/^' . $this->commandHeaderRegex . str_replace('|', '\|', $command) . '$/'
+ )
+ );
+
+ $engineService = new EngineService(
+ $this->engineRepository,
+ $this->engineConfigurationService,
+ $this->entityValidator
+ );
+
+ $engineService->filterByContact($this->adminContact);
+ $this->assertNull($engineService->addHostComment($this->hostComment, $this->host));
+ }
+
+ /**
+ * Testing the addServiceComment EngineService function in a nominal case.
+ */
+ public function testServiceComment()
+ {
+ $this->entityValidator->expects($this->once())
+ ->method('validate')
+ ->willReturn(new ConstraintViolationList());
+
+ /**
+ * Creating the command to check that the code
+ * will send the same to the sendExternalCommand
+ * repository function
+ */
+ $command = sprintf(
+ 'ADD_SVC_COMMENT;%s;%s;1;%s;%s',
+ $this->host->getName(),
+ $this->service->getDescription(),
+ $this->adminContact->getAlias(),
+ $this->serviceComment->getComment()
+ );
+
+ $this->engineRepository->expects($this->once())
+ ->method('sendExternalCommand')
+ ->with(
+ $this->matchesRegularExpression(
+ '/^' . $this->commandHeaderRegex . str_replace('|', '\|', $command) . '$/'
+ )
+ );
+
+ $engineService = new EngineService(
+ $this->engineRepository,
+ $this->engineConfigurationService,
+ $this->entityValidator
+ );
+
+ $engineService->filterByContact($this->adminContact);
+ $this->assertNull($engineService->addServiceComment($this->serviceComment, $this->service));
+ }
+
/**
* Testing the submitHostResult EngineService function in a nominal case.
*/
| 0
|
ea5b1d791e2a1ac481bbcc5792ab1f8b42f4bd39
|
https://github.com/vadz/libtiff/commit/ea5b1d791e2a1ac481bbcc5792ab1f8b42f4bd39
|
* tools/tiffset.c: fix setting a single value for the ExtraSamples tag
(and other tags with variable number of values).
So 'tiffset -s ExtraSamples 1 X'. This only worked
when setting 2 or more values, but not just one.
|
diff --git a/ChangeLog b/ChangeLog
index aa980846..f49af68d 100644
--- a/ChangeLog
+++ b/ChangeLog
@@ -1,3 +1,10 @@
+2017-10-01 Even Rouault <even.rouault at spatialys.com>
+
+ * tools/tiffset.c: fix setting a single value for the ExtraSamples tag
+ (and other tags with variable number of values).
+ So 'tiffset -s ExtraSamples 1 X'. This only worked
+ when setting 2 or more values, but not just one.
+
2017-09-29 Even Rouault <even.rouault at spatialys.com>
* libtiff/libtiff.def: add TIFFReadRGBAStripExt and TIFFReadRGBATileExt
diff --git a/tools/tiffset.c b/tools/tiffset.c
index 4d83344f..be72c6f9 100644
--- a/tools/tiffset.c
+++ b/tools/tiffset.c
@@ -155,7 +155,7 @@ main(int argc, char* argv[])
return 4;
}
- if (wc > 1) {
+ if (wc > 1 || TIFFFieldWriteCount(fip) == TIFF_VARIABLE) {
int i, size;
void *array;
| 0
|
419847a8aaa6383ea2859b666d3b22b361b76efd
|
https://github.com/lxc/lxc/commit/419847a8aaa6383ea2859b666d3b22b361b76efd
|
freezer: use lxc_cmd_notify_state_listeners()
Signed-off-by: Christian Brauner <[email protected]>
|
diff --git a/src/lxc/freezer.c b/src/lxc/freezer.c
index dbb70f61df..ae4d70f62b 100644
--- a/src/lxc/freezer.c
+++ b/src/lxc/freezer.c
@@ -15,6 +15,7 @@
#include "cgroups/cgroup.h"
#include "cgroups/cgroup_utils.h"
#include "commands.h"
+#include "commands_utils.h"
#include "config.h"
#include "error.h"
#include "log.h"
@@ -25,13 +26,6 @@
lxc_log_define(freezer, lxc);
-static void notify_state_listeners(const char *name, const char *lxcpath,
- lxc_state_t state)
-{
- (void)lxc_cmd_serve_state_clients(name, lxcpath, state);
- (void)lxc_monitor_send_state(name, state, lxcpath);
-}
-
static int do_freeze_thaw(bool freeze, struct lxc_conf *conf, const char *name,
const char *lxcpath)
{
@@ -64,7 +58,7 @@ static int do_freeze_thaw(bool freeze, struct lxc_conf *conf, const char *name,
cur_state[lxc_char_right_gc(cur_state, strlen(cur_state))] = '\0';
ret = strncmp(cur_state, state, state_len);
if (ret == 0) {
- notify_state_listeners(name, lxcpath, new_state);
+ lxc_cmd_notify_state_listeners(name, lxcpath, new_state);
return 0;
}
@@ -78,12 +72,12 @@ int lxc_freeze(struct lxc_conf *conf, const char *name, const char *lxcpath)
{
int ret;
- notify_state_listeners(name, lxcpath, FREEZING);
+ lxc_cmd_notify_state_listeners(name, lxcpath, FREEZING);
if (unified_cgroup_hierarchy() > 0)
ret = lxc_cmd_freeze(name, lxcpath, -1);
else
ret = do_freeze_thaw(true, conf, name, lxcpath);
- notify_state_listeners(name, lxcpath, !ret ? FROZEN : RUNNING);
+ lxc_cmd_notify_state_listeners(name, lxcpath, !ret ? FROZEN : RUNNING);
return ret;
}
@@ -91,11 +85,11 @@ int lxc_unfreeze(struct lxc_conf *conf, const char *name, const char *lxcpath)
{
int ret;
- notify_state_listeners(name, lxcpath, THAWED);
+ lxc_cmd_notify_state_listeners(name, lxcpath, THAWED);
if (unified_cgroup_hierarchy() > 0)
ret = lxc_cmd_unfreeze(name, lxcpath, -1);
else
ret = do_freeze_thaw(false, conf, name, lxcpath);
- notify_state_listeners(name, lxcpath, !ret ? RUNNING : FROZEN);
+ lxc_cmd_notify_state_listeners(name, lxcpath, !ret ? RUNNING : FROZEN);
return ret;
}
| 0
|
55270cb953c65d49b93407c6a283cbc18f70b183
|
https://github.com/apache/santuario-java/commit/55270cb953c65d49b93407c6a283cbc18f70b183
|
Change distribution URL.
git-svn-id: https://svn.apache.org/repos/asf/santuario/trunk@1003729 13f79535-47bb-0310-9956-ffa450edef68
|
diff --git a/c/xml-security-c.spec b/c/xml-security-c.spec
index edc349545..d44b6534f 100644
--- a/c/xml-security-c.spec
+++ b/c/xml-security-c.spec
@@ -4,7 +4,7 @@ Release: 1
Summary: Apache XML security C++ library
Group: System Environment/Libraries
License: Apache Software License
-URL: http://santuario.apache.org/c/
+URL: http://santuario.apache.org/dist/c-library/
Source: %{name}-%{version}.tar.gz
BuildRoot: %{_tmppath}/%{name}-%{version}-build
| 0
|
e447e8b92148ddb3d1956b96638600ec95e08f6b
|
https://github.com/symfony/symfony/commit/e447e8b92148ddb3d1956b96638600ec95e08f6b
|
[HttpFoundation] Remove support for legacy and risky HTTP headers
|
diff --git a/src/Symfony/Component/HttpFoundation/CHANGELOG.md b/src/Symfony/Component/HttpFoundation/CHANGELOG.md
index 9f48e8252d99..f8b043384de3 100644
--- a/src/Symfony/Component/HttpFoundation/CHANGELOG.md
+++ b/src/Symfony/Component/HttpFoundation/CHANGELOG.md
@@ -1,6 +1,12 @@
CHANGELOG
=========
+2.8.44
+------
+
+ * [BC BREAK] Support for the IIS-only `X_ORIGINAL_URL` and `X_REWRITE_URL`
+ HTTP headers has been dropped for security reasons.
+
2.8.0
-----
diff --git a/src/Symfony/Component/HttpFoundation/Request.php b/src/Symfony/Component/HttpFoundation/Request.php
index 60a7c47ad9cd..f8d43c5147a4 100644
--- a/src/Symfony/Component/HttpFoundation/Request.php
+++ b/src/Symfony/Component/HttpFoundation/Request.php
@@ -1691,18 +1691,7 @@ protected function prepareRequestUri()
{
$requestUri = '';
- if ($this->headers->has('X_ORIGINAL_URL')) {
- // IIS with Microsoft Rewrite Module
- $requestUri = $this->headers->get('X_ORIGINAL_URL');
- $this->headers->remove('X_ORIGINAL_URL');
- $this->server->remove('HTTP_X_ORIGINAL_URL');
- $this->server->remove('UNENCODED_URL');
- $this->server->remove('IIS_WasUrlRewritten');
- } elseif ($this->headers->has('X_REWRITE_URL')) {
- // IIS with ISAPI_Rewrite
- $requestUri = $this->headers->get('X_REWRITE_URL');
- $this->headers->remove('X_REWRITE_URL');
- } elseif ('1' == $this->server->get('IIS_WasUrlRewritten') && '' != $this->server->get('UNENCODED_URL')) {
+ if ('1' == $this->server->get('IIS_WasUrlRewritten') && '' != $this->server->get('UNENCODED_URL')) {
// IIS7 with URL Rewrite: make sure we get the unencoded URL (double slash problem)
$requestUri = $this->server->get('UNENCODED_URL');
$this->server->remove('UNENCODED_URL');
diff --git a/src/Symfony/Component/HttpFoundation/Tests/RequestTest.php b/src/Symfony/Component/HttpFoundation/Tests/RequestTest.php
index 3b65bcc99c25..e57bf62b5b0b 100644
--- a/src/Symfony/Component/HttpFoundation/Tests/RequestTest.php
+++ b/src/Symfony/Component/HttpFoundation/Tests/RequestTest.php
@@ -1809,52 +1809,8 @@ public function iisRequestUriProvider()
{
return array(
array(
- array(
- 'X_ORIGINAL_URL' => '/foo/bar',
- ),
- array(),
- '/foo/bar',
- ),
- array(
- array(
- 'X_REWRITE_URL' => '/foo/bar',
- ),
array(),
- '/foo/bar',
- ),
- array(
- array(),
- array(
- 'IIS_WasUrlRewritten' => '1',
- 'UNENCODED_URL' => '/foo/bar',
- ),
- '/foo/bar',
- ),
- array(
- array(
- 'X_ORIGINAL_URL' => '/foo/bar',
- ),
- array(
- 'HTTP_X_ORIGINAL_URL' => '/foo/bar',
- ),
- '/foo/bar',
- ),
- array(
- array(
- 'X_ORIGINAL_URL' => '/foo/bar',
- ),
- array(
- 'IIS_WasUrlRewritten' => '1',
- 'UNENCODED_URL' => '/foo/bar',
- ),
- '/foo/bar',
- ),
- array(
- array(
- 'X_ORIGINAL_URL' => '/foo/bar',
- ),
array(
- 'HTTP_X_ORIGINAL_URL' => '/foo/bar',
'IIS_WasUrlRewritten' => '1',
'UNENCODED_URL' => '/foo/bar',
),
| 1
|
27c6ddbd569ede8f8a4c981a5a63b17f5c3ec8a4
|
https://github.com/atheme/charybdis/commit/27c6ddbd569ede8f8a4c981a5a63b17f5c3ec8a4
|
Merge pull request #359 from edk0/stats-l-operhide
m_stats: Make /stats l respect oper hiding
|
diff --git a/modules/m_stats.c b/modules/m_stats.c
index ef255ee9d..e966f0f47 100644
--- a/modules/m_stats.c
+++ b/modules/m_stats.c
@@ -73,7 +73,7 @@ DECLARE_MODULE_AV2(stats, NULL, NULL, stats_clist, stats_hlist, NULL, NULL, NULL
const char *Lformat = "%s %u %u %u %u %u :%u %u %s";
static void stats_l_list(struct Client *s, const char *, bool, bool, rb_dlink_list *, char,
- bool (*check_fn)(struct Client *target_p));
+ bool (*check_fn)(struct Client *source_p, struct Client *target_p));
static void stats_l_client(struct Client *source_p, struct Client *target_p,
char statchar);
@@ -1582,9 +1582,9 @@ stats_servlinks (struct Client *source_p)
}
static inline bool
-stats_l_should_show_oper(struct Client *target_p)
+stats_l_should_show_oper(struct Client *source_p, struct Client *target_p)
{
- return (!IsOperInvis(target_p));
+ return SeesOper(target_p, source_p);
}
static void
@@ -1676,7 +1676,7 @@ stats_ltrace(struct Client *source_p, int parc, const char *parv[])
static void
stats_l_list(struct Client *source_p, const char *name, bool doall, bool wilds,
- rb_dlink_list * list, char statchar, bool (*check_fn)(struct Client *target_p))
+ rb_dlink_list * list, char statchar, bool (*check_fn)(struct Client *source_p, struct Client *target_p))
{
rb_dlink_node *ptr;
struct Client *target_p;
@@ -1692,7 +1692,7 @@ stats_l_list(struct Client *source_p, const char *name, bool doall, bool wilds,
if(!doall && wilds && !match(name, target_p->name))
continue;
- if (check_fn == NULL || check_fn(target_p))
+ if (check_fn == NULL || check_fn(source_p, target_p))
stats_l_client(source_p, target_p, statchar);
}
}
| 0
|
79747755db740a1be977fb76fb9dc841e426da29
|
https://github.com/simplesamlphp/simplesamlphp/commit/79747755db740a1be977fb76fb9dc841e426da29
|
Add changelogs from 1.18 branch
|
diff --git a/docs/simplesamlphp-changelog.md b/docs/simplesamlphp-changelog.md
index 0272d3eb41..3f69766ced 100644
--- a/docs/simplesamlphp-changelog.md
+++ b/docs/simplesamlphp-changelog.md
@@ -22,6 +22,98 @@ Released TBD
* This version will be the last of the 1.x branch and will provide a migration path to our new
templating system, routing system, translation system and hooks.
+## Version 1.18.8
+
+Released 2020-09-02
+
+ * Fixed Artifact Resolution due to incorrect use of Issuer objects (#1343).
+ * Fixed some of the German translations (#1331). Thanks @htto!
+ * Harden against CVE-2020-13625; this package is not affected, but 3rd party modules may (#1333).
+ * Harden against sevaral JS issues (npm update & npm audit fix)
+ * Fixed inconsistent configuration of backtraces logging
+ * Support for Symfony 3.x is now deprecated
+ * Support for Twig 1.x is now deprecated
+
+### authcrypt
+ * The dependency for whitehat101/apr1-md5 was moved from the base repository to the module (v0.9.2)
+
+### authx509
+ * Restore PHP 5.6 compatibility (v0.9.5)
+
+### cron
+ * Fixed old-ui (#1248)
+
+### ldap
+ * Moved array with binary attributes to authsource config (v0.9.9)
+ Instead of having to edit code, you can now set 'attributes.binary' in the authsource configuration.
+
+### metarefresh
+ * Add attributewhitelist to support e.g. R&S+Sirtfi (v0.9.5)
+ * Restore PHP 5.6 compatibility (v0.9.6)
+
+### negotiate ###
+ * Restore PHP 5.6 compatibility (v0.9.8)
+ * Fixed a link (v0.9.9)
+
+### saml2 library
+ * Fixed a bug in the AuthnRequest-class that would raise an InvalidArgumentException when setting
+ the AssertionConsumerServiceIndex as an integer on an saml:SP authsource.
+ Thanks to Andrea @ Oracle for reporting this.
+
+## Version 1.18.7
+
+Released 2020-05-12
+
+ * Fix spurious warnings when session_create_id() fails to create ID (#1291)
+ * Fix inconsistency in the way PATH_INFO is being used (#1227).
+ * Fix a potential security issue [CVE-2020-11022](https://nvd.nist.gov/vuln/detail/CVE-2020-11022) by updating jQuery. If any of your custom modules rely on jQuery,
+ make sure you read the following [update notes](https://jquery.com/upgrade-guide/3.5/), since jQuery has solved this in a non-BC way (#1321).
+ * Fix incorrect Polish translations (#1311).
+ * Fix a broken migration query in the LogoutStore (#1324).
+ * Fix an issue with the SameSite cookie parameter when running on PHP versions older than 7.3 (#1320).
+
+### adfs
+ * Fixed a broken link to one of the assets (v0.9.6).
+
+### ldap
+ * Handle binary attributes in a generic way (v0.9.5).
+
+### oauth
+ * Fix PHP 7.4 incompatibility (v0.9.2).
+
+### preprodwarning
+ * Fix Dutch translations (v0.9.2).
+
+### sanitycheck
+ * Fix broken HTML (v0.9.1).
+
+### saml
+ * Fix several issues in the saml:NameIDAttribute authproc filter (#1325).
+
+### saml2 library
+ * fixed a standards compliance issue regarding ContactPerson EMail addresses (v3.4.4).
+ * fixed an issue parsing very large metadata files (v3.4.3).
+
+## Version 1.18.6
+
+Released 2020-04-17
+
+ * Fix source code disclosure on case-insensitive file systems. See
+ [SSPSA 202004-01](https://simplesamlphp.org/security/202004-01).
+ * Fix spurious error in logs when using a custom theme (#1312).
+ * Fix broken metadata converter (#1305).
+
+## Version 1.18.5
+
+Released 2020-03-19
+
+ * Make the URLs for the cron module work again (#1248).
+ * Email error reports now include metadata again (#1269).
+ * Fix exampleauth module when using the legacy UI (#1275).
+ * Fix authorize module when using custom reject message.
+ * Documentation improvements.
+ * Fix connection persistence for deployments that switched to memcached.
+
## Version 1.18.4
Released 2020-01-24
@@ -50,10 +142,10 @@ Released 2019-11-26
* Fixed an issue with the `ldap` module that prevented installing SimpleSAMLphp from the repository (#1241).
- ## Version 1.18.1
-
+## Version 1.18.1
+
Released 2019-11-26
-
+
* Fixed an issue that prevented custom themes from working (#1240).
* Fixed an issue with translations in the discovery service (#1244).
* Fixed an issue with schema validation.
| 0
|
78d4c5db50fbab0b4beb69c46c6167f2c6513dec
|
https://github.com/ImageMagick/ImageMagick/commit/78d4c5db50fbab0b4beb69c46c6167f2c6513dec
|
https://github.com/ImageMagick/ImageMagick/issues/542
|
diff --git a/coders/png.c b/coders/png.c
index ad00b92f43..2ebb6e9d8f 100644
--- a/coders/png.c
+++ b/coders/png.c
@@ -5871,6 +5871,8 @@ static Image *ReadOneMNGImage(MngInfo* mng_info, const ImageInfo *image_info,
for (i=(ssize_t) first_object; i <= (ssize_t) last_object; i++)
{
+ if ((i < 0) || (i >= MNG_MAX_OBJECTS))
+ continue;
if (mng_info->exists[i] && !mng_info->frozen[i] &&
(p-chunk) < (ssize_t) (length-8))
{
| 1
|
9bacdec6b98f21e88eb0e13669e45be9fc37fa58
|
https://github.com/apache/geronimo/commit/9bacdec6b98f21e88eb0e13669e45be9fc37fa58
|
GERONIMO-6266 The jndi prefix URL could not work before the web application is totally started
git-svn-id: https://svn.apache.org/repos/asf/geronimo/server/trunk@1240958 13f79535-47bb-0310-9956-ffa450edef68
|
diff --git a/plugins/tomcat/geronimo-tomcat7/src/main/java/org/apache/geronimo/tomcat/GeronimoStandardContext.java b/plugins/tomcat/geronimo-tomcat7/src/main/java/org/apache/geronimo/tomcat/GeronimoStandardContext.java
index e49368d7be..68deabbc82 100644
--- a/plugins/tomcat/geronimo-tomcat7/src/main/java/org/apache/geronimo/tomcat/GeronimoStandardContext.java
+++ b/plugins/tomcat/geronimo-tomcat7/src/main/java/org/apache/geronimo/tomcat/GeronimoStandardContext.java
@@ -290,7 +290,7 @@ public void setContextProperties(TomcatContext ctx) throws DeploymentException {
int index = 0;
- BeforeAfter interceptor = new RequestListenerBeforeAfter(null, index++);
+ BeforeAfter interceptor = new RequestListenerBeforeAfter(null, index++, this);
interceptor = new InstanceContextBeforeAfter(interceptor,
index++,
@@ -575,71 +575,8 @@ protected void startInternal() throws LifecycleException {
}
@Override
- public synchronized void setLoader(final Loader delegate) {
- Loader loader = new Loader() {
-
- public void backgroundProcess() {
- delegate.backgroundProcess();
- }
-
- public ClassLoader getClassLoader() {
- // Implementation Note: the actual CL to be used by this
- // context is the Geronimo one and not the Tomcat one.
- return parentClassLoader;
- }
-
- public Container getContainer() {
- return delegate.getContainer();
- }
-
- public void setContainer(Container container) {
- delegate.setContainer(container);
- }
-
- public boolean getDelegate() {
- return delegate.getDelegate();
- }
-
- public void setDelegate(boolean delegateBoolean) {
- delegate.setDelegate(delegateBoolean);
- }
-
- public String getInfo() {
- return delegate.getInfo();
- }
-
- public boolean getReloadable() {
- return false;
- }
-
- public void setReloadable(boolean reloadable) {
- if (reloadable) {
- throw new UnsupportedOperationException("Reloadable context is not supported.");
- }
- }
-
- public void addPropertyChangeListener(PropertyChangeListener listener) {
- delegate.addPropertyChangeListener(listener);
- }
-
- public void addRepository(String repository) {
- delegate.addRepository(repository);
- }
-
- public String[] findRepositories() {
- return delegate.findRepositories();
- }
-
- public boolean modified() {
- return delegate.modified();
- }
-
- public void removePropertyChangeListener(PropertyChangeListener listener) {
- delegate.removePropertyChangeListener(listener);
- }
- };
-
- super.setLoader(loader);
+ public synchronized void setLoader(Loader delegate) {
+ super.setLoader(new GeronimoWebAppLoader(this, delegate));
}
public ServletContext getInternalServletContext() {
diff --git a/plugins/tomcat/geronimo-tomcat7/src/main/java/org/apache/geronimo/tomcat/GeronimoWebAppLoader.java b/plugins/tomcat/geronimo-tomcat7/src/main/java/org/apache/geronimo/tomcat/GeronimoWebAppLoader.java
new file mode 100644
index 0000000000..2581ba409f
--- /dev/null
+++ b/plugins/tomcat/geronimo-tomcat7/src/main/java/org/apache/geronimo/tomcat/GeronimoWebAppLoader.java
@@ -0,0 +1,140 @@
+/**
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements. See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package org.apache.geronimo.tomcat;
+
+import java.beans.PropertyChangeListener;
+
+import javax.naming.directory.DirContext;
+
+import org.apache.catalina.Container;
+import org.apache.catalina.LifecycleException;
+import org.apache.catalina.LifecycleState;
+import org.apache.catalina.Loader;
+import org.apache.catalina.util.LifecycleBase;
+import org.apache.naming.resources.DirContextURLStreamHandler;
+
+/**
+ * @version $Rev$ $Date$
+ */
+public class GeronimoWebAppLoader extends LifecycleBase implements Loader {
+
+ private final Loader delegate;
+
+ private final GeronimoStandardContext standardContext;
+
+ public GeronimoWebAppLoader(GeronimoStandardContext standardContext, Loader delegate) {
+ this.delegate = delegate;
+ this.standardContext = standardContext;
+ }
+
+ @Override
+ public void backgroundProcess() {
+ delegate.backgroundProcess();
+ }
+
+ @Override
+ public ClassLoader getClassLoader() {
+ return standardContext.getParentClassLoader();
+ }
+
+ @Override
+ public Container getContainer() {
+ return delegate.getContainer();
+ }
+
+ @Override
+ public void setContainer(Container container) {
+ delegate.setContainer(container);
+ }
+
+ @Override
+ public boolean getDelegate() {
+ return delegate.getDelegate();
+ }
+
+ @Override
+ public void setDelegate(boolean delegateBoolean) {
+ delegate.setDelegate(delegateBoolean);
+ }
+
+ @Override
+ public String getInfo() {
+ return delegate.getInfo();
+ }
+
+ @Override
+ public boolean getReloadable() {
+ return false;
+ }
+
+ @Override
+ public void setReloadable(boolean reloadable) {
+ if (reloadable) {
+ throw new UnsupportedOperationException("Reloadable context is not supported.");
+ }
+ }
+
+ @Override
+ public void addPropertyChangeListener(PropertyChangeListener listener) {
+ delegate.addPropertyChangeListener(listener);
+ }
+
+ @Override
+ public void addRepository(String repository) {
+ delegate.addRepository(repository);
+ }
+
+ @Override
+ public String[] findRepositories() {
+ return delegate.findRepositories();
+ }
+
+ @Override
+ public boolean modified() {
+ return delegate.modified();
+ }
+
+ @Override
+ public void removePropertyChangeListener(PropertyChangeListener listener) {
+ delegate.removePropertyChangeListener(listener);
+ }
+
+ @Override
+ protected void startInternal() throws LifecycleException {
+ DirContext resources = delegate.getContainer().getResources();
+ if (resources == null) {
+ throw new IllegalStateException("JNDI environment was not set up correctly due to previous error");
+ }
+ DirContextURLStreamHandler.bind(standardContext.getParentClassLoader(), resources);
+ setState(LifecycleState.STARTING);
+ }
+
+ @Override
+ protected void stopInternal() throws LifecycleException {
+ setState(LifecycleState.STOPPING);
+ DirContextURLStreamHandler.unbind(standardContext.getParentClassLoader());
+ }
+
+ @Override
+ protected void destroyInternal() throws LifecycleException {
+ }
+
+ @Override
+ protected void initInternal() throws LifecycleException {
+ }
+}
diff --git a/plugins/tomcat/geronimo-tomcat7/src/main/java/org/apache/geronimo/tomcat/TomcatWebAppContext.java b/plugins/tomcat/geronimo-tomcat7/src/main/java/org/apache/geronimo/tomcat/TomcatWebAppContext.java
index d719e6bf1c..9d132b6afc 100644
--- a/plugins/tomcat/geronimo-tomcat7/src/main/java/org/apache/geronimo/tomcat/TomcatWebAppContext.java
+++ b/plugins/tomcat/geronimo-tomcat7/src/main/java/org/apache/geronimo/tomcat/TomcatWebAppContext.java
@@ -564,12 +564,6 @@ public void doStart() throws Exception {
container.addContext(this);
// Is it necessary - doesn't Tomcat Embedded take care of it?
// super.start();
- //register the classloader <> dir context association so that tomcat's jndi based getResources works.
- DirContext resources = context.getResources();
- if (resources == null) {
- throw new IllegalStateException("JNDI environment was not set up correctly due to previous error");
- }
- DirContextURLStreamHandler.bind(classLoader, resources);
if (context instanceof StandardContext) {
statsProvider = new ModuleStats((StandardContext) context);
}
@@ -584,7 +578,6 @@ public void doStart() throws Exception {
public void doStop() throws Exception {
statsProvider = null;
container.removeContext(this);
- DirContextURLStreamHandler.unbind(classLoader);
log.debug("TomcatWebAppContext stopped");
}
diff --git a/plugins/tomcat/geronimo-tomcat7/src/main/java/org/apache/geronimo/tomcat/interceptor/RequestListenerBeforeAfter.java b/plugins/tomcat/geronimo-tomcat7/src/main/java/org/apache/geronimo/tomcat/interceptor/RequestListenerBeforeAfter.java
index 48c255df4b..a4e768d404 100644
--- a/plugins/tomcat/geronimo-tomcat7/src/main/java/org/apache/geronimo/tomcat/interceptor/RequestListenerBeforeAfter.java
+++ b/plugins/tomcat/geronimo-tomcat7/src/main/java/org/apache/geronimo/tomcat/interceptor/RequestListenerBeforeAfter.java
@@ -24,35 +24,24 @@
public class RequestListenerBeforeAfter implements BeforeAfter{
private final BeforeAfter next;
private final int index;
+ private final GeronimoStandardContext standardContext;
- public RequestListenerBeforeAfter(BeforeAfter next, int index) {
+ public RequestListenerBeforeAfter(BeforeAfter next, int index, GeronimoStandardContext standardContext) {
this.next = next;
this.index = index;
+ this.standardContext = standardContext;
}
public void before(BeforeAfterContext beforeAfterContext, ServletRequest httpRequest, ServletResponse httpResponse, int dispatch) {
-
- if (httpRequest instanceof org.apache.catalina.connector.Request){
-
- org.apache.catalina.connector.Request catalinaRequest = (org.apache.catalina.connector.Request) httpRequest;
-
- if (catalinaRequest.getContext() instanceof GeronimoStandardContext) {
-
- GeronimoStandardContext GeronimoContext = (GeronimoStandardContext) catalinaRequest.getContext();
- GeronimoContext.fireRequestInitEventInBeforeAfter(httpRequest);
- }
-
- }
-
- if (next != null) {
- next.before(beforeAfterContext, httpRequest, httpResponse, dispatch);
- }
+ standardContext.fireRequestInitEventInBeforeAfter(httpRequest);
+ if (next != null) {
+ next.before(beforeAfterContext, httpRequest, httpResponse, dispatch);
+ }
}
- public void after(BeforeAfterContext beforeAfterContext, ServletRequest httpRequest, ServletResponse httpResponse, int dispatch) {
-
+ public void after(BeforeAfterContext beforeAfterContext, ServletRequest httpRequest, ServletResponse httpResponse, int dispatch) {
if (next != null) {
next.after(beforeAfterContext, httpRequest, httpResponse, dispatch);
}
| 0
|
9a28db32cc78a475598af5f861fd4f270c8ffd6f
|
https://github.com/apache/logging-log4j2/commit/9a28db32cc78a475598af5f861fd4f270c8ffd6f
|
LOG4J2-2973 Rename EventTemplateAdditionalField#type (conflicting with properties file parser) to #format. (#462)
|
diff --git a/log4j-layout-template-json/src/main/java/org/apache/logging/log4j/layout/template/json/JsonTemplateLayout.java b/log4j-layout-template-json/src/main/java/org/apache/logging/log4j/layout/template/json/JsonTemplateLayout.java
index 1003599f62..25656bbaff 100644
--- a/log4j-layout-template-json/src/main/java/org/apache/logging/log4j/layout/template/json/JsonTemplateLayout.java
+++ b/log4j-layout-template-json/src/main/java/org/apache/logging/log4j/layout/template/json/JsonTemplateLayout.java
@@ -531,18 +531,18 @@ private void validate() {
printObject = true)
public static final class EventTemplateAdditionalField {
- public enum Type { STRING, JSON }
+ public enum Format { STRING, JSON }
private final String key;
private final String value;
- private final Type type;
+ private final Format format;
private EventTemplateAdditionalField(final Builder builder) {
this.key = builder.key;
this.value = builder.value;
- this.type = builder.type;
+ this.format = builder.format;
}
public String getKey() {
@@ -553,8 +553,8 @@ public String getValue() {
return value;
}
- public Type getType() {
- return type;
+ public Format getFormat() {
+ return format;
}
@Override
@@ -568,17 +568,17 @@ public boolean equals(Object object) {
EventTemplateAdditionalField that = (EventTemplateAdditionalField) object;
return key.equals(that.key) &&
value.equals(that.value) &&
- type == that.type;
+ format == that.format;
}
@Override
public int hashCode() {
- return Objects.hash(key, value, type);
+ return Objects.hash(key, value, format);
}
@Override
public String toString() {
- final String formattedValue = Type.STRING.equals(type)
+ final String formattedValue = Format.STRING.equals(format)
? String.format("\"%s\"", value)
: value;
return String.format("%s=%s", key, formattedValue);
@@ -599,7 +599,7 @@ public String toString() {
private String value;
@PluginBuilderAttribute
- private Type type = Type.STRING;
+ private Format format = Format.STRING;
public Builder setKey(final String key) {
this.key = key;
@@ -611,8 +611,8 @@ public Builder setValue(final String value) {
return this;
}
- public Builder setType(final Type type) {
- this.type = type;
+ public Builder setFormat(final Format format) {
+ this.format = format;
return this;
}
@@ -629,7 +629,7 @@ private void validate() {
if (Strings.isBlank(value)) {
throw new IllegalArgumentException("blank value");
}
- Objects.requireNonNull(type, "type");
+ Objects.requireNonNull(format, "format");
}
}
diff --git a/log4j-layout-template-json/src/main/java/org/apache/logging/log4j/layout/template/json/resolver/TemplateResolvers.java b/log4j-layout-template-json/src/main/java/org/apache/logging/log4j/layout/template/json/resolver/TemplateResolvers.java
index d713edd825..b0cede2908 100644
--- a/log4j-layout-template-json/src/main/java/org/apache/logging/log4j/layout/template/json/resolver/TemplateResolvers.java
+++ b/log4j-layout-template-json/src/main/java/org/apache/logging/log4j/layout/template/json/resolver/TemplateResolvers.java
@@ -129,7 +129,7 @@ private static void appendAdditionalFields(
for (final EventTemplateAdditionalField additionalField : additionalFields) {
final String additionalFieldKey = additionalField.getKey();
final Object additionalFieldValue;
- switch (additionalField.getType()) {
+ switch (additionalField.getFormat()) {
case STRING:
additionalFieldValue = additionalField.getValue();
break;
@@ -145,8 +145,8 @@ private static void appendAdditionalFields(
break;
default: {
final String message = String.format(
- "unknown type %s for additional field: %s",
- additionalFieldKey, additionalField.getType());
+ "unknown format %s for additional field: %s",
+ additionalFieldKey, additionalField.getFormat());
throw new IllegalArgumentException(message);
}
}
diff --git a/log4j-layout-template-json/src/test/java/org/apache/logging/log4j/layout/template/json/JsonTemplateLayoutAdditionalFieldTest.java b/log4j-layout-template-json/src/test/java/org/apache/logging/log4j/layout/template/json/JsonTemplateLayoutAdditionalFieldTestHelper.java
similarity index 54%
rename from log4j-layout-template-json/src/test/java/org/apache/logging/log4j/layout/template/json/JsonTemplateLayoutAdditionalFieldTest.java
rename to log4j-layout-template-json/src/test/java/org/apache/logging/log4j/layout/template/json/JsonTemplateLayoutAdditionalFieldTestHelper.java
index 465bcc6bd5..605cc3a2f0 100644
--- a/log4j-layout-template-json/src/test/java/org/apache/logging/log4j/layout/template/json/JsonTemplateLayoutAdditionalFieldTest.java
+++ b/log4j-layout-template-json/src/test/java/org/apache/logging/log4j/layout/template/json/JsonTemplateLayoutAdditionalFieldTestHelper.java
@@ -1,47 +1,23 @@
-/*
- * Licensed to the Apache Software Foundation (ASF) under one or more
- * contributor license agreements. See the NOTICE file distributed with
- * this work for additional information regarding copyright ownership.
- * The ASF licenses this file to You under the Apache license, Version 2.0
- * (the "License"); you may not use this file except in compliance with
- * the License. You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the license for the specific language governing permissions and
- * limitations under the license.
- */
package org.apache.logging.log4j.layout.template.json;
import org.apache.logging.log4j.Logger;
import org.apache.logging.log4j.core.LoggerContext;
-import org.apache.logging.log4j.junit.LoggerContextSource;
-import org.apache.logging.log4j.junit.Named;
import org.apache.logging.log4j.layout.template.json.util.JsonReader;
import org.apache.logging.log4j.test.appender.ListAppender;
import org.assertj.core.api.Assertions;
-import org.junit.jupiter.api.Test;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;
import java.util.Map;
-@LoggerContextSource("additionalFieldEnrichedJsonTemplateLayoutLogging.xml")
-class JsonTemplateLayoutAdditionalFieldTest {
-
- @Test
- void test_additional_fields_are_resolved(
- final LoggerContext loggerContext,
- @Named("List") final ListAppender appender) {
+class JsonTemplateLayoutAdditionalFieldTestHelper {
+ static void assertAdditionalFields(final LoggerContext loggerContext, ListAppender appender) {
// Log an event.
final Logger logger =
loggerContext.getLogger(
- JsonTemplateLayoutAdditionalFieldTest.class);
+ JsonTemplateLayoutAdditionalFieldTestHelper.class);
logger.info("trigger");
// Verify that the appender has logged the event.
@@ -56,8 +32,7 @@ void test_additional_fields_are_resolved(
JsonTemplateLayoutDefaults.getCharset());
final Object serializedEventObject = JsonReader.read(serializedEventJson);
Assertions.assertThat(serializedEventObject).isInstanceOf(Map.class);
- @SuppressWarnings("unchecked")
- final Map<String, Object> serializedEventMap =
+ @SuppressWarnings("unchecked") final Map<String, Object> serializedEventMap =
(Map<String, Object>) serializedEventObject;
// Verify the serialized additional fields.
@@ -69,5 +44,4 @@ void test_additional_fields_are_resolved(
.containsEntry("listField", Arrays.asList(1, "two"));
}
-
}
diff --git a/log4j-layout-template-json/src/test/java/org/apache/logging/log4j/layout/template/json/JsonTemplateLayoutAdditionalFieldTestProperties.java b/log4j-layout-template-json/src/test/java/org/apache/logging/log4j/layout/template/json/JsonTemplateLayoutAdditionalFieldTestProperties.java
new file mode 100644
index 0000000000..5c3911e805
--- /dev/null
+++ b/log4j-layout-template-json/src/test/java/org/apache/logging/log4j/layout/template/json/JsonTemplateLayoutAdditionalFieldTestProperties.java
@@ -0,0 +1,34 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements. See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache license, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the license for the specific language governing permissions and
+ * limitations under the license.
+ */
+package org.apache.logging.log4j.layout.template.json;
+
+import org.apache.logging.log4j.core.LoggerContext;
+import org.apache.logging.log4j.junit.LoggerContextSource;
+import org.apache.logging.log4j.junit.Named;
+import org.apache.logging.log4j.test.appender.ListAppender;
+import org.junit.jupiter.api.Test;
+
+@LoggerContextSource("additionalFieldEnrichedJsonTemplateLayoutLogging.properties")
+class JsonTemplateLayoutAdditionalFieldTestProperties {
+
+ @Test
+ void test_additional_fields_are_resolved(
+ final LoggerContext loggerContext,
+ final @Named(value = "List") ListAppender appender) {
+ JsonTemplateLayoutAdditionalFieldTestHelper.assertAdditionalFields(loggerContext, appender);
+ }
+}
diff --git a/log4j-layout-template-json/src/test/java/org/apache/logging/log4j/layout/template/json/JsonTemplateLayoutAdditionalFieldTestXML.java b/log4j-layout-template-json/src/test/java/org/apache/logging/log4j/layout/template/json/JsonTemplateLayoutAdditionalFieldTestXML.java
new file mode 100644
index 0000000000..d96da369ae
--- /dev/null
+++ b/log4j-layout-template-json/src/test/java/org/apache/logging/log4j/layout/template/json/JsonTemplateLayoutAdditionalFieldTestXML.java
@@ -0,0 +1,33 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements. See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache license, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the license for the specific language governing permissions and
+ * limitations under the license.
+ */
+package org.apache.logging.log4j.layout.template.json;
+
+import org.apache.logging.log4j.core.LoggerContext;
+import org.apache.logging.log4j.junit.LoggerContextSource;
+import org.apache.logging.log4j.junit.Named;
+import org.apache.logging.log4j.test.appender.ListAppender;
+import org.junit.jupiter.api.Test;
+
+@LoggerContextSource("additionalFieldEnrichedJsonTemplateLayoutLogging.xml")
+class JsonTemplateLayoutAdditionalFieldTestXML {
+ @Test
+ void test_additional_fields_are_resolved(
+ final LoggerContext loggerContext,
+ final @Named(value = "List") ListAppender appender) {
+ JsonTemplateLayoutAdditionalFieldTestHelper.assertAdditionalFields(loggerContext, appender);
+ }
+}
diff --git a/log4j-layout-template-json/src/test/java/org/apache/logging/log4j/layout/template/json/JsonTemplateLayoutAdditionalFieldTestYAML.java b/log4j-layout-template-json/src/test/java/org/apache/logging/log4j/layout/template/json/JsonTemplateLayoutAdditionalFieldTestYAML.java
new file mode 100644
index 0000000000..204ead8f8e
--- /dev/null
+++ b/log4j-layout-template-json/src/test/java/org/apache/logging/log4j/layout/template/json/JsonTemplateLayoutAdditionalFieldTestYAML.java
@@ -0,0 +1,34 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements. See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache license, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the license for the specific language governing permissions and
+ * limitations under the license.
+ */
+package org.apache.logging.log4j.layout.template.json;
+
+import org.apache.logging.log4j.core.LoggerContext;
+import org.apache.logging.log4j.junit.LoggerContextSource;
+import org.apache.logging.log4j.junit.Named;
+import org.apache.logging.log4j.test.appender.ListAppender;
+import org.junit.jupiter.api.Test;
+
+@LoggerContextSource("additionalFieldEnrichedJsonTemplateLayoutLogging.yaml")
+class JsonTemplateLayoutAdditionalFieldTestYAML {
+
+ @Test
+ void test_additional_fields_are_resolved(
+ final LoggerContext loggerContext,
+ final @Named(value = "List") ListAppender appender) {
+ JsonTemplateLayoutAdditionalFieldTestHelper.assertAdditionalFields(loggerContext, appender);
+ }
+}
diff --git a/log4j-layout-template-json/src/test/java/org/apache/logging/log4j/layout/template/json/JsonTemplateLayoutTest.java b/log4j-layout-template-json/src/test/java/org/apache/logging/log4j/layout/template/json/JsonTemplateLayoutTest.java
index 68152ea984..81bead024c 100644
--- a/log4j-layout-template-json/src/test/java/org/apache/logging/log4j/layout/template/json/JsonTemplateLayoutTest.java
+++ b/log4j-layout-template-json/src/test/java/org/apache/logging/log4j/layout/template/json/JsonTemplateLayoutTest.java
@@ -1359,7 +1359,7 @@ void test_event_template_additional_fields() {
.newBuilder()
.setKey("number")
.setValue("1")
- .setType(EventTemplateAdditionalField.Type.JSON)
+ .setFormat(EventTemplateAdditionalField.Format.JSON)
.build(),
EventTemplateAdditionalField
.newBuilder()
@@ -1370,7 +1370,7 @@ void test_event_template_additional_fields() {
.newBuilder()
.setKey("level")
.setValue("{\"$resolver\": \"level\", \"field\": \"name\"}")
- .setType(EventTemplateAdditionalField.Type.JSON)
+ .setFormat(EventTemplateAdditionalField.Format.JSON)
.build()
};
final JsonTemplateLayout layout = JsonTemplateLayout
diff --git a/log4j-layout-template-json/src/test/resources/additionalFieldEnrichedJsonTemplateLayoutLogging.properties b/log4j-layout-template-json/src/test/resources/additionalFieldEnrichedJsonTemplateLayoutLogging.properties
new file mode 100644
index 0000000000..58e65baca3
--- /dev/null
+++ b/log4j-layout-template-json/src/test/resources/additionalFieldEnrichedJsonTemplateLayoutLogging.properties
@@ -0,0 +1,40 @@
+# Licensed to the Apache Software Foundation (ASF) under one or more
+# contributor license agreements. See the NOTICE file distributed with
+# this work for additional information regarding copyright ownership.
+# The ASF licenses this file to You under the Apache License, Version 2.0
+# (the "License"); you may not use this file except in compliance with
+# the License. You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+
+appender.list.name = List
+appender.list.type = List
+appender.list.raw = true
+appender.list.layout.type = JsonTemplateLayout
+appender.list.layout.charset = UTF-8
+appender.list.layout.extra[0].key = stringField
+appender.list.layout.extra[0].value = string
+appender.list.layout.extra[0].type = EventTemplateAdditionalField
+appender.list.layout.extra[0].format = STRING
+appender.list.layout.extra[1].key = numberField
+appender.list.layout.extra[1].value = 1
+appender.list.layout.extra[1].format = JSON
+appender.list.layout.extra[1].type = EventTemplateAdditionalField
+appender.list.layout.extra[2].key = objectField
+appender.list.layout.extra[2].value = {"numberField":1}
+appender.list.layout.extra[2].format = JSON
+appender.list.layout.extra[2].type = EventTemplateAdditionalField
+appender.list.layout.extra[3].key = listField
+appender.list.layout.extra[3].value = [1, "two"]
+appender.list.layout.extra[3].format = JSON
+appender.list.layout.extra[3].type = EventTemplateAdditionalField
+
+rootLogger.level = info
+rootLogger.appenderRef.stdout.ref = List
+
diff --git a/log4j-layout-template-json/src/test/resources/additionalFieldEnrichedJsonTemplateLayoutLogging.xml b/log4j-layout-template-json/src/test/resources/additionalFieldEnrichedJsonTemplateLayoutLogging.xml
index 3449c6dd69..b27bfde58e 100644
--- a/log4j-layout-template-json/src/test/resources/additionalFieldEnrichedJsonTemplateLayoutLogging.xml
+++ b/log4j-layout-template-json/src/test/resources/additionalFieldEnrichedJsonTemplateLayoutLogging.xml
@@ -20,9 +20,9 @@
<List name="List" raw="true">
<JsonTemplateLayout>
<EventTemplateAdditionalField key="stringField" value="string"/>
- <EventTemplateAdditionalField key="numberField" value="1" type="JSON"/>
- <EventTemplateAdditionalField key="objectField" value='{"numberField":1}' type="JSON"/>
- <EventTemplateAdditionalField key="listField" value='[1, "two"]' type="JSON"/>
+ <EventTemplateAdditionalField key="numberField" value="1" format="JSON"/>
+ <EventTemplateAdditionalField key="objectField" value='{"numberField":1}' format="JSON"/>
+ <EventTemplateAdditionalField key="listField" value='[1, "two"]' format="JSON"/>
</JsonTemplateLayout>
</List>
</Appenders>
diff --git a/log4j-layout-template-json/src/test/resources/additionalFieldEnrichedJsonTemplateLayoutLogging.yaml b/log4j-layout-template-json/src/test/resources/additionalFieldEnrichedJsonTemplateLayoutLogging.yaml
new file mode 100644
index 0000000000..676b3cebc9
--- /dev/null
+++ b/log4j-layout-template-json/src/test/resources/additionalFieldEnrichedJsonTemplateLayoutLogging.yaml
@@ -0,0 +1,39 @@
+# Licensed to the Apache Software Foundation (ASF) under one or more
+# contributor license agreements. See the NOTICE file distributed with
+# this work for additional information regarding copyright ownership.
+# The ASF licenses this file to You under the Apache License, Version 2.0
+# (the "License"); you may not use this file except in compliance with
+# the License. You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+
+Configuration:
+ status: OFF
+ appenders:
+ List:
+ name: "List"
+ raw: "true"
+ JsonTemplateLayout:
+ EventTemplateadditionalField:
+ - key: "stringField"
+ value: "string"
+ - key: "numberField"
+ value: "1"
+ format: "JSON"
+ - key: "objectField"
+ value: '{"numberField":1}'
+ format: "JSON"
+ - key: "listField"
+ value: '[1, "two"]'
+ format: "JSON"
+ loggers:
+ root:
+ level: "trace"
+ AppenderRef:
+ ref: List
diff --git a/src/changes/changes.xml b/src/changes/changes.xml
index 3883f3913e..2b33676dd5 100644
--- a/src/changes/changes.xml
+++ b/src/changes/changes.xml
@@ -31,6 +31,9 @@
- "remove" - Removed
-->
<release version="3.0.0" date="2021-MM-DD" description="GA Release 3.0.0">
+ <action issue="LOG4J2-2973" dev="fricchiuti" typ="fix">
+ Rename EventTemplateAdditionalField#type (conflicting with properties file parser) to "format"
+ </action>
<action issue="LOG4J2-2999" dev="vy" type="add">
Replace JsonTemplateLayout resolver configurations table in docs with sections.
</action>
diff --git a/src/site/asciidoc/manual/json-template-layout.adoc.vm b/src/site/asciidoc/manual/json-template-layout.vm.adoc
similarity index 97%
rename from src/site/asciidoc/manual/json-template-layout.adoc.vm
rename to src/site/asciidoc/manual/json-template-layout.vm.adoc
index fdc6534ebf..d3f700c434 100644
--- a/src/site/asciidoc/manual/json-template-layout.adoc.vm
+++ b/src/site/asciidoc/manual/json-template-layout.vm.adoc
@@ -256,25 +256,43 @@ custom fields:
</JsonTemplateLayout>
----
-The default `type` for the added new fields are `String`.
+The default `format` for the added new fields are `String`.
One can also pass JSON literals into additional fields:
[source,xml]
----
<EventTemplateAdditionalField
key="marker"
- type="JSON"
+ format="JSON"
value='{"$resolver": "marker", "field": "name"}'/>
<EventTemplateAdditionalField
key="aNumber"
- type="JSON"
+ format="JSON"
value="1"/>
<EventTemplateAdditionalField
key="aList"
- type="JSON"
+ format="JSON"
value='[1,2,"string"]'/>
----
+When using a configuration file with a `.properties` extension, additional fields can be added as follows:
+
+[source, properties]
+----
+appender.console.layout.extra[0].key = marker
+appender.console.layout.extra[0].value = {"$resolver": "marker", "field": "name"}
+appender.console.layout.extra[0].format = JSON
+appender.console.layout.extra[0].type = EventTemplateAdditionalField
+appender.console.layout.extra[1].key = aNumber
+appender.console.layout.extra[1].value = 1
+appender.console.layout.extra[1].format = JSON
+appender.console.layout.extra[1].type = EventTemplateAdditionalField
+appender.console.layout.extra[2].key = aList
+appender.console.layout.extra[2].value = [1,2,"string"]
+appender.console.layout.extra[2].format = JSON
+appender.console.layout.extra[2].type = EventTemplateAdditionalField
+----
+
[#recycling-strategy]
=== Recycling strategy
| 0
|
f0950197d33c50a35619db94434211ec770b737a
|
https://github.com/bmizerany/sinatra/commit/f0950197d33c50a35619db94434211ec770b737a
|
Update README links to Haml
The Haml site has moved to http://haml.info.
|
diff --git a/README.de.rdoc b/README.de.rdoc
index 0bbb949398..f708338740 100644
--- a/README.de.rdoc
+++ b/README.de.rdoc
@@ -360,7 +360,7 @@ Beginn ein 'require':
=== Haml Templates
-Abhängigkeit:: {haml}[http://haml-lang.com/]
+Abhängigkeit:: {haml}[http://haml.info/]
Dateierweiterungs:: <tt>.haml</tt>
Beispiel:: <tt>haml :index, :format => :html5</tt>
diff --git a/README.es.rdoc b/README.es.rdoc
index d4b9bcb4d6..082f2342c8 100644
--- a/README.es.rdoc
+++ b/README.es.rdoc
@@ -357,7 +357,7 @@ usarla:
=== Plantillas Haml
-Dependencias:: {haml}[http://haml-lang.com/]
+Dependencias:: {haml}[http://haml.info/]
Extensiones de Archivo:: <tt>.haml</tt>
Ejemplo:: <tt>haml :index, :format => :html5</tt>
diff --git a/README.fr.rdoc b/README.fr.rdoc
index e4584cf022..dddcaa9bfb 100644
--- a/README.fr.rdoc
+++ b/README.fr.rdoc
@@ -363,7 +363,7 @@ chargée au préalable :
=== Templates Haml
-Dépendances:: {haml}[http://haml-lang.com/]
+Dépendances:: {haml}[http://haml.info/]
Extensions de fichier:: <tt>.haml</tt>
Exemple:: <tt>haml :index, :format => :html5</tt>
diff --git a/README.jp.rdoc b/README.jp.rdoc
index 1765bb977e..3a737548ca 100644
--- a/README.jp.rdoc
+++ b/README.jp.rdoc
@@ -184,7 +184,7 @@ hamlを使うにはhamlライブラリが必要です:
<tt>./views/index.haml</tt>を表示します。
-{Haml's options}[http://haml-lang.com/docs/yardoc/file.HAML_REFERENCE.html#options]
+{Haml's options}[http://haml.info/docs/yardoc/file.HAML_REFERENCE.html#options]
はSinatraの設定でグローバルに設定することができます。
{Options and Configurations}[http://www.sinatrarb.com/configuration.html],
を参照してそれぞれ設定を上書きして下さい。
diff --git a/README.ko.rdoc b/README.ko.rdoc
index 1f77b5544c..6705e37270 100644
--- a/README.ko.rdoc
+++ b/README.ko.rdoc
@@ -323,7 +323,7 @@ render 메서드에서 전달된 옵션값들은 +set+을 통해 설정한 옵
=== Haml 템플릿
-의존:: {haml}[http://haml-lang.com/]
+의존:: {haml}[http://haml.info/]
파일 확장자:: <tt>.haml</tt>
예:: <tt>haml :index, :format => :html5</tt>
diff --git a/README.pt-br.rdoc b/README.pt-br.rdoc
index 6b3ba2e100..2212895646 100644
--- a/README.pt-br.rdoc
+++ b/README.pt-br.rdoc
@@ -128,7 +128,7 @@ A gem/biblioteca haml é necessária para renderizar templates HAML:
Renderiza <tt>./views/index.haml</tt>.
-{Opções Haml}[http://haml-lang.com/docs/yardoc/file.HAML_REFERENCE.html#options]
+{Opções Haml}[http://haml.info/docs/yardoc/file.HAML_REFERENCE.html#options]
podem ser setadas globalmente através das configurações do sinatra,
veja {Opções e Configurações}[http://www.sinatrarb.com/configuration.html],
e substitua em uma requisição individual.
diff --git a/README.pt-pt.rdoc b/README.pt-pt.rdoc
index 5b1908274a..64e1b70121 100644
--- a/README.pt-pt.rdoc
+++ b/README.pt-pt.rdoc
@@ -128,7 +128,7 @@ A gem/biblioteca haml é necessária para renderizar templates HAML:
Renderiza <tt>./views/index.haml</tt>.
-{Opções Haml}[http://haml-lang.com/docs/yardoc/file.HAML_REFERENCE.html#options]
+{Opções Haml}[http://haml.info/docs/yardoc/file.HAML_REFERENCE.html#options]
podem ser definidas globalmente através das configurações do sinatra,
veja {Opções e Configurações}[http://www.sinatrarb.com/configuration.html],
e substitua em uma requisição individual.
diff --git a/README.rdoc b/README.rdoc
index b61ade274c..1acb1f6d4b 100644
--- a/README.rdoc
+++ b/README.rdoc
@@ -344,7 +344,7 @@ to use (and to be thread-safe), you should simply require it first:
=== Haml Templates
-Dependency:: {haml}[http://haml-lang.com/]
+Dependency:: {haml}[http://haml.info/]
File Extensions:: <tt>.haml</tt>
Example:: <tt>haml :index, :format => :html5</tt>
diff --git a/README.ru.rdoc b/README.ru.rdoc
index 6a64f43de8..aa0eb0de3e 100644
--- a/README.ru.rdoc
+++ b/README.ru.rdoc
@@ -352,7 +352,7 @@ Thin — это более производительный и функцион
=== Haml шаблоны
-Зависимости:: {haml}[http://haml-lang.com/]
+Зависимости:: {haml}[http://haml.info/]
Расширения файлов:: <tt>.haml</tt>
Пример:: <tt>haml :index, :format => :html5</tt>
diff --git a/README.zh.rdoc b/README.zh.rdoc
index 4b6fc37385..f6fe6bed72 100644
--- a/README.zh.rdoc
+++ b/README.zh.rdoc
@@ -229,7 +229,7 @@ Rack body对象或者HTTP状态码:
渲染 <tt>./views/index.haml</tt>。
-{Haml的选项}[http://haml-lang.com/docs/yardoc/file.HAML_REFERENCE.html#options]
+{Haml的选项}[http://haml.info/docs/yardoc/file.HAML_REFERENCE.html#options]
可以通过Sinatra的配置全局设定,
参见 {选项和配置}[http://www.sinatrarb.com/configuration.html],
也可以个别的被覆盖。
| 0
|
2fc9d03ffbc3fe7eabfd272380807ac0ddcf748d
|
https://github.com/apache/tomcat80/commit/2fc9d03ffbc3fe7eabfd272380807ac0ddcf748d
|
Fix Javadoc
Separate test cases into separate test methods and add some additional tests.
Clean up the code and fix a couple of edge cases
git-svn-id: https://svn.apache.org/repos/asf/tomcat/tc8.0.x/trunk@1696281 13f79535-47bb-0310-9956-ffa450edef68
|
diff --git a/java/org/apache/tomcat/util/http/RequestUtil.java b/java/org/apache/tomcat/util/http/RequestUtil.java
index ebe4f34c8..32fece87f 100644
--- a/java/org/apache/tomcat/util/http/RequestUtil.java
+++ b/java/org/apache/tomcat/util/http/RequestUtil.java
@@ -30,6 +30,9 @@ private RequestUtil() {
* try to perform security checks for malicious input.
*
* @param path Relative path to be normalized
+ *
+ * @return The normalized path or <code>null</code> of the path cannot be
+ * normalized
*/
public static String normalize(String path) {
return normalize(path, true);
@@ -44,11 +47,15 @@ public static String normalize(String path) {
*
* @param path Relative path to be normalized
* @param replaceBackSlash Should '\\' be replaced with '/'
+ *
+ * @return The normalized path or <code>null</code> of the path cannot be
+ * normalized
*/
public static String normalize(String path, boolean replaceBackSlash) {
- if (path == null)
+ if (path == null) {
return null;
+ }
// Create a place for the normalized path
String normalized = path;
@@ -56,44 +63,50 @@ public static String normalize(String path, boolean replaceBackSlash) {
if (replaceBackSlash && normalized.indexOf('\\') >= 0)
normalized = normalized.replace('\\', '/');
- if (normalized.equals("/."))
- return "/";
-
// Add a leading "/" if necessary
if (!normalized.startsWith("/"))
normalized = "/" + normalized;
+ if (normalized.equals("/.")) {
+ return "/";
+ }
+
+ if (normalized.equals("/..")) {
+ return null; // Trying to go outside our context
+ }
+
// Resolve occurrences of "//" in the normalized path
while (true) {
int index = normalized.indexOf("//");
- if (index < 0)
+ if (index < 0) {
break;
- normalized = normalized.substring(0, index) +
- normalized.substring(index + 1);
+ }
+ normalized = normalized.substring(0, index) + normalized.substring(index + 1);
}
// Resolve occurrences of "/./" in the normalized path
while (true) {
int index = normalized.indexOf("/./");
- if (index < 0)
+ if (index < 0) {
break;
- normalized = normalized.substring(0, index) +
- normalized.substring(index + 2);
+ }
+ normalized = normalized.substring(0, index) + normalized.substring(index + 2);
}
// Resolve occurrences of "/../" in the normalized path
while (true) {
int index = normalized.indexOf("/../");
- if (index < 0)
+ if (index < 0) {
break;
- if (index == 0)
- return (null); // Trying to go outside our context
+ }
+ if (index == 0) {
+ return null; // Trying to go outside our context
+ }
int index2 = normalized.lastIndexOf('/', index - 1);
- normalized = normalized.substring(0, index2) +
- normalized.substring(index + 3);
+ normalized = normalized.substring(0, index2) + normalized.substring(index + 3);
}
// Return the normalized path that we have completed
- return (normalized);
+ return normalized;
}
}
diff --git a/test/org/apache/tomcat/util/http/TestRequestUtil.java b/test/org/apache/tomcat/util/http/TestRequestUtil.java
index fe3115fe2..410773cd4 100644
--- a/test/org/apache/tomcat/util/http/TestRequestUtil.java
+++ b/test/org/apache/tomcat/util/http/TestRequestUtil.java
@@ -23,11 +23,71 @@
public class TestRequestUtil {
@Test
- public void testNormalizeString() {
- assertEquals("/something",RequestUtil.normalize("//something"));
- assertEquals("/some/thing",RequestUtil.normalize("some//thing"));
- assertEquals("/something/",RequestUtil.normalize("something//"));
- assertEquals("/",RequestUtil.normalize("//"));
+ public void testNormalize01() {
+ doTestNormalize("//something", "/something");
}
+ @Test
+ public void testNormalize02() {
+ doTestNormalize("some//thing", "/some/thing");
+ }
+
+ @Test
+ public void testNormalize03() {
+ doTestNormalize("something//", "/something/");
+ }
+
+ @Test
+ public void testNormalize04() {
+ doTestNormalize("//", "/");
+ }
+
+ @Test
+ public void testNormalize05() {
+ doTestNormalize("//", "/");
+ }
+
+ @Test
+ public void testNormalize06() {
+ doTestNormalize("///", "/");
+ }
+
+ @Test
+ public void testNormalize07() {
+ doTestNormalize("////", "/");
+ }
+
+ @Test
+ public void testNormalize08() {
+ doTestNormalize("/.", "/");
+ }
+
+ @Test
+ public void testNormalize09() {
+ doTestNormalize("/./", "/");
+ }
+
+ @Test
+ public void testNormalize10() {
+ doTestNormalize(".", "/");
+ }
+
+ @Test
+ public void testNormalize11() {
+ doTestNormalize("/..", null);
+ }
+
+ @Test
+ public void testNormalize12() {
+ doTestNormalize("/../", null);
+ }
+
+ @Test
+ public void testNormalize13() {
+ doTestNormalize("..", null);
+ }
+
+ private void doTestNormalize(String input, String expected) {
+ assertEquals(expected,RequestUtil.normalize(input));
+ }
}
diff --git a/webapps/docs/changelog.xml b/webapps/docs/changelog.xml
index 8aef57359..d2f2fafc7 100644
--- a/webapps/docs/changelog.xml
+++ b/webapps/docs/changelog.xml
@@ -164,6 +164,10 @@
with multiple attempts to process the same event for the same socket.
(markt)
</fix>
+ <fix>
+ Correct a coupe of edge cases in <code>RequestUtil.normalize()</code>.
+ (markt)
+ </fix>
</changelog>
</subsection>
<subsection name="Jasper">
| 1
|
ee4aad1e1f043d8d519eabcd13964ccc42a4b029
|
https://github.com/lxc/lxc/commit/ee4aad1e1f043d8d519eabcd13964ccc42a4b029
|
Merge pull request #3639 from brauner/2021-01-28/fixes
cgroups: fixes and improvements
|
diff --git a/src/lxc/attach.c b/src/lxc/attach.c
index 8a42e6ce4e..ed0f08e404 100644
--- a/src/lxc/attach.c
+++ b/src/lxc/attach.c
@@ -476,7 +476,7 @@ static int lxc_attach_set_environment(struct attach_context *ctx,
return log_warn(-1, "Failed to set environment variable");
/* Set container environment variables.*/
- if (ctx && ctx->container && ctx->container->lxc_conf) {
+ if (ctx->container->lxc_conf) {
lxc_list_for_each(iterator, &ctx->container->lxc_conf->environment) {
char *env_tmp;
@@ -929,8 +929,7 @@ __noreturn static void do_attach(struct attach_payload *ap)
TRACE("Set %s LSM label to \"%s\"", ctx->lsm_ops->name, ctx->lsm_label);
}
- if ((ctx->container && conf && conf->no_new_privs) ||
- (options->attach_flags & LXC_ATTACH_NO_NEW_PRIVS)) {
+ if (conf->no_new_privs || (options->attach_flags & LXC_ATTACH_NO_NEW_PRIVS)) {
ret = prctl(PR_SET_NO_NEW_PRIVS, prctl_arg(1), prctl_arg(0),
prctl_arg(0), prctl_arg(0));
if (ret < 0)
@@ -939,7 +938,7 @@ __noreturn static void do_attach(struct attach_payload *ap)
TRACE("Set PR_SET_NO_NEW_PRIVS");
}
- if (ctx->container && conf && conf->seccomp.seccomp) {
+ if (conf->seccomp.seccomp) {
ret = lxc_seccomp_load(conf);
if (ret < 0)
goto on_error;
diff --git a/src/lxc/cgroups/cgfsng.c b/src/lxc/cgroups/cgfsng.c
index 4e8512360b..8872163d5c 100644
--- a/src/lxc/cgroups/cgfsng.c
+++ b/src/lxc/cgroups/cgfsng.c
@@ -695,6 +695,8 @@ static struct hierarchy *add_hierarchy(struct hierarchy ***h, char **clist, char
int newentry;
new = zalloc(sizeof(*new));
+ if (!new)
+ return ret_set_errno(NULL, ENOMEM);
new->controllers = clist;
new->mountpoint = mountpoint;
new->container_base_path = container_base_path;
@@ -2662,8 +2664,8 @@ __cgfsng_ops static int cgfsng_set(struct cgroup_ops *ops,
struct hierarchy *h;
int ret = -1;
- if (!ops)
- return ret_set_errno(-1, ENOENT);
+ if (!ops || !key || !value || !name || !lxcpath)
+ return ret_errno(ENOENT);
controller = must_copy_string(key);
p = strchr(controller, '.');
@@ -2963,12 +2965,12 @@ __cgfsng_ops static bool cgfsng_setup_limits(struct cgroup_ops *ops,
__cgfsng_ops static bool cgfsng_devices_activate(struct cgroup_ops *ops, struct lxc_handler *handler)
{
#ifdef HAVE_STRUCT_BPF_CGROUP_DEV_CTX
- __do_bpf_program_free struct bpf_program *devices = NULL;
+ __do_bpf_program_free struct bpf_program *prog = NULL;
int ret;
struct lxc_conf *conf;
struct hierarchy *unified;
struct lxc_list *it;
- struct bpf_program *devices_old;
+ struct bpf_program *prog_old;
if (!ops)
return ret_set_errno(false, ENOENT);
@@ -2988,18 +2990,18 @@ __cgfsng_ops static bool cgfsng_devices_activate(struct cgroup_ops *ops, struct
!unified->container_full_path || lxc_list_empty(&conf->devices))
return true;
- devices = bpf_program_new(BPF_PROG_TYPE_CGROUP_DEVICE);
- if (!devices)
+ prog = bpf_program_new(BPF_PROG_TYPE_CGROUP_DEVICE);
+ if (!prog)
return log_error_errno(false, ENOMEM, "Failed to create new bpf program");
- ret = bpf_program_init(devices);
+ ret = bpf_program_init(prog);
if (ret)
return log_error_errno(false, ENOMEM, "Failed to initialize bpf program");
lxc_list_for_each(it, &conf->devices) {
struct device_item *cur = it->elem;
- ret = bpf_program_append_device(devices, cur);
+ ret = bpf_program_append_device(prog, cur);
if (ret)
return log_error_errno(false, ENOMEM, "Failed to add new rule to bpf device program: type %c, major %d, minor %d, access %s, allow %d, global_rule %d",
cur->type,
@@ -3017,20 +3019,20 @@ __cgfsng_ops static bool cgfsng_devices_activate(struct cgroup_ops *ops, struct
cur->global_rule);
}
- ret = bpf_program_finalize(devices);
+ ret = bpf_program_finalize(prog);
if (ret)
return log_error_errno(false, ENOMEM, "Failed to finalize bpf program");
- ret = bpf_program_cgroup_attach(devices, BPF_CGROUP_DEVICE,
+ ret = bpf_program_cgroup_attach(prog, BPF_CGROUP_DEVICE,
unified->container_limit_path,
BPF_F_ALLOW_MULTI);
if (ret)
return log_error_errno(false, ENOMEM, "Failed to attach bpf program");
/* Replace old bpf program. */
- devices_old = move_ptr(ops->cgroup2_devices);
- ops->cgroup2_devices = move_ptr(devices);
- devices = move_ptr(devices_old);
+ prog_old = move_ptr(ops->cgroup2_devices);
+ ops->cgroup2_devices = move_ptr(prog);
+ prog = move_ptr(prog_old);
#endif
return true;
}
@@ -3283,6 +3285,8 @@ static int cg_hybrid_init(struct cgroup_ops *ops, bool relative, bool unprivileg
}
new = add_hierarchy(&ops->hierarchies, move_ptr(controller_list), move_ptr(mountpoint), move_ptr(base_cgroup), type);
+ if (!new)
+ return log_error_errno(-1, errno, "Failed to add cgroup hierarchy");
if (type == CGROUP2_SUPER_MAGIC && !ops->unified) {
if (unprivileged)
cg_unified_delegate(&new->cgroup2_chown);
@@ -3333,9 +3337,9 @@ static int cg_unified_init(struct cgroup_ops *ops, bool relative,
{
__do_close int cgroup_root_fd = -EBADF;
__do_free char *base_cgroup = NULL, *controllers_path = NULL;
+ __do_free_string_list char **delegatable;
+ __do_free struct hierarchy *new = NULL;
int ret;
- char **delegatable;
- struct hierarchy *new;
ret = unified_cgroup_hierarchy();
if (ret == -ENOMEDIUM)
@@ -3375,10 +3379,13 @@ static int cg_unified_init(struct cgroup_ops *ops, bool relative,
*/
new = add_hierarchy(&ops->hierarchies,
- delegatable,
+ move_ptr(delegatable),
must_copy_string(DEFAULT_CGROUP_MOUNTPOINT),
move_ptr(base_cgroup),
CGROUP2_SUPER_MAGIC);
+ if (!new)
+ return log_error_errno(-1, errno, "Failed to add unified cgroup hierarchy");
+
if (unprivileged)
cg_unified_delegate(&new->cgroup2_chown);
@@ -3386,7 +3393,7 @@ static int cg_unified_init(struct cgroup_ops *ops, bool relative,
new->bpf_device_controller = 1;
ops->cgroup_layout = CGROUP_LAYOUT_UNIFIED;
- ops->unified = new;
+ ops->unified = move_ptr(new);
return CGROUP2_SUPER_MAGIC;
}
@@ -3438,11 +3445,10 @@ struct cgroup_ops *cgfsng_ops_init(struct lxc_conf *conf)
{
__do_free struct cgroup_ops *cgfsng_ops = NULL;
- cgfsng_ops = malloc(sizeof(struct cgroup_ops));
+ cgfsng_ops = zalloc(sizeof(struct cgroup_ops));
if (!cgfsng_ops)
return ret_set_errno(NULL, ENOMEM);
- memset(cgfsng_ops, 0, sizeof(struct cgroup_ops));
cgfsng_ops->cgroup_layout = CGROUP_LAYOUT_UNKNOWN;
if (cg_init(cgfsng_ops, conf))
diff --git a/src/lxc/cgroups/cgroup2_devices.c b/src/lxc/cgroups/cgroup2_devices.c
index 54d333c3f6..faee4cc535 100644
--- a/src/lxc/cgroups/cgroup2_devices.c
+++ b/src/lxc/cgroups/cgroup2_devices.c
@@ -27,6 +27,7 @@
lxc_log_define(cgroup2_devices, cgroup);
+#define BPF_LOG_BUF_SIZE (1 << 23) /* 8MB */
#ifndef BPF_LOG_LEVEL1
#define BPF_LOG_LEVEL1 1
#endif
@@ -52,8 +53,9 @@ static int bpf_program_add_instructions(struct bpf_program *prog,
new_insn = realloc(prog->instructions, sizeof(struct bpf_insn) * (count + prog->n_instructions));
if (!new_insn)
return log_error_errno(-1, ENOMEM, "Failed to reallocate bpf cgroup program");
-
prog->instructions = new_insn;
+ memset(prog->instructions + prog->n_instructions, 0,
+ sizeof(struct bpf_insn) * count);
memcpy(prog->instructions + prog->n_instructions, instructions,
sizeof(struct bpf_insn) * count);
prog->n_instructions += count;
@@ -179,7 +181,7 @@ struct bpf_program *bpf_program_new(uint32_t prog_type)
prog = zalloc(sizeof(struct bpf_program));
if (!prog)
- return NULL;
+ return ret_set_errno(NULL, ENOMEM);
prog->prog_type = prog_type;
prog->kernel_fd = -EBADF;
@@ -194,19 +196,19 @@ struct bpf_program *bpf_program_new(uint32_t prog_type)
int bpf_program_init(struct bpf_program *prog)
{
const struct bpf_insn pre_insn[] = {
- /* load device type to r2 */
- BPF_LDX_MEM(BPF_W, BPF_REG_2, BPF_REG_1, offsetof(struct bpf_cgroup_dev_ctx, access_type)),
- BPF_ALU32_IMM(BPF_AND, BPF_REG_2, 0xFFFF),
+ /* load device type to r2 */
+ BPF_LDX_MEM(BPF_W, BPF_REG_2, BPF_REG_1, offsetof(struct bpf_cgroup_dev_ctx, access_type)),
+ BPF_ALU32_IMM(BPF_AND, BPF_REG_2, 0xFFFF),
- /* load access type to r3 */
- BPF_LDX_MEM(BPF_W, BPF_REG_3, BPF_REG_1, offsetof(struct bpf_cgroup_dev_ctx, access_type)),
- BPF_ALU32_IMM(BPF_RSH, BPF_REG_3, 16),
+ /* load access type to r3 */
+ BPF_LDX_MEM(BPF_W, BPF_REG_3, BPF_REG_1, offsetof(struct bpf_cgroup_dev_ctx, access_type)),
+ BPF_ALU32_IMM(BPF_RSH, BPF_REG_3, 16),
- /* load major number to r4 */
- BPF_LDX_MEM(BPF_W, BPF_REG_4, BPF_REG_1, offsetof(struct bpf_cgroup_dev_ctx, major)),
+ /* load major number to r4 */
+ BPF_LDX_MEM(BPF_W, BPF_REG_4, BPF_REG_1, offsetof(struct bpf_cgroup_dev_ctx, major)),
- /* load minor number to r5 */
- BPF_LDX_MEM(BPF_W, BPF_REG_5, BPF_REG_1, offsetof(struct bpf_cgroup_dev_ctx, minor)),
+ /* load minor number to r5 */
+ BPF_LDX_MEM(BPF_W, BPF_REG_5, BPF_REG_1, offsetof(struct bpf_cgroup_dev_ctx, minor)),
};
if (!prog)
@@ -245,17 +247,17 @@ int bpf_program_append_device(struct bpf_program *prog, struct device_item *devi
if (device_type > 0)
jump_nr++;
- if (device->major != -1)
+ if (device->major >= 0)
jump_nr++;
- if (device->minor != -1)
+ if (device->minor >= 0)
jump_nr++;
if (!bpf_device_all_access(access_mask)) {
struct bpf_insn ins[] = {
- BPF_MOV32_REG(BPF_REG_1, BPF_REG_3),
- BPF_ALU32_IMM(BPF_AND, BPF_REG_1, access_mask),
- BPF_JMP_REG(BPF_JNE, BPF_REG_1, BPF_REG_3, jump_nr--),
+ BPF_MOV32_REG(BPF_REG_1, BPF_REG_3),
+ BPF_ALU32_IMM(BPF_AND, BPF_REG_1, access_mask),
+ BPF_JMP_REG(BPF_JNE, BPF_REG_1, BPF_REG_3, jump_nr--),
};
ret = bpf_program_add_instructions(prog, ins, ARRAY_SIZE(ins));
@@ -265,7 +267,7 @@ int bpf_program_append_device(struct bpf_program *prog, struct device_item *devi
if (device_type > 0) {
struct bpf_insn ins[] = {
- BPF_JMP_IMM(BPF_JNE, BPF_REG_2, device_type, jump_nr--),
+ BPF_JMP_IMM(BPF_JNE, BPF_REG_2, device_type, jump_nr--),
};
ret = bpf_program_add_instructions(prog, ins, ARRAY_SIZE(ins));
@@ -275,7 +277,7 @@ int bpf_program_append_device(struct bpf_program *prog, struct device_item *devi
if (device->major >= 0) {
struct bpf_insn ins[] = {
- BPF_JMP_IMM(BPF_JNE, BPF_REG_4, device->major, jump_nr--),
+ BPF_JMP_IMM(BPF_JNE, BPF_REG_4, device->major, jump_nr--),
};
ret = bpf_program_add_instructions(prog, ins, ARRAY_SIZE(ins));
@@ -285,7 +287,7 @@ int bpf_program_append_device(struct bpf_program *prog, struct device_item *devi
if (device->minor >= 0) {
struct bpf_insn ins[] = {
- BPF_JMP_IMM(BPF_JNE, BPF_REG_5, device->minor, jump_nr--),
+ BPF_JMP_IMM(BPF_JNE, BPF_REG_5, device->minor, jump_nr--),
};
ret = bpf_program_add_instructions(prog, ins, ARRAY_SIZE(ins));
@@ -320,30 +322,36 @@ int bpf_program_finalize(struct bpf_program *prog)
return bpf_program_add_instructions(prog, ins, ARRAY_SIZE(ins));
}
-static int bpf_program_load_kernel(struct bpf_program *prog, char *log_buf,
- __u32 log_size, __u32 log_level)
+static int bpf_program_load_kernel(struct bpf_program *prog)
{
- union bpf_attr attr;
+ __do_free char *log_buf = NULL;
+ __u32 log_level = 0, log_size = 0;
+ union bpf_attr *attr;
- if ((log_size != 0 && !log_buf) || (log_size == 0 && log_buf))
- return ret_errno(EINVAL);
-
- if (prog->kernel_fd >= 0) {
- memset(log_buf, 0, log_size);
+ if (prog->kernel_fd >= 0)
return 0;
+
+ if (lxc_log_trace()) {
+ log_buf = zalloc(BPF_LOG_BUF_SIZE);
+ if (!log_buf) {
+ WARN("Failed to allocate bpf log buffer");
+ } else {
+ log_level = BPF_LOG_LEVEL;
+ log_size = BPF_LOG_BUF_SIZE;
+ }
}
- attr = (union bpf_attr){
+ attr = &(union bpf_attr){
.prog_type = prog->prog_type,
- .insns = PTR_TO_UINT64(prog->instructions),
+ .insns = PTR_TO_U64(prog->instructions),
.insn_cnt = prog->n_instructions,
- .license = PTR_TO_UINT64("GPL"),
- .log_buf = PTR_TO_UINT64(log_buf),
+ .license = PTR_TO_U64("GPL"),
+ .log_buf = PTR_TO_U64(log_buf),
.log_level = log_level,
.log_size = log_size,
};
- prog->kernel_fd = bpf(BPF_PROG_LOAD, &attr, sizeof(attr));
+ prog->kernel_fd = bpf(BPF_PROG_LOAD, attr, sizeof(*attr));
if (prog->kernel_fd < 0)
return log_error_errno(-1, errno, "Failed to load bpf program: %s",
log_buf ?: "(null)");
@@ -357,7 +365,7 @@ int bpf_program_cgroup_attach(struct bpf_program *prog, int type,
{
__do_close int fd = -EBADF;
__do_free char *copy = NULL;
- union bpf_attr attr;
+ union bpf_attr *attr;
int ret;
if (!path || !prog)
@@ -377,7 +385,7 @@ int bpf_program_cgroup_attach(struct bpf_program *prog, int type,
return true;
}
- ret = bpf_program_load_kernel(prog, NULL, 0, 0);
+ ret = bpf_program_load_kernel(prog);
if (ret < 0)
return log_error_errno(-1, ret, "Failed to load bpf program");
@@ -389,14 +397,14 @@ int bpf_program_cgroup_attach(struct bpf_program *prog, int type,
if (fd < 0)
return log_error_errno(-1, errno, "Failed to open cgroup path %s", path);
- attr = (union bpf_attr){
- .attach_type = type,
- .target_fd = fd,
- .attach_bpf_fd = prog->kernel_fd,
- .attach_flags = flags,
+ attr = &(union bpf_attr){
+ .attach_type = type,
+ .target_fd = fd,
+ .attach_bpf_fd = prog->kernel_fd,
+ .attach_flags = flags,
};
- ret = bpf(BPF_PROG_ATTACH, &attr, sizeof(attr));
+ ret = bpf(BPF_PROG_ATTACH, attr, sizeof(*attr));
if (ret < 0)
return log_error_errno(-1, errno, "Failed to attach bpf program");
@@ -425,15 +433,15 @@ int bpf_program_cgroup_detach(struct bpf_program *prog)
return log_error_errno(-1, errno, "Failed to open attach cgroup %s",
prog->attached_path);
} else {
- union bpf_attr attr;
+ union bpf_attr *attr;
- attr = (union bpf_attr){
- .attach_type = prog->attached_type,
- .target_fd = fd,
- .attach_bpf_fd = prog->kernel_fd,
+ attr = &(union bpf_attr){
+ .attach_type = prog->attached_type,
+ .target_fd = fd,
+ .attach_bpf_fd = prog->kernel_fd,
};
- ret = bpf(BPF_PROG_DETACH, &attr, sizeof(attr));
+ ret = bpf(BPF_PROG_DETACH, attr, sizeof(*attr));
if (ret < 0)
return log_error_errno(-1, errno, "Failed to detach bpf program from cgroup %s",
prog->attached_path);
@@ -523,8 +531,8 @@ bool bpf_devices_cgroup_supported(void)
{
__do_bpf_program_free struct bpf_program *prog = NULL;
const struct bpf_insn dummy[] = {
- BPF_MOV64_IMM(BPF_REG_0, 1),
- BPF_EXIT_INSN(),
+ BPF_MOV64_IMM(BPF_REG_0, 1),
+ BPF_EXIT_INSN(),
};
int ret;
@@ -536,11 +544,15 @@ bool bpf_devices_cgroup_supported(void)
if (!prog)
return log_trace(false, "Failed to allocate new bpf device cgroup program");
+ ret = bpf_program_init(prog);
+ if (ret)
+ return log_error_errno(false, ENOMEM, "Failed to initialize bpf program");
+
ret = bpf_program_add_instructions(prog, dummy, ARRAY_SIZE(dummy));
if (ret < 0)
return log_trace(false, "Failed to add new instructions to bpf device cgroup program");
- ret = bpf_program_load_kernel(prog, NULL, 0, 0);
+ ret = bpf_program_load_kernel(prog);
if (ret < 0)
return log_trace(false, "Failed to load new bpf device cgroup program");
diff --git a/src/lxc/cgroups/cgroup2_devices.h b/src/lxc/cgroups/cgroup2_devices.h
index 04f493e029..2da101ab4c 100644
--- a/src/lxc/cgroups/cgroup2_devices.h
+++ b/src/lxc/cgroups/cgroup2_devices.h
@@ -19,6 +19,7 @@
#include "compiler.h"
#include "conf.h"
#include "config.h"
+#include "memory_utils.h"
#include "syscall_numbers.h"
#ifdef HAVE_STRUCT_BPF_CGROUP_DEV_CTX
@@ -65,14 +66,6 @@ __hidden extern void bpf_program_free(struct bpf_program *prog);
__hidden extern void bpf_device_program_free(struct cgroup_ops *ops);
__hidden extern bool bpf_devices_cgroup_supported(void);
-static inline void __auto_bpf_program_free__(struct bpf_program **prog)
-{
- if (*prog) {
- bpf_program_free(*prog);
- *prog = NULL;
- }
-}
-
__hidden extern int bpf_list_add_device(struct lxc_conf *conf, struct device_item *device);
#else /* !HAVE_STRUCT_BPF_CGROUP_DEV_CTX */
@@ -129,10 +122,6 @@ static inline bool bpf_devices_cgroup_supported(void)
return false;
}
-static inline void __auto_bpf_program_free__(struct bpf_program **prog)
-{
-}
-
static inline int bpf_list_add_device(struct lxc_conf *conf,
struct device_item *device)
{
@@ -141,7 +130,7 @@ static inline int bpf_list_add_device(struct lxc_conf *conf,
}
#endif /* !HAVE_STRUCT_BPF_CGROUP_DEV_CTX */
-#define __do_bpf_program_free \
- __attribute__((__cleanup__(__auto_bpf_program_free__)))
+define_cleanup_function(struct bpf_program *, bpf_program_free);
+#define __do_bpf_program_free call_cleaner(bpf_program_free)
#endif /* __LXC_CGROUP2_DEVICES_H */
diff --git a/src/lxc/log.c b/src/lxc/log.c
index 6c75744534..7f1d5a8612 100644
--- a/src/lxc/log.c
+++ b/src/lxc/log.c
@@ -46,7 +46,7 @@
int lxc_log_fd = -EBADF;
static bool wants_syslog = false;
static int lxc_quiet_specified;
-int lxc_log_use_global_fd;
+bool lxc_log_use_global_fd = false;
static int lxc_loglevel_specified;
static char log_prefix[LXC_LOG_PREFIX_SIZE] = "lxc";
@@ -92,6 +92,20 @@ static const char *lxc_log_get_container_name(void)
return log_vmname;
}
+int lxc_log_get_fd(void)
+{
+ int fd_log = -EBADF;
+
+#ifndef NO_LXC_CONF
+ if (current_config && !lxc_log_use_global_fd)
+ fd_log = current_config->logfd;
+#endif
+ if (fd_log < 0)
+ fd_log = lxc_log_fd;
+
+ return fd_log;
+}
+
static char *lxc_log_get_va_msg(struct lxc_log_event *event)
{
__do_free char *msg = NULL;
@@ -659,7 +673,7 @@ int lxc_log_init(struct lxc_log *log)
if (ret < 0)
return log_error_errno(-1, errno, "Failed to enable logfile");
- lxc_log_use_global_fd = 1;
+ lxc_log_use_global_fd = true;
} else {
/* if no name was specified, there nothing to do */
if (!log->name)
@@ -762,9 +776,18 @@ int lxc_log_set_level(int *dest, int level)
return 0;
}
-inline int lxc_log_get_level(void)
+int lxc_log_get_level(void)
{
- return lxc_log_category_lxc.priority;
+ int level = LXC_LOG_LEVEL_NOTSET;
+
+#ifndef NO_LXC_CONF
+ if (current_config)
+ level = current_config->loglevel;
+#endif
+ if (level == LXC_LOG_LEVEL_NOTSET)
+ level = lxc_log_category_lxc.priority;
+
+ return level;
}
bool lxc_log_has_valid_level(void)
diff --git a/src/lxc/log.h b/src/lxc/log.h
index 0361db40fa..e4081950e2 100644
--- a/src/lxc/log.h
+++ b/src/lxc/log.h
@@ -85,7 +85,7 @@ struct lxc_log_category {
};
#ifndef NO_LXC_CONF
-extern int lxc_log_use_global_fd;
+extern bool lxc_log_use_global_fd;
#endif
/*
@@ -568,11 +568,16 @@ __hidden extern void lxc_log_syslog_enable(void);
__hidden extern void lxc_log_syslog_disable(void);
__hidden extern int lxc_log_set_level(int *dest, int level);
__hidden extern int lxc_log_get_level(void);
+static inline bool lxc_log_trace(void)
+{
+ return lxc_log_get_level() <= LXC_LOG_LEVEL_TRACE;
+}
__hidden extern bool lxc_log_has_valid_level(void);
__hidden extern int lxc_log_set_file(int *fd, const char *fname);
__hidden extern const char *lxc_log_get_file(void);
__hidden extern void lxc_log_set_prefix(const char *prefix);
__hidden extern const char *lxc_log_get_prefix(void);
__hidden extern void lxc_log_options_no_override(void);
+__hidden extern int lxc_log_get_fd(void);
#endif /* __LXC_LOG_H */
diff --git a/src/lxc/macro.h b/src/lxc/macro.h
index 11da99118e..ae629a7904 100644
--- a/src/lxc/macro.h
+++ b/src/lxc/macro.h
@@ -602,7 +602,8 @@ enum {
#define PTR_TO_PID(p) ((pid_t)((intptr_t)(p)))
#define PID_TO_PTR(u) ((void *)((intptr_t)(u)))
-#define PTR_TO_UINT64(p) ((uint64_t)((intptr_t)(p)))
+#define PTR_TO_UINT64(p) ((uint64_t)((uintptr_t)(p)))
+#define PTR_TO_U64(p) ((__u64)((uintptr_t)(p)))
#define UINT_TO_PTR(u) ((void *) ((uintptr_t) (u)))
#define PTR_TO_USHORT(p) ((unsigned short)((uintptr_t)(p)))
diff --git a/src/lxc/seccomp.c b/src/lxc/seccomp.c
index ba6811d903..94d33d26d8 100644
--- a/src/lxc/seccomp.c
+++ b/src/lxc/seccomp.c
@@ -1260,14 +1260,16 @@ int lxc_seccomp_load(struct lxc_conf *conf)
/* After load seccomp filter into the kernel successfully, export the current seccomp
* filter to log file */
#if HAVE_SCMP_FILTER_CTX
- if ((lxc_log_get_level() <= LXC_LOG_LEVEL_TRACE ||
- conf->loglevel <= LXC_LOG_LEVEL_TRACE) &&
- lxc_log_fd >= 0) {
- ret = seccomp_export_pfc(conf->seccomp.seccomp_ctx, lxc_log_fd);
- /* Just give an warning when export error */
- if (ret < 0) {
- errno = -ret;
- SYSWARN("Failed to export seccomp filter to log file");
+ if (lxc_log_trace()) {
+ int fd_log;
+
+ fd_log = lxc_log_get_fd();
+ if (fd_log >= 0) {
+ ret = seccomp_export_pfc(conf->seccomp.seccomp_ctx, fd_log);
+ if (ret < 0) {
+ errno = -ret;
+ SYSWARN("Failed to export seccomp filter to log file");
+ }
}
}
#endif
| 0
|
983a2e08cc4f850cf5f70f4c40d52d4792d6a08d
|
https://github.com/cockpit-project/cockpit/commit/983a2e08cc4f850cf5f70f4c40d52d4792d6a08d
|
machines: put back the controlling of `Disk edit` dialog inside the react state
See commit 20963cbc5b for the reason this was like this. The original
problem was resolved in the previous commit so let's add the control of
the modal's open state inside the component as we do everywhere else.
|
diff --git a/pkg/machines/components/vm/disks/diskEdit.jsx b/pkg/machines/components/vm/disks/diskEdit.jsx
index 99e5d9cc3fcc..c3831fa1d9c0 100644
--- a/pkg/machines/components/vm/disks/diskEdit.jsx
+++ b/pkg/machines/components/vm/disks/diskEdit.jsx
@@ -111,7 +111,7 @@ const AccessRow = ({ onValueChanged, dialogValues, driverType, idPrefix }) => {
);
};
-class EditDiskModalBody extends React.Component {
+export class EditDiskAction extends React.Component {
constructor(props) {
super(props);
let access;
@@ -151,7 +151,7 @@ class EditDiskModalBody extends React.Component {
busType: this.state.busType,
existingTargets
})
- .then(() => this.props.close())
+ .then(() => this.setState({ isOpen: false }))
.fail((exc) => {
this.dialogErrorSet(_("Disk settings could not be saved"), exc.message);
});
@@ -187,59 +187,33 @@ class EditDiskModalBody extends React.Component {
}
};
- return (
- <Modal position="top" variant="medium" id={`${idPrefix}-dialog`} isOpen onClose={this.props.close}
- title={cockpit.format(_("Edit $0 attributes"), getDiskPrettyName(vm.disks[disk.target]))}
- footer={
- <>
- {this.state.dialogError && <ModalError dialogError={this.state.dialogError} dialogErrorDetail={this.state.dialogErrorDetail} />}
- <Button id={`${idPrefix}-dialog-save`} variant='primary' onClick={this.onSaveClicked}>
- {_("Save")}
- </Button>
- <Button id={`${idPrefix}-dialog-cancel`} variant='link' className='btn-cancel' onClick={this.props.close}>
- {_("Cancel")}
- </Button>
- </>
- }>
- <>
- { showWarning() }
- {defaultBody}
- </>
- </Modal>
- );
- }
-}
-
-const EditDiskActionShowModal = { };
-
-export class EditDiskAction extends React.Component {
- constructor(props) {
- super(props);
- this.open = this.open.bind(this);
- this.close = this.close.bind(this);
- }
-
- close() {
- EditDiskActionShowModal[this.props.idPrefix] = false;
- this.setState({ });
- }
-
- open() {
- EditDiskActionShowModal[this.props.idPrefix] = true;
- this.setState({ });
- }
-
- render() {
- const { disk, vm } = this.props;
- const idPrefix = `${this.props.idPrefix}`;
- const showModal = EditDiskActionShowModal[this.props.idPrefix];
-
return (
<>
- <Button id={`${idPrefix}-edit`} variant='secondary' onClick={this.open}>
+ <Button id={idPrefix} variant='secondary' onClick={() => this.setState({ isOpen: true })}>
{_("Edit")}
</Button>
- { showModal && <EditDiskModalBody close={this.close} disk={disk} idPrefix={idPrefix} vm={vm} /> }
+ {this.state.isOpen &&
+ <Modal position="top" variant="medium" id={`${idPrefix}-dialog`}
+ isOpen
+ onClose={() => this.setState({ isOpen: false })}
+ title={cockpit.format(_("Edit $0 attributes"), getDiskPrettyName(vm.disks[disk.target]))}
+ footer={
+ <>
+ {this.state.dialogError && <ModalError dialogError={this.state.dialogError} dialogErrorDetail={this.state.dialogErrorDetail} />}
+ <Button id={`${idPrefix}-dialog-save`} variant='primary' onClick={this.onSaveClicked}>
+ {_("Save")}
+ </Button>
+ <Button id={`${idPrefix}-dialog-cancel`} variant='link' className='btn-cancel' onClick={() => this.setState({ isOpen: false })}>
+ {_("Cancel")}
+ </Button>
+ </>
+ }
+ >
+ <>
+ {showWarning()}
+ {defaultBody}
+ </>
+ </Modal>}
</>
);
}
| 0
|
08e8ae289bbd1b581986c7238604a147119c1336
|
https://github.com/spring-projects/spring-ldap/commit/08e8ae289bbd1b581986c7238604a147119c1336
|
Force reconnect with credentials on DefaultTlsDirContextAuthenticationStrategy
refs #430
|
diff --git a/core/src/main/java/org/springframework/ldap/core/support/DefaultTlsDirContextAuthenticationStrategy.java b/core/src/main/java/org/springframework/ldap/core/support/DefaultTlsDirContextAuthenticationStrategy.java
index 56975408b..9fe144d60 100755
--- a/core/src/main/java/org/springframework/ldap/core/support/DefaultTlsDirContextAuthenticationStrategy.java
+++ b/core/src/main/java/org/springframework/ldap/core/support/DefaultTlsDirContextAuthenticationStrategy.java
@@ -36,6 +36,8 @@ protected void applyAuthentication(LdapContext ctx, String userDn, String passwo
ctx.addToEnvironment(Context.SECURITY_AUTHENTICATION, SIMPLE_AUTHENTICATION);
ctx.addToEnvironment(Context.SECURITY_PRINCIPAL, userDn);
ctx.addToEnvironment(Context.SECURITY_CREDENTIALS, password);
+ // Force reconnect with user credentials
+ ctx.reconnect(null);
}
}
| 1
|
5a1e4edcd42c3349e10494d88b174b513f642bf8
|
https://github.com/apache/santuario-java/commit/5a1e4edcd42c3349e10494d88b174b513f642bf8
|
Adding a release script and updating the website for the forthcoming 1.4.4 release.
git-svn-id: https://svn.apache.org/repos/asf/santuario/trunk@1028025 13f79535-47bb-0310-9956-ffa450edef68
|
diff --git a/contrib/santuario-release.sh b/contrib/santuario-release.sh
new file mode 100755
index 000000000..67b88a21e
--- /dev/null
+++ b/contrib/santuario-release.sh
@@ -0,0 +1,77 @@
+#!/bin/sh
+#
+# Copyright (c) The Apache Software Foundation.
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+#
+if [ -z "${SANTUARIO_SRC_ROOT}" ]
+then
+ echo "Assuming Santuario source tree is the CWD..."
+ SANTUARIO_SRC_ROOT=`pwd`
+fi
+if [ -z "${SANTUARIO_VERSION}" ]
+then
+ SANTUARIO_VERSION=SNAPSHOT
+ echo "Setting SANTUARIO_VERSION to ${SANTUARIO_VERSION}"
+fi
+if [ -z "${SANTUARIO_STAGE_ROOT}" ]
+then
+ SANTUARIO_STAGE_ROOT=/tmp/$(id -u -nr)/stage_santuario/${SANTUARIO_VERSION}
+ echo "Setting SANTUARIO_STAGE_ROOT to ${SANTUARIO_STAGE_ROOT}"
+fi
+#
+# set up the staging area
+#
+rm -rf ${SANTUARIO_STAGE_ROOT}
+mkdir -p ${SANTUARIO_STAGE_ROOT}/dist
+mkdir -p ${SANTUARIO_STAGE_ROOT}/maven/org/apache/santuario/xmlsec/${SANTUARIO_VERSION}
+#
+# Build and stage the distribution using ant
+#
+cd ${SANTUARIO_SRC_ROOT}
+ant clean
+ant dist || exit 1
+cp -r build/*.zip ${SANTUARIO_STAGE_ROOT}/dist
+cp pom.xml ${SANTUARIO_STAGE_ROOT}/maven/org/apache/santuario/xmlsec/${SANTUARIO_VERSION}/xmlsec-${SANTUARIO_VERSION}.pom
+cp build/xmlsec-${SANTUARIO_VERSION}.jar ${SANTUARIO_STAGE_ROOT}/maven/org/apache/santuario/xmlsec/${SANTUARIO_VERSION}
+
+#
+# Sign and hash the release bits
+#
+cd ${SANTUARIO_STAGE_ROOT}/dist
+for i in *
+do
+ gpg --detach-sign --armor $i
+ gpg --verify $i.asc
+done
+for i in *.zip
+do
+ md5sum $i > $i.md5
+done
+cd ${SANTUARIO_STAGE_ROOT}/maven/org/apache/santuario/xmlsec/${SANTUARIO_VERSION}
+for i in *
+do
+ gpg --detach-sign --armor $i
+ gpg --verify $i.asc
+done
+for i in *.jar *.pom
+do
+ md5sum $i > $i.md5
+done
+#
+# Build the web site
+#
+cd ${SANTUARIO_SRC_ROOT}
+ant xdocs || exit 1
+cp -r doc/site/build/site ${SANTUARIO_STAGE_ROOT}
+
diff --git a/doc/site/src/documentation/content/xdocs/Java/index.xml b/doc/site/src/documentation/content/xdocs/Java/index.xml
index 1b2594189..22ae0f71c 100644
--- a/doc/site/src/documentation/content/xdocs/Java/index.xml
+++ b/doc/site/src/documentation/content/xdocs/Java/index.xml
@@ -25,6 +25,15 @@ limitations under the License.
<title>The Java section</title>
</header>
<body>
+ <section>
+ <title>Version 1.4.4 Released</title>
+ <p>
+ Version 1.4.4 of the Java library has been released. This release
+ contains some enhancements to the resolver API's. It also fixes
+ some longstanding issues with interned Strings, as well as a number
+ of bug fixes.
+ </p>
+ </section>
<section>
<title>Version 1.4.3 Released</title>
<p>
diff --git a/doc/site/src/documentation/content/xdocs/index.xml b/doc/site/src/documentation/content/xdocs/index.xml
index bb2d1994a..886b7b2ce 100644
--- a/doc/site/src/documentation/content/xdocs/index.xml
+++ b/doc/site/src/documentation/content/xdocs/index.xml
@@ -22,6 +22,19 @@ limitations under the License.
<body>
<section>
<title>News</title>
+ <section>
+ <title>November 2010</title>
+ <p>
+ The Apache Santuario team are pleased to announce the release
+ of version 1.4.4 of the Java library. This release contains some
+ enhancements to the resolver API's. It also fixes some longstanding
+ issues with interned Strings, as well as a number of bug fixes.
+ </p>
+ <p>
+ Please see the <link href="site:changes">changelog</link> for more
+ information.
+ </p>
+ </section>
<section>
<title>July 2009</title>
<p>
diff --git a/doc/site/src/documentation/content/xdocs/who.xml b/doc/site/src/documentation/content/xdocs/who.xml
index 7cbd1af3c..181820e62 100644
--- a/doc/site/src/documentation/content/xdocs/who.xml
+++ b/doc/site/src/documentation/content/xdocs/who.xml
@@ -41,12 +41,20 @@ limitations under the License.
The following people are members of the Project Management Committee (PMC) for this project:
</p>
<ul>
- <li> [AXL] Axl Mattheus </li>
<li> [BL] Berin Lautenbach </li>
<li> [CO] Colm O hEigeartaigh (chair) </li>
<li> [SM] Sean Mullan </li>
<li> [RB] Raul Benito Garcia </li>
<li> [SC] Scott Cantor </li>
+ </ul>
+ </section>
+ <section>
+ <title>Emeritus PMC</title>
+ <p>
+ The following people are emeritus members of the Project Management Committee (PMC) for this project:
+ </p>
+ <ul>
+ <li> [AXL] Axl Mattheus </li>
<li> [WD] Werner Dittman </li>
</ul>
</section>
diff --git a/doc/site/status.xml b/doc/site/status.xml
index d4f83bc97..5165d6482 100644
--- a/doc/site/status.xml
+++ b/doc/site/status.xml
@@ -28,13 +28,85 @@ limitations under the License.
<person name="Sean Mullan" email="[email protected]" id="SM"/>
<person name="Scott Cantor" email="[email protected]" id="SC"/>
<person name="Colm O hEigeartaigh" email="[email protected]" id="CO"/>
+ <person name="Chad La Joie" email="[email protected]" id="CL"/>
<!-- Add more people here -->
</developers>
<changes>
<!-- Add new releases here; action attributes: type:(add | fix | update); -->
<!-- context:(docs | java_something | c_something ) -->
-
+
+ <release version="Java 1.4.4" date="November 2010">
+ <action dev="SM" type="fix" fixes-bug="50122" context="java_general">
+ JSR 105 TransformService classloading issue
+ </action>
+ <action dev="CL" type="fix" fixes-bug="40897" context="java_general">
+ String comparisons using '==' causes validation errors with some parsers.
+ </action>
+ <action dev="SM" type="fix" fixes-bug="50050" context="java_general">
+ UnsyncByteArrayOutputStream throws ArrayIndexOutOfBoundsException if
+ array length > internal buffer expansion size.
+ </action>
+ <action dev="CO" type="fix" fixes-bug="50036" context="java_general"
+ due-to="Stefan Vladov">
+ IdResolver Java API extension.
+ </action>
+ <action dev="CO" type="fix" fixes-bug="49493" context="java_general"
+ due-to="Clement Pellerin">
+ Cannot resolve PrivateKeys used in Key Transport algorithms.
+ </action>
+ <action dev="CO" type="fix" fixes-bug="49577" context="java_general">
+ DOMSubTreeData allows for only one iteration over referenced data.
+ </action>
+ <action dev="CO" type="fix" fixes-bug="49692" context="java_general">
+ Xmlsec 1.4.3 not compatible with xmlbeans 2.4.0.
+ </action>
+ <action dev="CO" type="fix" fixes-bug="49629" context="java_general">
+ Some changes to the build system.
+ </action>
+ <action dev="CO" type="fix" fixes-bug="49483" context="java_general"
+ due-to="Clement Pellerin">
+ KeyResolver.registerAtStart() leads to ClassCastException
+ </action>
+ <action dev="CO" type="fix" fixes-bug="49458" context="java_general"
+ due-to="Clement Pellerin">
+ StorageResolver always exhausted after first use.
+ </action>
+ <action dev="CO" type="fix" fixes-bug="49456" context="java_general"
+ due-to="Clement Pellerin">
+ StorageResolver.next() gives ClassCastException.
+ </action>
+ <action dev="CO" type="fix" fixes-bug="49450" context="java_general"
+ due-to="Clement Pellerin">
+ KeyStoreResolver always exhausted after first use.
+ </action>
+ <action dev="CO" type="fix" fixes-bug="49447" context="java_general"
+ due-to="Clement Pellerin">
+ KeyStoreResolver iterator returns null for symmetric keys.
+ </action>
+ <action dev="SM" type="fix" fixes-bug="48368" context="java_general">
+ Digest Value of References inside Manifest - calculation order problem
+ </action>
+ <action dev="CO" type="fix" fixes-bug="47779" context="java_general">
+ ConcurrentModificationException in XMLUtils.
+ </action>
+ <action dev="SC" type="fix" fixes-bug="47761" context="java_general">
+ xmlns:xml namespace improperly emitted during excl c14n.
+ </action>
+ <action dev="SM" type="fix" fixes-bug="36526" context="java_general"
+ due-to="Agnes Juhasz">
+ Out of memory error when signing or verifying big files.
+ </action>
+ <action dev="CO" type="fix" fixes-bug="47784" context="java_general"
+ due-to="Willem Jiang">
+ ClassNotFoundException when init the xml security in OSGi plateform.
+ </action>
+ <action dev="CO" type="fix" fixes-bug="47762" context="java_general"
+ due-to="Julien Pasquier">
+ contextChild parameter of Transform.getInstance may be null
+ </action>
+ </release>
+
<release version="Java 1.4.3" date="July 2009">
<action dev="SM" type="fix" fixes-bug="47526" context="java_general"
due-to="Sean Mullan">
| 0
|
44b01e11b72eb191877dd7627e6ed833b42b2ca2
|
https://github.com/evanphx/json-patch/commit/44b01e11b72eb191877dd7627e6ed833b42b2ca2
|
Fix map comparison of nil values and missing keys
|
diff --git a/merge.go b/merge.go
index 5dc6d34..14e8bb5 100644
--- a/merge.go
+++ b/merge.go
@@ -311,7 +311,12 @@ func matchesValue(av, bv interface{}) bool {
return false
}
for key := range bt {
- if !matchesValue(at[key], bt[key]) {
+ av, aOK := at[key]
+ bv, bOK := bt[key]
+ if aOK != bOK {
+ return false
+ }
+ if !matchesValue(av, bv) {
return false
}
}
diff --git a/merge_test.go b/merge_test.go
index c87b078..cd90c56 100644
--- a/merge_test.go
+++ b/merge_test.go
@@ -462,6 +462,73 @@ func createNestedMap(m map[string]interface{}, depth int, objectCount *int) {
}
}
+func TestMatchesValue(t *testing.T) {
+ testcases := []struct {
+ name string
+ a interface{}
+ b interface{}
+ want bool
+ }{
+ {
+ name: "map empty",
+ a: map[string]interface{}{},
+ b: map[string]interface{}{},
+ want: true,
+ },
+ {
+ name: "map equal keys, equal non-nil value",
+ a: map[string]interface{}{"1": true},
+ b: map[string]interface{}{"1": true},
+ want: true,
+ },
+ {
+ name: "map equal keys, equal nil value",
+ a: map[string]interface{}{"1": nil},
+ b: map[string]interface{}{"1": nil},
+ want: true,
+ },
+
+ {
+ name: "map different value",
+ a: map[string]interface{}{"1": true},
+ b: map[string]interface{}{"1": false},
+ want: false,
+ },
+ {
+ name: "map different key, matching non-nil value",
+ a: map[string]interface{}{"1": true},
+ b: map[string]interface{}{"2": true},
+ want: false,
+ },
+ {
+ name: "map different key, matching nil value",
+ a: map[string]interface{}{"1": nil},
+ b: map[string]interface{}{"2": nil},
+ want: false,
+ },
+ {
+ name: "map different key, first nil value",
+ a: map[string]interface{}{"1": true},
+ b: map[string]interface{}{"2": nil},
+ want: false,
+ },
+ {
+ name: "map different key, second nil value",
+ a: map[string]interface{}{"1": nil},
+ b: map[string]interface{}{"2": true},
+ want: false,
+ },
+ }
+ for _, tc := range testcases {
+ t.Run(tc.name, func(t *testing.T) {
+ got := matchesValue(tc.a, tc.b)
+ if got != tc.want {
+ t.Fatalf("want %v, got %v", tc.want, got)
+ }
+ })
+ }
+}
+
func benchmarkMatchesValueWithDeeplyNestedFields(depth int, b *testing.B) {
a := map[string]interface{}{}
objCount := 1
diff --git a/v5/merge.go b/v5/merge.go
index 5dc6d34..14e8bb5 100644
--- a/v5/merge.go
+++ b/v5/merge.go
@@ -311,7 +311,12 @@ func matchesValue(av, bv interface{}) bool {
return false
}
for key := range bt {
- if !matchesValue(at[key], bt[key]) {
+ av, aOK := at[key]
+ bv, bOK := bt[key]
+ if aOK != bOK {
+ return false
+ }
+ if !matchesValue(av, bv) {
return false
}
}
diff --git a/v5/merge_test.go b/v5/merge_test.go
index c87b078..cd90c56 100644
--- a/v5/merge_test.go
+++ b/v5/merge_test.go
@@ -462,6 +462,73 @@ func createNestedMap(m map[string]interface{}, depth int, objectCount *int) {
}
}
+func TestMatchesValue(t *testing.T) {
+ testcases := []struct {
+ name string
+ a interface{}
+ b interface{}
+ want bool
+ }{
+ {
+ name: "map empty",
+ a: map[string]interface{}{},
+ b: map[string]interface{}{},
+ want: true,
+ },
+ {
+ name: "map equal keys, equal non-nil value",
+ a: map[string]interface{}{"1": true},
+ b: map[string]interface{}{"1": true},
+ want: true,
+ },
+ {
+ name: "map equal keys, equal nil value",
+ a: map[string]interface{}{"1": nil},
+ b: map[string]interface{}{"1": nil},
+ want: true,
+ },
+
+ {
+ name: "map different value",
+ a: map[string]interface{}{"1": true},
+ b: map[string]interface{}{"1": false},
+ want: false,
+ },
+ {
+ name: "map different key, matching non-nil value",
+ a: map[string]interface{}{"1": true},
+ b: map[string]interface{}{"2": true},
+ want: false,
+ },
+ {
+ name: "map different key, matching nil value",
+ a: map[string]interface{}{"1": nil},
+ b: map[string]interface{}{"2": nil},
+ want: false,
+ },
+ {
+ name: "map different key, first nil value",
+ a: map[string]interface{}{"1": true},
+ b: map[string]interface{}{"2": nil},
+ want: false,
+ },
+ {
+ name: "map different key, second nil value",
+ a: map[string]interface{}{"1": nil},
+ b: map[string]interface{}{"2": true},
+ want: false,
+ },
+ }
+ for _, tc := range testcases {
+ t.Run(tc.name, func(t *testing.T) {
+ got := matchesValue(tc.a, tc.b)
+ if got != tc.want {
+ t.Fatalf("want %v, got %v", tc.want, got)
+ }
+ })
+ }
+}
+
func benchmarkMatchesValueWithDeeplyNestedFields(depth int, b *testing.B) {
a := map[string]interface{}{}
objCount := 1
| 0
|
eaada474dabafabfbe53569614edb465067cfcb0
|
https://github.com/ImageMagick/ImageMagick/commit/eaada474dabafabfbe53569614edb465067cfcb0
|
https://github.com/ImageMagick/ImageMagick/issues/672
|
diff --git a/MagickCore/blob.c b/MagickCore/blob.c
index 4bd5c97249..477527d059 100644
--- a/MagickCore/blob.c
+++ b/MagickCore/blob.c
@@ -4276,6 +4276,7 @@ MagickExport char *ReadBlobString(Image *image,char *string)
{
if (i == 0)
return((char *) NULL);
+ string[i]='\0';
break;
}
string[i]=(char) (*p);
| 0
|
6d1c73b5858fefc6161c7d686345f0dc887ea799
|
https://github.com/illumos/illumos-gate/commit/6d1c73b5858fefc6161c7d686345f0dc887ea799
|
7483 SMB flush on pipe triggers NULL pointer dereference in module smbsrv
Reviewed by: Gordon Ross <[email protected]>
Reviewed by: Matt Barden <[email protected]>
Reviewed by: Evan Layton <[email protected]>
Reviewed by: Dan McDonald <[email protected]>
Approved by: Gordon Ross <[email protected]>
|
diff --git a/usr/src/uts/common/fs/smbsrv/smb2_flush.c b/usr/src/uts/common/fs/smbsrv/smb2_flush.c
index ecdf2fdcb877..82263d59366b 100644
--- a/usr/src/uts/common/fs/smbsrv/smb2_flush.c
+++ b/usr/src/uts/common/fs/smbsrv/smb2_flush.c
@@ -11,6 +11,7 @@
/*
* Copyright 2014 Nexenta Systems, Inc. All rights reserved.
+ * Copyright 2016 Syneto S.R.L. All rights reserved.
*/
/*
@@ -23,7 +24,6 @@
smb_sdrc_t
smb2_flush(smb_request_t *sr)
{
- smb_ofile_t *of = NULL;
uint16_t StructSize;
uint16_t reserved1;
uint32_t reserved2;
@@ -51,14 +51,8 @@ smb2_flush(smb_request_t *sr)
smb2sr_put_error(sr, status);
return (SDRC_SUCCESS);
}
- of = sr->fid_ofile;
- /*
- * XXX - todo:
- * Flush named pipe should drain writes.
- */
- if ((of->f_node->flags & NODE_FLAGS_WRITE_THROUGH) == 0)
- (void) smb_fsop_commit(sr, of->f_cr, of->f_node);
+ smb_ofile_flush(sr, sr->fid_ofile);
/*
* SMB2 Flush reply
diff --git a/usr/src/uts/common/fs/smbsrv/smb_flush.c b/usr/src/uts/common/fs/smbsrv/smb_flush.c
index 5de347b6b555..1d210c3d8990 100644
--- a/usr/src/uts/common/fs/smbsrv/smb_flush.c
+++ b/usr/src/uts/common/fs/smbsrv/smb_flush.c
@@ -21,6 +21,8 @@
/*
* Copyright 2009 Sun Microsystems, Inc. All rights reserved.
* Use is subject to license terms.
+ *
+ * Copyright 2016 Syneto S.R.L. All rights reserved.
*/
/*
@@ -40,8 +42,6 @@
#include <smbsrv/smb_fsops.h>
-static void smb_flush_file(struct smb_request *sr, struct smb_ofile *ofile);
-
/*
* smb_com_flush
*
@@ -90,15 +90,14 @@ smb_com_flush(smb_request_t *sr)
ERRDOS, ERRbadfid);
return (SDRC_ERROR);
}
-
- smb_flush_file(sr, sr->fid_ofile);
+ smb_ofile_flush(sr, sr->fid_ofile);
} else {
flist = &sr->tid_tree->t_ofile_list;
smb_llist_enter(flist, RW_READER);
file = smb_llist_head(flist);
while (file) {
mutex_enter(&file->f_mutex);
- smb_flush_file(sr, file);
+ smb_ofile_flush(sr, file);
mutex_exit(&file->f_mutex);
file = smb_llist_next(flist, file);
}
@@ -108,19 +107,3 @@ smb_com_flush(smb_request_t *sr)
rc = smbsr_encode_empty_result(sr);
return ((rc == 0) ? SDRC_SUCCESS : SDRC_ERROR);
}
-
-
-/*
- * smb_flush_file
- *
- * If writes on this file are not synchronous, flush it using the NFSv3
- * commit interface.
- */
-static void
-smb_flush_file(struct smb_request *sr, struct smb_ofile *ofile)
-{
- sr->user_cr = smb_ofile_getcred(ofile);
-
- if ((ofile->f_node->flags & NODE_FLAGS_WRITE_THROUGH) == 0)
- (void) smb_fsop_commit(sr, sr->user_cr, ofile->f_node);
-}
diff --git a/usr/src/uts/common/fs/smbsrv/smb_ofile.c b/usr/src/uts/common/fs/smbsrv/smb_ofile.c
index 34ef5dc52614..582091d1dd64 100644
--- a/usr/src/uts/common/fs/smbsrv/smb_ofile.c
+++ b/usr/src/uts/common/fs/smbsrv/smb_ofile.c
@@ -21,6 +21,7 @@
/*
* Copyright (c) 2007, 2010, Oracle and/or its affiliates. All rights reserved.
* Copyright 2015 Nexenta Systems, Inc. All rights reserved.
+ * Copyright 2016 Syneto S.R.L. All rights reserved.
*/
/*
@@ -836,6 +837,27 @@ smb_ofile_seek(
return (rc);
}
+/*
+ * smb_ofile_flush
+ *
+ * If writes on this file are not synchronous, flush it using the NFSv3
+ * commit interface.
+ *
+ * XXX - todo: Flush named pipe should drain writes.
+ */
+void
+smb_ofile_flush(struct smb_request *sr, struct smb_ofile *of)
+{
+ switch (of->f_ftype) {
+ case SMB_FTYPE_DISK:
+ if ((of->f_node->flags & NODE_FLAGS_WRITE_THROUGH) == 0)
+ (void) smb_fsop_commit(sr, of->f_cr, of->f_node);
+ break;
+ default:
+ break;
+ }
+}
+
/*
* smb_ofile_is_open
*/
diff --git a/usr/src/uts/common/smbsrv/smb_kproto.h b/usr/src/uts/common/smbsrv/smb_kproto.h
index f394773c0ab5..2dd8787aebfd 100644
--- a/usr/src/uts/common/smbsrv/smb_kproto.h
+++ b/usr/src/uts/common/smbsrv/smb_kproto.h
@@ -22,6 +22,7 @@
/*
* Copyright (c) 2007, 2010, Oracle and/or its affiliates. All rights reserved.
* Copyright 2015 Nexenta Systems, Inc. All rights reserved.
+ * Copyright 2016 Syneto S.R.L. All rights reserved.
*/
/*
@@ -673,6 +674,7 @@ void smb_ofile_close(smb_ofile_t *, int32_t);
void smb_ofile_delete(void *);
uint32_t smb_ofile_access(smb_ofile_t *, cred_t *, uint32_t);
int smb_ofile_seek(smb_ofile_t *, ushort_t, int32_t, uint32_t *);
+void smb_ofile_flush(smb_request_t *, smb_ofile_t *);
boolean_t smb_ofile_hold(smb_ofile_t *);
void smb_ofile_release(smb_ofile_t *);
void smb_ofile_request_complete(smb_ofile_t *);
| 1
|
391877b92e385a0f815798e4fb57cbaf8a93c22b
|
https://github.com/apache/ranger/commit/391877b92e385a0f815798e4fb57cbaf8a93c22b
|
RANGER-3140:Ranger ShutdownHook hook to be called in RangerHBaseCoprocessor preShutdown apis for a clean shutdown of HBase
Signed-off-by: Ramesh Mani <[email protected]>
|
diff --git a/agents-audit/src/main/java/org/apache/ranger/audit/provider/AuditProviderFactory.java b/agents-audit/src/main/java/org/apache/ranger/audit/provider/AuditProviderFactory.java
index 1be9c2f86a..f971a76f0c 100644
--- a/agents-audit/src/main/java/org/apache/ranger/audit/provider/AuditProviderFactory.java
+++ b/agents-audit/src/main/java/org/apache/ranger/audit/provider/AuditProviderFactory.java
@@ -19,6 +19,7 @@
package org.apache.ranger.audit.provider;
import java.util.ArrayList;
+import java.util.Arrays;
import java.util.List;
import java.util.Properties;
import java.util.concurrent.Semaphore;
@@ -71,6 +72,7 @@
private String componentAppType = "";
private boolean mInitDone = false;
private JVMShutdownHook jvmShutdownHook = null;
+ private ArrayList<String> hbaseAppTypes = new ArrayList<>(Arrays.asList("hbaseMaster","hbaseRegional"));
public AuditProviderFactory() {
LOG.info("AuditProviderFactory: creating..");
@@ -476,7 +478,10 @@ private AuditHandler getDefaultProvider() {
private void installJvmSutdownHook(Properties props) {
int shutdownHookMaxWaitSeconds = MiscUtil.getIntProperty(props, AUDIT_SHUTDOWN_HOOK_MAX_WAIT_SEC, AUDIT_SHUTDOWN_HOOK_MAX_WAIT_SEC_DEFAULT);
jvmShutdownHook = new JVMShutdownHook(mProvider, shutdownHookMaxWaitSeconds);
- ShutdownHookManager.get().addShutdownHook(jvmShutdownHook, RANGER_AUDIT_SHUTDOWN_HOOK_PRIORITY);
+ String appType = this.componentAppType;
+ if (appType != null && !hbaseAppTypes.contains(appType)) {
+ ShutdownHookManager.get().addShutdownHook(jvmShutdownHook, RANGER_AUDIT_SHUTDOWN_HOOK_PRIORITY);
+ }
}
private static class RangerAsyncAuditCleanup implements Runnable {
diff --git a/agents-audit/src/main/java/org/apache/ranger/audit/queue/AuditFileSpool.java b/agents-audit/src/main/java/org/apache/ranger/audit/queue/AuditFileSpool.java
index cbd819dda6..f8c2aa5f31 100644
--- a/agents-audit/src/main/java/org/apache/ranger/audit/queue/AuditFileSpool.java
+++ b/agents-audit/src/main/java/org/apache/ranger/audit/queue/AuditFileSpool.java
@@ -864,6 +864,7 @@ public void runLogAudit() {
}
} catch (InterruptedException e) {
logger.info("Caught exception in consumer thread. Shutdown might be in progress");
+ break;
} catch (Throwable t) {
logger.error("Exception in destination writing thread.", t);
}
diff --git a/hbase-agent/src/main/java/org/apache/ranger/authorization/hbase/AuthorizationSession.java b/hbase-agent/src/main/java/org/apache/ranger/authorization/hbase/AuthorizationSession.java
index 1b13d3b8f0..95ab5047c7 100644
--- a/hbase-agent/src/main/java/org/apache/ranger/authorization/hbase/AuthorizationSession.java
+++ b/hbase-agent/src/main/java/org/apache/ranger/authorization/hbase/AuthorizationSession.java
@@ -243,7 +243,7 @@ void publishResults() throws AccessDeniedException {
}
boolean authorized = isAuthorized();
- if (_auditHandler != null) {
+ if (_auditHandler != null && isAudited()) {
List<AuthzAuditEvent> events = null;
/*
* What we log to audit depends on authorization status. For success we log all accumulated events. In case of failure
diff --git a/hbase-agent/src/main/java/org/apache/ranger/authorization/hbase/RangerAuthorizationCoprocessor.java b/hbase-agent/src/main/java/org/apache/ranger/authorization/hbase/RangerAuthorizationCoprocessor.java
index d9872ff6c5..2232953172 100644
--- a/hbase-agent/src/main/java/org/apache/ranger/authorization/hbase/RangerAuthorizationCoprocessor.java
+++ b/hbase-agent/src/main/java/org/apache/ranger/authorization/hbase/RangerAuthorizationCoprocessor.java
@@ -58,10 +58,13 @@
import org.apache.hadoop.hbase.wal.WALEdit;
import org.apache.hadoop.security.AccessControlException;
import org.apache.ranger.audit.model.AuthzAuditEvent;
+import org.apache.ranger.audit.provider.AuditProviderFactory;
import org.apache.ranger.authorization.hadoop.constants.RangerHadoopConstants;
import org.apache.ranger.authorization.utils.StringUtil;
import org.apache.ranger.plugin.audit.RangerDefaultAuditHandler;
+import org.apache.ranger.plugin.model.RangerPolicy;
import org.apache.ranger.plugin.policyengine.RangerAccessRequest;
+import org.apache.ranger.plugin.policyengine.RangerAccessResult;
import org.apache.ranger.plugin.policyengine.RangerAccessResultProcessor;
import org.apache.ranger.plugin.policyengine.RangerAccessRequestImpl;
import org.apache.ranger.plugin.policyengine.RangerAccessResourceImpl;
@@ -1022,6 +1025,7 @@ public void preScannerOpen(ObserverContext<RegionCoprocessorEnvironment> c, Scan
@Override
public void preShutdown(ObserverContext<MasterCoprocessorEnvironment> c) throws IOException {
requirePermission(c, "shutdown", Permission.Action.ADMIN);
+ cleanUp_HBaseRangerPlugin();
}
@Override
public void preSnapshot(ObserverContext<MasterCoprocessorEnvironment> ctx, SnapshotDescription snapshot, TableDescriptor hTableDescriptor) throws IOException {
@@ -1031,10 +1035,12 @@ public void preSnapshot(ObserverContext<MasterCoprocessorEnvironment> ctx, Snaps
@Override
public void preStopMaster(ObserverContext<MasterCoprocessorEnvironment> c) throws IOException {
requirePermission(c, "stopMaster", Permission.Action.ADMIN);
+ cleanUp_HBaseRangerPlugin();
}
@Override
public void preStopRegionServer(ObserverContext<RegionServerCoprocessorEnvironment> env) throws IOException {
requirePermission(env, "stop", Permission.Action.ADMIN);
+ cleanUp_HBaseRangerPlugin();
}
@Override
public void preUnassign(ObserverContext<MasterCoprocessorEnvironment> c, RegionInfo regionInfo, boolean force) throws IOException {
@@ -1645,6 +1651,24 @@ private GrantRevokeRequest createRevokeData(AccessControlProtos.RevokeRequest re
return ret;
}
+
+ private void cleanUp_HBaseRangerPlugin() {
+ if (LOG.isDebugEnabled()) {
+ LOG.debug("==> RangerAuthorizationCoprocessor.cleanUp_HBaseRangerPlugin()");
+ }
+ if (hbasePlugin != null) {
+ hbasePlugin.setHBaseShuttingDown(true);
+ hbasePlugin.cleanup();
+ AuditProviderFactory auditProviderFactory = hbasePlugin.getAuditProviderFactory();
+ if (auditProviderFactory != null) {
+ auditProviderFactory.shutdown();
+ }
+ }
+ if (LOG.isDebugEnabled()) {
+ LOG.debug("<== RangerAuthorizationCoprocessor.cleanUp_HBaseRangerPlugin() completed!");
+ }
+ }
+
private String getCommandString(String operationName, String tableNameStr, Map<String,Object> opMetaData) {
StringBuilder ret = new StringBuilder();
if (!HbaseConstants.HBASE_META_TABLE.equals(tableNameStr)) {
@@ -1787,10 +1811,30 @@ private void checkAccess(ObserverContext<MasterCoprocessorEnvironment> ctx, Stri
class RangerHBasePlugin extends RangerBasePlugin {
+ private static final Log LOG = LogFactory.getLog(RangerHBasePlugin.class);
+ boolean isHBaseShuttingDown = false;
+
public RangerHBasePlugin(String appType) {
super("hbase", appType);
}
+ public void setHBaseShuttingDown(boolean hbaseShuttingDown) {
+ isHBaseShuttingDown = hbaseShuttingDown;
+ }
+
+ @Override
+ public RangerAccessResult isAccessAllowed(RangerAccessRequest request, RangerAccessResultProcessor resultProcessor) {
+ RangerAccessResult ret = null;
+ if (isHBaseShuttingDown) {
+ ret = new RangerAccessResult(RangerPolicy.POLICY_TYPE_ACCESS, this.getServiceName(), this.getServiceDef(), request);
+ ret.setIsAllowed(true);
+ ret.setIsAudited(false);
+ LOG.warn("Auth request came after HBase shutdown....");
+ } else {
+ ret = super.isAccessAllowed(request, resultProcessor);
+ }
+ return ret;
+ }
}
| 0
|
ad418eeb974e357f2797aef64aa0e3ffaaa6125b
|
https://github.com/FasterXML/jackson-databind/commit/ad418eeb974e357f2797aef64aa0e3ffaaa6125b
|
Backport #2387, #2389 fixes
|
diff --git a/src/main/java/com/fasterxml/jackson/databind/jsontype/impl/SubTypeValidator.java b/src/main/java/com/fasterxml/jackson/databind/jsontype/impl/SubTypeValidator.java
index c4d7f38272..fa7ff2368b 100644
--- a/src/main/java/com/fasterxml/jackson/databind/jsontype/impl/SubTypeValidator.java
+++ b/src/main/java/com/fasterxml/jackson/databind/jsontype/impl/SubTypeValidator.java
@@ -89,6 +89,12 @@
s.add("org.jdom.transform.XSLTransformer");
s.add("org.jdom2.transform.XSLTransformer");
+ // [databind#2387]: EHCache
+ s.add("net.sf.ehcache.transaction.manager.DefaultTransactionManagerLookup");
+
+ // [databind#2389]: logback/jndi
+ s.add("ch.qos.logback.core.db.JNDIConnectionSource");
+
DEFAULT_NO_DESER_CLASS_NAMES = Collections.unmodifiableSet(s);
}
| 1
|
64ebdae8f24b096f157bf8cfeb907a214c1d8cfd
|
https://github.com/pojome/activity-log/commit/64ebdae8f24b096f157bf8cfeb907a214c1d8cfd
|
Added support for CloudFlare client IP header
|
diff --git a/classes/class-aal-api.php b/classes/class-aal-api.php
index 879cd1a..79aacc6 100644
--- a/classes/class-aal-api.php
+++ b/classes/class-aal-api.php
@@ -33,6 +33,8 @@ protected function _delete_old_items() {
*/
protected function _get_ip_address() {
$server_ip_keys = array(
+ 'HTTP_CF_CONNECTING_IP', // CloudFlare
+ 'HTTP_TRUE_CLIENT_IP', // CloudFlare Enterprise header
'HTTP_CLIENT_IP',
'HTTP_X_FORWARDED_FOR',
'HTTP_X_FORWARDED',
@@ -40,7 +42,6 @@ protected function _get_ip_address() {
'HTTP_FORWARDED_FOR',
'HTTP_FORWARDED',
'REMOTE_ADDR',
- 'HTTP_CF_CONNECTING_IP',
);
foreach ( $server_ip_keys as $key ) {
| 0
|
3c6cbd04a79307b1905f472a5dad3a168f414f68
|
https://github.com/micahflee/onionshare/commit/3c6cbd04a79307b1905f472a5dad3a168f414f68
|
Merge branch 'develop' into 929_download_errors
|
diff --git a/cli/onionshare_cli/onion.py b/cli/onionshare_cli/onion.py
index 311de936a..56a191336 100644
--- a/cli/onionshare_cli/onion.py
+++ b/cli/onionshare_cli/onion.py
@@ -22,7 +22,14 @@
from stem import ProtocolError, SocketClosed
from stem.connection import MissingPassword, UnreadableCookieFile, AuthenticationFailure
from Crypto.PublicKey import RSA
-import base64, os, sys, tempfile, shutil, urllib, platform, subprocess, time, shlex
+import base64
+import os
+import tempfile
+import subprocess
+import time
+import shlex
+import getpass
+import psutil
from distutils.version import LooseVersion as Version
from . import common
@@ -109,13 +116,6 @@ class TorTooOld(Exception):
pass
-class BundledTorNotSupported(Exception):
- """
- This exception is raised if onionshare is set to use the bundled Tor binary,
- but it's not supported on that platform, or in dev mode.
- """
-
-
class BundledTorTimeout(Exception):
"""
This exception is raised if onionshare is set to use the bundled Tor binary,
@@ -158,14 +158,6 @@ def __init__(self, common, use_tmp_dir=False, get_tor_paths=None):
self.use_tmp_dir = use_tmp_dir
- # Is bundled tor supported?
- if (
- self.common.platform == "Windows" or self.common.platform == "Darwin"
- ) and getattr(sys, "onionshare_dev_mode", False):
- self.bundle_tor_supported = False
- else:
- self.bundle_tor_supported = True
-
# Set the path of the tor binary, for bundled tor
if not get_tor_paths:
get_tor_paths = self.common.get_tor_paths
@@ -221,12 +213,6 @@ def connect(
self.c = None
if self.settings.get("connection_type") == "bundled":
- if not self.bundle_tor_supported:
- raise BundledTorNotSupported(
- # strings._("settings_error_bundled_tor_not_supported")
- "Using the Tor version that comes with OnionShare does not work in developer mode on Windows or macOS."
- )
-
# Create a torrc for this session
if self.use_tmp_dir:
self.tor_data_directory = tempfile.TemporaryDirectory(
@@ -253,6 +239,26 @@ def connect(
raise OSError("OnionShare port not available")
self.tor_torrc = os.path.join(self.tor_data_directory_name, "torrc")
+ # If there is an existing OnionShare tor process, kill it
+ for proc in psutil.process_iter(["pid", "name", "username"]):
+ try:
+ cmdline = proc.cmdline()
+ if (
+ cmdline[0] == self.tor_path
+ and cmdline[1] == "-f"
+ and cmdline[2] == self.tor_torrc
+ ):
+ self.common.log(
+ "Onion",
+ "connect",
+ "found a stale tor process, killing it",
+ )
+ proc.terminate()
+ proc.wait()
+ break
+ except:
+ pass
+
if self.common.platform == "Windows" or self.common.platform == "Darwin":
# Windows doesn't support unix sockets, so it must use a network port.
# macOS can't use unix sockets either because socket filenames are limited to
diff --git a/cli/onionshare_cli/resources/templates/listing.html b/cli/onionshare_cli/resources/templates/listing.html
index ea0507107..e1dd6d9f7 100644
--- a/cli/onionshare_cli/resources/templates/listing.html
+++ b/cli/onionshare_cli/resources/templates/listing.html
@@ -1,55 +1,59 @@
<!DOCTYPE html>
<html>
- <head>
- <title>OnionShare</title>
- <meta charset="utf-8" />
- <meta name="viewport" content="width=device-width, initial-scale=1">
- <link href="{{ static_url_path }}/img/favicon.ico" rel="icon" type="image/x-icon" />
- <link href="{{ static_url_path }}/css/style.css" rel="stylesheet" type="text/css" />
- </head>
- <body>
-
- <header class="clearfix">
- <img class="logo" src="{{ static_url_path }}/img/logo.png" title="OnionShare">
- <h1>OnionShare</h1>
- </header>
-
- {% if breadcrumbs %}
- <ul class="breadcrumbs">
- {% for breadcrumb in breadcrumbs %}<li><a href="{{ breadcrumb[1] }}">{{ breadcrumb[0] }}</a> <span class="sep">‣</span></li>{% endfor %}<li>{{ breadcrumbs_leaf }}</li>
- </ul>
- {% endif %}
-
- <table class="file-list" id="file-list">
- <tr>
- <th id="filename-header">Filename</th>
- <th id="size-header">Size</th>
- <th></th>
- </tr>
-
- {% for info in dirs %}
- <tr>
- <td>
- <img width="30" height="30" title="" alt="" src="{{ static_url_path }}/img/web_folder.png" />
- <a href="{{ info.basename }}">
- {{ info.basename }}
- </a>
- </td>
- <td>—</td>
- </tr>
- {% endfor %}
-
- {% for info in files %}
- <tr>
- <td>
- <img width="30" height="30" title="" alt="" src="{{ static_url_path }}/img/web_file.png" />
- <a href="{{ info.basename }}">
- {{ info.basename }}
- </a>
- </td>
- <td>{{ info.size_human }}</td>
- </tr>
- {% endfor %}
- </table>
- </body>
-</html>
+
+<head>
+ <title>OnionShare</title>
+ <meta charset="utf-8" />
+ <meta name="viewport" content="width=device-width, initial-scale=1">
+ <link href="{{ static_url_path }}/img/favicon.ico" rel="icon" type="image/x-icon" />
+ <link href="{{ static_url_path }}/css/style.css" rel="stylesheet" type="text/css" />
+</head>
+
+<body>
+
+ <header class="clearfix">
+ <img class="logo" src="{{ static_url_path }}/img/logo.png" title="OnionShare">
+ <h1>OnionShare</h1>
+ </header>
+
+ {% if breadcrumbs %}
+ <ul class="breadcrumbs">
+ {% for breadcrumb in breadcrumbs %}<li><a href="{{ breadcrumb[1] }}">{{ breadcrumb[0] }}</a> <span
+ class="sep">‣</span></li>{% endfor %}<li>{{ breadcrumbs_leaf }}</li>
+ </ul>
+ {% endif %}
+
+ <table class="file-list" id="file-list">
+ <tr>
+ <th id="filename-header">Filename</th>
+ <th id="size-header">Size</th>
+ <th></th>
+ </tr>
+
+ {% for info in dirs %}
+ <tr>
+ <td>
+ <img width="30" height="30" title="" alt="" src="{{ static_url_path }}/img/web_folder.png" />
+ <a href="{{ info.link }}">
+ {{ info.basename }}
+ </a>
+ </td>
+ <td>—</td>
+ </tr>
+ {% endfor %}
+
+ {% for info in files %}
+ <tr>
+ <td>
+ <img width="30" height="30" title="" alt="" src="{{ static_url_path }}/img/web_file.png" />
+ <a href="{{ info.link }}">
+ {{ info.basename }}
+ </a>
+ </td>
+ <td>{{ info.size_human }}</td>
+ </tr>
+ {% endfor %}
+ </table>
+</body>
+
+</html>
\ No newline at end of file
diff --git a/cli/onionshare_cli/web/send_base_mode.py b/cli/onionshare_cli/web/send_base_mode.py
index f9db28c6e..9913996ed 100644
--- a/cli/onionshare_cli/web/send_base_mode.py
+++ b/cli/onionshare_cli/web/send_base_mode.py
@@ -85,7 +85,7 @@ def set_file_info(self, filenames, processed_size_callback=None):
# If it's a directory, add it recursively
elif os.path.isdir(filename):
- self.root_files[basename + "/"] = filename
+ self.root_files[basename] = filename
for root, _, nested_filenames in os.walk(filename):
# Normalize the root path. So if the directory name is "/home/user/Documents/some_folder",
@@ -96,7 +96,7 @@ def set_file_info(self, filenames, processed_size_callback=None):
).rstrip("/")
# Add the dir itself
- self.files[normalized_root + "/"] = root
+ self.files[normalized_root] = root
# Add the files in this dir
for nested_filename in nested_filenames:
@@ -117,19 +117,21 @@ def directory_listing(self, filenames, path="", filesystem_path=None):
)
breadcrumbs = [("☗", "/")]
- parts = path.split("/")[:-1]
+ parts = path.split("/")
+ if parts[-1] == "":
+ parts = parts[:-1]
for i in range(len(parts)):
- breadcrumbs.append((parts[i], f"/{'/'.join(parts[0 : i + 1])}/"))
+ breadcrumbs.append((parts[i], f"/{'/'.join(parts[0 : i + 1])}"))
breadcrumbs_leaf = breadcrumbs.pop()[0]
# If filesystem_path is None, this is the root directory listing
- files, dirs = self.build_directory_listing(filenames, filesystem_path)
+ files, dirs = self.build_directory_listing(path, filenames, filesystem_path)
r = self.directory_listing_template(
path, files, dirs, breadcrumbs, breadcrumbs_leaf
)
return self.web.add_security_headers(r)
- def build_directory_listing(self, filenames, filesystem_path):
+ def build_directory_listing(self, path, filenames, filesystem_path):
files = []
dirs = []
@@ -142,11 +144,20 @@ def build_directory_listing(self, filenames, filesystem_path):
is_dir = os.path.isdir(this_filesystem_path)
if is_dir:
- dirs.append({"basename": filename})
+ dirs.append(
+ {"link": os.path.join(f"/{path}", filename), "basename": filename}
+ )
else:
size = os.path.getsize(this_filesystem_path)
size_human = self.common.human_readable_filesize(size)
- files.append({"basename": filename, "size_human": size_human})
+ files.append(
+ {
+ "link": os.path.join(f"/{path}", filename),
+ "basename": filename,
+ "size_human": size_human,
+ }
+ )
+
return files, dirs
def stream_individual_file(self, filesystem_path):
diff --git a/cli/onionshare_cli/web/website_mode.py b/cli/onionshare_cli/web/website_mode.py
index ef37ab12b..352f4f3c3 100644
--- a/cli/onionshare_cli/web/website_mode.py
+++ b/cli/onionshare_cli/web/website_mode.py
@@ -71,6 +71,9 @@ def set_file_info_custom(self, filenames, processed_size_callback):
self.web.cancel_compression = True
def render_logic(self, path=""):
+ # Strip trailing slash
+ path = path.rstrip("/")
+
if path in self.files:
filesystem_path = self.files[path]
@@ -86,10 +89,7 @@ def render_logic(self, path=""):
# Otherwise, render directory listing
filenames = []
for filename in os.listdir(filesystem_path):
- if os.path.isdir(os.path.join(filesystem_path, filename)):
- filenames.append(filename + "/")
- else:
- filenames.append(filename)
+ filenames.append(filename)
filenames.sort()
return self.directory_listing(filenames, path, filesystem_path)
diff --git a/cli/poetry.lock b/cli/poetry.lock
index 00331cc47..cdac85650 100644
--- a/cli/poetry.lock
+++ b/cli/poetry.lock
@@ -98,7 +98,7 @@ dotenv = ["python-dotenv"]
[[package]]
name = "flask-httpauth"
-version = "4.1.0"
+version = "4.2.0"
description = "Basic and Digest HTTP authentication for Flask routes"
category = "main"
optional = false
@@ -214,6 +214,17 @@ importlib-metadata = {version = ">=0.12", markers = "python_version < \"3.8\""}
[package.extras]
dev = ["pre-commit", "tox"]
+[[package]]
+name = "psutil"
+version = "5.7.3"
+description = "Cross-platform lib for process and system monitoring in Python."
+category = "main"
+optional = false
+python-versions = ">=2.6, !=3.0.*, !=3.1.*, !=3.2.*, !=3.3.*"
+
+[package.extras]
+test = ["ipaddress", "mock", "unittest2", "enum34", "pywin32", "wmi"]
+
[[package]]
name = "py"
version = "1.9.0"
@@ -302,7 +313,7 @@ client = ["requests (>=2.21.0)", "websocket-client (>=0.54.0)"]
[[package]]
name = "requests"
-version = "2.24.0"
+version = "2.25.0"
description = "Python HTTP for Humans."
category = "main"
optional = false
@@ -312,7 +323,7 @@ python-versions = ">=2.7, !=3.0.*, !=3.1.*, !=3.2.*, !=3.3.*, !=3.4.*"
certifi = ">=2017.4.17"
chardet = ">=3.0.2,<4"
idna = ">=2.5,<3"
-urllib3 = ">=1.21.1,<1.25.0 || >1.25.0,<1.25.1 || >1.25.1,<1.26"
+urllib3 = ">=1.21.1,<1.27"
[package.extras]
security = ["pyOpenSSL (>=0.14)", "cryptography (>=1.3.4)"]
@@ -344,7 +355,7 @@ python-versions = ">=2.6, !=3.0.*, !=3.1.*, !=3.2.*"
[[package]]
name = "urllib3"
-version = "1.25.11"
+version = "1.26.2"
description = "HTTP library with thread-safe connection pooling, file post, and more."
category = "main"
optional = false
@@ -382,7 +393,7 @@ testing = ["pytest (>=3.5,!=3.7.3)", "pytest-checkdocs (>=1.2.3)", "pytest-flake
[metadata]
lock-version = "1.1"
python-versions = "^3.6"
-content-hash = "3947b230139f4b699f40c97e0b90d8c8ab6d3d7ef9093d16d2acb507131e14da"
+content-hash = "38f69a7cfa72b1da17d995e8c33dcceb0568ebfb065439927a5a007f3c8bd873"
[metadata.files]
atomicwrites = [
@@ -422,8 +433,8 @@ flask = [
{file = "Flask-1.1.2.tar.gz", hash = "sha256:4efa1ae2d7c9865af48986de8aeb8504bf32c7f3d6fdc9353d34b21f4b127060"},
]
flask-httpauth = [
- {file = "Flask-HTTPAuth-4.1.0.tar.gz", hash = "sha256:9e028e4375039a49031eb9ecc40be4761f0540476040f6eff329a31dabd4d000"},
- {file = "Flask_HTTPAuth-4.1.0-py2.py3-none-any.whl", hash = "sha256:29e0288869a213c7387f0323b6bf2c7191584fb1da8aa024d9af118e5cd70de7"},
+ {file = "Flask-HTTPAuth-4.2.0.tar.gz", hash = "sha256:8c7e49e53ce7dc14e66fe39b9334e4b7ceb8d0b99a6ba1c3562bb528ef9da84a"},
+ {file = "Flask_HTTPAuth-4.2.0-py2.py3-none-any.whl", hash = "sha256:3fcedb99a03985915335a38c35bfee6765cbd66d7f46440fa3b42ae94a90fac7"},
]
flask-socketio = [
{file = "Flask-SocketIO-4.3.1.tar.gz", hash = "sha256:36c1d5765010d1f4e4f05b4cc9c20c289d9dc70698c88d1addd0afcfedc5b062"},
@@ -512,6 +523,19 @@ pluggy = [
{file = "pluggy-0.13.1-py2.py3-none-any.whl", hash = "sha256:966c145cd83c96502c3c3868f50408687b38434af77734af1e9ca461a4081d2d"},
{file = "pluggy-0.13.1.tar.gz", hash = "sha256:15b2acde666561e1298d71b523007ed7364de07029219b604cf808bfa1c765b0"},
]
+psutil = [
+ {file = "psutil-5.7.3-cp27-none-win32.whl", hash = "sha256:1cd6a0c9fb35ece2ccf2d1dd733c1e165b342604c67454fd56a4c12e0a106787"},
+ {file = "psutil-5.7.3-cp27-none-win_amd64.whl", hash = "sha256:e02c31b2990dcd2431f4524b93491941df39f99619b0d312dfe1d4d530b08b4b"},
+ {file = "psutil-5.7.3-cp35-cp35m-win32.whl", hash = "sha256:56c85120fa173a5d2ad1d15a0c6e0ae62b388bfb956bb036ac231fbdaf9e4c22"},
+ {file = "psutil-5.7.3-cp35-cp35m-win_amd64.whl", hash = "sha256:fa38ac15dbf161ab1e941ff4ce39abd64b53fec5ddf60c23290daed2bc7d1157"},
+ {file = "psutil-5.7.3-cp36-cp36m-win32.whl", hash = "sha256:01bc82813fbc3ea304914581954979e637bcc7084e59ac904d870d6eb8bb2bc7"},
+ {file = "psutil-5.7.3-cp36-cp36m-win_amd64.whl", hash = "sha256:6a3e1fd2800ca45083d976b5478a2402dd62afdfb719b30ca46cd28bb25a2eb4"},
+ {file = "psutil-5.7.3-cp37-cp37m-win32.whl", hash = "sha256:fbcac492cb082fa38d88587d75feb90785d05d7e12d4565cbf1ecc727aff71b7"},
+ {file = "psutil-5.7.3-cp37-cp37m-win_amd64.whl", hash = "sha256:5d9106ff5ec2712e2f659ebbd112967f44e7d33f40ba40530c485cc5904360b8"},
+ {file = "psutil-5.7.3-cp38-cp38-win32.whl", hash = "sha256:ade6af32eb80a536eff162d799e31b7ef92ddcda707c27bbd077238065018df4"},
+ {file = "psutil-5.7.3-cp38-cp38-win_amd64.whl", hash = "sha256:2cb55ef9591b03ef0104bedf67cc4edb38a3edf015cf8cf24007b99cb8497542"},
+ {file = "psutil-5.7.3.tar.gz", hash = "sha256:af73f7bcebdc538eda9cc81d19db1db7bf26f103f91081d780bbacfcb620dee2"},
+]
py = [
{file = "py-1.9.0-py2.py3-none-any.whl", hash = "sha256:366389d1db726cd2fcfc79732e75410e5fe4d31db13692115529d34069a043c2"},
{file = "py-1.9.0.tar.gz", hash = "sha256:9ca6883ce56b4e8da7e79ac18787889fa5206c79dcc67fb065376cd2fe03f342"},
@@ -575,8 +599,8 @@ python-socketio = [
{file = "python_socketio-4.6.0-py2.py3-none-any.whl", hash = "sha256:d437f797c44b6efba2f201867cf02b8c96b97dff26d4e4281ac08b45817cd522"},
]
requests = [
- {file = "requests-2.24.0-py2.py3-none-any.whl", hash = "sha256:fe75cc94a9443b9246fc7049224f75604b113c36acb93f87b80ed42c44cbb898"},
- {file = "requests-2.24.0.tar.gz", hash = "sha256:b3559a131db72c33ee969480840fff4bb6dd111de7dd27c8ee1f820f4f00231b"},
+ {file = "requests-2.25.0-py2.py3-none-any.whl", hash = "sha256:e786fa28d8c9154e6a4de5d46a1d921b8749f8b74e28bde23768e5e16eece998"},
+ {file = "requests-2.25.0.tar.gz", hash = "sha256:7f1a0b932f4a60a1a65caa4263921bb7d9ee911957e0ae4a23a6dd08185ad5f8"},
]
six = [
{file = "six-1.15.0-py2.py3-none-any.whl", hash = "sha256:8b74bedcbbbaca38ff6d7491d76f2b06b3592611af620f8426e82dddb04a5ced"},
@@ -590,8 +614,8 @@ toml = [
{file = "toml-0.10.2.tar.gz", hash = "sha256:b3bda1d108d5dd99f4a20d24d9c348e91c4db7ab1b749200bded2f839ccbe68f"},
]
urllib3 = [
- {file = "urllib3-1.25.11-py2.py3-none-any.whl", hash = "sha256:f5321fbe4bf3fefa0efd0bfe7fb14e90909eb62a48ccda331726b4319897dd5e"},
- {file = "urllib3-1.25.11.tar.gz", hash = "sha256:8d7eaa5a82a1cac232164990f04874c594c9453ec55eef02eab885aa02fc17a2"},
+ {file = "urllib3-1.26.2-py2.py3-none-any.whl", hash = "sha256:d8ff90d979214d7b4f8ce956e80f4028fc6860e4431f731ea4a8c08f23f99473"},
+ {file = "urllib3-1.26.2.tar.gz", hash = "sha256:19188f96923873c92ccb987120ec4acaa12f0461fa9ce5d3d0772bc965a39e08"},
]
werkzeug = [
{file = "Werkzeug-1.0.1-py2.py3-none-any.whl", hash = "sha256:2de2a5db0baeae7b2d2664949077c2ac63fbd16d98da0ff71837f7d1dea3fd43"},
diff --git a/cli/pyproject.toml b/cli/pyproject.toml
index 08206844a..84c9656a1 100644
--- a/cli/pyproject.toml
+++ b/cli/pyproject.toml
@@ -21,6 +21,7 @@ click = "*"
flask = "*"
flask-httpauth = "*"
flask-socketio = "*"
+psutil = "*"
pycryptodome = "*"
pysocks = "*"
requests = "*"
diff --git a/desktop/pyproject.toml b/desktop/pyproject.toml
index d1be9c45a..028f1ec19 100644
--- a/desktop/pyproject.toml
+++ b/desktop/pyproject.toml
@@ -14,7 +14,6 @@ icon = "src/onionshare/resources/onionshare"
sources = ['src/onionshare']
requires = [
"./onionshare_cli-2.3.dev2-py3-none-any.whl",
- "psutil",
"pyside2==5.15.1",
"qrcode"
]
diff --git a/desktop/src/onionshare/gui_common.py b/desktop/src/onionshare/gui_common.py
index 7a32f8eca..f488a7401 100644
--- a/desktop/src/onionshare/gui_common.py
+++ b/desktop/src/onionshare/gui_common.py
@@ -128,7 +128,15 @@ def __init__(self, common, qtapp, local_only):
""",
"server_status_url_buttons": """
QPushButton {
- color: #3f7fcf;
+ border: 1px solid #d3d3d3;
+ border-radius: 4px;
+ background-color: #ffffff;
+ padding: 8px 16px;
+ text-align: center;
+ color: #4e0d4e;
+ }
+ QPushButton:pressed {
+ background-color: qlineargradient(spread:pad, x1:0, y1:0, x2:0, y2:1, stop:0 rgba(255, 255, 255, 255), stop:1 rgba(239, 239, 240, 255))
}
""",
"server_status_button_stopped": """
| 0
|
2dfaedeb4390569af2036a6e4bd8fcc18506de8
|
https://github.com/apache/hadoop/commit/2dfaedeb4390569af2036a6e4bd8fcc18506de8
|
HDFS-10276. HDFS should not expose path info that user has no permission to see. (Yuanbo Liu via Yongjun Zhang)
(cherry picked from commit 5ea6fd85c7aff6df28b87789f607bb57ee920639)
|
diff --git a/hadoop-hdfs-project/hadoop-hdfs/src/main/java/org/apache/hadoop/hdfs/server/namenode/FSPermissionChecker.java b/hadoop-hdfs-project/hadoop-hdfs/src/main/java/org/apache/hadoop/hdfs/server/namenode/FSPermissionChecker.java
index 9edcda13264b..084eeec7668c 100644
--- a/hadoop-hdfs-project/hadoop-hdfs/src/main/java/org/apache/hadoop/hdfs/server/namenode/FSPermissionChecker.java
+++ b/hadoop-hdfs-project/hadoop-hdfs/src/main/java/org/apache/hadoop/hdfs/server/namenode/FSPermissionChecker.java
@@ -196,9 +196,9 @@ void checkPermission(INodesInPath inodesInPath, boolean doCheckOwner,
* Check whether exception e is due to an ancestor inode's not being
* directory.
*/
- private void checkAncestorType(INode[] inodes, int ancestorIndex,
+ private void checkAncestorType(INode[] inodes, int checkedAncestorIndex,
AccessControlException e) throws AccessControlException {
- for (int i = 0; i <= ancestorIndex; i++) {
+ for (int i = 0; i <= checkedAncestorIndex; i++) {
if (inodes[i] == null) {
break;
}
@@ -221,11 +221,8 @@ public void checkPermission(String fsOwner, String supergroup,
throws AccessControlException {
for(; ancestorIndex >= 0 && inodes[ancestorIndex] == null;
ancestorIndex--);
- try {
- checkTraverse(inodeAttrs, path, ancestorIndex);
- } catch (AccessControlException e) {
- checkAncestorType(inodes, ancestorIndex, e);
- }
+
+ checkTraverse(inodeAttrs, inodes, path, ancestorIndex);
final INodeAttributes last = inodeAttrs[inodeAttrs.length - 1];
if (parentAccess != null && parentAccess.implies(FsAction.WRITE)
@@ -276,10 +273,15 @@ private void checkOwner(INodeAttributes inode
}
/** Guarded by {@link FSNamesystem#readLock()} */
- private void checkTraverse(INodeAttributes[] inodes, String path, int last
- ) throws AccessControlException {
- for(int j = 0; j <= last; j++) {
- check(inodes[j], path, FsAction.EXECUTE);
+ private void checkTraverse(INodeAttributes[] inodeAttrs, INode[] inodes,
+ String path, int last) throws AccessControlException {
+ int j = 0;
+ try {
+ for (; j <= last; j++) {
+ check(inodeAttrs[j], path, FsAction.EXECUTE);
+ }
+ } catch (AccessControlException e) {
+ checkAncestorType(inodes, j, e);
}
}
diff --git a/hadoop-hdfs-project/hadoop-hdfs/src/test/java/org/apache/hadoop/hdfs/TestDFSPermission.java b/hadoop-hdfs-project/hadoop-hdfs/src/test/java/org/apache/hadoop/hdfs/TestDFSPermission.java
index 8885ce75f42e..66a0380f92fd 100644
--- a/hadoop-hdfs-project/hadoop-hdfs/src/test/java/org/apache/hadoop/hdfs/TestDFSPermission.java
+++ b/hadoop-hdfs-project/hadoop-hdfs/src/test/java/org/apache/hadoop/hdfs/TestDFSPermission.java
@@ -560,6 +560,19 @@ public FileSystem run() throws Exception {
+ "a directory, when checked on /existing_file/non_existing_name",
e.getMessage().contains("is not a directory"));
}
+
+ rootFs.setPermission(p4, new FsPermission("600"));
+ try {
+ fs.exists(nfpath);
+ fail("The exists call should have failed.");
+ } catch (AccessControlException e) {
+ assertTrue("Permission denied messages must carry file path",
+ e.getMessage().contains(fpath.getName()));
+ assertFalse("Permission denied messages should not specify existing_file"
+ + " is not a directory, since the user does not have permission"
+ + " on /p4",
+ e.getMessage().contains("is not a directory"));
+ }
}
/* Check if namenode performs permission checking correctly
| 1
|
8798b92a6d693063a54d2500757c6c8d8b1c07f0
|
https://github.com/twitter/finagle/commit/8798b92a6d693063a54d2500757c6c8d8b1c07f0
|
finagle-core: Add fixedinet scheme resolution to global Namer
Problem
Name paths with fixed addresses don't need background
DNS updates. But "fixedinet" scheme was not recognized
by global namer and path like "/$/fixedinet/localhost/1234"
was not resolved.
Solution
Add additional checks for "fixedinet" scheme in InetPath
object inside global Namer.
Result
Global namer recognizes both "inet" and "fixedinet" schemes
and uses corresponding Resolver.
Differential Revision: https://phabricator.twitter.biz/D589429
|
diff --git a/CHANGELOG.rst b/CHANGELOG.rst
index 763a86647c..b5d7e15923 100644
--- a/CHANGELOG.rst
+++ b/CHANGELOG.rst
@@ -80,6 +80,9 @@ Bug Fixes
`java.lang.UnsupportedOperationException: tail of empty stream` when a `c.t.f.s.RetryPolicy`
is converted to a String for showing. ``PHAB_ID=D582199``
+* finagle-core: Recognize `fixedinet` name scheme in global `com.twitter.finagle.Namer`.
+ ``PHAB_ID=D589429``
+
20.10.0
-------
diff --git a/finagle-core/src/main/scala/com/twitter/finagle/Namer.scala b/finagle-core/src/main/scala/com/twitter/finagle/Namer.scala
index 5d38ec22e1..e7c9f0ed72 100644
--- a/finagle-core/src/main/scala/com/twitter/finagle/Namer.scala
+++ b/finagle-core/src/main/scala/com/twitter/finagle/Namer.scala
@@ -72,8 +72,8 @@ object Namer {
private[this] object InetPath {
- private[this] def resolve(host: String, port: Int): Var[Addr] =
- Resolver.eval(s"inet!$host:$port") match {
+ private[this] def resolve(scheme: String, host: String, port: Int): Var[Addr] =
+ Resolver.eval(s"$scheme!$host:$port") match {
case Name.Bound(va) => va
case n: Name.Path =>
Var.value(
@@ -82,11 +82,16 @@ object Namer {
}
def unapply(path: Path): Option[(Var[Addr], Path)] = path match {
- case Path.Utf8("$", "inet", host, IntegerString(port), residual @ _*) =>
- Some((resolve(host, port), Path.Utf8(residual: _*)))
- case Path.Utf8("$", "inet", IntegerString(port), residual @ _*) =>
+ case Path.Utf8(
+ "$",
+ scheme @ ("inet" | "fixedinet"),
+ host,
+ IntegerString(port),
+ residual @ _*) =>
+ Some((resolve(scheme, host, port), Path.Utf8(residual: _*)))
+ case Path.Utf8("$", scheme @ ("inet" | "fixedinet"), IntegerString(port), residual @ _*) =>
// no host provided means localhost
- Some((resolve("", port), Path.Utf8(residual: _*)))
+ Some((resolve(scheme, "", port), Path.Utf8(residual: _*)))
case _ => None
}
}
diff --git a/finagle-core/src/test/scala/com/twitter/finagle/NamerTest.scala b/finagle-core/src/test/scala/com/twitter/finagle/NamerTest.scala
index 2226c42bd4..f2d1805802 100644
--- a/finagle-core/src/test/scala/com/twitter/finagle/NamerTest.scala
+++ b/finagle-core/src/test/scala/com/twitter/finagle/NamerTest.scala
@@ -188,6 +188,39 @@ class NamerTest extends FunSuite with AssertionsForJUnit {
}
}
+ test("Namer.global: /$/fixedinet") {
+ Namer.global.lookup(Path.read("/$/fixedinet/1234")).sample() match {
+ case NameTree.Leaf(Name.Bound(addr)) =>
+ assert(addr.sample() == Addr.Bound(Set(Address(1234))))
+ case _ => fail()
+ }
+
+ Await.result(
+ Namer.global.lookup(Path.read("/$/fixedinet/127.0.0.1/1234")).values.toFuture(),
+ 1.second
+ )() match {
+ case NameTree.Leaf(Name.Bound(addr)) =>
+ assert(
+ Await.result(addr.changes.filter(_ != Addr.Pending).toFuture(), 1.second)
+ == Addr.Bound(Set(Address("127.0.0.1", 1234)))
+ )
+ case _ => fail()
+ }
+
+ intercept[ClassNotFoundException] {
+ Namer.global.lookup(Path.read("/$/fixedinet")).sample()
+ }
+
+ Namer.global.lookup(Path.read("/$/fixedinet/1234/foobar")).sample() match {
+ case NameTree.Leaf(bound: Name.Bound) =>
+ assert(bound.addr.sample() == Addr.Bound(Address(1234)))
+ assert(bound.id == Path.Utf8("$", "fixedinet", "1234"))
+ assert(bound.path == Path.Utf8("foobar"))
+
+ case _ => fail()
+ }
+ }
+
test("Namer.global: /$/fail") {
assert(
Namer.global.lookup(Path.read("/$/fail")).sample()
| 0
|
f03b986b4439e20b0fd635109b48afe96cf0099b#diff-37b0d289d6375ba4a7740401950ccdd6R287
|
https://github.com/nov/jose-php/commit/f03b986b4439e20b0fd635109b48afe96cf0099b#diff-37b0d289d6375ba4a7740401950ccdd6R287
|
one more hash_equals, and better CEK decryption error handling
|
diff --git a/src/JOSE/JWE.php b/src/JOSE/JWE.php
index 4bc1923..964d8ce 100644
--- a/src/JOSE/JWE.php
+++ b/src/JOSE/JWE.php
@@ -168,6 +168,8 @@ private function encryptContentEncryptionKey($public_key_or_secret) {
}
private function decryptContentEncryptionKey($private_key_or_secret) {
+ $this->generateContentEncryptionKey(null); # NOTE: run this always not to make timing difference
+ $fake_content_encryption_key = $this->content_encryption_key;
switch ($this->header['alg']) {
case 'RSA1_5':
$rsa = $this->rsa($private_key_or_secret, RSA::ENCRYPTION_PKCS1);
@@ -194,7 +196,7 @@ private function decryptContentEncryptionKey($private_key_or_secret) {
# Not to disclose timing difference between CEK decryption error and others.
# Mitigating Bleichenbacher Attack on PKCS#1 v1.5
# ref.) http://inaz2.hatenablog.com/entry/2016/01/26/222303
- $this->generateContentEncryptionKey(null);
+ $this->content_encryption_key = $fake_content_encryption_key;
}
}
@@ -282,7 +284,7 @@ private function calculateAuthenticationTagCBC($sha_size) {
}
private function checkAuthenticationTag() {
- if ($this->authentication_tag === $this->calculateAuthenticationTag()) {
+ if (hash_equals($this->authentication_tag, $this->calculateAuthenticationTag())) {
return true;
} else {
throw new JOSE_Exception_UnexpectedAlgorithm('Invalid authentication tag');
| 1
|
e6a19454c117a5964bff505567ba7c5afe5d7150
|
https://github.com/h2o/h2o/commit/e6a19454c117a5964bff505567ba7c5afe5d7150
|
Merge pull request #2548 from h2o/kazuho/configurable-iw
[http3] add knob to configure IW
|
diff --git a/deps/quicly/include/quicly.h b/deps/quicly/include/quicly.h
index 91d21dcc9c..98190645cf 100644
--- a/deps/quicly/include/quicly.h
+++ b/deps/quicly/include/quicly.h
@@ -272,6 +272,10 @@ struct st_quicly_context_t {
* maximum number of bytes that can be transmitted on a CRYPTO stream (per each epoch)
*/
uint64_t max_crypto_bytes;
+ /**
+ * initial CWND in terms of packet numbers
+ */
+ uint32_t initcwnd_packets;
/**
* (client-only) Initial QUIC protocol version used by the client. Setting this to a greased version will enforce version
* negotiation.
diff --git a/deps/quicly/include/quicly/cc.h b/deps/quicly/include/quicly/cc.h
index 1185f89d39..031ed51af2 100644
--- a/deps/quicly/include/quicly/cc.h
+++ b/deps/quicly/include/quicly/cc.h
@@ -168,7 +168,7 @@ extern struct st_quicly_init_cc_t quicly_cc_cubic_init;
/**
* Calculates the initial congestion window size given the maximum UDP payload size.
*/
-uint32_t quicly_cc_calc_initial_cwnd(uint16_t max_udp_payload_size);
+uint32_t quicly_cc_calc_initial_cwnd(uint32_t max_packets, uint16_t max_udp_payload_size);
#ifdef __cplusplus
}
diff --git a/deps/quicly/lib/cc-reno.c b/deps/quicly/lib/cc-reno.c
index 583b91d3e0..b1fe1e97d2 100644
--- a/deps/quicly/lib/cc-reno.c
+++ b/deps/quicly/lib/cc-reno.c
@@ -98,13 +98,15 @@ static void reno_init(quicly_init_cc_t *self, quicly_cc_t *cc, uint32_t initcwnd
quicly_init_cc_t quicly_cc_reno_init = {reno_init};
-uint32_t quicly_cc_calc_initial_cwnd(uint16_t max_udp_payload_size)
+uint32_t quicly_cc_calc_initial_cwnd(uint32_t max_packets, uint16_t max_udp_payload_size)
{
- static const uint32_t max_packets = 10, max_bytes = 14720;
- uint32_t cwnd = max_packets * max_udp_payload_size;
- if (cwnd > max_bytes)
- cwnd = max_bytes;
- if (cwnd < QUICLY_MIN_CWND * max_udp_payload_size)
- cwnd = QUICLY_MIN_CWND * max_udp_payload_size;
- return cwnd;
+ static const uint32_t mtu_max = 1472;
+
+ /* apply filters to the two arguments */
+ if (max_packets < QUICLY_MIN_CWND)
+ max_packets = QUICLY_MIN_CWND;
+ if (max_udp_payload_size > mtu_max)
+ max_udp_payload_size = mtu_max;
+
+ return max_packets * max_udp_payload_size;
}
diff --git a/deps/quicly/lib/defaults.c b/deps/quicly/lib/defaults.c
index 074d4ae930..e4a35cab7f 100644
--- a/deps/quicly/lib/defaults.c
+++ b/deps/quicly/lib/defaults.c
@@ -26,6 +26,7 @@
#define DEFAULT_MAX_UDP_PAYLOAD_SIZE 1472
#define DEFAULT_MAX_PACKETS_PER_KEY 16777216
#define DEFAULT_MAX_CRYPTO_BYTES 65536
+#define DEFAULT_INITCWND_PACKETS 10
#define DEFAULT_PRE_VALIDATION_AMPLIFICATION_LIMIT 3
/* profile that employs IETF specified values */
@@ -40,6 +41,7 @@ const quicly_context_t quicly_spec_context = {NULL,
DEFAULT_MAX_UDP_PAYLOAD_SIZE},
DEFAULT_MAX_PACKETS_PER_KEY,
DEFAULT_MAX_CRYPTO_BYTES,
+ DEFAULT_INITCWND_PACKETS,
QUICLY_PROTOCOL_VERSION_CURRENT,
DEFAULT_PRE_VALIDATION_AMPLIFICATION_LIMIT,
0, /* is_clustered */
@@ -67,6 +69,7 @@ const quicly_context_t quicly_performant_context = {NULL,
DEFAULT_MAX_UDP_PAYLOAD_SIZE},
DEFAULT_MAX_PACKETS_PER_KEY,
DEFAULT_MAX_CRYPTO_BYTES,
+ DEFAULT_INITCWND_PACKETS,
QUICLY_PROTOCOL_VERSION_CURRENT,
DEFAULT_PRE_VALIDATION_AMPLIFICATION_LIMIT,
0, /* is_clustered */
@@ -414,7 +417,7 @@ static int default_setup_cipher(quicly_crypto_engine_t *engine, quicly_conn_t *c
ptls_aead_free(*aead_ctx);
*aead_ctx = NULL;
}
- if (*hp_ctx != NULL) {
+ if (hp_ctx != NULL && *hp_ctx != NULL) {
ptls_cipher_free(*hp_ctx);
*hp_ctx = NULL;
}
diff --git a/deps/quicly/lib/quicly.c b/deps/quicly/lib/quicly.c
index 1454ed18fc..9a4fb8b82d 100644
--- a/deps/quicly/lib/quicly.c
+++ b/deps/quicly/lib/quicly.c
@@ -2148,8 +2148,9 @@ int quicly_connect(quicly_conn_t **_conn, quicly_context_t *ctx, const char *ser
}
}
- if ((conn = create_connection(ctx, ctx->initial_version, server_name, dest_addr, src_addr, NULL, new_cid, handshake_properties,
- quicly_cc_calc_initial_cwnd(ctx->transport_params.max_udp_payload_size))) == NULL) {
+ if ((conn = create_connection(
+ ctx, ctx->initial_version, server_name, dest_addr, src_addr, NULL, new_cid, handshake_properties,
+ quicly_cc_calc_initial_cwnd(ctx->initcwnd_packets, ctx->transport_params.max_udp_payload_size))) == NULL) {
ret = PTLS_ERROR_NO_MEMORY;
goto Exit;
}
@@ -2906,7 +2907,8 @@ struct st_quicly_send_context_t {
uint8_t *end;
} payload_buf;
/**
- * the currently available window for sending (in bytes)
+ * Currently available window for sending (in bytes); the value becomes negative when the sender uses more space than permitted.
+ * That happens because the sender operates at packet-level rather than byte-level.
*/
ssize_t send_window;
/**
@@ -3078,7 +3080,8 @@ static int _do_allocate_frame(quicly_conn_t *conn, quicly_send_context_t *s, siz
} else {
if (s->num_datagrams >= s->max_datagrams)
return QUICLY_ERROR_SENDBUF_FULL;
- if (ack_eliciting && s->send_window == 0)
+ /* note: send_window (ssize_t) can become negative; see doc-comment */
+ if (ack_eliciting && s->send_window <= 0)
return QUICLY_ERROR_SENDBUF_FULL;
if (s->payload_buf.end - s->payload_buf.datagram < conn->egress.max_udp_payload_size)
return QUICLY_ERROR_SENDBUF_FULL;
@@ -5485,8 +5488,9 @@ int quicly_accept(quicly_conn_t **conn, quicly_context_t *ctx, struct sockaddr *
}
/* create connection */
- if ((*conn = create_connection(ctx, packet->version, NULL, src_addr, dest_addr, &packet->cid.src, new_cid, handshake_properties,
- quicly_cc_calc_initial_cwnd(ctx->transport_params.max_udp_payload_size))) == NULL) {
+ if ((*conn = create_connection(
+ ctx, packet->version, NULL, src_addr, dest_addr, &packet->cid.src, new_cid, handshake_properties,
+ quicly_cc_calc_initial_cwnd(ctx->initcwnd_packets, ctx->transport_params.max_udp_payload_size))) == NULL) {
ret = PTLS_ERROR_NO_MEMORY;
goto Exit;
}
diff --git a/deps/quicly/src/cli.c b/deps/quicly/src/cli.c
index be2219758b..a87ffc676f 100644
--- a/deps/quicly/src/cli.c
+++ b/deps/quicly/src/cli.c
@@ -1057,6 +1057,7 @@ static void usage(const char *cmd)
" -U size maximum size of UDP datagarm payload\n"
" -V verify peer using the default certificates\n"
" -v verbose mode (-vv emits packet dumps as well)\n"
+ " -w packets initial congestion window (default: 10)\n"
" -x named-group named group to be used (default: secp256r1)\n"
" -X max bidirectional stream count (default: 100)\n"
" -y cipher-suite cipher-suite to be used (default: all)\n"
@@ -1103,7 +1104,7 @@ int main(int argc, char **argv)
address_token_aead.dec = ptls_aead_new(&ptls_openssl_aes128gcm, &ptls_openssl_sha256, 0, secret, "");
}
- while ((ch = getopt(argc, argv, "a:b:B:c:C:Dd:k:Ee:Gi:I:K:l:M:m:NnOp:P:Rr:S:s:u:U:Vvx:X:y:h")) != -1) {
+ while ((ch = getopt(argc, argv, "a:b:B:c:C:Dd:k:Ee:Gi:I:K:l:M:m:NnOp:P:Rr:S:s:u:U:Vvw:x:X:y:h")) != -1) {
switch (ch) {
case 'a':
assert(negotiated_protocols.count < PTLS_ELEMENTSOF(negotiated_protocols.list));
@@ -1252,6 +1253,12 @@ int main(int argc, char **argv)
case 'v':
++verbosity;
break;
+ case 'w':
+ if (sscanf(optarg, "%" SCNu32, &ctx.initcwnd_packets) != 1) {
+ fprintf(stderr, "invalid argument passed to `-w`\n");
+ exit(1);
+ }
+ break;
case 'x': {
size_t i;
for (i = 0; key_exchanges[i] != NULL; ++i)
diff --git a/deps/quicly/t/lossy.c b/deps/quicly/t/lossy.c
index 8c4ec841f0..14cc3ab6f3 100644
--- a/deps/quicly/t/lossy.c
+++ b/deps/quicly/t/lossy.c
@@ -426,14 +426,14 @@ static void test_downstream(void)
subtest("75%", loss_core);
time_spent[i] = quic_now - 1;
}
- loss_check_stats(time_spent, 4, 13812, 3582, 17579);
+ loss_check_stats(time_spent, 4, 14193, 3610, 17579);
for (i = 0; i != 100; ++i) {
init_cond_rand(&loss_cond_down, 1, 2);
subtest("50%", loss_core);
time_spent[i] = quic_now - 1;
}
- loss_check_stats(time_spent, 0, 1941, 608, 3006);
+ loss_check_stats(time_spent, 0, 2220, 608, 2779);
for (i = 0; i != 100; ++i) {
init_cond_rand(&loss_cond_down, 1, 4);
@@ -483,7 +483,7 @@ static void test_bidirectional(void)
subtest("75%", loss_core);
time_spent[i] = quic_now - 1;
}
- loss_check_stats(time_spent, 27, 266649.4, 102052, 649336);
+ loss_check_stats(time_spent, 20, 240012.7, 126541, 652328);
for (i = 0; i != 100; ++i) {
init_cond_rand(&loss_cond_down, 1, 2);
@@ -491,7 +491,7 @@ static void test_bidirectional(void)
subtest("50%", loss_core);
time_spent[i] = quic_now - 1;
}
- loss_check_stats(time_spent, 1, 2283.5, 1171, 6424);
+ loss_check_stats(time_spent, 0, 2286.9, 1175, 6424);
for (i = 0; i != 100; ++i) {
init_cond_rand(&loss_cond_down, 1, 4);
@@ -499,7 +499,7 @@ static void test_bidirectional(void)
subtest("25%", loss_core);
time_spent[i] = quic_now - 1;
}
- loss_check_stats(time_spent, 0, 331, 284, 635);
+ loss_check_stats(time_spent, 0, 328.7, 237, 530);
for (i = 0; i != 100; ++i) {
init_cond_rand(&loss_cond_down, 1, 10);
@@ -507,7 +507,7 @@ static void test_bidirectional(void)
subtest("10%", loss_core);
time_spent[i] = quic_now - 1;
}
- loss_check_stats(time_spent, 0, 151.7, 80, 298);
+ loss_check_stats(time_spent, 0, 150.1, 80, 298);
for (i = 0; i != 100; ++i) {
init_cond_rand(&loss_cond_down, 1, 20);
@@ -515,7 +515,7 @@ static void test_bidirectional(void)
subtest("5%", loss_core);
time_spent[i] = quic_now - 1;
}
- loss_check_stats(time_spent, 0, 110.4, 80, 230);
+ loss_check_stats(time_spent, 0, 103.5, 80, 192);
for (i = 0; i != 100; ++i) {
init_cond_rand(&loss_cond_down, 1, 40);
@@ -523,7 +523,7 @@ static void test_bidirectional(void)
subtest("2.5%", loss_core);
time_spent[i] = quic_now - 1;
}
- loss_check_stats(time_spent, 0, 95.6, 80, 190);
+ loss_check_stats(time_spent, 0, 96.7, 80, 80);
for (i = 0; i != 100; ++i) {
init_cond_rand(&loss_cond_down, 1, 64);
@@ -531,7 +531,7 @@ static void test_bidirectional(void)
subtest("1.6%", loss_core);
time_spent[i] = quic_now - 1;
}
- loss_check_stats(time_spent, 0, 95.8, 80, 190);
+ loss_check_stats(time_spent, 0, 96.7, 80, 190);
}
void test_lossy(void)
diff --git a/src/main.c b/src/main.c
index 7ff5d86e0b..9ce88ff121 100644
--- a/src/main.c
+++ b/src/main.c
@@ -731,7 +731,8 @@ static h2o_iovec_t *build_http2_origin_frame(h2o_configurator_command_t *cmd, yo
}
static int listener_setup_ssl(h2o_configurator_command_t *cmd, h2o_configurator_context_t *ctx, yoml_t *listen_node,
- yoml_t **ssl_node, yoml_t **cc_node, struct listener_config_t *listener, int listener_is_new)
+ yoml_t **ssl_node, yoml_t **cc_node, yoml_t **initcwnd_node, struct listener_config_t *listener,
+ int listener_is_new)
{
SSL_CTX *ssl_ctx = NULL;
yoml_t **certificate_file, **key_file, **dh_file, **min_version, **max_version, **cipher_suite, **ocsp_update_cmd,
@@ -996,6 +997,19 @@ static int listener_setup_ssl(h2o_configurator_command_t *cmd, h2o_configurator_
}
}
+ /* initcwnd */
+ if (initcwnd_node != NULL) {
+ if (listener->quic.ctx == NULL) {
+ /* TCP; skip as there's no way of setting */
+ } else {
+ /* QUIC */
+ uint32_t initcwnd_packets;
+ if (h2o_configurator_scanf(cmd, *initcwnd_node, "%" SCNu32, &initcwnd_packets) != 0)
+ goto Error;
+ listener->quic.ctx->initcwnd_packets = initcwnd_packets;
+ }
+ }
+
pthread_mutex_init(&ssl_config->dynamic.mutex, NULL);
build_ssl_dynamic_data(ssl_config, NULL);
ssl_config->ocsp_stapling.cmd = ocsp_update_cmd != NULL ? h2o_strdup(NULL, (*ocsp_update_cmd)->data.scalar, SIZE_MAX).base
@@ -1365,7 +1379,8 @@ static void on_http3_conn_destroy(h2o_quic_conn_t *conn)
static int on_config_listen(h2o_configurator_command_t *cmd, h2o_configurator_context_t *ctx, yoml_t *node)
{
const char *hostname = NULL, *servname, *type = "tcp";
- yoml_t **ssl_node = NULL, **owner_node = NULL, **permission_node = NULL, **quic_node = NULL, **cc_node = NULL;
+ yoml_t **ssl_node = NULL, **owner_node = NULL, **permission_node = NULL, **quic_node = NULL, **cc_node = NULL,
+ **initcwnd_node = NULL;
int proxy_protocol = 0;
/* fetch servname (and hostname) */
@@ -1375,9 +1390,10 @@ static int on_config_listen(h2o_configurator_command_t *cmd, h2o_configurator_co
break;
case YOML_TYPE_MAPPING: {
yoml_t **port_node, **host_node, **type_node, **proxy_protocol_node;
- if (h2o_configurator_parse_mapping(
- cmd, node, "port:s", "host:s,type:s,owner:s,permission:*,ssl:m,proxy-protocol:*,quic:m,cc:s", &port_node,
- &host_node, &type_node, &owner_node, &permission_node, &ssl_node, &proxy_protocol_node, &quic_node, &cc_node) != 0)
+ if (h2o_configurator_parse_mapping(cmd, node, "port:s",
+ "host:s,type:s,owner:s,permission:*,ssl:m,proxy-protocol:*,quic:m,cc:s,initcwnd:s",
+ &port_node, &host_node, &type_node, &owner_node, &permission_node, &ssl_node,
+ &proxy_protocol_node, &quic_node, &cc_node, &initcwnd_node) != 0)
return -1;
servname = (*port_node)->data.scalar;
if (host_node != NULL)
@@ -1400,6 +1416,8 @@ static int on_config_listen(h2o_configurator_command_t *cmd, h2o_configurator_co
if (cc_node != NULL)
h2o_configurator_errprintf(cmd, *cc_node, "[warning] cannot set congestion controller for unix socket");
+ if (initcwnd_node != NULL)
+ h2o_configurator_errprintf(cmd, *initcwnd_node, "[warning] cannot set initial congestion window for unix socket");
/* unix socket */
struct sockaddr_un sa;
@@ -1438,7 +1456,7 @@ static int on_config_listen(h2o_configurator_command_t *cmd, h2o_configurator_co
} else if (listener->proxy_protocol != proxy_protocol) {
goto ProxyConflict;
}
- if (listener_setup_ssl(cmd, ctx, node, ssl_node, NULL, listener, listener_is_new) != 0)
+ if (listener_setup_ssl(cmd, ctx, node, ssl_node, NULL, NULL, listener, listener_is_new) != 0)
return -1;
if (listener->hosts != NULL && ctx->hostconf != NULL)
h2o_append_to_null_terminated_list((void *)&listener->hosts, ctx->hostconf);
@@ -1451,6 +1469,8 @@ static int on_config_listen(h2o_configurator_command_t *cmd, h2o_configurator_co
h2o_configurator_errprintf(
cmd, *cc_node, "[warning] Setting ignored. TCP congestion controller cannot be set at runtime on this environment");
#endif
+ if (initcwnd_node != NULL)
+ h2o_configurator_errprintf(cmd, *initcwnd_node, "[warning] cannot set initial congestion window for TCP");
struct addrinfo *res, *ai;
if ((res = resolve_address(cmd, node, SOCK_STREAM, IPPROTO_TCP, hostname, servname)) == NULL)
return -1;
@@ -1487,7 +1507,7 @@ static int on_config_listen(h2o_configurator_command_t *cmd, h2o_configurator_co
freeaddrinfo(res);
goto ProxyConflict;
}
- if (listener_setup_ssl(cmd, ctx, node, ssl_node, cc_node, listener, listener_is_new) != 0) {
+ if (listener_setup_ssl(cmd, ctx, node, ssl_node, cc_node, NULL, listener, listener_is_new) != 0) {
freeaddrinfo(res);
return -1;
}
@@ -1575,7 +1595,7 @@ static int on_config_listen(h2o_configurator_command_t *cmd, h2o_configurator_co
}
listener_is_new = 1;
}
- if (listener_setup_ssl(cmd, ctx, node, ssl_node, cc_node, listener, listener_is_new) != 0) {
+ if (listener_setup_ssl(cmd, ctx, node, ssl_node, cc_node, initcwnd_node, listener, listener_is_new) != 0) {
freeaddrinfo(res);
return -1;
}
| 0
|
c90524c34884acf732ccd58e7692d84d105849f9
|
https://github.com/jenkinsci/pmd-plugin/commit/c90524c34884acf732ccd58e7692d84d105849f9
|
Upgrade to analysis-core 1.88.
|
diff --git a/pmd.iml b/pmd.iml
index 6046894..bb39618 100644
--- a/pmd.iml
+++ b/pmd.iml
@@ -13,7 +13,7 @@
</content>
<orderEntry type="inheritedJdk" />
<orderEntry type="sourceFolder" forTests="false" />
- <orderEntry type="module" module-name="analysis-core" />
+ <orderEntry type="library" name="Maven: org.jvnet.hudson.plugins:analysis-core:1.88-SNAPSHOT" level="project" />
<orderEntry type="library" name="Maven: de.java2html:java2html:5.0" level="project" />
<orderEntry type="library" name="Maven: org.apache.commons:commons-lang3:3.3.2" level="project" />
<orderEntry type="library" name="Maven: xerces:xercesImpl:2.11.0" level="project" />
diff --git a/pom.xml b/pom.xml
index 1ea9d64..09cd52c 100644
--- a/pom.xml
+++ b/pom.xml
@@ -38,7 +38,7 @@
<dependency>
<groupId>org.jvnet.hudson.plugins</groupId>
<artifactId>analysis-core</artifactId>
- <version>1.88-SNAPSHOT</version>
+ <version>1.88</version>
</dependency>
<dependency>
<groupId>org.jvnet.hudson.plugins</groupId>
| 0
|
89d991e9461e43a68efc1a0d81a93a66e5bca2c6
|
https://github.com/libtom/libtomcrypt/commit/89d991e9461e43a68efc1a0d81a93a66e5bca2c6
|
add macro name check to helper.pl
|
diff --git a/helper.pl b/helper.pl
index 3bbc48a2b..655bf1f12 100755
--- a/helper.pl
+++ b/helper.pl
@@ -68,6 +68,12 @@ sub check_source {
$l =~ /^static(\s+[a-zA-Z0-9_]+)+\s+([^_][a-zA-Z0-9_]+)\s*\(/) {
push @{$troubles->{staticfunc_name}}, "$lineno($2)";
}
+ if ($file =~ m|src/.*\.[ch]$| && $l =~ /^\s*#\s*define\s+(_[A-Z_][a-zA-Z0-9_]*)\b/) {
+ my $n = $1;
+ push @{$troubles->{invalid_macro_name}}, "$lineno($n)"
+ unless ($file eq 'src/headers/tomcrypt_cfg.h' && $n eq '__has_builtin') ||
+ ($file eq 'src/prngs/rng_get_bytes.c' && $n eq '_WIN32_WINNT');
+ }
$lineno++;
}
for my $k (sort keys %$troubles) {
| 0
|
0c4120fffa3dffe97b95c486a120eded82afe8a6
|
https://github.com/enferex/pdfresurrect/commit/0c4120fffa3dffe97b95c486a120eded82afe8a6
|
Zero and sanity check all dynamic allocs.
This addresses the memory issues in Issue #6 expressed in
calloc_some.pdf and malloc_some.pdf
|
diff --git a/main.c b/main.c
index 9cc40f5..bde5388 100644
--- a/main.c
+++ b/main.c
@@ -72,7 +72,7 @@ static void write_version(
/* Create file */
if ((c = strstr(fname, ".pdf")))
*c = '\0';
- new_fname = malloc(strlen(fname) + strlen(dirname) + 16);
+ new_fname = safe_calloc(strlen(fname) + strlen(dirname) + 16);
snprintf(new_fname, strlen(fname) + strlen(dirname) + 16,
"%s/%s-version-%d.pdf", dirname, fname, xref->version);
@@ -213,6 +213,23 @@ static pdf_t *init_pdf(FILE *fp, const char *name)
}
+void *safe_calloc(size_t size) {
+ void *addr;
+
+ if (!size)
+ {
+ ERR("Invalid allocation size.\n");
+ exit(EXIT_FAILURE);
+ }
+ if (!(addr = calloc(1, size)))
+ {
+ ERR("Failed to allocate requested number of bytes, out of memory?\n");
+ exit(EXIT_FAILURE);
+ }
+ return addr;
+}
+
+
int main(int argc, char **argv)
{
int i, n_valid, do_write, do_scrub;
@@ -295,7 +312,7 @@ int main(int argc, char **argv)
if ((c = strrchr(name, '.')))
*c = '\0';
- dname = malloc(strlen(name) + 16);
+ dname = safe_calloc(strlen(name) + 16);
sprintf(dname, "%s-versions", name);
if (!(dir = opendir(dname)))
mkdir(dname, S_IRWXU);
diff --git a/main.h b/main.h
index 30b504c..c01f70d 100644
--- a/main.h
+++ b/main.h
@@ -40,5 +40,7 @@
#define TAG "[pdfresurrect]"
#define ERR(...) {fprintf(stderr, TAG" -- Error -- " __VA_ARGS__);}
+/* Returns a zero'd buffer of 'size' bytes or exits in failure. */
+extern void *safe_calloc(size_t bytes);
#endif /* MAIN_H_INCLUDE */
diff --git a/pdf.c b/pdf.c
index 81a204b..6debe68 100644
--- a/pdf.c
+++ b/pdf.c
@@ -122,7 +122,7 @@ pdf_t *pdf_new(const char *name)
const char *n;
pdf_t *pdf;
- pdf = calloc(1, sizeof(pdf_t));
+ pdf = safe_calloc(sizeof(pdf_t));
if (name)
{
@@ -132,12 +132,12 @@ pdf_t *pdf_new(const char *name)
else
n = name;
- pdf->name = malloc(strlen(n) + 1);
+ pdf->name = safe_calloc(strlen(n) + 1);
strcpy(pdf->name, n);
}
else /* !name */
{
- pdf->name = malloc(strlen("Unknown") + 1);
+ pdf->name = safe_calloc(strlen("Unknown") + 1);
strcpy(pdf->name, "Unknown");
}
@@ -216,7 +216,7 @@ int pdf_load_xrefs(FILE *fp, pdf_t *pdf)
/* Load in the start/end positions */
fseek(fp, 0, SEEK_SET);
- pdf->xrefs = calloc(1, sizeof(xref_t) * pdf->n_xrefs);
+ pdf->xrefs = safe_calloc(sizeof(xref_t) * pdf->n_xrefs);
ver = 1;
for (i=0; i<pdf->n_xrefs; i++)
{
@@ -314,7 +314,7 @@ void pdf_load_pages_kids(FILE *fp, pdf_t *pdf)
/* Get root catalog */
sz = pdf->xrefs[i].end - ftell(fp);
- buf = malloc(sz + 1);
+ buf = safe_calloc(sz + 1);
SAFE_E(fread(buf, 1, sz, fp), sz, "Failed to load /Root.\n");
buf[sz] = '\0';
if (!(c = strstr(buf, "/Root")))
@@ -444,7 +444,7 @@ void pdf_summarize(
if (name)
{
- dst_name = malloc(strlen(name) * 2 + 16);
+ dst_name = safe_calloc(strlen(name) * 2 + 16);
sprintf(dst_name, "%s/%s", name, name);
if ((c = strrchr(dst_name, '.')) && (strncmp(c, ".pdf", 4) == 0))
@@ -643,7 +643,7 @@ static void load_xref_from_plaintext(FILE *fp, xref_t *xref)
SAFE_E(fread(buf, 1, 21, fp), 21, "Failed to load entry Size string.\n");
xref->n_entries = atoi(buf + strlen("ize "));
- xref->entries = calloc(1, xref->n_entries * sizeof(struct _xref_entry));
+ xref->entries = safe_calloc(xref->n_entries * sizeof(struct _xref_entry));
/* Load entry data */
obj_id = 0;
@@ -810,7 +810,7 @@ static pdf_creator_t *new_creator(int *n_elements)
{"Trapped", ""},
};
- daddy = malloc(sizeof(creator_template));
+ daddy = safe_calloc(sizeof(creator_template));
memcpy(daddy, creator_template, sizeof(creator_template));
if (n_elements)
@@ -1099,8 +1099,7 @@ static char *get_object(
obj_sz = 0; /* Bytes in object */
total_sz = 0; /* Bytes read in */
n_blks = 1;
- data = malloc(blk_sz * n_blks);
- memset(data, 0, blk_sz * n_blks);
+ data = safe_calloc(blk_sz * n_blks);
/* Suck in data */
stream = 0;
@@ -1266,18 +1265,12 @@ static int get_page(int obj_id, const xref_t *xref)
static char *get_header(FILE *fp)
{
- long start;
-
/* First 1024 bytes of doc must be header (1.7 spec pg 1102) */
- char *header;
-
- header = calloc(1, 1024);
-
- start = ftell(fp);
+ char *header = safe_calloc(1024);
+ long start = ftell(fp);
fseek(fp, 0, SEEK_SET);
SAFE_E(fread(header, 1, 1023, fp), 1023, "Failed to load PDF header.\n");
fseek(fp, start, SEEK_SET);
-
return header;
}
@@ -1292,7 +1285,7 @@ static char *decode_text_string(const char *str, size_t str_len)
/* Regular encoding */
if (str[0] == '(')
{
- ascii = malloc(strlen(str) + 1);
+ ascii = safe_calloc(strlen(str) + 1);
strncpy(ascii, str, strlen(str) + 1);
return ascii;
}
@@ -1314,7 +1307,7 @@ static char *decode_text_string(const char *str, size_t str_len)
return NULL;
/* Now decode as hex */
- ascii = malloc(str_len);
+ ascii = safe_calloc(str_len);
for ( ; idx<str_len; ++idx)
{
hex_buf[0] = str[idx++];
| 1
|
d71757c297f56344a51c683bcf2b70c9381e9627
|
https://github.com/hapijs/hapi/commit/d71757c297f56344a51c683bcf2b70c9381e9627
|
20.0.2
|
diff --git a/package.json b/package.json
index b4a360ce1..5bac56775 100755
--- a/package.json
+++ b/package.json
@@ -2,7 +2,7 @@
"name": "@hapi/hapi",
"description": "HTTP Server framework",
"homepage": "https://hapi.dev",
- "version": "20.0.1",
+ "version": "20.0.2",
"repository": "git://github.com/hapijs/hapi",
"main": "lib/index.js",
"engines": {
| 0
|
0a0289086b6a9e5bf1ffb0c58dba3ff5a80800b9
|
https://github.com/rubinius/rubinius/commit/0a0289086b6a9e5bf1ffb0c58dba3ff5a80800b9
|
Updated fileutils.rb for 1.8 and 1.9 to fix security issue.
See http://www.ruby-lang.org/en/news/2011/02/18/fileutils-is-vulnerable-to-symlink-race-attacks/
|
diff --git a/lib/fileutils.rb b/lib/18/fileutils.rb
similarity index 98%
rename from lib/fileutils.rb
rename to lib/18/fileutils.rb
index 85af928df8..f044ae89f5 100644
--- a/lib/fileutils.rb
+++ b/lib/18/fileutils.rb
@@ -216,7 +216,7 @@ def mkdir_p(list, options = {})
begin
fu_mkdir path, options[:mode]
rescue SystemCallError => err
- raise(err) unless File.directory?(path)
+ raise unless File.directory?(path)
end
end
end
@@ -418,6 +418,7 @@ def cp_r(src, dest, options = {})
fu_check_options options, OPT_TABLE['cp_r']
fu_output_message "cp -r#{options[:preserve] ? 'p' : ''}#{options[:remove_destination] ? ' --remove-destination' : ''} #{[src,dest].flatten.join ' '}" if options[:verbose]
return if options[:noop]
+ options = options.dup
options[:dereference_root] = true unless options.key?(:dereference_root)
fu_each_src_dest(src, dest) do |s, d|
copy_entry s, d, options[:preserve], options[:dereference_root], options[:remove_destination]
@@ -657,10 +658,10 @@ def rm_rf(list, options = {})
# removing directories. This requires the current process is the
# owner of the removing whole directory tree, or is the super user (root).
#
- # WARNING: You must ensure that *ALL* parent directories are not
- # world writable. Otherwise this method does not work.
- # Only exception is temporary directory like /tmp and /var/tmp,
- # whose permission is 1777.
+ # WARNING: You must ensure that *ALL* parent directories cannot be
+ # moved by other untrusted users. For example, parent directories
+ # should not be owned by untrusted users, and should not be world
+ # writable except when the sticky bit set.
#
# WARNING: Only the owner of the removing directory tree, or Unix super
# user (root) should invoke this method. Otherwise this method does not
@@ -703,6 +704,11 @@ def remove_entry_secure(path, force = false)
end
f.chown euid, -1
f.chmod 0700
+ unless fu_stat_identical_entry?(st, File.lstat(fullpath))
+ # TOC-to-TOU attack?
+ File.unlink fullpath
+ return
+ end
}
# ---- tree root is frozen ----
root = Entry_.new(path)
@@ -984,6 +990,7 @@ def fu_get_uid(user) #:nodoc:
def fu_get_gid(group) #:nodoc:
return nil unless group
+ group = group.to_s
if /\A\d+\z/ =~ group
then group.to_i
else Etc.getgrnam(group).gid
@@ -1345,7 +1352,7 @@ def postorder_traverse
def have_lchmod?
# This is not MT-safe, but it does not matter.
- if $fileutils_rb_have_lchmod.nil?
+ if $fileutils_rb_have_lchmod == nil
$fileutils_rb_have_lchmod = check_have_lchmod?
end
$fileutils_rb_have_lchmod
@@ -1363,7 +1370,7 @@ def check_have_lchmod?
def have_lchown?
# This is not MT-safe, but it does not matter.
- if $fileutils_rb_have_lchown.nil?
+ if $fileutils_rb_have_lchown == nil
$fileutils_rb_have_lchown = check_have_lchown?
end
$fileutils_rb_have_lchown
@@ -1509,10 +1516,8 @@ def FileUtils.collect_method(opt)
OPT_TABLE.keys.select {|m| OPT_TABLE[m].include?(opt) }
end
- # NOTE: Modified from the original to be compatible with both Ruby 1.8 and 1.9
- # in which #singleton_methods return strings or symbols
- METHODS = singleton_methods.map{|m| m.to_sym} - [:private_module_function,
- :commands, :options, :have_option?, :options_of, :collect_method]
+ METHODS = singleton_methods() - %w( private_module_function
+ commands options have_option? options_of collect_method )
#
# This module has all methods of FileUtils module, but it outputs messages
diff --git a/lib/19/fileutils.rb b/lib/19/fileutils.rb
new file mode 100644
index 0000000000..7cc223c17e
--- /dev/null
+++ b/lib/19/fileutils.rb
@@ -0,0 +1,1606 @@
+#
+# = fileutils.rb
+#
+# Copyright (c) 2000-2007 Minero Aoki
+#
+# This program is free software.
+# You can distribute/modify this program under the same terms of ruby.
+#
+# == module FileUtils
+#
+# Namespace for several file utility methods for copying, moving, removing, etc.
+#
+# === Module Functions
+#
+# cd(dir, options)
+# cd(dir, options) {|dir| .... }
+# pwd()
+# mkdir(dir, options)
+# mkdir(list, options)
+# mkdir_p(dir, options)
+# mkdir_p(list, options)
+# rmdir(dir, options)
+# rmdir(list, options)
+# ln(old, new, options)
+# ln(list, destdir, options)
+# ln_s(old, new, options)
+# ln_s(list, destdir, options)
+# ln_sf(src, dest, options)
+# cp(src, dest, options)
+# cp(list, dir, options)
+# cp_r(src, dest, options)
+# cp_r(list, dir, options)
+# mv(src, dest, options)
+# mv(list, dir, options)
+# rm(list, options)
+# rm_r(list, options)
+# rm_rf(list, options)
+# install(src, dest, mode = <src's>, options)
+# chmod(mode, list, options)
+# chmod_R(mode, list, options)
+# chown(user, group, list, options)
+# chown_R(user, group, list, options)
+# touch(list, options)
+#
+# The <tt>options</tt> parameter is a hash of options, taken from the list
+# <tt>:force</tt>, <tt>:noop</tt>, <tt>:preserve</tt>, and <tt>:verbose</tt>.
+# <tt>:noop</tt> means that no changes are made. The other two are obvious.
+# Each method documents the options that it honours.
+#
+# All methods that have the concept of a "source" file or directory can take
+# either one file or a list of files in that argument. See the method
+# documentation for examples.
+#
+# There are some `low level' methods, which do not accept any option:
+#
+# copy_entry(src, dest, preserve = false, dereference = false)
+# copy_file(src, dest, preserve = false, dereference = true)
+# copy_stream(srcstream, deststream)
+# remove_entry(path, force = false)
+# remove_entry_secure(path, force = false)
+# remove_file(path, force = false)
+# compare_file(path_a, path_b)
+# compare_stream(stream_a, stream_b)
+# uptodate?(file, cmp_list)
+#
+# == module FileUtils::Verbose
+#
+# This module has all methods of FileUtils module, but it outputs messages
+# before acting. This equates to passing the <tt>:verbose</tt> flag to methods
+# in FileUtils.
+#
+# == module FileUtils::NoWrite
+#
+# This module has all methods of FileUtils module, but never changes
+# files/directories. This equates to passing the <tt>:noop</tt> flag to methods
+# in FileUtils.
+#
+# == module FileUtils::DryRun
+#
+# This module has all methods of FileUtils module, but never changes
+# files/directories. This equates to passing the <tt>:noop</tt> and
+# <tt>:verbose</tt> flags to methods in FileUtils.
+#
+
+module FileUtils
+
+ def self.private_module_function(name) #:nodoc:
+ module_function name
+ private_class_method name
+ end
+
+ # This hash table holds command options.
+ OPT_TABLE = {} #:nodoc: internal use only
+
+ #
+ # Options: (none)
+ #
+ # Returns the name of the current directory.
+ #
+ def pwd
+ Dir.pwd
+ end
+ module_function :pwd
+
+ alias getwd pwd
+ module_function :getwd
+
+ #
+ # Options: verbose
+ #
+ # Changes the current directory to the directory +dir+.
+ #
+ # If this method is called with block, resumes to the old
+ # working directory after the block execution finished.
+ #
+ # FileUtils.cd('/', :verbose => true) # chdir and report it
+ #
+ def cd(dir, options = {}, &block) # :yield: dir
+ fu_check_options options, OPT_TABLE['cd']
+ fu_output_message "cd #{dir}" if options[:verbose]
+ Dir.chdir(dir, &block)
+ fu_output_message 'cd -' if options[:verbose] and block
+ end
+ module_function :cd
+
+ alias chdir cd
+ module_function :chdir
+
+ OPT_TABLE['cd'] =
+ OPT_TABLE['chdir'] = [:verbose]
+
+ #
+ # Options: (none)
+ #
+ # Returns true if +newer+ is newer than all +old_list+.
+ # Non-existent files are older than any file.
+ #
+ # FileUtils.uptodate?('hello.o', %w(hello.c hello.h)) or \
+ # system 'make hello.o'
+ #
+ def uptodate?(new, old_list, options = nil)
+ raise ArgumentError, 'uptodate? does not accept any option' if options
+
+ return false unless File.exist?(new)
+ new_time = File.mtime(new)
+ old_list.each do |old|
+ if File.exist?(old)
+ return false unless new_time > File.mtime(old)
+ end
+ end
+ true
+ end
+ module_function :uptodate?
+
+ #
+ # Options: mode noop verbose
+ #
+ # Creates one or more directories.
+ #
+ # FileUtils.mkdir 'test'
+ # FileUtils.mkdir %w( tmp data )
+ # FileUtils.mkdir 'notexist', :noop => true # Does not really create.
+ # FileUtils.mkdir 'tmp', :mode => 0700
+ #
+ def mkdir(list, options = {})
+ fu_check_options options, OPT_TABLE['mkdir']
+ list = fu_list(list)
+ fu_output_message "mkdir #{options[:mode] ? ('-m %03o ' % options[:mode]) : ''}#{list.join ' '}" if options[:verbose]
+ return if options[:noop]
+
+ list.each do |dir|
+ fu_mkdir dir, options[:mode]
+ end
+ end
+ module_function :mkdir
+
+ OPT_TABLE['mkdir'] = [:mode, :noop, :verbose]
+
+ #
+ # Options: mode noop verbose
+ #
+ # Creates a directory and all its parent directories.
+ # For example,
+ #
+ # FileUtils.mkdir_p '/usr/local/lib/ruby'
+ #
+ # causes to make following directories, if it does not exist.
+ # * /usr
+ # * /usr/local
+ # * /usr/local/lib
+ # * /usr/local/lib/ruby
+ #
+ # You can pass several directories at a time in a list.
+ #
+ def mkdir_p(list, options = {})
+ fu_check_options options, OPT_TABLE['mkdir_p']
+ list = fu_list(list)
+ fu_output_message "mkdir -p #{options[:mode] ? ('-m %03o ' % options[:mode]) : ''}#{list.join ' '}" if options[:verbose]
+ return *list if options[:noop]
+
+ list.map {|path| path.sub(%r</\z>, '') }.each do |path|
+ # optimize for the most common case
+ begin
+ fu_mkdir path, options[:mode]
+ next
+ rescue SystemCallError
+ next if File.directory?(path)
+ end
+
+ stack = []
+ until path == stack.last # dirname("/")=="/", dirname("C:/")=="C:/"
+ stack.push path
+ path = File.dirname(path)
+ end
+ stack.reverse_each do |dir|
+ begin
+ fu_mkdir dir, options[:mode]
+ rescue SystemCallError
+ raise unless File.directory?(dir)
+ end
+ end
+ end
+
+ return *list
+ end
+ module_function :mkdir_p
+
+ alias mkpath mkdir_p
+ alias makedirs mkdir_p
+ module_function :mkpath
+ module_function :makedirs
+
+ OPT_TABLE['mkdir_p'] =
+ OPT_TABLE['mkpath'] =
+ OPT_TABLE['makedirs'] = [:mode, :noop, :verbose]
+
+ def fu_mkdir(path, mode) #:nodoc:
+ path = path.sub(%r</\z>, '')
+ if mode
+ Dir.mkdir path, mode
+ File.chmod mode, path
+ else
+ Dir.mkdir path
+ end
+ end
+ private_module_function :fu_mkdir
+
+ #
+ # Options: noop, verbose
+ #
+ # Removes one or more directories.
+ #
+ # FileUtils.rmdir 'somedir'
+ # FileUtils.rmdir %w(somedir anydir otherdir)
+ # # Does not really remove directory; outputs message.
+ # FileUtils.rmdir 'somedir', :verbose => true, :noop => true
+ #
+ def rmdir(list, options = {})
+ fu_check_options options, OPT_TABLE['rmdir']
+ list = fu_list(list)
+ parents = options[:parents]
+ fu_output_message "rmdir #{parents ? '-p ' : ''}#{list.join ' '}" if options[:verbose]
+ return if options[:noop]
+ list.each do |dir|
+ begin
+ Dir.rmdir(dir = dir.sub(%r</\z>, ''))
+ if parents
+ until (parent = File.dirname(dir)) == '.' or parent == dir
+ Dir.rmdir(dir)
+ end
+ end
+ rescue Errno::ENOTEMPTY, Errno::ENOENT
+ end
+ end
+ end
+ module_function :rmdir
+
+ OPT_TABLE['rmdir'] = [:parents, :noop, :verbose]
+
+ #
+ # Options: force noop verbose
+ #
+ # <b><tt>ln(old, new, options = {})</tt></b>
+ #
+ # Creates a hard link +new+ which points to +old+.
+ # If +new+ already exists and it is a directory, creates a link +new/old+.
+ # If +new+ already exists and it is not a directory, raises Errno::EEXIST.
+ # But if :force option is set, overwrite +new+.
+ #
+ # FileUtils.ln 'gcc', 'cc', :verbose => true
+ # FileUtils.ln '/usr/bin/emacs21', '/usr/bin/emacs'
+ #
+ # <b><tt>ln(list, destdir, options = {})</tt></b>
+ #
+ # Creates several hard links in a directory, with each one pointing to the
+ # item in +list+. If +destdir+ is not a directory, raises Errno::ENOTDIR.
+ #
+ # include FileUtils
+ # cd '/sbin'
+ # FileUtils.ln %w(cp mv mkdir), '/bin' # Now /sbin/cp and /bin/cp are linked.
+ #
+ def ln(src, dest, options = {})
+ fu_check_options options, OPT_TABLE['ln']
+ fu_output_message "ln#{options[:force] ? ' -f' : ''} #{[src,dest].flatten.join ' '}" if options[:verbose]
+ return if options[:noop]
+ fu_each_src_dest0(src, dest) do |s,d|
+ remove_file d, true if options[:force]
+ File.link s, d
+ end
+ end
+ module_function :ln
+
+ alias link ln
+ module_function :link
+
+ OPT_TABLE['ln'] =
+ OPT_TABLE['link'] = [:force, :noop, :verbose]
+
+ #
+ # Options: force noop verbose
+ #
+ # <b><tt>ln_s(old, new, options = {})</tt></b>
+ #
+ # Creates a symbolic link +new+ which points to +old+. If +new+ already
+ # exists and it is a directory, creates a symbolic link +new/old+. If +new+
+ # already exists and it is not a directory, raises Errno::EEXIST. But if
+ # :force option is set, overwrite +new+.
+ #
+ # FileUtils.ln_s '/usr/bin/ruby', '/usr/local/bin/ruby'
+ # FileUtils.ln_s 'verylongsourcefilename.c', 'c', :force => true
+ #
+ # <b><tt>ln_s(list, destdir, options = {})</tt></b>
+ #
+ # Creates several symbolic links in a directory, with each one pointing to the
+ # item in +list+. If +destdir+ is not a directory, raises Errno::ENOTDIR.
+ #
+ # If +destdir+ is not a directory, raises Errno::ENOTDIR.
+ #
+ # FileUtils.ln_s Dir.glob('bin/*.rb'), '/home/aamine/bin'
+ #
+ def ln_s(src, dest, options = {})
+ fu_check_options options, OPT_TABLE['ln_s']
+ fu_output_message "ln -s#{options[:force] ? 'f' : ''} #{[src,dest].flatten.join ' '}" if options[:verbose]
+ return if options[:noop]
+ fu_each_src_dest0(src, dest) do |s,d|
+ remove_file d, true if options[:force]
+ File.symlink s, d
+ end
+ end
+ module_function :ln_s
+
+ alias symlink ln_s
+ module_function :symlink
+
+ OPT_TABLE['ln_s'] =
+ OPT_TABLE['symlink'] = [:force, :noop, :verbose]
+
+ #
+ # Options: noop verbose
+ #
+ # Same as
+ # #ln_s(src, dest, :force)
+ #
+ def ln_sf(src, dest, options = {})
+ fu_check_options options, OPT_TABLE['ln_sf']
+ options = options.dup
+ options[:force] = true
+ ln_s src, dest, options
+ end
+ module_function :ln_sf
+
+ OPT_TABLE['ln_sf'] = [:noop, :verbose]
+
+ #
+ # Options: preserve noop verbose
+ #
+ # Copies a file content +src+ to +dest+. If +dest+ is a directory,
+ # copies +src+ to +dest/src+.
+ #
+ # If +src+ is a list of files, then +dest+ must be a directory.
+ #
+ # FileUtils.cp 'eval.c', 'eval.c.org'
+ # FileUtils.cp %w(cgi.rb complex.rb date.rb), '/usr/lib/ruby/1.6'
+ # FileUtils.cp %w(cgi.rb complex.rb date.rb), '/usr/lib/ruby/1.6', :verbose => true
+ # FileUtils.cp 'symlink', 'dest' # copy content, "dest" is not a symlink
+ #
+ def cp(src, dest, options = {})
+ fu_check_options options, OPT_TABLE['cp']
+ fu_output_message "cp#{options[:preserve] ? ' -p' : ''} #{[src,dest].flatten.join ' '}" if options[:verbose]
+ return if options[:noop]
+ fu_each_src_dest(src, dest) do |s, d|
+ copy_file s, d, options[:preserve]
+ end
+ end
+ module_function :cp
+
+ alias copy cp
+ module_function :copy
+
+ OPT_TABLE['cp'] =
+ OPT_TABLE['copy'] = [:preserve, :noop, :verbose]
+
+ #
+ # Options: preserve noop verbose dereference_root remove_destination
+ #
+ # Copies +src+ to +dest+. If +src+ is a directory, this method copies
+ # all its contents recursively. If +dest+ is a directory, copies
+ # +src+ to +dest/src+.
+ #
+ # +src+ can be a list of files.
+ #
+ # # Installing ruby library "mylib" under the site_ruby
+ # FileUtils.rm_r site_ruby + '/mylib', :force
+ # FileUtils.cp_r 'lib/', site_ruby + '/mylib'
+ #
+ # # Examples of copying several files to target directory.
+ # FileUtils.cp_r %w(mail.rb field.rb debug/), site_ruby + '/tmail'
+ # FileUtils.cp_r Dir.glob('*.rb'), '/home/aamine/lib/ruby', :noop => true, :verbose => true
+ #
+ # # If you want to copy all contents of a directory instead of the
+ # # directory itself, c.f. src/x -> dest/x, src/y -> dest/y,
+ # # use following code.
+ # FileUtils.cp_r 'src/.', 'dest' # cp_r('src', 'dest') makes src/dest,
+ # # but this doesn't.
+ #
+ def cp_r(src, dest, options = {})
+ fu_check_options options, OPT_TABLE['cp_r']
+ fu_output_message "cp -r#{options[:preserve] ? 'p' : ''}#{options[:remove_destination] ? ' --remove-destination' : ''} #{[src,dest].flatten.join ' '}" if options[:verbose]
+ return if options[:noop]
+ options = options.dup
+ options[:dereference_root] = true unless options.key?(:dereference_root)
+ fu_each_src_dest(src, dest) do |s, d|
+ copy_entry s, d, options[:preserve], options[:dereference_root], options[:remove_destination]
+ end
+ end
+ module_function :cp_r
+
+ OPT_TABLE['cp_r'] = [:preserve, :noop, :verbose,
+ :dereference_root, :remove_destination]
+
+ #
+ # Copies a file system entry +src+ to +dest+.
+ # If +src+ is a directory, this method copies its contents recursively.
+ # This method preserves file types, c.f. symlink, directory...
+ # (FIFO, device files and etc. are not supported yet)
+ #
+ # Both of +src+ and +dest+ must be a path name.
+ # +src+ must exist, +dest+ must not exist.
+ #
+ # If +preserve+ is true, this method preserves owner, group, permissions
+ # and modified time.
+ #
+ # If +dereference_root+ is true, this method dereference tree root.
+ #
+ # If +remove_destination+ is true, this method removes each destination file before copy.
+ #
+ def copy_entry(src, dest, preserve = false, dereference_root = false, remove_destination = false)
+ Entry_.new(src, nil, dereference_root).traverse do |ent|
+ destent = Entry_.new(dest, ent.rel, false)
+ File.unlink destent.path if remove_destination && File.file?(destent.path)
+ ent.copy destent.path
+ ent.copy_metadata destent.path if preserve
+ end
+ end
+ module_function :copy_entry
+
+ #
+ # Copies file contents of +src+ to +dest+.
+ # Both of +src+ and +dest+ must be a path name.
+ #
+ def copy_file(src, dest, preserve = false, dereference = true)
+ ent = Entry_.new(src, nil, dereference)
+ ent.copy_file dest
+ ent.copy_metadata dest if preserve
+ end
+ module_function :copy_file
+
+ #
+ # Copies stream +src+ to +dest+.
+ # +src+ must respond to #read(n) and
+ # +dest+ must respond to #write(str).
+ #
+ def copy_stream(src, dest)
+ IO.copy_stream(src, dest)
+ end
+ module_function :copy_stream
+
+ #
+ # Options: force noop verbose
+ #
+ # Moves file(s) +src+ to +dest+. If +file+ and +dest+ exist on the different
+ # disk partition, the file is copied then the original file is removed.
+ #
+ # FileUtils.mv 'badname.rb', 'goodname.rb'
+ # FileUtils.mv 'stuff.rb', '/notexist/lib/ruby', :force => true # no error
+ #
+ # FileUtils.mv %w(junk.txt dust.txt), '/home/aamine/.trash/'
+ # FileUtils.mv Dir.glob('test*.rb'), 'test', :noop => true, :verbose => true
+ #
+ def mv(src, dest, options = {})
+ fu_check_options options, OPT_TABLE['mv']
+ fu_output_message "mv#{options[:force] ? ' -f' : ''} #{[src,dest].flatten.join ' '}" if options[:verbose]
+ return if options[:noop]
+ fu_each_src_dest(src, dest) do |s, d|
+ destent = Entry_.new(d, nil, true)
+ begin
+ if destent.exist?
+ if destent.directory?
+ raise Errno::EEXIST, dest
+ else
+ destent.remove_file if rename_cannot_overwrite_file?
+ end
+ end
+ begin
+ File.rename s, d
+ rescue Errno::EXDEV
+ copy_entry s, d, true
+ if options[:secure]
+ remove_entry_secure s, options[:force]
+ else
+ remove_entry s, options[:force]
+ end
+ end
+ rescue SystemCallError
+ raise unless options[:force]
+ end
+ end
+ end
+ module_function :mv
+
+ alias move mv
+ module_function :move
+
+ OPT_TABLE['mv'] =
+ OPT_TABLE['move'] = [:force, :noop, :verbose, :secure]
+
+ def rename_cannot_overwrite_file? #:nodoc:
+ /cygwin|mswin|mingw|bccwin|emx/ =~ RUBY_PLATFORM
+ end
+ private_module_function :rename_cannot_overwrite_file?
+
+ #
+ # Options: force noop verbose
+ #
+ # Remove file(s) specified in +list+. This method cannot remove directories.
+ # All StandardErrors are ignored when the :force option is set.
+ #
+ # FileUtils.rm %w( junk.txt dust.txt )
+ # FileUtils.rm Dir.glob('*.so')
+ # FileUtils.rm 'NotExistFile', :force => true # never raises exception
+ #
+ def rm(list, options = {})
+ fu_check_options options, OPT_TABLE['rm']
+ list = fu_list(list)
+ fu_output_message "rm#{options[:force] ? ' -f' : ''} #{list.join ' '}" if options[:verbose]
+ return if options[:noop]
+
+ list.each do |path|
+ remove_file path, options[:force]
+ end
+ end
+ module_function :rm
+
+ alias remove rm
+ module_function :remove
+
+ OPT_TABLE['rm'] =
+ OPT_TABLE['remove'] = [:force, :noop, :verbose]
+
+ #
+ # Options: noop verbose
+ #
+ # Equivalent to
+ #
+ # #rm(list, :force => true)
+ #
+ def rm_f(list, options = {})
+ fu_check_options options, OPT_TABLE['rm_f']
+ options = options.dup
+ options[:force] = true
+ rm list, options
+ end
+ module_function :rm_f
+
+ alias safe_unlink rm_f
+ module_function :safe_unlink
+
+ OPT_TABLE['rm_f'] =
+ OPT_TABLE['safe_unlink'] = [:noop, :verbose]
+
+ #
+ # Options: force noop verbose secure
+ #
+ # remove files +list+[0] +list+[1]... If +list+[n] is a directory,
+ # removes its all contents recursively. This method ignores
+ # StandardError when :force option is set.
+ #
+ # FileUtils.rm_r Dir.glob('/tmp/*')
+ # FileUtils.rm_r '/', :force => true # :-)
+ #
+ # WARNING: This method causes local vulnerability
+ # if one of parent directories or removing directory tree are world
+ # writable (including /tmp, whose permission is 1777), and the current
+ # process has strong privilege such as Unix super user (root), and the
+ # system has symbolic link. For secure removing, read the documentation
+ # of #remove_entry_secure carefully, and set :secure option to true.
+ # Default is :secure=>false.
+ #
+ # NOTE: This method calls #remove_entry_secure if :secure option is set.
+ # See also #remove_entry_secure.
+ #
+ def rm_r(list, options = {})
+ fu_check_options options, OPT_TABLE['rm_r']
+ # options[:secure] = true unless options.key?(:secure)
+ list = fu_list(list)
+ fu_output_message "rm -r#{options[:force] ? 'f' : ''} #{list.join ' '}" if options[:verbose]
+ return if options[:noop]
+ list.each do |path|
+ if options[:secure]
+ remove_entry_secure path, options[:force]
+ else
+ remove_entry path, options[:force]
+ end
+ end
+ end
+ module_function :rm_r
+
+ OPT_TABLE['rm_r'] = [:force, :noop, :verbose, :secure]
+
+ #
+ # Options: noop verbose secure
+ #
+ # Equivalent to
+ #
+ # #rm_r(list, :force => true)
+ #
+ # WARNING: This method causes local vulnerability.
+ # Read the documentation of #rm_r first.
+ #
+ def rm_rf(list, options = {})
+ fu_check_options options, OPT_TABLE['rm_rf']
+ options = options.dup
+ options[:force] = true
+ rm_r list, options
+ end
+ module_function :rm_rf
+
+ alias rmtree rm_rf
+ module_function :rmtree
+
+ OPT_TABLE['rm_rf'] =
+ OPT_TABLE['rmtree'] = [:noop, :verbose, :secure]
+
+ #
+ # This method removes a file system entry +path+. +path+ shall be a
+ # regular file, a directory, or something. If +path+ is a directory,
+ # remove it recursively. This method is required to avoid TOCTTOU
+ # (time-of-check-to-time-of-use) local security vulnerability of #rm_r.
+ # #rm_r causes security hole when:
+ #
+ # * Parent directory is world writable (including /tmp).
+ # * Removing directory tree includes world writable directory.
+ # * The system has symbolic link.
+ #
+ # To avoid this security hole, this method applies special preprocess.
+ # If +path+ is a directory, this method chown(2) and chmod(2) all
+ # removing directories. This requires the current process is the
+ # owner of the removing whole directory tree, or is the super user (root).
+ #
+ # WARNING: You must ensure that *ALL* parent directories cannot be
+ # moved by other untrusted users. For example, parent directories
+ # should not be owned by untrusted users, and should not be world
+ # writable except when the sticky bit set.
+ #
+ # WARNING: Only the owner of the removing directory tree, or Unix super
+ # user (root) should invoke this method. Otherwise this method does not
+ # work.
+ #
+ # For details of this security vulnerability, see Perl's case:
+ #
+ # http://www.cve.mitre.org/cgi-bin/cvename.cgi?name=CAN-2005-0448
+ # http://www.cve.mitre.org/cgi-bin/cvename.cgi?name=CAN-2004-0452
+ #
+ # For fileutils.rb, this vulnerability is reported in [ruby-dev:26100].
+ #
+ def remove_entry_secure(path, force = false)
+ unless fu_have_symlink?
+ remove_entry path, force
+ return
+ end
+ fullpath = File.expand_path(path)
+ st = File.lstat(fullpath)
+ unless st.directory?
+ File.unlink fullpath
+ return
+ end
+ # is a directory.
+ parent_st = File.stat(File.dirname(fullpath))
+ unless parent_st.world_writable?
+ remove_entry path, force
+ return
+ end
+ unless parent_st.sticky?
+ raise ArgumentError, "parent directory is world writable, FileUtils#remove_entry_secure does not work; abort: #{path.inspect} (parent directory mode #{'%o' % parent_st.mode})"
+ end
+ # freeze tree root
+ euid = Process.euid
+ File.open(fullpath + '/.') {|f|
+ unless fu_stat_identical_entry?(st, f.stat)
+ # symlink (TOC-to-TOU attack?)
+ File.unlink fullpath
+ return
+ end
+ f.chown euid, -1
+ f.chmod 0700
+ unless fu_stat_identical_entry?(st, File.lstat(fullpath))
+ # TOC-to-TOU attack?
+ File.unlink fullpath
+ return
+ end
+ }
+ # ---- tree root is frozen ----
+ root = Entry_.new(path)
+ root.preorder_traverse do |ent|
+ if ent.directory?
+ ent.chown euid, -1
+ ent.chmod 0700
+ end
+ end
+ root.postorder_traverse do |ent|
+ begin
+ ent.remove
+ rescue
+ raise unless force
+ end
+ end
+ rescue
+ raise unless force
+ end
+ module_function :remove_entry_secure
+
+ def fu_have_symlink? #:nodoc
+ File.symlink nil, nil
+ rescue NotImplementedError
+ return false
+ rescue
+ return true
+ end
+ private_module_function :fu_have_symlink?
+
+ def fu_stat_identical_entry?(a, b) #:nodoc:
+ a.dev == b.dev and a.ino == b.ino
+ end
+ private_module_function :fu_stat_identical_entry?
+
+ #
+ # This method removes a file system entry +path+.
+ # +path+ might be a regular file, a directory, or something.
+ # If +path+ is a directory, remove it recursively.
+ #
+ # See also #remove_entry_secure.
+ #
+ def remove_entry(path, force = false)
+ Entry_.new(path).postorder_traverse do |ent|
+ begin
+ ent.remove
+ rescue
+ raise unless force
+ end
+ end
+ rescue
+ raise unless force
+ end
+ module_function :remove_entry
+
+ #
+ # Removes a file +path+.
+ # This method ignores StandardError if +force+ is true.
+ #
+ def remove_file(path, force = false)
+ Entry_.new(path).remove_file
+ rescue
+ raise unless force
+ end
+ module_function :remove_file
+
+ #
+ # Removes a directory +dir+ and its contents recursively.
+ # This method ignores StandardError if +force+ is true.
+ #
+ def remove_dir(path, force = false)
+ remove_entry path, force # FIXME?? check if it is a directory
+ end
+ module_function :remove_dir
+
+ #
+ # Returns true if the contents of a file A and a file B are identical.
+ #
+ # FileUtils.compare_file('somefile', 'somefile') #=> true
+ # FileUtils.compare_file('/bin/cp', '/bin/mv') #=> maybe false
+ #
+ def compare_file(a, b)
+ return false unless File.size(a) == File.size(b)
+ File.open(a, 'rb') {|fa|
+ File.open(b, 'rb') {|fb|
+ return compare_stream(fa, fb)
+ }
+ }
+ end
+ module_function :compare_file
+
+ alias identical? compare_file
+ alias cmp compare_file
+ module_function :identical?
+ module_function :cmp
+
+ #
+ # Returns true if the contents of a stream +a+ and +b+ are identical.
+ #
+ def compare_stream(a, b)
+ bsize = fu_stream_blksize(a, b)
+ sa = sb = nil
+ while sa == sb
+ sa = a.read(bsize)
+ sb = b.read(bsize)
+ unless sa and sb
+ if sa.nil? and sb.nil?
+ return true
+ end
+ end
+ end
+ false
+ end
+ module_function :compare_stream
+
+ #
+ # Options: mode preserve noop verbose
+ #
+ # If +src+ is not same as +dest+, copies it and changes the permission
+ # mode to +mode+. If +dest+ is a directory, destination is +dest+/+src+.
+ # This method removes destination before copy.
+ #
+ # FileUtils.install 'ruby', '/usr/local/bin/ruby', :mode => 0755, :verbose => true
+ # FileUtils.install 'lib.rb', '/usr/local/lib/ruby/site_ruby', :verbose => true
+ #
+ def install(src, dest, options = {})
+ fu_check_options options, OPT_TABLE['install']
+ fu_output_message "install -c#{options[:preserve] && ' -p'}#{options[:mode] ? (' -m 0%o' % options[:mode]) : ''} #{[src,dest].flatten.join ' '}" if options[:verbose]
+ return if options[:noop]
+ fu_each_src_dest(src, dest) do |s, d, st|
+ unless File.exist?(d) and compare_file(s, d)
+ remove_file d, true
+ copy_file s, d
+ File.utime st.atime, st.mtime, d if options[:preserve]
+ File.chmod options[:mode], d if options[:mode]
+ end
+ end
+ end
+ module_function :install
+
+ OPT_TABLE['install'] = [:mode, :preserve, :noop, :verbose]
+
+ #
+ # Options: noop verbose
+ #
+ # Changes permission bits on the named files (in +list+) to the bit pattern
+ # represented by +mode+.
+ #
+ # FileUtils.chmod 0755, 'somecommand'
+ # FileUtils.chmod 0644, %w(my.rb your.rb his.rb her.rb)
+ # FileUtils.chmod 0755, '/usr/bin/ruby', :verbose => true
+ #
+ def chmod(mode, list, options = {})
+ fu_check_options options, OPT_TABLE['chmod']
+ list = fu_list(list)
+ fu_output_message sprintf('chmod %o %s', mode, list.join(' ')) if options[:verbose]
+ return if options[:noop]
+ list.each do |path|
+ Entry_.new(path).chmod mode
+ end
+ end
+ module_function :chmod
+
+ OPT_TABLE['chmod'] = [:noop, :verbose]
+
+ #
+ # Options: noop verbose force
+ #
+ # Changes permission bits on the named files (in +list+)
+ # to the bit pattern represented by +mode+.
+ #
+ # FileUtils.chmod_R 0700, "/tmp/app.#{$$}"
+ #
+ def chmod_R(mode, list, options = {})
+ fu_check_options options, OPT_TABLE['chmod_R']
+ list = fu_list(list)
+ fu_output_message sprintf('chmod -R%s %o %s',
+ (options[:force] ? 'f' : ''),
+ mode, list.join(' ')) if options[:verbose]
+ return if options[:noop]
+ list.each do |root|
+ Entry_.new(root).traverse do |ent|
+ begin
+ ent.chmod mode
+ rescue
+ raise unless options[:force]
+ end
+ end
+ end
+ end
+ module_function :chmod_R
+
+ OPT_TABLE['chmod_R'] = [:noop, :verbose, :force]
+
+ #
+ # Options: noop verbose
+ #
+ # Changes owner and group on the named files (in +list+)
+ # to the user +user+ and the group +group+. +user+ and +group+
+ # may be an ID (Integer/String) or a name (String).
+ # If +user+ or +group+ is nil, this method does not change
+ # the attribute.
+ #
+ # FileUtils.chown 'root', 'staff', '/usr/local/bin/ruby'
+ # FileUtils.chown nil, 'bin', Dir.glob('/usr/bin/*'), :verbose => true
+ #
+ def chown(user, group, list, options = {})
+ fu_check_options options, OPT_TABLE['chown']
+ list = fu_list(list)
+ fu_output_message sprintf('chown %s%s',
+ [user,group].compact.join(':') + ' ',
+ list.join(' ')) if options[:verbose]
+ return if options[:noop]
+ uid = fu_get_uid(user)
+ gid = fu_get_gid(group)
+ list.each do |path|
+ Entry_.new(path).chown uid, gid
+ end
+ end
+ module_function :chown
+
+ OPT_TABLE['chown'] = [:noop, :verbose]
+
+ #
+ # Options: noop verbose force
+ #
+ # Changes owner and group on the named files (in +list+)
+ # to the user +user+ and the group +group+ recursively.
+ # +user+ and +group+ may be an ID (Integer/String) or
+ # a name (String). If +user+ or +group+ is nil, this
+ # method does not change the attribute.
+ #
+ # FileUtils.chown_R 'www', 'www', '/var/www/htdocs'
+ # FileUtils.chown_R 'cvs', 'cvs', '/var/cvs', :verbose => true
+ #
+ def chown_R(user, group, list, options = {})
+ fu_check_options options, OPT_TABLE['chown_R']
+ list = fu_list(list)
+ fu_output_message sprintf('chown -R%s %s%s',
+ (options[:force] ? 'f' : ''),
+ [user,group].compact.join(':') + ' ',
+ list.join(' ')) if options[:verbose]
+ return if options[:noop]
+ uid = fu_get_uid(user)
+ gid = fu_get_gid(group)
+ return unless uid or gid
+ list.each do |root|
+ Entry_.new(root).traverse do |ent|
+ begin
+ ent.chown uid, gid
+ rescue
+ raise unless options[:force]
+ end
+ end
+ end
+ end
+ module_function :chown_R
+
+ OPT_TABLE['chown_R'] = [:noop, :verbose, :force]
+
+ begin
+ require 'etc'
+
+ def fu_get_uid(user) #:nodoc:
+ return nil unless user
+ case user
+ when Integer
+ user
+ when /\A\d+\z/
+ user.to_i
+ else
+ Etc.getpwnam(user).uid
+ end
+ end
+ private_module_function :fu_get_uid
+
+ def fu_get_gid(group) #:nodoc:
+ return nil unless group
+ case group
+ when Integer
+ group
+ when /\A\d+\z/
+ group.to_i
+ else
+ Etc.getgrnam(group).gid
+ end
+ end
+ private_module_function :fu_get_gid
+
+ rescue LoadError
+ # need Win32 support???
+
+ def fu_get_uid(user) #:nodoc:
+ user # FIXME
+ end
+ private_module_function :fu_get_uid
+
+ def fu_get_gid(group) #:nodoc:
+ group # FIXME
+ end
+ private_module_function :fu_get_gid
+ end
+
+ #
+ # Options: noop verbose
+ #
+ # Updates modification time (mtime) and access time (atime) of file(s) in
+ # +list+. Files are created if they don't exist.
+ #
+ # FileUtils.touch 'timestamp'
+ # FileUtils.touch Dir.glob('*.c'); system 'make'
+ #
+ def touch(list, options = {})
+ fu_check_options options, OPT_TABLE['touch']
+ list = fu_list(list)
+ created = nocreate = options[:nocreate]
+ t = options[:mtime]
+ if options[:verbose]
+ fu_output_message "touch #{nocreate ? ' -c' : ''}#{t ? t.strftime(' -t %Y%m%d%H%M.%S') : ''}#{list.join ' '}"
+ end
+ return if options[:noop]
+ list.each do |path|
+ created = nocreate
+ begin
+ File.utime(t, t, path)
+ rescue Errno::ENOENT
+ raise if created
+ File.open(path, 'a') {
+ ;
+ }
+ created = true
+ retry if t
+ end
+ end
+ end
+ module_function :touch
+
+ OPT_TABLE['touch'] = [:noop, :verbose, :mtime, :nocreate]
+
+ private
+
+ module StreamUtils_
+ private
+
+ def fu_windows?
+ /mswin|mingw|bccwin|emx/ =~ RUBY_PLATFORM
+ end
+
+ def fu_copy_stream0(src, dest, blksize = nil) #:nodoc:
+ IO.copy_stream(src, dest)
+ end
+
+ def fu_stream_blksize(*streams)
+ streams.each do |s|
+ next unless s.respond_to?(:stat)
+ size = fu_blksize(s.stat)
+ return size if size
+ end
+ fu_default_blksize()
+ end
+
+ def fu_blksize(st)
+ s = st.blksize
+ return nil unless s
+ return nil if s == 0
+ s
+ end
+
+ def fu_default_blksize
+ 1024
+ end
+ end
+
+ include StreamUtils_
+ extend StreamUtils_
+
+ class Entry_ #:nodoc: internal use only
+ include StreamUtils_
+
+ def initialize(a, b = nil, deref = false)
+ @prefix = @rel = @path = nil
+ if b
+ @prefix = a
+ @rel = b
+ else
+ @path = a
+ end
+ @deref = deref
+ @stat = nil
+ @lstat = nil
+ end
+
+ def inspect
+ "\#<#{self.class} #{path()}>"
+ end
+
+ def path
+ if @path
+ File.path(@path)
+ else
+ join(@prefix, @rel)
+ end
+ end
+
+ def prefix
+ @prefix || @path
+ end
+
+ def rel
+ @rel
+ end
+
+ def dereference?
+ @deref
+ end
+
+ def exist?
+ lstat! ? true : false
+ end
+
+ def file?
+ s = lstat!
+ s and s.file?
+ end
+
+ def directory?
+ s = lstat!
+ s and s.directory?
+ end
+
+ def symlink?
+ s = lstat!
+ s and s.symlink?
+ end
+
+ def chardev?
+ s = lstat!
+ s and s.chardev?
+ end
+
+ def blockdev?
+ s = lstat!
+ s and s.blockdev?
+ end
+
+ def socket?
+ s = lstat!
+ s and s.socket?
+ end
+
+ def pipe?
+ s = lstat!
+ s and s.pipe?
+ end
+
+ S_IF_DOOR = 0xD000
+
+ def door?
+ s = lstat!
+ s and (s.mode & 0xF000 == S_IF_DOOR)
+ end
+
+ def entries
+ opts = {}
+ opts[:encoding] = "UTF-8" if /mswin|mignw/ =~ RUBY_PLATFORM
+ Dir.entries(path(), opts)\
+ .reject {|n| n == '.' or n == '..' }\
+ .map {|n| Entry_.new(prefix(), join(rel(), n.untaint)) }
+ end
+
+ def stat
+ return @stat if @stat
+ if lstat() and lstat().symlink?
+ @stat = File.stat(path())
+ else
+ @stat = lstat()
+ end
+ @stat
+ end
+
+ def stat!
+ return @stat if @stat
+ if lstat! and lstat!.symlink?
+ @stat = File.stat(path())
+ else
+ @stat = lstat!
+ end
+ @stat
+ rescue SystemCallError
+ nil
+ end
+
+ def lstat
+ if dereference?
+ @lstat ||= File.stat(path())
+ else
+ @lstat ||= File.lstat(path())
+ end
+ end
+
+ def lstat!
+ lstat()
+ rescue SystemCallError
+ nil
+ end
+
+ def chmod(mode)
+ if symlink?
+ File.lchmod mode, path() if have_lchmod?
+ else
+ File.chmod mode, path()
+ end
+ end
+
+ def chown(uid, gid)
+ if symlink?
+ File.lchown uid, gid, path() if have_lchown?
+ else
+ File.chown uid, gid, path()
+ end
+ end
+
+ def copy(dest)
+ case
+ when file?
+ copy_file dest
+ when directory?
+ if !File.exist?(dest) and descendant_diretory?(dest, path)
+ raise ArgumentError, "cannot copy directory %s to itself %s" % [path, dest]
+ end
+ begin
+ Dir.mkdir dest
+ rescue
+ raise unless File.directory?(dest)
+ end
+ when symlink?
+ File.symlink File.readlink(path()), dest
+ when chardev?
+ raise "cannot handle device file" unless File.respond_to?(:mknod)
+ mknod dest, ?c, 0666, lstat().rdev
+ when blockdev?
+ raise "cannot handle device file" unless File.respond_to?(:mknod)
+ mknod dest, ?b, 0666, lstat().rdev
+ when socket?
+ raise "cannot handle socket" unless File.respond_to?(:mknod)
+ mknod dest, nil, lstat().mode, 0
+ when pipe?
+ raise "cannot handle FIFO" unless File.respond_to?(:mkfifo)
+ mkfifo dest, 0666
+ when door?
+ raise "cannot handle door: #{path()}"
+ else
+ raise "unknown file type: #{path()}"
+ end
+ end
+
+ def copy_file(dest)
+ File.open(path()) do |s|
+ File.open(dest, 'wb') do |f|
+ IO.copy_stream(s, f)
+ end
+ end
+ end
+
+ def copy_metadata(path)
+ st = lstat()
+ File.utime st.atime, st.mtime, path
+ begin
+ File.chown st.uid, st.gid, path
+ rescue Errno::EPERM
+ # clear setuid/setgid
+ File.chmod st.mode & 01777, path
+ else
+ File.chmod st.mode, path
+ end
+ end
+
+ def remove
+ if directory?
+ remove_dir1
+ else
+ remove_file
+ end
+ end
+
+ def remove_dir1
+ platform_support {
+ Dir.rmdir path().sub(%r</\z>, '')
+ }
+ end
+
+ def remove_file
+ platform_support {
+ File.unlink path
+ }
+ end
+
+ def platform_support
+ return yield unless fu_windows?
+ first_time_p = true
+ begin
+ yield
+ rescue Errno::ENOENT
+ raise
+ rescue => err
+ if first_time_p
+ first_time_p = false
+ begin
+ File.chmod 0700, path() # Windows does not have symlink
+ retry
+ rescue SystemCallError
+ end
+ end
+ raise err
+ end
+ end
+
+ def preorder_traverse
+ stack = [self]
+ while ent = stack.pop
+ yield ent
+ stack.concat ent.entries.reverse if ent.directory?
+ end
+ end
+
+ alias traverse preorder_traverse
+
+ def postorder_traverse
+ if directory?
+ entries().each do |ent|
+ ent.postorder_traverse do |e|
+ yield e
+ end
+ end
+ end
+ yield self
+ end
+
+ private
+
+ $fileutils_rb_have_lchmod = nil
+
+ def have_lchmod?
+ # This is not MT-safe, but it does not matter.
+ if $fileutils_rb_have_lchmod == nil
+ $fileutils_rb_have_lchmod = check_have_lchmod?
+ end
+ $fileutils_rb_have_lchmod
+ end
+
+ def check_have_lchmod?
+ return false unless File.respond_to?(:lchmod)
+ File.lchmod 0
+ return true
+ rescue NotImplementedError
+ return false
+ end
+
+ $fileutils_rb_have_lchown = nil
+
+ def have_lchown?
+ # This is not MT-safe, but it does not matter.
+ if $fileutils_rb_have_lchown == nil
+ $fileutils_rb_have_lchown = check_have_lchown?
+ end
+ $fileutils_rb_have_lchown
+ end
+
+ def check_have_lchown?
+ return false unless File.respond_to?(:lchown)
+ File.lchown nil, nil
+ return true
+ rescue NotImplementedError
+ return false
+ end
+
+ def join(dir, base)
+ return File.path(dir) if not base or base == '.'
+ return File.path(base) if not dir or dir == '.'
+ File.join(dir, base)
+ end
+
+ if File::ALT_SEPARATOR
+ DIRECTORY_TERM = "(?=[/#{Regexp.quote(File::ALT_SEPARATOR)}]|\\z)".freeze
+ else
+ DIRECTORY_TERM = "(?=/|\\z)".freeze
+ end
+ SYSCASE = File::FNM_SYSCASE.nonzero? ? "-i" : ""
+
+ def descendant_diretory?(descendant, ascendant)
+ /\A(?#{SYSCASE}:#{Regexp.quote(ascendant)})#{DIRECTORY_TERM}/ =~ File.dirname(descendant)
+ end
+ end # class Entry_
+
+ def fu_list(arg) #:nodoc:
+ [arg].flatten.map {|path| File.path(path) }
+ end
+ private_module_function :fu_list
+
+ def fu_each_src_dest(src, dest) #:nodoc:
+ fu_each_src_dest0(src, dest) do |s, d|
+ raise ArgumentError, "same file: #{s} and #{d}" if fu_same?(s, d)
+ yield s, d, File.stat(s)
+ end
+ end
+ private_module_function :fu_each_src_dest
+
+ def fu_each_src_dest0(src, dest) #:nodoc:
+ if tmp = Array.try_convert(src)
+ tmp.each do |s|
+ s = File.path(s)
+ yield s, File.join(dest, File.basename(s))
+ end
+ else
+ src = File.path(src)
+ if File.directory?(dest)
+ yield src, File.join(dest, File.basename(src))
+ else
+ yield src, File.path(dest)
+ end
+ end
+ end
+ private_module_function :fu_each_src_dest0
+
+ def fu_same?(a, b) #:nodoc:
+ File.identical?(a, b)
+ end
+ private_module_function :fu_same?
+
+ def fu_check_options(options, optdecl) #:nodoc:
+ h = options.dup
+ optdecl.each do |opt|
+ h.delete opt
+ end
+ raise ArgumentError, "no such option: #{h.keys.join(' ')}" unless h.empty?
+ end
+ private_module_function :fu_check_options
+
+ def fu_update_option(args, new) #:nodoc:
+ if tmp = Hash.try_convert(args.last)
+ args[-1] = tmp.dup.update(new)
+ else
+ args.push new
+ end
+ args
+ end
+ private_module_function :fu_update_option
+
+ @fileutils_output = $stderr
+ @fileutils_label = ''
+
+ def fu_output_message(msg) #:nodoc:
+ @fileutils_output ||= $stderr
+ @fileutils_label ||= ''
+ @fileutils_output.puts @fileutils_label + msg
+ end
+ private_module_function :fu_output_message
+
+ #
+ # Returns an Array of method names which have any options.
+ #
+ # p FileUtils.commands #=> ["chmod", "cp", "cp_r", "install", ...]
+ #
+ def FileUtils.commands
+ OPT_TABLE.keys
+ end
+
+ #
+ # Returns an Array of option names.
+ #
+ # p FileUtils.options #=> ["noop", "force", "verbose", "preserve", "mode"]
+ #
+ def FileUtils.options
+ OPT_TABLE.values.flatten.uniq.map {|sym| sym.to_s }
+ end
+
+ #
+ # Returns true if the method +mid+ have an option +opt+.
+ #
+ # p FileUtils.have_option?(:cp, :noop) #=> true
+ # p FileUtils.have_option?(:rm, :force) #=> true
+ # p FileUtils.have_option?(:rm, :perserve) #=> false
+ #
+ def FileUtils.have_option?(mid, opt)
+ li = OPT_TABLE[mid.to_s] or raise ArgumentError, "no such method: #{mid}"
+ li.include?(opt)
+ end
+
+ #
+ # Returns an Array of option names of the method +mid+.
+ #
+ # p FileUtils.options(:rm) #=> ["noop", "verbose", "force"]
+ #
+ def FileUtils.options_of(mid)
+ OPT_TABLE[mid.to_s].map {|sym| sym.to_s }
+ end
+
+ #
+ # Returns an Array of method names which have the option +opt+.
+ #
+ # p FileUtils.collect_method(:preserve) #=> ["cp", "cp_r", "copy", "install"]
+ #
+ def FileUtils.collect_method(opt)
+ OPT_TABLE.keys.select {|m| OPT_TABLE[m].include?(opt) }
+ end
+
+ METHODS = singleton_methods() - [:private_module_function,
+ :commands, :options, :have_option?, :options_of, :collect_method]
+
+ #
+ # This module has all methods of FileUtils module, but it outputs messages
+ # before acting. This equates to passing the <tt>:verbose</tt> flag to
+ # methods in FileUtils.
+ #
+ module Verbose
+ include FileUtils
+ @fileutils_output = $stderr
+ @fileutils_label = ''
+ ::FileUtils.collect_method(:verbose).each do |name|
+ module_eval(<<-EOS, __FILE__, __LINE__ + 1)
+ def #{name}(*args)
+ super(*fu_update_option(args, :verbose => true))
+ end
+ private :#{name}
+ EOS
+ end
+ extend self
+ class << self
+ ::FileUtils::METHODS.each do |m|
+ public m
+ end
+ end
+ end
+
+ #
+ # This module has all methods of FileUtils module, but never changes
+ # files/directories. This equates to passing the <tt>:noop</tt> flag
+ # to methods in FileUtils.
+ #
+ module NoWrite
+ include FileUtils
+ @fileutils_output = $stderr
+ @fileutils_label = ''
+ ::FileUtils.collect_method(:noop).each do |name|
+ module_eval(<<-EOS, __FILE__, __LINE__ + 1)
+ def #{name}(*args)
+ super(*fu_update_option(args, :noop => true))
+ end
+ private :#{name}
+ EOS
+ end
+ extend self
+ class << self
+ ::FileUtils::METHODS.each do |m|
+ public m
+ end
+ end
+ end
+
+ #
+ # This module has all methods of FileUtils module, but never changes
+ # files/directories, with printing message before acting.
+ # This equates to passing the <tt>:noop</tt> and <tt>:verbose</tt> flag
+ # to methods in FileUtils.
+ #
+ module DryRun
+ include FileUtils
+ @fileutils_output = $stderr
+ @fileutils_label = ''
+ ::FileUtils.collect_method(:noop).each do |name|
+ module_eval(<<-EOS, __FILE__, __LINE__ + 1)
+ def #{name}(*args)
+ super(*fu_update_option(args, :noop => true, :verbose => true))
+ end
+ private :#{name}
+ EOS
+ end
+ extend self
+ class << self
+ ::FileUtils::METHODS.each do |m|
+ public m
+ end
+ end
+ end
+
+end
| 1
|
05fe4bdd1dbe3162abb6efe830bc21bb94c73fa8
|
https://github.com/inspircd/inspircd/commit/05fe4bdd1dbe3162abb6efe830bc21bb94c73fa8
|
Allow disabling connectban for specific connect classes.
Ref: #1841.
|
diff --git a/docs/conf/inspircd.conf.example b/docs/conf/inspircd.conf.example
index 06ad9669da..fecaafdc2d 100644
--- a/docs/conf/inspircd.conf.example
+++ b/docs/conf/inspircd.conf.example
@@ -304,6 +304,10 @@
# in this class. This can save a lot of resources on very busy servers.
resolvehostnames="yes"
+ # useconnectban: Defines if users in this class should be exempt from connectban limits.
+ # This setting only has effect when the connectban module is loaded.
+ #useconnectban="yes"
+
# usednsbl: Defines whether or not users in this class are subject to DNSBL. Default is yes.
# This setting only has effect when the dnsbl module is loaded.
#usednsbl="yes"
diff --git a/src/modules/m_connectban.cpp b/src/modules/m_connectban.cpp
index 81b0fcfa79..b4b16f5394 100644
--- a/src/modules/m_connectban.cpp
+++ b/src/modules/m_connectban.cpp
@@ -61,6 +61,16 @@ class ModuleConnectBan
return 0;
}
+ static bool IsExempt(LocalUser* user)
+ {
+ // E-lined and already banned users shouldn't be hit.
+ if (user->exempt || user->quitting)
+ return true;
+
+ // Users in an exempt class shouldn't be hit.
+ return user->GetClass() && !user->GetClass()->config->getBool("useconnectban", true);
+ }
+
public:
ModuleConnectBan()
: WebIRC::EventListener(this)
@@ -91,7 +101,7 @@ class ModuleConnectBan
void OnWebIRCAuth(LocalUser* user, const WebIRC::FlagMap* flags) CXX11_OVERRIDE
{
- if (user->exempt)
+ if (IsExempt(user))
return;
// HACK: Lower the connection attempts for the gateway IP address. The user
@@ -105,7 +115,7 @@ class ModuleConnectBan
void OnSetUserIP(LocalUser* u) CXX11_OVERRIDE
{
- if (u->exempt || u->quitting)
+ if (IsExempt(u))
return;
irc::sockets::cidr_mask mask(u->client_sa, GetRange(u));
| 0
|
4cf0a9f20b37f977a4338ae0ccac9e8980ee1943
|
https://github.com/apache/ofbiz/commit/4cf0a9f20b37f977a4338ae0ccac9e8980ee1943
|
"Applied fix from trunk for revision: 1377388"
------------------------------------------------------------------------
r1377388 | jleroux | 2012-08-26 10:35:34 +0200 (dim., 26 août 2012) | 1 line
CVE-2012-3506: Unlike descriptions and values, tooltips were not encoded, thanks to Scott for spotting it (r1377382 was flawed)
------------------------------------------------------------------------
git-svn-id: https://svn.apache.org/repos/asf/ofbiz/branches/release12.04@1377389 13f79535-47bb-0310-9956-ffa450edef68
|
diff --git a/framework/widget/src/org/ofbiz/widget/form/ModelFormField.java b/framework/widget/src/org/ofbiz/widget/form/ModelFormField.java
index 7f8805963a..5d9e97f4e5 100644
--- a/framework/widget/src/org/ofbiz/widget/form/ModelFormField.java
+++ b/framework/widget/src/org/ofbiz/widget/form/ModelFormField.java
@@ -953,10 +953,14 @@ public String getSortFieldStyleDesc() {
}
public String getTooltip(Map<String, Object> context) {
- if (UtilValidate.isNotEmpty(tooltip)) return tooltip.expandString(context);
- return "";
+ String tooltipString = "";
+ if (UtilValidate.isNotEmpty(tooltip)) tooltipString = tooltip.expandString(context);
+ if (this.getEncodeOutput()) {
+ StringUtil.SimpleEncoder simpleEncoder = (StringUtil.SimpleEncoder) context.get("simpleEncoder");
+ if (simpleEncoder != null) tooltipString = simpleEncoder.encode(tooltipString);
}
-
+ return tooltipString;
+ }
public String getUseWhen(Map<String, Object> context) {
if (UtilValidate.isNotEmpty(this.useWhen)) return this.useWhen.expandString(context);
| 1
|
1044b43637fa7f70fb19b93593777b78bd20da86
|
https://github.com/vadz/libtiff/commit/1044b43637fa7f70fb19b93593777b78bd20da86
|
* libtiff/tif_pixarlog.c, libtiff/tif_luv.c: fix heap-based buffer
overflow on generation of PixarLog / LUV compressed files, with
ColorMap, TransferFunction attached and nasty plays with bitspersample.
The fix for LUV has not been tested, but suffers from the same kind
of issue of PixarLog.
Reported by Agostino Sarubbo.
Fixes http://bugzilla.maptools.org/show_bug.cgi?id=2604
|
diff --git a/ChangeLog b/ChangeLog
index 0f154d66..93c01f80 100644
--- a/ChangeLog
+++ b/ChangeLog
@@ -1,3 +1,13 @@
+2016-12-03 Even Rouault <even.rouault at spatialys.com>
+
+ * libtiff/tif_pixarlog.c, libtiff/tif_luv.c: fix heap-based buffer
+ overflow on generation of PixarLog / LUV compressed files, with
+ ColorMap, TransferFunction attached and nasty plays with bitspersample.
+ The fix for LUV has not been tested, but suffers from the same kind
+ of issue of PixarLog.
+ Reported by Agostino Sarubbo.
+ Fixes http://bugzilla.maptools.org/show_bug.cgi?id=2604
+
2016-12-02 Even Rouault <even.rouault at spatialys.com>
* tools/tiffcp.c: avoid uint32 underflow in cpDecodedStrips that
diff --git a/libtiff/tif_luv.c b/libtiff/tif_luv.c
index f68a9b13..e6783db5 100644
--- a/libtiff/tif_luv.c
+++ b/libtiff/tif_luv.c
@@ -158,6 +158,7 @@
typedef struct logLuvState LogLuvState;
struct logLuvState {
+ int encoder_state; /* 1 if encoder correctly initialized */
int user_datafmt; /* user data format */
int encode_meth; /* encoding method */
int pixel_size; /* bytes per pixel */
@@ -1552,6 +1553,7 @@ LogLuvSetupEncode(TIFF* tif)
td->td_photometric, "must be either LogLUV or LogL");
break;
}
+ sp->encoder_state = 1;
return (1);
notsupported:
TIFFErrorExt(tif->tif_clientdata, module,
@@ -1563,19 +1565,27 @@ LogLuvSetupEncode(TIFF* tif)
static void
LogLuvClose(TIFF* tif)
{
+ LogLuvState* sp = (LogLuvState*) tif->tif_data;
TIFFDirectory *td = &tif->tif_dir;
+ assert(sp != 0);
/*
* For consistency, we always want to write out the same
* bitspersample and sampleformat for our TIFF file,
* regardless of the data format being used by the application.
* Since this routine is called after tags have been set but
* before they have been recorded in the file, we reset them here.
+ * Note: this is really a nasty approach. See PixarLogClose
*/
- td->td_samplesperpixel =
- (td->td_photometric == PHOTOMETRIC_LOGL) ? 1 : 3;
- td->td_bitspersample = 16;
- td->td_sampleformat = SAMPLEFORMAT_INT;
+ if( sp->encoder_state )
+ {
+ /* See PixarLogClose. Might avoid issues with tags whose size depends
+ * on those below, but not completely sure this is enough. */
+ td->td_samplesperpixel =
+ (td->td_photometric == PHOTOMETRIC_LOGL) ? 1 : 3;
+ td->td_bitspersample = 16;
+ td->td_sampleformat = SAMPLEFORMAT_INT;
+ }
}
static void
diff --git a/libtiff/tif_pixarlog.c b/libtiff/tif_pixarlog.c
index d1246c3d..aa99bc92 100644
--- a/libtiff/tif_pixarlog.c
+++ b/libtiff/tif_pixarlog.c
@@ -1233,8 +1233,10 @@ PixarLogPostEncode(TIFF* tif)
static void
PixarLogClose(TIFF* tif)
{
+ PixarLogState* sp = (PixarLogState*) tif->tif_data;
TIFFDirectory *td = &tif->tif_dir;
+ assert(sp != 0);
/* In a really sneaky (and really incorrect, and untruthful, and
* troublesome, and error-prone) maneuver that completely goes against
* the spirit of TIFF, and breaks TIFF, on close, we covertly
@@ -1243,8 +1245,19 @@ PixarLogClose(TIFF* tif)
* readers that don't know about PixarLog, or how to set
* the PIXARLOGDATFMT pseudo-tag.
*/
- td->td_bitspersample = 8;
- td->td_sampleformat = SAMPLEFORMAT_UINT;
+
+ if (sp->state&PLSTATE_INIT) {
+ /* We test the state to avoid an issue such as in
+ * http://bugzilla.maptools.org/show_bug.cgi?id=2604
+ * What appends in that case is that the bitspersample is 1 and
+ * a TransferFunction is set. The size of the TransferFunction
+ * depends on 1<<bitspersample. So if we increase it, an access
+ * out of the buffer will happen at directory flushing.
+ * Another option would be to clear those targs.
+ */
+ td->td_bitspersample = 8;
+ td->td_sampleformat = SAMPLEFORMAT_UINT;
+ }
}
static void
| 1
|
112f6983fd6a9f94dffc9f05b1a39020c1c95540
|
https://github.com/punbb/punbb/commit/112f6983fd6a9f94dffc9f05b1a39020c1c95540
|
Fixed missing profile identity fieldset hooks
|
diff --git a/profile.php b/profile.php
index a14ca6a0..b5196269 100644
--- a/profile.php
+++ b/profile.php
@@ -2098,7 +2098,9 @@ function extract_elements($allowed_elements)
<span class="fld-input"><input type="url" id="fld<?php echo $forum_page['fld_count'] ?>" name="form[linkedin]" value="<?php echo(isset($form['linkedin']) ? forum_htmlencode($form['linkedin']) : forum_htmlencode($user['linkedin'])) ?>" size="35" maxlength="80" /></span>
</div>
</div>
+<?php ($hook = get_hook('pf_change_details_identity_pre_contact_fieldset_end')) ? eval($hook) : null; ?>
</fieldset>
+<?php ($hook = get_hook('pf_change_details_identity_contact_fieldset_end')) ? eval($hook) : null; ?>
<fieldset class="frm-group group<?php echo ++$forum_page['group_count'] ?>">
<legend class="group-legend"><strong><?php echo $lang_profile['Contact messengers legend'] ?></strong></legend>
<?php ($hook = get_hook('pf_change_details_identity_pre_jabber')) ? eval($hook) : null; ?>
| 0
|
4778965f2158b07ea68b69045af09eb2e9971501
|
https://github.com/drk1wi/portspoof/commit/4778965f2158b07ea68b69045af09eb2e9971501
|
Tweak exit codes
* Add exit code to status action
* Improve relevance of exit codes for various errors
|
diff --git a/system_files/improved/etc/init.d/portspoof b/system_files/improved/etc/init.d/portspoof
index f9e670a..c845fec 100755
--- a/system_files/improved/etc/init.d/portspoof
+++ b/system_files/improved/etc/init.d/portspoof
@@ -81,8 +81,7 @@ get_pid() {
fi
}
-case "$1" in
-start)
+do_start() {
# Ensure that the PIDFILE is still valid.
pid=$(get_pid)
if [ ! -d "/proc/$pid" ]; then
@@ -116,18 +115,18 @@ start)
# Check whether the specified user exists
user_exists=$(id -u "${PS_USER:-root}" &> /dev/null && echo $?)
[ -z "$user_exists" ] \
- && log_failure_msg "User '${PS_USER:-root}' does not exist" && exit 2
+ && log_failure_msg "User '${PS_USER:-root}' does not exist" && exit 124
# Check whether the user can execute the daemon
has_permission=$(sh -c "sudo -n -u \"${PS_USER:-root}\" test -x $DAEMON && echo y" 2> /dev/null)
[ -z "$has_permission" ] \
- && log_failure_msg "User '${PS_USER}' cannot execute $DAEMON" && exit 2
+ && log_failure_msg "User '${PS_USER}' cannot execute $DAEMON" && exit 126
# Check whether config files can be read
[ ! -r "$CONFIG" ] \
- && log_failure_msg "Can't read configuration file" "$CONFIG" && exit 2
+ && log_failure_msg "Can't read configuration file" "$CONFIG" && exit 126
[ ! -r "$SIGNATURES" ] \
- && log_failure_msg "Can't read signatures file" "$SIGNATURES" && exit 2
+ && log_failure_msg "Can't read signatures file" "$SIGNATURES" && exit 126
if [ -z "$PS_USER" ]; then
log_daemon_msg "Starting portspoof"
@@ -152,9 +151,9 @@ start)
exit 2
fi
fi
-;;
+}
-stop)
+do_stop() {
pid=$(get_pid)
if [ ! -z "$pid" ]; then
kill $pid
@@ -167,22 +166,28 @@ stop)
else
log_daemon_msg "portspoof not running"
fi
-;;
+}
-reload)
+do_reload() {
log_daemon_msg "Reloading iptables rules"
setup_iptables
-;;
+}
-restart)
- $0 stop
- $0 start
-;;
+do_restart() {
+ do_stop
+ [ "$?" -eq 0 ] && do_start
+}
+case "$1" in
+start) do_start ;;
+stop) do_stop ;;
+reload) do_reload ;;
+restart) do_restart ;;
status)
- status_of_proc -p "${PIDFILE}" $DAEMON portspoof
+ retval=0
+ status_of_proc -p "${PIDFILE}" $DAEMON portspoof || retval=$?
+ exit $retval
;;
-
*)
log_action_msg "Usage: $0 {start|stop|reload|restart|status}"
exit 1
| 0
|
02dd1975ec61052cb9a17342c9bbec289257b701
|
https://github.com/eclipse/jetty.project/commit/02dd1975ec61052cb9a17342c9bbec289257b701
|
JETTY-1042
git-svn-id: svn+ssh://dev.eclipse.org/svnroot/rt/org.eclipse.jetty/jetty/trunk@438 7e9141cc-0065-0410-87d8-b60c137991c4
|
diff --git a/VERSION.txt b/VERSION.txt
index 3edc0ef961b..12492b8d39b 100644
--- a/VERSION.txt
+++ b/VERSION.txt
@@ -1,5 +1,6 @@
jetty-7.0.0.M4-SNAPSHOT
+ 281059 NPE in QTP with debug on
+ + JETTY-1042 Prevent cookie leak between shared connection
jetty-7.0.0.M3 20 June 2009
+ fixed race with expired async listeners
diff --git a/jetty-server/src/main/java/org/eclipse/jetty/server/CookieCutter.java b/jetty-server/src/main/java/org/eclipse/jetty/server/CookieCutter.java
index d3e98271ad8..7c6a874fe75 100644
--- a/jetty-server/src/main/java/org/eclipse/jetty/server/CookieCutter.java
+++ b/jetty-server/src/main/java/org/eclipse/jetty/server/CookieCutter.java
@@ -39,95 +39,85 @@
private static final byte STATE_UNQUOTED_VALUE = 16;
private Cookie[] _cookies;
- private String[] _fields;
- int _added=0;
- boolean _dirty;
- HttpServletRequest _request;
+ private Cookie[] _lastCookies;
+ Object _lazyFields;
+ int _fields;
public CookieCutter()
- {
-
- }
-
- public CookieCutter(HttpServletRequest request)
- {
- _request = request;
+ {
}
public Cookie[] getCookies()
{
- if (_added>0)
- {
- if (!_dirty && _added==_fields.length)
- {
- // same cookies as last time!
- _added=0;
- return _cookies;
- }
-
+ if (_cookies!=null)
+ return _cookies;
+
+ if (_lastCookies!=null &&
+ _lazyFields!=null &&
+ _fields==LazyList.size(_lazyFields))
+ _cookies=_lastCookies;
+ else
parseFields();
- }
+ _lastCookies=_cookies;
return _cookies;
}
public void setCookies(Cookie[] cookies)
{
- _dirty=false;
- _added=0;
_cookies=cookies;
+ _lastCookies=null;
+ _lazyFields=null;
+ _fields=0;
}
public void reset()
{
- _fields=null;
_cookies=null;
+ _fields=0;
}
public void addCookieField(String f)
{
- if (!_dirty &&
- _fields!=null &&
- _fields.length>_added &&
- _fields[_added].equals(f))
- {
- _added++;
+ if (f==null)
return;
- }
-
- if (_dirty)
- {
- _added++;
- _fields=(String[])LazyList.addToArray(_fields,f,String.class);
- }
- else
+ f=f.trim();
+ if (f.length()==0)
+ return;
+
+ if (LazyList.size(_lazyFields)>_fields)
{
- _dirty=true;
- if (_added>0)
- {
- String[] fields=new String[_added+1];
- System.arraycopy(_fields,0,fields,0,_added);
- fields[_added++]=f;
- _fields=fields;
- }
- else
+ if (f.equals(LazyList.get(_lazyFields,_fields)))
{
- _fields = new String[]{f};
- _added=1;
+ _fields++;
+ return;
}
+ while (LazyList.size(_lazyFields)>_fields)
+ _lazyFields=LazyList.remove(_lazyFields,_fields);
}
+ _cookies=null;
+ _lastCookies=null;
+ _lazyFields=LazyList.add(_lazyFields,_fields++,f);
}
+
protected void parseFields()
{
+ _lastCookies=null;
+ _cookies=null;
+
Object cookies = null;
int version = 0;
+ // delete excess fields
+ while (LazyList.size(_lazyFields)>_fields)
+ _lazyFields=LazyList.remove(_lazyFields,_fields);
+
// For each cookie field
- for (int f=0;f<_added;f++)
+ for (int f=0;f<_fields;f++)
{
- String hdr = _fields[f];
+ String hdr = LazyList.get(_lazyFields,f);
// Parse the header
String name = null;
@@ -152,8 +142,6 @@ protected void parseFields()
case STATE_UNQUOTED_VALUE:
state = STATE_NAME;
value = hdr.substring(tokenstart, i).trim();
- if(_request!=null && _request.isRequestedSessionIdFromURL())
- value = URIUtil.decodePath(value);
tokenstart = i + 1;
break;
case STATE_NAME:
@@ -218,8 +206,6 @@ protected void parseFields()
{
case STATE_UNQUOTED_VALUE:
value = hdr.substring(tokenstart).trim();
- if(_request!=null && _request.isRequestedSessionIdFromURL())
- value = URIUtil.decodePath(value);
break;
case STATE_NAME:
name = hdr.substring(tokenstart);
@@ -276,21 +262,8 @@ else if ("$version".equals(lowercaseName))
}
}
- int l = LazyList.size(cookies);
- if (l>0)
- {
- if (_cookies != null && _cookies.length == l)
- {
- for (int i = 0; i < l; i++)
- _cookies[i] = (Cookie) LazyList.get(cookies, i);
- }
- else
- _cookies = (Cookie[]) LazyList.toArray(cookies,Cookie.class);
- }
-
- _added=0;
- _dirty=false;
-
+ _cookies = (Cookie[]) LazyList.toArray(cookies,Cookie.class);
+ _lastCookies=_cookies;
}
}
diff --git a/jetty-server/src/main/java/org/eclipse/jetty/server/Request.java b/jetty-server/src/main/java/org/eclipse/jetty/server/Request.java
index 9734b04f8bf..53759947d5e 100644
--- a/jetty-server/src/main/java/org/eclipse/jetty/server/Request.java
+++ b/jetty-server/src/main/java/org/eclipse/jetty/server/Request.java
@@ -433,27 +433,24 @@ public String getContextPath()
if (_cookiesExtracted)
return _cookies==null?null:_cookies.getCookies();
+ _cookiesExtracted = true;
+
+ Enumeration enm = _connection.getRequestFields().getValues(HttpHeaders.COOKIE_BUFFER);
+
// Handle no cookies
- if (!_connection.getRequestFields().containsKey(HttpHeaders.COOKIE_BUFFER))
+ if (enm!=null)
{
- _cookiesExtracted = true;
- if (_cookies!=null)
- _cookies.reset();
- return null;
- }
-
- if (_cookies==null)
- _cookies=new CookieCutter(this);
+ if (_cookies==null)
+ _cookies=new CookieCutter();
- Enumeration enm = _connection.getRequestFields().getValues(HttpHeaders.COOKIE_BUFFER);
- while (enm.hasMoreElements())
- {
- String c = (String)enm.nextElement();
- _cookies.addCookieField(c);
+ while (enm.hasMoreElements())
+ {
+ String c = (String)enm.nextElement();
+ _cookies.addCookieField(c);
+ }
}
- _cookiesExtracted=true;
- return _cookies.getCookies();
+ return _cookies==null?null:_cookies.getCookies();
}
/* ------------------------------------------------------------ */
@@ -1308,13 +1305,16 @@ protected void recycle()
if(_attributes!=null)
_attributes.clearAttributes();
_characterEncoding=null;
- _queryEncoding=null;
+ if (_cookies!=null)
+ _cookies.reset();
+ _cookiesExtracted=false;
_context=null;
_serverName=null;
_method=null;
_pathInfo=null;
_port=0;
_protocol=HttpVersions.HTTP_1_1;
+ _queryEncoding=null;
_queryString=null;
_requestedSessionId=null;
_requestedSessionIdFromCookie=false;
@@ -1332,7 +1332,6 @@ protected void recycle()
_paramsExtracted=false;
_inputState=__NONE;
- _cookiesExtracted=false;
if (_savedNewSessions!=null)
_savedNewSessions.clear();
_savedNewSessions=null;
@@ -1571,7 +1570,7 @@ public void setContextPath(String contextPath)
public void setCookies(Cookie[] cookies)
{
if (_cookies==null)
- _cookies=new CookieCutter(this);
+ _cookies=new CookieCutter();
_cookies.setCookies(cookies);
}
| 1
|
4acb6c075d100d6ce8757083ec7382423f2a7126
|
https://github.com/golang/net/commit/4acb6c075d100d6ce8757083ec7382423f2a7126
|
internal/socket: use correct cmsg alignment for netbsd/arm64
netbsd/arm64 requires 128-bit alignment for cmsgs.
Change-Id: I8e45e7d7f6b09d3c128d932dc5a73e3f2bd3a269
Reviewed-on: https://go-review.googlesource.com/c/net/+/258377
Trust: Tobias Klauser <[email protected]>
Trust: Benny Siegert <[email protected]>
Run-TryBot: Tobias Klauser <[email protected]>
TryBot-Result: Go Bot <[email protected]>
Reviewed-by: Benny Siegert <[email protected]>
|
diff --git a/internal/socket/sys_bsdvar.go b/internal/socket/sys_bsdvar.go
index b4f41b552..6e7e3d3cc 100644
--- a/internal/socket/sys_bsdvar.go
+++ b/internal/socket/sys_bsdvar.go
@@ -12,6 +12,9 @@ import (
)
func probeProtocolStack() int {
+ if runtime.GOOS == "netbsd" && runtime.GOARCH == "arm64" {
+ return 16
+ }
if (runtime.GOOS == "netbsd" || runtime.GOOS == "openbsd") && runtime.GOARCH == "arm" {
return 8
}
| 0
|
c27f4945e9be556e5fd84bef1c54d2f5a28903d5
|
https://github.com/rainlab/user-plugin/commit/c27f4945e9be556e5fd84bef1c54d2f5a28903d5
|
Slovenian language updates (#431)
|
diff --git a/lang/sl/lang.php b/lang/sl/lang.php
new file mode 100644
index 0000000..50ed53d
--- /dev/null
+++ b/lang/sl/lang.php
@@ -0,0 +1,222 @@
+<?php
+
+return [
+ 'plugin' => [
+ 'name' => 'Uporabniki',
+ 'description' => 'Upravljanje uporabnikov spletne strani.',
+ 'tab' => 'Uporabniki',
+ 'access_users' => 'Upravljanje uporabnikov',
+ 'access_groups' => 'Upravljanje uporabniških skupin',
+ 'access_settings' => 'Upravljanje uporabniških nastavitev',
+ 'impersonate_user' => 'Impersonacija uporabnikov',
+ ],
+ 'users' => [
+ 'menu_label' => 'Uporabniki',
+ 'all_users' => 'Vsi uporabniki',
+ 'new_user' => 'Nov uporabnik',
+ 'list_title' => 'Upravljanje uporabnikov',
+ 'trashed_hint_title' => 'Uporabnik je deaktiviral svoj račun',
+ 'trashed_hint_desc' => 'Ta uporabnik je deaktiviral svoj račun in se ne želi več pojavljati na spletni strani. Svoj račun lahko kadarkoli obnovi s prijavo.',
+ 'banned_hint_title' => 'Uporabnik je bil blokiran',
+ 'banned_hint_desc' => 'Tega uporabnika je administrator blokiral in se ne more več prijaviti.',
+ 'guest_hint_title' => 'Ta uporabnik je gost',
+ 'guest_hint_desc' => 'Ta uporabnik je shranjen samo za referenčne namene. Če se želi prijaviti, se mora najprej registrirati.',
+ 'activate_warning_title' => 'Uporabnik ni aktiven.',
+ 'activate_warning_desc' => 'Ta uporabnik ni bil aktiviran in se ne more prijaviti.',
+ 'activate_confirm' => 'Ali ste prepričani, da želite aktivirati tega uporabnika?',
+ 'activated_success' => 'Uporabnik je bil aktiviran.',
+ 'activate_manually' => 'Ročno aktivirajte tega uporabnika',
+ 'convert_guest_confirm' => 'Želite gosta spremeniti v uporabnika?',
+ 'convert_guest_manually' => 'Spremeni v registriranega uporabnika',
+ 'convert_guest_success' => 'Uporabnik je bil spremenjen v registriranega uporabnika.',
+ 'impersonate_user' => 'Impersoniraj uporabnika',
+ 'impersonate_confirm' => 'Ali ste prepričani, da želite impersonirati tega uporabnika? V prvotno stanje se lahko vrnete tako, da se odjavite.',
+ 'impersonate_success' => 'Sedaj impersonirate tega uporabnika.',
+ 'delete_confirm' => 'Ali ste prepričani, da želite izbrisati tega uporabnika?',
+ 'unban_user' => 'Odblokiranje uporabnika',
+ 'unban_confirm' => 'Ali ste prepričani, da želite odblokirati tega uporabnika?',
+ 'unbanned_success' => 'Uporabnik je bil odblokiran.',
+ 'return_to_list' => 'Vrni se na seznam uporabnikov',
+ 'update_details' => 'Posodobite podrobnosti',
+ 'bulk_actions' => 'Skupna dejanja',
+ 'delete_selected' => 'Izbriši izbrane',
+ 'delete_selected_confirm' => 'Izbrišem izbrane uporabnike?',
+ 'delete_selected_empty' => 'Ni izbranih uporabnikov za izbris.',
+ 'delete_selected_success' => 'Izbrani uporabniki so bili uspešno izbrisani.',
+ 'activate_selected' => 'Aktiviraj izbrane',
+ 'activate_selected_confirm' => 'Aktiviram izbrane uporabnike?',
+ 'activate_selected_empty' => 'Ni izbranih uporabnikov za aktivacijo.',
+ 'activate_selected_success' => 'Izbrani uporabniki so bili uspešno aktivirani.',
+ 'deactivate_selected' => 'Deaktiviraj izbrane',
+ 'deactivate_selected_confirm' => 'Deaktiviram izbrane uporabnike?',
+ 'deactivate_selected_empty' => 'Ni izbranih uporabnikov za deaktivacijo.',
+ 'deactivate_selected_success' => 'Izbrani uporabniki so bili uspešno deaktivirani.',
+ 'restore_selected' => 'Obnovi izbrane',
+ 'restore_selected_confirm' => 'Obnovim izbrane uporabnike?',
+ 'restore_selected_empty' => 'Ni izbranih uporabnikov za obnovitev.',
+ 'restore_selected_success' => 'Izbrani uporabniki so bili uspešno obnovljeni.',
+ 'ban_selected' => 'Blokiraj izbrane',
+ 'ban_selected_confirm' => 'Blokiram izbrane uporabnike?',
+ 'ban_selected_empty' => 'Ni izbranih uporabnikov za blokado.',
+ 'ban_selected_success' => 'Izbrani uporabniki so bili uspešno blokirani.',
+ 'unban_selected' => 'Odblokiraj izbrane',
+ 'unban_selected_confirm' => 'Odblokiram izbrane uporabnike?',
+ 'unban_selected_empty' => 'Ni izbranih uporabnikov za deblokado.',
+ 'unban_selected_success' => 'Izbrani uporabniki so bili uspešno odblokirani.',
+ 'unsuspend' => 'Odsuspendiraj',
+ 'unsuspend_success' => 'Uporabnik ni več suspendiran.',
+ 'unsuspend_confirm' => 'Odsuspendiram tega uporabnika?',
+ ],
+ 'settings' => [
+ 'users' => 'Uporabniki',
+ 'menu_label' => 'Nastavitve za uporabnike',
+ 'menu_description' => 'Upravljanje z nastavitvami za uporabnike.',
+ 'activation_tab' => 'Aktivacija',
+ 'signin_tab' => 'Prijava',
+ 'registration_tab' => 'Registracija',
+ 'profile_tab' => 'Profil',
+ 'notifications_tab' => 'Obvestila',
+ 'allow_registration' => 'Dovoli registracijo uporabnikov',
+ 'allow_registration_comment' => 'Če je onemogočeno, lahko uporabnike ustvarijo le administratorji.',
+ 'activate_mode' => 'Način aktivacije',
+ 'activate_mode_comment' => 'Izberite, na kakšen način naj bo aktiviran uporabniški račun.',
+ 'activate_mode_auto' => 'Avtomatski',
+ 'activate_mode_auto_comment' => 'Aktivacija je avtomatska in se zgodi takoj po registraciji.',
+ 'activate_mode_user' => 'Uporabniški',
+ 'activate_mode_user_comment' => 'Uporabnik sam aktivira svoj račun z uporabo e-pošte.',
+ 'activate_mode_admin' => 'Administratorski',
+ 'activate_mode_admin_comment' => 'Uporabnika lahko aktivira le administrator.',
+ 'require_activation' => 'Prijava zahteva aktivacijo',
+ 'require_activation_comment' => 'Uporabniki potrebujejo za prijavo aktiviran račun.',
+ 'use_throttle' => 'Blokiranje večkratnih prijav',
+ 'use_throttle_comment' => 'Večkratni ponovljeni neuspešni poskusi prijave bodo uporabnika začasno suspendirali.',
+ 'use_register_throttle' => 'Blokiranje registracij',
+ 'use_register_throttle_comment' => 'Prepreči več zaporednih registracij z istega IP naslova v kratkem času.',
+ 'block_persistence' => 'Prepreči sočasne prijave',
+ 'block_persistence_comment' => 'Če je omogočeno, se uporabniki ne morejo prijaviti v več naprav hkrati.',
+ 'login_attribute' => 'Atribut prijave',
+ 'login_attribute_comment' => 'Izberite, kateri primarni atribut uporabnika naj bo uporabljen za prijavo.',
+ 'remember_login' => 'Zapomni si način prijave',
+ 'remember_login_comment' => 'Določite ali naj bo uporabniška seja obstojna.',
+ 'remember_always' => 'Vedno',
+ 'remember_never' => 'Nikoli',
+ 'remember_ask' => 'Vprašaj uporabnika ob prijavi',
+ ],
+ 'user' => [
+ 'label' => 'Uporabnik',
+ 'id' => 'ID',
+ 'username' => 'Uporabniško ime',
+ 'name' => 'Ime',
+ 'name_empty' => 'Anonimni uporabnik',
+ 'surname' => 'Priimek',
+ 'email' => 'E-pošta',
+ 'created_at' => 'Registriran dne',
+ 'last_seen' => 'Zadnjič viden',
+ 'is_guest' => 'Gost',
+ 'joined' => 'Prijavljen',
+ 'is_online' => 'Trenutno na spletu',
+ 'is_offline' => 'Trenutno ni na spletu',
+ 'send_invite' => 'Pošlji povabilo prek e-pošte',
+ 'send_invite_comment' => 'Pošlje pozdravno sporočilo, ki vsebuje podatke za prijavo.',
+ 'create_password' => 'Geslo',
+ 'create_password_comment' => 'Ustvarite novo geslo, ki se bo uporabljalo za prijavo.',
+ 'reset_password' => 'Ponastavi geslo',
+ 'reset_password_comment' => 'Če želite ponastaviti geslo tega uporabnika, vnesite tukaj novo geslo.',
+ 'confirm_password' => 'Potrditev gesla',
+ 'confirm_password_comment' => 'Za potrditev ponovno vnesite geslo.',
+ 'groups' => 'Skupine',
+ 'empty_groups' => 'Ni uporabniških skupin.',
+ 'avatar' => 'Avatar',
+ 'details' => 'Podrobnosti',
+ 'account' => 'Račun',
+ 'block_mail' => 'Blokiraj vso odhodno pošto, poslano temu uporabniku.',
+ 'status_guest' => 'Gost',
+ 'status_activated' => 'Aktiviran',
+ 'status_registered' => 'Registriran',
+ 'created_ip_address' => 'Ustvarjen IP naslov',
+ 'last_ip_address' => 'Zadnji IP naslov',
+ ],
+ 'group' => [
+ 'label' => 'Skupina',
+ 'id' => 'ID',
+ 'name' => 'Ime',
+ 'description_field' => 'Opis',
+ 'code' => 'Koda',
+ 'code_comment' => 'Vnesite unikatno kodo za identifikacijo te skupine.',
+ 'created_at' => 'Ustvarjeno',
+ 'users_count' => 'Uporabniki',
+ ],
+ 'groups' => [
+ 'menu_label' => 'Skupine',
+ 'all_groups' => 'Skupine uporabnikov',
+ 'new_group' => 'Nova skupina',
+ 'delete_selected_confirm' => 'Ali ste prepričani, da želite izbrisati izbrane skupine?',
+ 'list_title' => 'Upravljanje skupin',
+ 'delete_confirm' => 'Ali ste prepričani, da želite izbrisati to skupino?',
+ 'delete_selected_success' => 'Izbrane skupine so uspešno izbrisane.',
+ 'delete_selected_empty' => 'Ni izbranih skupin za izbris.',
+ 'return_to_list' => 'Nazaj na seznam skupin',
+ 'return_to_users' => 'Nazaj na seznam uporabnikov',
+ 'create_title' => 'Ustvari skupino uporabnikov',
+ 'update_title' => 'Uredi skupino uporabnikov',
+ 'preview_title' => 'Predogled skupine uporabnikov',
+ ],
+ 'login' => [
+ 'attribute_email' => 'E-pošta',
+ 'attribute_username' => 'Uporabniško ime',
+ ],
+ 'account' => [
+ 'account' => 'Račun',
+ 'account_desc' => 'Upravljanje uporabnika.',
+ 'banned' => 'Oprostite, ta uporabnik trenutno ni aktiviran. Prosimo, kontaktirajte nas za nadaljnjo pomoč.',
+ 'redirect_to' => 'Preusmeritev na',
+ 'redirect_to_desc' => 'Stran, na katero bo uporabnik preusmerjen po posodobitvi profila, po prijavi ali po registraciji.',
+ 'code_param' => 'Parameter aktivacijske kode',
+ 'code_param_desc' => 'Parameter v URL-ju strani, ki se uporablja za aktivacijsko kodo registracije.',
+ 'force_secure' => 'Vsili zaščitni protokol',
+ 'force_secure_desc' => 'URL vedno preusmeri s shemo HTTPS.',
+ 'invalid_user' => 'Uporabnika ni mogoče najti glede na podane poverilnice.',
+ 'invalid_activation_code' => 'Podana je neveljavna aktivacijska koda.',
+ 'invalid_deactivation_pass' => 'Geslo, ki ste ga vnesli, je neveljavno.',
+ 'invalid_current_pass' => 'Trenutno geslo, ki ste ga vnesli, je neveljavno.',
+ 'success_activation' => 'Vaš račun je uspešno aktiviran.',
+ 'success_deactivation' => 'Vaš račun je bil uspešno deaktiviran. Žal nam je, ker nas zapuščate!',
+ 'success_saved' => 'Nastavitve so uspešno shranjene.',
+ 'login_first' => 'Najprej se morate prijaviti.',
+ 'already_active' => 'Vaš račun je že aktiviran.',
+ 'activation_email_sent' => 'Aktivacijsko sporočilo je bilo poslano na vaš e-poštni naslov.',
+ 'registration_disabled' => 'Registracije so trenutno onemogočene.',
+ 'registration_throttled' => 'Registracija je trenutno onemogočena. Prosimo, poskusite zopet kasneje.',
+ 'sign_in' => 'Prijava',
+ 'register' => 'Registracija',
+ 'full_name' => 'Polno ime',
+ 'email' => 'E-pošta',
+ 'password' => 'Geslo',
+ 'login' => 'Prijava',
+ 'new_password' => 'Novo geslo',
+ 'new_password_confirm' => 'Potrdite novo geslo',
+ 'update_requires_password' => 'Posodobitev zahteva potrditev gesla',
+ 'update_requires_password_comment' => 'Pri spreminjanju profila od uporabnika zahteva trenutno geslo.',
+ ],
+ 'reset_password' => [
+ 'reset_password' => 'Ponastavitev gesla',
+ 'reset_password_desc' => 'Obrazec za pozabljeno geslo.',
+ 'code_param' => 'Parameter za ponastavitev',
+ 'code_param_desc' => 'Parameter v URL-ju strani, ki se uporablja za ponastavitev gesla.',
+ ],
+ 'session' => [
+ 'session' => 'Seja',
+ 'session_desc' => 'Namestitev uporabniške seje, ki lahko omeji dostop do strani.',
+ 'security_title' => 'Dovoljenje za dostop',
+ 'security_desc' => 'Določite, kdo lahko dostopa do te strani.',
+ 'all' => 'Vsi',
+ 'users' => 'Uporabniki',
+ 'guests' => 'Gosti',
+ 'allowed_groups_title' => 'Dovoljenje za skupine',
+ 'allowed_groups_description' => 'Določite, katere skupine lahko dostopajo do te strani. Če ne izberete nobene, imajo dovoljenje vse skupine.',
+ 'redirect_title' => 'Preusmeritev na stran',
+ 'redirect_desc' => 'Določite stran, na katero je preusmerjen uporabnik, če je dostop onemogočen.',
+ 'logout' => 'Uspešno ste se odjavili.',
+ 'stop_impersonate_success' => 'Uporabnika ne impersonirate več.',
+ ],
+];
| 0
|
1221c5e93a0e88e8a4c75927d359cb0689cf9d95
|
https://github.com/rofl0r/proxychains-ng/commit/1221c5e93a0e88e8a4c75927d359cb0689cf9d95
|
get_chain_data: fix strstr() config parsing
using strstr() is a very error-prone way for config parsing.
for example if "proxy_dns" is being tested for the line "proxy_dns_old",
it would return true.
we fix this by removing leading and trailing whitespace from the line
to parse and use strcmp/strncmp() instead.
the if(1) has been inserted so we can keep the same indentation level
and not spam the commit with whitespace changes.
|
diff --git a/src/libproxychains.c b/src/libproxychains.c
index ad75636..8cdfbce 100644
--- a/src/libproxychains.c
+++ b/src/libproxychains.c
@@ -22,6 +22,7 @@
#include <unistd.h>
#include <stdlib.h>
#include <string.h>
+#include <ctype.h>
#include <errno.h>
#include <assert.h>
#include <netdb.h>
@@ -270,11 +271,12 @@ static const char* bool_str(int bool_val) {
return "false";
}
+#define STR_STARTSWITH(P, LIT) (!strncmp(P, LIT, sizeof(LIT)-1))
/* get configuration from config file */
static void get_chain_data(proxy_data * pd, unsigned int *proxy_count, chain_type * ct) {
int count = 0, port_n = 0, list = 0;
- char buff[1024], type[1024], host[1024], user[1024];
- char *env;
+ char buf[1024], type[1024], host[1024], user[1024];
+ char *buff, *env, *p;
char local_in_addr_port[32];
char local_in_addr[32], local_in_port[32], local_netmask[32];
char dnat_orig_addr_port[32], dnat_new_addr_port[32];
@@ -291,7 +293,7 @@ static void get_chain_data(proxy_data * pd, unsigned int *proxy_count, chain_typ
tcp_connect_time_out = 10 * 1000;
*ct = DYNAMIC_TYPE;
- env = get_config_path(getenv(PROXYCHAINS_CONF_FILE_ENV_VAR), buff, sizeof(buff));
+ env = get_config_path(getenv(PROXYCHAINS_CONF_FILE_ENV_VAR), buf, sizeof(buf));
if( ( file = fopen(env, "r") ) == NULL )
{
perror("couldnt read configuration file");
@@ -302,8 +304,17 @@ static void get_chain_data(proxy_data * pd, unsigned int *proxy_count, chain_typ
if(env && *env == '1')
proxychains_quiet_mode = 1;
- while(fgets(buff, sizeof(buff), file)) {
- if(buff[0] != '\n' && buff[strspn(buff, " ")] != '#') {
+ while(fgets(buf, sizeof(buf), file)) {
+ buff = buf;
+ /* remove leading whitespace */
+ while(isspace(*buff)) buff++;
+ /* remove trailing '\n' */
+ if((p = strrchr(buff, '\n'))) *p = 0;
+ p = buff + strlen(buff)-1;
+ /* remove trailing whitespace */
+ while(p >= buff && isspace(*p)) *(p--) = 0;
+ if(!*buff || *buff == '#') continue; /* skip empty lines and comments */
+ if(1) {
/* proxylist has to come last */
if(list) {
if(count >= MAX_CHAIN)
@@ -357,28 +368,28 @@ static void get_chain_data(proxy_data * pd, unsigned int *proxy_count, chain_typ
if(port_n)
count++;
} else {
- if(strstr(buff, "[ProxyList]")) {
+ if(!strcmp(buff, "[ProxyList]")) {
list = 1;
- } else if(strstr(buff, "random_chain")) {
+ } else if(!strcmp(buff, "random_chain")) {
*ct = RANDOM_TYPE;
- } else if(strstr(buff, "strict_chain")) {
+ } else if(!strcmp(buff, "strict_chain")) {
*ct = STRICT_TYPE;
- } else if(strstr(buff, "dynamic_chain")) {
+ } else if(!strcmp(buff, "dynamic_chain")) {
*ct = DYNAMIC_TYPE;
- } else if(strstr(buff, "round_robin_chain")) {
+ } else if(!strcmp(buff, "round_robin_chain")) {
*ct = ROUND_ROBIN_TYPE;
- } else if(strstr(buff, "tcp_read_time_out")) {
+ } else if(STR_STARTSWITH(buff, "tcp_read_time_out")) {
sscanf(buff, "%s %d", user, &tcp_read_time_out);
- } else if(strstr(buff, "tcp_connect_time_out")) {
+ } else if(STR_STARTSWITH(buff, "tcp_connect_time_out")) {
sscanf(buff, "%s %d", user, &tcp_connect_time_out);
- } else if(strstr(buff, "remote_dns_subnet")) {
+ } else if(STR_STARTSWITH(buff, "remote_dns_subnet")) {
sscanf(buff, "%s %u", user, &remote_dns_subnet);
if(remote_dns_subnet >= 256) {
fprintf(stderr,
"remote_dns_subnet: invalid value. requires a number between 0 and 255.\n");
exit(1);
}
- } else if(strstr(buff, "localnet")) {
+ } else if(STR_STARTSWITH(buff, "localnet")) {
if(sscanf(buff, "%s %21[^/]/%15s", user, local_in_addr_port, local_netmask) < 3) {
fprintf(stderr, "localnet format error");
exit(1);
@@ -419,7 +430,7 @@ static void get_chain_data(proxy_data * pd, unsigned int *proxy_count, chain_typ
} else {
fprintf(stderr, "# of localnet exceed %d.\n", MAX_LOCALNET);
}
- } else if(strstr(buff, "chain_len")) {
+ } else if(STR_STARTSWITH(buff, "chain_len")) {
char *pc;
int len;
pc = strchr(buff, '=');
@@ -429,13 +440,13 @@ static void get_chain_data(proxy_data * pd, unsigned int *proxy_count, chain_typ
}
len = atoi(++pc);
proxychains_max_chain = (len ? len : 1);
- } else if(strstr(buff, "quiet_mode")) {
+ } else if(!strcmp(buff, "quiet_mode")) {
proxychains_quiet_mode = 1;
- } else if(strstr(buff, "proxy_dns_old")) {
+ } else if(!strcmp(buff, "proxy_dns_old")) {
proxychains_resolver = 2;
- } else if(strstr(buff, "proxy_dns")) {
+ } else if(!strcmp(buff, "proxy_dns")) {
proxychains_resolver = 1;
- } else if(strstr(buff, "dnat")) {
+ } else if(STR_STARTSWITH(buff, "dnat")) {
if(sscanf(buff, "%s %21[^ ] %21s\n", user, dnat_orig_addr_port, dnat_new_addr_port) < 3) {
fprintf(stderr, "dnat format error");
exit(1);
| 0
|
92b57b1e4f84adcdcc3a375278f299274be62445
|
https://github.com/svenfuchs/i18n/commit/92b57b1e4f84adcdcc3a375278f299274be62445
|
The I18n::MissingTranslation exception escapes key names for its html_message
Also added deprecation message for the :rescue_format option
|
diff --git a/lib/i18n/exceptions.rb b/lib/i18n/exceptions.rb
index c0cf4383..669d4cd4 100644
--- a/lib/i18n/exceptions.rb
+++ b/lib/i18n/exceptions.rb
@@ -1,3 +1,5 @@
+require 'cgi'
+
module I18n
# Handles exceptions raised in the backend. All exceptions except for
# MissingTranslationData exceptions are re-thrown. When a MissingTranslationData
@@ -7,7 +9,19 @@ class ExceptionHandler
include Module.new {
def call(exception, locale, key, options)
if exception.is_a?(MissingTranslation)
- options[:rescue_format] == :html ? exception.html_message : exception.message
+ #
+ # TODO: this block is to be replaced by `exception.message` when
+ # rescue_format is removed
+ if options[:rescue_format] == :html
+ if @rescue_format_deprecation
+ $stderr.puts "[DEPRECATED] I18n's :recue_format option will be removed from a future release. All exception messages will be plain text. If you need the exception handler to return an html format please set or pass a custom exception handler."
+ @rescue_format_deprecation = true
+ end
+ exception.html_message
+ else
+ exception.message
+ end
+
elsif exception.is_a?(Exception)
raise exception
else
@@ -45,8 +59,9 @@ def initialize(locale, key, options = nil)
end
def html_message
- key = keys.last.to_s.gsub('_', ' ').gsub(/\b('?[a-z])/) { $1.capitalize }
- %(<span class="translation_missing" title="translation missing: #{keys.join('.')}">#{key}</span>)
+ key = CGI.escape_html titleize(keys.last)
+ path = CGI.escape_html keys.join('.')
+ %(<span class="translation_missing" title="translation missing: #{path}">#{key}</span>)
end
def keys
@@ -63,6 +78,13 @@ def message
def to_exception
MissingTranslationData.new(locale, key, options)
end
+
+ protected
+
+ # TODO : remove when #html_message is removed
+ def titleize(key)
+ key.to_s.gsub('_', ' ').gsub(/\b('?[a-z])/) { $1.capitalize }
+ end
end
include Base
diff --git a/test/i18n/exceptions_test.rb b/test/i18n/exceptions_test.rb
index 3c2e1cb7..098eefe6 100644
--- a/test/i18n/exceptions_test.rb
+++ b/test/i18n/exceptions_test.rb
@@ -28,9 +28,13 @@ def test_invalid_locale_stores_locale
end
test "MissingTranslationData html_message is a span with the titlelized last key token" do
- force_missing_translation_data do |exception|
- assert_equal '<span class="translation_missing" title="translation missing: de.bar.foo">Foo</span>', exception.html_message
- end
+ exception = I18n::MissingTranslationData.new(:de, :foo, :scope => :bar)
+ assert_equal '<span class="translation_missing" title="translation missing: de.bar.foo">Foo</span>', exception.html_message
+ end
+
+ test "MissingTranslationData html_message html escapes key names" do
+ exception = I18n::MissingTranslationData.new(:de, '<script>Evil</script>', :scope => '<iframe src="example.com" />')
+ assert_equal '<span class="translation_missing" title="translation missing: de.<iframe src="example.com" />.<script>Evil</script>"><Script>Evil</Script></span>', exception.html_message
end
test "ExceptionHandler returns the html_message if :rescue_format => :html was given" do
| 1
|
96478a8ea5df397a97b9e520f328fca71e544911
|
https://github.com/OpenNMS/opennms/commit/96478a8ea5df397a97b9e520f328fca71e544911
|
NMS-13098: update license year
|
diff --git a/opennms-services/src/test/java/org/opennms/netmgt/vacuumd/AutomationProcessorTest.java b/opennms-services/src/test/java/org/opennms/netmgt/vacuumd/AutomationProcessorTest.java
index 60a37c8c23b7..52b269602d96 100644
--- a/opennms-services/src/test/java/org/opennms/netmgt/vacuumd/AutomationProcessorTest.java
+++ b/opennms-services/src/test/java/org/opennms/netmgt/vacuumd/AutomationProcessorTest.java
@@ -1,8 +1,8 @@
/*******************************************************************************
* This file is part of OpenNMS(R).
*
- * Copyright (C) 2007-2014 The OpenNMS Group, Inc.
- * OpenNMS(R) is Copyright (C) 1999-2014 The OpenNMS Group, Inc.
+ * Copyright (C) 2003-2021 The OpenNMS Group, Inc.
+ * OpenNMS(R) is Copyright (C) 2021 The OpenNMS Group, Inc.
*
* OpenNMS(R) is a registered trademark of The OpenNMS Group, Inc.
*
| 0
|
37b70dee718eedbf8bfc7c944e580d23723d0c97
|
https://github.com/davidben/nspluginwrapper/commit/37b70dee718eedbf8bfc7c944e580d23723d0c97
|
Update to latest NPAPI SDK
Added a new variable. OS X only, so uninteresting.
|
diff --git a/npapi/npapi.h b/npapi/npapi.h
index 082feec..ccf41be 100644
--- a/npapi/npapi.h
+++ b/npapi/npapi.h
@@ -429,6 +429,8 @@ typedef enum {
, NPNVsupportsCocoaBool = 3001 /* TRUE if the browser supports the Cocoa event model */
, NPNVsupportsUpdatedCocoaTextInputBool = 3002 /* TRUE if the browser supports the updated
Cocoa text input specification. */
+ , NPNVsupportsCompositingCoreAnimationPluginsBool = 74656 /* TRUE if the browser supports
+ CA model compositing */
#endif
#if (MOZ_PLATFORM_MAEMO == 5) || (MOZ_PLATFORM_MAEMO == 6)
, NPNVSupportsWindowlessLocal = 2002
| 0
|
244d83bc3d859293f55812d48b3db168e581f6ab
|
https://github.com/nothings/stb/commit/244d83bc3d859293f55812d48b3db168e581f6ab
|
fix unchecked length in stb_vorbis that could crash on corrupt/invalid files
|
diff --git a/stb_vorbis.c b/stb_vorbis.c
index 14cebbf87e..49829d2c03 100644
--- a/stb_vorbis.c
+++ b/stb_vorbis.c
@@ -3,9 +3,9 @@
//
// Original version written by Sean Barrett in 2007.
//
-// Originally sponsored by RAD Game Tools. Seeking sponsored
-// by Phillip Bennefall, Marc Andersen, Aaron Baker, Elias Software,
-// Aras Pranckevicius, and Sean Barrett.
+// Originally sponsored by RAD Game Tools. Seeking implementation
+// sponsored by Phillip Bennefall, Marc Andersen, Aaron Baker,
+// Elias Software, Aras Pranckevicius, and Sean Barrett.
//
// LICENSE
//
@@ -32,6 +32,7 @@
// manxorist@github saga musix github:infatum
//
// Partial history:
+// 1.12 - 2017/11/21 - limit residue begin/end to blocksize/2 to avoid large temp allocs in bad/corrupt files
// 1.11 - 2017/07/23 - fix MinGW compilation
// 1.10 - 2017/03/03 - more robust seeking; fix negative ilog(); clear error in open_memory
// 1.09 - 2016/04/04 - back out 'truncation of last frame' fix from previous version
@@ -2042,6 +2043,8 @@ static int residue_decode(vorb *f, Codebook *book, float *target, int offset, in
return TRUE;
}
+// n is 1/2 of the blocksize --
+// specification: "Correct per-vector decode length is [n]/2"
static void decode_residue(vorb *f, float *residue_buffers[], int ch, int n, int rn, uint8 *do_not_decode)
{
int i,j,pass;
@@ -2049,7 +2052,10 @@ static void decode_residue(vorb *f, float *residue_buffers[], int ch, int n, int
int rtype = f->residue_types[rn];
int c = r->classbook;
int classwords = f->codebooks[c].dimensions;
- int n_read = r->end - r->begin;
+ unsigned int actual_size = rtype == 2 ? n*2 : n;
+ unsigned int limit_r_begin = (r->begin < actual_size ? r->begin : actual_size);
+ unsigned int limit_r_end = (r->end < actual_size ? r->end : actual_size);
+ int n_read = limit_r_end - limit_r_begin;
int part_read = n_read / r->part_size;
int temp_alloc_point = temp_alloc_save(f);
#ifndef STB_VORBIS_DIVIDES_IN_RESIDUE
@@ -4077,7 +4083,10 @@ static int start_decoder(vorb *f)
int i,max_part_read=0;
for (i=0; i < f->residue_count; ++i) {
Residue *r = f->residue_config + i;
- int n_read = r->end - r->begin;
+ unsigned int actual_size = f->blocksize_1 / 2;
+ unsigned int limit_r_begin = r->begin < actual_size ? r->begin : actual_size;
+ unsigned int limit_r_end = r->end < actual_size ? r->end : actual_size;
+ int n_read = limit_r_end - limit_r_begin;
int part_read = n_read / r->part_size;
if (part_read > max_part_read)
max_part_read = part_read;
@@ -4088,6 +4097,8 @@ static int start_decoder(vorb *f)
classify_mem = f->channels * (sizeof(void*) + max_part_read * sizeof(int *));
#endif
+ // maximum reasonable partition size is f->blocksize_1
+
f->temp_memory_required = classify_mem;
if (imdct_mem > f->temp_memory_required)
f->temp_memory_required = imdct_mem;
@@ -5351,6 +5362,8 @@ int stb_vorbis_get_samples_float(stb_vorbis *f, int channels, float **buffer, in
#endif // STB_VORBIS_NO_PULLDATA_API
/* Version history
+ 1.12 - 2017/11/21 - limit residue begin/end to blocksize/2 to avoid large temp allocs in bad/corrupt files
+ 1.11 - 2017/07/23 - fix MinGW compilation
1.10 - 2017/03/03 - more robust seeking; fix negative ilog(); clear error in open_memory
1.09 - 2016/04/04 - back out 'avoid discarding last frame' fix from previous version
1.08 - 2016/04/02 - fixed multiple warnings; fix setup memory leaks;
| 1
|
1577e06b5acc0fc3214492f8185cbadfcd042554
|
https://github.com/sitaramc/gitolite/commit/1577e06b5acc0fc3214492f8185cbadfcd042554
|
VREF/NAME_NC -- like VREF/NAME but for "new commits" only
|
diff --git a/src/VREF/NAME_NC b/src/VREF/NAME_NC
new file mode 100755
index 000000000..1a8171450
--- /dev/null
+++ b/src/VREF/NAME_NC
@@ -0,0 +1,33 @@
+#!/bin/sh
+
+# ----------------------------------------------------------------------
+# VREF/NAME_NC
+# Like VREF/NAME, but only considers "new commits" -- i.e., commits that
+# don't already exist in the repo as part of some other ref.
+
+# ----------------------------------------------------------------------
+# WHY
+# VREF/NAME doesn't deal well with tag creation (or new branch creation),
+# since then all files in the project look like they are being created (due
+# to comparison with an empty tree).
+
+# Use this instead of VREF/NAME when you need to make that distinction.
+
+newsha=$3
+
+[ $newsha = "0000000000000000000000000000000000000000" ] && {
+ echo "we don't currently handle deletions" >&2
+ exit 1
+}
+
+git log --name-only --format=%n $newsha --not --all |
+ sort -u | grep . | sed -e 's.^.VREF/NAME_NC/.'
+
+# ----------------------------------------------------------------------
+# OTHER NOTES
+# The built-in NAME does have a wee bit of a performance advantage. I plan
+# to ignore this until someone notices this enough to be a problem :)
+#
+# I could explain it here at least, but I fear that any explanation will
+# only add to the already rampant confusion about how VREFs work. I'm not
+# rocking THAT boat again, sorry!
| 0
|
1707bf3d898a8ada3b213acb0e3b38f16eaae73d
|
https://github.com/dom4j/dom4j/commit/1707bf3d898a8ada3b213acb0e3b38f16eaae73d
|
#28 Disable downloading external resources with DocumentHelper.parseText() helper.
(cherry picked from commit 8f6a7f6001d679176c1079ac65871d4e493360db)
|
diff --git a/src/main/java/org/dom4j/DocumentHelper.java b/src/main/java/org/dom4j/DocumentHelper.java
index a3a69dca..6ceed9a3 100644
--- a/src/main/java/org/dom4j/DocumentHelper.java
+++ b/src/main/java/org/dom4j/DocumentHelper.java
@@ -270,6 +270,14 @@ public static void sort(List<Node> list, String expression, boolean distinct) {
*/
public static Document parseText(String text) throws DocumentException {
SAXReader reader = new SAXReader();
+ try {
+ reader.setFeature("http://apache.org/xml/features/nonvalidating/load-external-dtd", false);
+ reader.setFeature("http://xml.org/sax/features/external-general-entities", false);
+ reader.setFeature("http://xml.org/sax/features/external-parameter-entities", false);
+ } catch (SAXException e) {
+ //Parse with external resources downloading allowed.
+ }
+
String encoding = getEncoding(text);
InputSource source = new InputSource(new StringReader(text));
| 0
|
ff06c7c885dc94ed7c828e8cdbb8b5d850a7e654
|
https://github.com/openstack/nova/commit/ff06c7c885dc94ed7c828e8cdbb8b5d850a7e654
|
Fix up protocol case handling for security groups.
Fix bug 985184.
When creating security group rules, any case for the protocol was
accepted as input, such as TCP, Tcp, tcp, etc., and was stored in the
database as specified. However, unless specified as all lowercase, the
code to apply the rules would break and result in some rules not being
applied.
Change-Id: I6c723d371579eb37a94bd484d39beeb773668ed4
|
diff --git a/nova/api/ec2/cloud.py b/nova/api/ec2/cloud.py
index 43686aa12a16..723c7fca7486 100644
--- a/nova/api/ec2/cloud.py
+++ b/nova/api/ec2/cloud.py
@@ -598,7 +598,7 @@ def _rule_dict_last_step(self, context, to_port=None, from_port=None,
to_port=to_port, msg="For ICMP, the"
" type:code must be valid")
- values['protocol'] = ip_protocol
+ values['protocol'] = ip_protocol.lower()
values['from_port'] = from_port
values['to_port'] = to_port
else:
diff --git a/nova/api/openstack/compute/contrib/security_groups.py b/nova/api/openstack/compute/contrib/security_groups.py
index 7e3f93752169..4a69d392ea1d 100644
--- a/nova/api/openstack/compute/contrib/security_groups.py
+++ b/nova/api/openstack/compute/contrib/security_groups.py
@@ -524,7 +524,7 @@ def _rule_args_to_dict(self, context, to_port=None, from_port=None,
to_port=to_port, msg="For ICMP, the"
" type:code must be valid")
- values['protocol'] = ip_protocol
+ values['protocol'] = ip_protocol.lower()
values['from_port'] = from_port
values['to_port'] = to_port
else:
diff --git a/nova/virt/firewall.py b/nova/virt/firewall.py
index bca50d21f373..be6a0f7c972b 100644
--- a/nova/virt/firewall.py
+++ b/nova/virt/firewall.py
@@ -331,8 +331,8 @@ def instance_rules(self, instance, network_info):
else:
fw_rules = ipv6_rules
- protocol = rule.protocol
- if version == 6 and rule.protocol == 'icmp':
+ protocol = rule.protocol.lower()
+ if version == 6 and protocol == 'icmp':
protocol = 'icmpv6'
args = ['-j ACCEPT']
| 1
|
14bc2c0a6fde0da04b47130707e01df850eedc7e
|
https://github.com/WordPress/WordPress/commit/14bc2c0a6fde0da04b47130707e01df850eedc7e
|
Login: Use `wp_safe_redirect()` when redirecting the login page if forced to use HTTPS.
Built from https://develop.svn.wordpress.org/trunk@42892
git-svn-id: http://core.svn.wordpress.org/trunk@42722 1a063a9b-81f0-0310-95a4-ce76da25c4cd
|
diff --git a/wp-includes/version.php b/wp-includes/version.php
index b54e649f2ce6..87d92b4eb33c 100644
--- a/wp-includes/version.php
+++ b/wp-includes/version.php
@@ -4,7 +4,7 @@
*
* @global string $wp_version
*/
-$wp_version = '5.0-alpha-42891';
+$wp_version = '5.0-alpha-42892';
/**
* Holds the WordPress DB revision, increments when changes are made to the WordPress DB schema.
diff --git a/wp-login.php b/wp-login.php
index 93d08181ee3b..e7467cb5b8de 100644
--- a/wp-login.php
+++ b/wp-login.php
@@ -14,10 +14,10 @@
// Redirect to https login if forced to use SSL
if ( force_ssl_admin() && ! is_ssl() ) {
if ( 0 === strpos( $_SERVER['REQUEST_URI'], 'http' ) ) {
- wp_redirect( set_url_scheme( $_SERVER['REQUEST_URI'], 'https' ) );
+ wp_safe_redirect( set_url_scheme( $_SERVER['REQUEST_URI'], 'https' ) );
exit();
} else {
- wp_redirect( 'https://' . $_SERVER['HTTP_HOST'] . $_SERVER['REQUEST_URI'] );
+ wp_safe_redirect( 'https://' . $_SERVER['HTTP_HOST'] . $_SERVER['REQUEST_URI'] );
exit();
}
}
| 1
|
740289c61d60256c6270756bc84b9e24b76e4913
|
https://github.com/apache/geode/commit/740289c61d60256c6270756bc84b9e24b76e4913
|
GEODE-3974: Improve permissions for geode-lucene functions
|
diff --git a/geode-lucene/src/main/java/org/apache/geode/cache/lucene/internal/cli/functions/LuceneCreateIndexFunction.java b/geode-lucene/src/main/java/org/apache/geode/cache/lucene/internal/cli/functions/LuceneCreateIndexFunction.java
index b1b974d1b4cb..df8bf303d33b 100644
--- a/geode-lucene/src/main/java/org/apache/geode/cache/lucene/internal/cli/functions/LuceneCreateIndexFunction.java
+++ b/geode-lucene/src/main/java/org/apache/geode/cache/lucene/internal/cli/functions/LuceneCreateIndexFunction.java
@@ -18,6 +18,9 @@
import static org.apache.geode.cache.lucene.internal.LuceneServiceImpl.validateCommandParameters.INDEX_NAME;
import static org.apache.geode.cache.lucene.internal.LuceneServiceImpl.validateCommandParameters.REGION_PATH;
+import java.util.Collection;
+import java.util.Collections;
+
import org.apache.commons.lang.StringUtils;
import org.apache.lucene.analysis.Analyzer;
import org.apache.lucene.analysis.standard.StandardAnalyzer;
@@ -33,11 +36,15 @@
import org.apache.geode.cache.lucene.internal.cli.LuceneCliStrings;
import org.apache.geode.cache.lucene.internal.cli.LuceneIndexDetails;
import org.apache.geode.cache.lucene.internal.cli.LuceneIndexInfo;
+import org.apache.geode.cache.lucene.internal.security.LucenePermission;
import org.apache.geode.internal.InternalEntity;
import org.apache.geode.management.internal.cli.CliUtil;
import org.apache.geode.management.internal.cli.functions.CliFunctionResult;
import org.apache.geode.management.internal.cli.i18n.CliStrings;
import org.apache.geode.management.internal.configuration.domain.XmlEntity;
+import org.apache.geode.security.ResourcePermission;
+import org.apache.geode.security.ResourcePermission.Operation;
+import org.apache.geode.security.ResourcePermission.Resource;
/**
@@ -110,6 +117,12 @@ public void execute(final FunctionContext context) {
}
}
+ @Override
+ public Collection<ResourcePermission> getRequiredPermissions(String regionName) {
+ return Collections.singleton(
+ new ResourcePermission(Resource.CLUSTER, Operation.MANAGE, LucenePermission.TARGET));
+ }
+
private LuceneSerializer toSerializer(String serializerName)
throws InstantiationException, IllegalAccessException, ClassNotFoundException {
String trimmedName = StringUtils.trim(serializerName);
@@ -136,5 +149,4 @@ private Analyzer toAnalyzer(String className) {
CliUtil.forName(className, LuceneCliStrings.LUCENE_CREATE_INDEX__ANALYZER);
return CliUtil.newInstance(clazz, LuceneCliStrings.LUCENE_CREATE_INDEX__ANALYZER);
}
-
}
diff --git a/geode-lucene/src/main/java/org/apache/geode/cache/lucene/internal/cli/functions/LuceneDescribeIndexFunction.java b/geode-lucene/src/main/java/org/apache/geode/cache/lucene/internal/cli/functions/LuceneDescribeIndexFunction.java
index dd90116856f1..8f9bac37ed98 100755
--- a/geode-lucene/src/main/java/org/apache/geode/cache/lucene/internal/cli/functions/LuceneDescribeIndexFunction.java
+++ b/geode-lucene/src/main/java/org/apache/geode/cache/lucene/internal/cli/functions/LuceneDescribeIndexFunction.java
@@ -15,6 +15,9 @@
package org.apache.geode.cache.lucene.internal.cli.functions;
+import java.util.Collection;
+import java.util.Collections;
+
import org.apache.geode.cache.Cache;
import org.apache.geode.cache.execute.Function;
import org.apache.geode.cache.execute.FunctionContext;
@@ -25,7 +28,11 @@
import org.apache.geode.cache.lucene.internal.LuceneServiceImpl;
import org.apache.geode.cache.lucene.internal.cli.LuceneIndexDetails;
import org.apache.geode.cache.lucene.internal.cli.LuceneIndexInfo;
+import org.apache.geode.cache.lucene.internal.security.LucenePermission;
import org.apache.geode.internal.InternalEntity;
+import org.apache.geode.security.ResourcePermission;
+import org.apache.geode.security.ResourcePermission.Operation;
+import org.apache.geode.security.ResourcePermission.Resource;
/**
* The LuceneDescribeIndexFunction class is a function used to collect the information on a
@@ -66,4 +73,10 @@ public void execute(final FunctionContext context) {
}
context.getResultSender().lastResult(result);
}
+
+ @Override
+ public Collection<ResourcePermission> getRequiredPermissions(String regionName) {
+ return Collections.singleton(
+ new ResourcePermission(Resource.CLUSTER, Operation.READ, LucenePermission.TARGET));
+ }
}
diff --git a/geode-lucene/src/main/java/org/apache/geode/cache/lucene/internal/cli/functions/LuceneDestroyIndexFunction.java b/geode-lucene/src/main/java/org/apache/geode/cache/lucene/internal/cli/functions/LuceneDestroyIndexFunction.java
index 9803192e3fda..1a12894fdacf 100644
--- a/geode-lucene/src/main/java/org/apache/geode/cache/lucene/internal/cli/functions/LuceneDestroyIndexFunction.java
+++ b/geode-lucene/src/main/java/org/apache/geode/cache/lucene/internal/cli/functions/LuceneDestroyIndexFunction.java
@@ -14,6 +14,9 @@
*/
package org.apache.geode.cache.lucene.internal.cli.functions;
+import java.util.Collection;
+import java.util.Collections;
+
import org.apache.commons.lang.StringUtils;
import org.apache.geode.cache.execute.Function;
@@ -22,16 +25,19 @@
import org.apache.geode.cache.lucene.LuceneServiceProvider;
import org.apache.geode.cache.lucene.internal.LuceneServiceImpl;
import org.apache.geode.cache.lucene.internal.cli.LuceneDestroyIndexInfo;
+import org.apache.geode.cache.lucene.internal.security.LucenePermission;
import org.apache.geode.cache.lucene.internal.xml.LuceneXmlConstants;
import org.apache.geode.internal.InternalEntity;
import org.apache.geode.internal.cache.xmlcache.CacheXml;
import org.apache.geode.management.internal.cli.functions.CliFunctionResult;
import org.apache.geode.management.internal.configuration.domain.XmlEntity;
+import org.apache.geode.security.ResourcePermission;
+import org.apache.geode.security.ResourcePermission.Operation;
+import org.apache.geode.security.ResourcePermission.Resource;
public class LuceneDestroyIndexFunction implements Function, InternalEntity {
-
public void execute(final FunctionContext context) {
- CliFunctionResult result = null;
+ CliFunctionResult result;
String memberId = context.getCache().getDistributedSystem().getDistributedMember().getId();
try {
LuceneDestroyIndexInfo indexInfo = (LuceneDestroyIndexInfo) context.getArguments();
@@ -66,4 +72,10 @@ protected XmlEntity getXmlEntity(String indexName, String regionPath) {
return new XmlEntity(CacheXml.REGION, "name", regionName, LuceneXmlConstants.PREFIX,
LuceneXmlConstants.NAMESPACE, LuceneXmlConstants.INDEX, "name", indexName);
}
+
+ @Override
+ public Collection<ResourcePermission> getRequiredPermissions(String regionName) {
+ return Collections.singleton(
+ new ResourcePermission(Resource.CLUSTER, Operation.MANAGE, LucenePermission.TARGET));
+ }
}
diff --git a/geode-lucene/src/main/java/org/apache/geode/cache/lucene/internal/cli/functions/LuceneListIndexFunction.java b/geode-lucene/src/main/java/org/apache/geode/cache/lucene/internal/cli/functions/LuceneListIndexFunction.java
index 34d445b22bcf..31c8122d368c 100755
--- a/geode-lucene/src/main/java/org/apache/geode/cache/lucene/internal/cli/functions/LuceneListIndexFunction.java
+++ b/geode-lucene/src/main/java/org/apache/geode/cache/lucene/internal/cli/functions/LuceneListIndexFunction.java
@@ -15,6 +15,8 @@
package org.apache.geode.cache.lucene.internal.cli.functions;
+import java.util.Collection;
+import java.util.Collections;
import java.util.HashSet;
import java.util.Set;
@@ -27,7 +29,11 @@
import org.apache.geode.cache.lucene.internal.LuceneIndexImpl;
import org.apache.geode.cache.lucene.internal.LuceneServiceImpl;
import org.apache.geode.cache.lucene.internal.cli.LuceneIndexDetails;
+import org.apache.geode.cache.lucene.internal.security.LucenePermission;
import org.apache.geode.internal.InternalEntity;
+import org.apache.geode.security.ResourcePermission;
+import org.apache.geode.security.ResourcePermission.Operation;
+import org.apache.geode.security.ResourcePermission.Resource;
/**
* The LuceneListIndexFunction class is a function used to collect the information on all lucene
@@ -64,4 +70,10 @@ public void execute(final FunctionContext context) {
}
context.getResultSender().lastResult(indexDetailsSet);
}
+
+ @Override
+ public Collection<ResourcePermission> getRequiredPermissions(String regionName) {
+ return Collections.singleton(
+ new ResourcePermission(Resource.CLUSTER, Operation.READ, LucenePermission.TARGET));
+ }
}
diff --git a/geode-lucene/src/main/java/org/apache/geode/cache/lucene/internal/cli/functions/LuceneSearchIndexFunction.java b/geode-lucene/src/main/java/org/apache/geode/cache/lucene/internal/cli/functions/LuceneSearchIndexFunction.java
index 0a6cc3ec3eab..c0433881b764 100755
--- a/geode-lucene/src/main/java/org/apache/geode/cache/lucene/internal/cli/functions/LuceneSearchIndexFunction.java
+++ b/geode-lucene/src/main/java/org/apache/geode/cache/lucene/internal/cli/functions/LuceneSearchIndexFunction.java
@@ -15,14 +15,14 @@
package org.apache.geode.cache.lucene.internal.cli.functions;
+import java.util.Collection;
+import java.util.Collections;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import org.apache.geode.cache.Cache;
-import org.apache.geode.cache.CacheFactory;
import org.apache.geode.cache.execute.Function;
-import org.apache.geode.cache.execute.FunctionAdapter;
import org.apache.geode.cache.execute.FunctionContext;
import org.apache.geode.cache.lucene.LuceneQuery;
import org.apache.geode.cache.lucene.LuceneQueryException;
@@ -35,6 +35,9 @@
import org.apache.geode.cache.lucene.internal.cli.LuceneQueryInfo;
import org.apache.geode.cache.lucene.internal.cli.LuceneSearchResults;
import org.apache.geode.internal.InternalEntity;
+import org.apache.geode.security.ResourcePermission;
+import org.apache.geode.security.ResourcePermission.Operation;
+import org.apache.geode.security.ResourcePermission.Resource;
/**
* The LuceneSearchIndexFunction class is a function used to collect the information on a particular
@@ -95,4 +98,9 @@ public void execute(final FunctionContext context) {
context.getResultSender().lastResult(result);
}
}
+
+ @Override
+ public Collection<ResourcePermission> getRequiredPermissions(String regionName) {
+ return Collections.singleton(new ResourcePermission(Resource.DATA, Operation.READ, regionName));
+ }
}
diff --git a/geode-lucene/src/main/java/org/apache/geode/cache/lucene/internal/directory/DumpDirectoryFiles.java b/geode-lucene/src/main/java/org/apache/geode/cache/lucene/internal/directory/DumpDirectoryFiles.java
index 910f50f23c8e..4d720da3db08 100644
--- a/geode-lucene/src/main/java/org/apache/geode/cache/lucene/internal/directory/DumpDirectoryFiles.java
+++ b/geode-lucene/src/main/java/org/apache/geode/cache/lucene/internal/directory/DumpDirectoryFiles.java
@@ -17,6 +17,8 @@
import java.io.File;
import java.util.Collection;
+import java.util.HashSet;
+import java.util.Set;
import org.apache.logging.log4j.Logger;
import org.apache.lucene.index.IndexWriter;
@@ -35,6 +37,9 @@
import org.apache.geode.internal.InternalEntity;
import org.apache.geode.internal.cache.BucketNotFoundException;
import org.apache.geode.internal.logging.LogService;
+import org.apache.geode.security.ResourcePermission;
+import org.apache.geode.security.ResourcePermission.Operation;
+import org.apache.geode.security.ResourcePermission.Resource;
public class DumpDirectoryFiles implements Function, InternalEntity {
private static final long serialVersionUID = 1L;
@@ -96,4 +101,12 @@ public String getId() {
public boolean optimizeForWrite() {
return true;
}
+
+ @Override
+ public Collection<ResourcePermission> getRequiredPermissions(String regionName) {
+ Set<ResourcePermission> required = new HashSet<>();
+ required.add(new ResourcePermission(Resource.DATA, Operation.READ, regionName));
+ required.add(new ResourcePermission(Resource.CLUSTER, Operation.MANAGE));
+ return required;
+ }
}
diff --git a/geode-lucene/src/main/java/org/apache/geode/cache/lucene/internal/distributed/LuceneQueryFunction.java b/geode-lucene/src/main/java/org/apache/geode/cache/lucene/internal/distributed/LuceneQueryFunction.java
index 0b104a3152c6..bc5ced6134fe 100644
--- a/geode-lucene/src/main/java/org/apache/geode/cache/lucene/internal/distributed/LuceneQueryFunction.java
+++ b/geode-lucene/src/main/java/org/apache/geode/cache/lucene/internal/distributed/LuceneQueryFunction.java
@@ -19,7 +19,6 @@
import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
-import java.util.Optional;
import org.apache.logging.log4j.Logger;
import org.apache.lucene.search.Query;
diff --git a/geode-lucene/src/main/java/org/apache/geode/cache/lucene/internal/distributed/WaitUntilFlushedFunction.java b/geode-lucene/src/main/java/org/apache/geode/cache/lucene/internal/distributed/WaitUntilFlushedFunction.java
index c9e10d9daaf0..f0c88a4f6f06 100644
--- a/geode-lucene/src/main/java/org/apache/geode/cache/lucene/internal/distributed/WaitUntilFlushedFunction.java
+++ b/geode-lucene/src/main/java/org/apache/geode/cache/lucene/internal/distributed/WaitUntilFlushedFunction.java
@@ -17,7 +17,6 @@
import java.util.Collection;
import java.util.Collections;
-import java.util.Optional;
import java.util.concurrent.TimeUnit;
import org.apache.geode.cache.Cache;
diff --git a/geode-lucene/src/main/java/org/apache/geode/cache/lucene/internal/results/LuceneGetPageFunction.java b/geode-lucene/src/main/java/org/apache/geode/cache/lucene/internal/results/LuceneGetPageFunction.java
index 07dc1ad27efe..8e2bfcc02a99 100644
--- a/geode-lucene/src/main/java/org/apache/geode/cache/lucene/internal/results/LuceneGetPageFunction.java
+++ b/geode-lucene/src/main/java/org/apache/geode/cache/lucene/internal/results/LuceneGetPageFunction.java
@@ -18,7 +18,6 @@
import java.util.Collection;
import java.util.Collections;
import java.util.List;
-import java.util.Optional;
import java.util.Set;
import org.apache.logging.log4j.Logger;
diff --git a/geode-lucene/src/test/java/org/apache/geode/cache/lucene/test/LuceneFunctionSecurityTest.java b/geode-lucene/src/test/java/org/apache/geode/cache/lucene/test/LuceneFunctionSecurityTest.java
new file mode 100644
index 000000000000..2fa054eef493
--- /dev/null
+++ b/geode-lucene/src/test/java/org/apache/geode/cache/lucene/test/LuceneFunctionSecurityTest.java
@@ -0,0 +1,485 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more contributor license
+ * agreements. See the NOTICE file distributed with this work for additional information regarding
+ * copyright ownership. The ASF licenses this file to You under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance with the License. You may obtain a
+ * copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software distributed under the License
+ * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express
+ * or implied. See the License for the specific language governing permissions and limitations under
+ * the License.
+ */
+
+package org.apache.geode.cache.lucene.test;
+
+import static org.apache.geode.management.internal.security.ResourcePermissions.CLUSTER_MANAGE;
+import static org.apache.geode.management.internal.security.ResourcePermissions.DATA_READ;
+import static org.assertj.core.api.Assertions.assertThat;
+import static org.mockito.ArgumentMatchers.any;
+
+import java.util.function.Predicate;
+
+import org.assertj.core.api.Condition;
+import org.junit.BeforeClass;
+import org.junit.ClassRule;
+import org.junit.Rule;
+import org.junit.Test;
+import org.junit.experimental.categories.Category;
+import org.mockito.Mockito;
+
+import org.apache.geode.cache.RegionShortcut;
+import org.apache.geode.cache.execute.Function;
+import org.apache.geode.cache.execute.FunctionService;
+import org.apache.geode.cache.lucene.internal.cli.functions.LuceneCreateIndexFunction;
+import org.apache.geode.cache.lucene.internal.cli.functions.LuceneDescribeIndexFunction;
+import org.apache.geode.cache.lucene.internal.cli.functions.LuceneDestroyIndexFunction;
+import org.apache.geode.cache.lucene.internal.cli.functions.LuceneListIndexFunction;
+import org.apache.geode.cache.lucene.internal.cli.functions.LuceneSearchIndexFunction;
+import org.apache.geode.cache.lucene.internal.directory.DumpDirectoryFiles;
+import org.apache.geode.cache.lucene.internal.distributed.LuceneQueryFunction;
+import org.apache.geode.cache.lucene.internal.distributed.WaitUntilFlushedFunction;
+import org.apache.geode.cache.lucene.internal.results.LuceneGetPageFunction;
+import org.apache.geode.cache.lucene.internal.security.LucenePermission;
+import org.apache.geode.examples.SimpleSecurityManager;
+import org.apache.geode.security.ResourcePermission;
+import org.apache.geode.security.ResourcePermission.Operation;
+import org.apache.geode.security.ResourcePermission.Resource;
+import org.apache.geode.test.junit.categories.IntegrationTest;
+import org.apache.geode.test.junit.categories.SecurityTest;
+import org.apache.geode.test.junit.rules.ConnectionConfiguration;
+import org.apache.geode.test.junit.rules.GfshCommandRule;
+import org.apache.geode.test.junit.rules.ServerStarterRule;
+
+@Category({IntegrationTest.class, SecurityTest.class})
+public class LuceneFunctionSecurityTest {
+ // Note: this region name is embedded below in several @ConnectionConfiguration inputs,
+ // which is itself case-sensitive in parsing.
+ private static String regionName = "this_test_region";
+
+ private static ResourcePermission CLUSTER_MANAGE_LUCENE =
+ new ResourcePermission(Resource.CLUSTER, Operation.MANAGE, LucenePermission.TARGET);
+ private static ResourcePermission CLUSTER_READ_LUCENE =
+ new ResourcePermission(Resource.CLUSTER, Operation.READ, LucenePermission.TARGET);
+ private static ResourcePermission DATA_READ_REGION =
+ new ResourcePermission(Resource.DATA, Operation.READ, regionName);
+
+ private static Function luceneCreateIndexFunction = Mockito.spy(new LuceneCreateIndexFunction());
+ private static Function luceneDescribeIndexFunction =
+ Mockito.spy(new LuceneDescribeIndexFunction());
+ private static Function luceneDestroyIndexFunction =
+ Mockito.spy(new LuceneDestroyIndexFunction());
+ private static Function luceneListIndexFunction = Mockito.spy(new LuceneListIndexFunction());
+ private static Function luceneSearchIndexFunction = Mockito.spy(new LuceneSearchIndexFunction());
+ private static Function dumpDirectoryFiles = Mockito.spy(new DumpDirectoryFiles());
+ private static Function luceneQueryFunction = Mockito.spy(new LuceneQueryFunction());
+ private static Function waitUntilFlushedFunction = Mockito.spy(new WaitUntilFlushedFunction());
+ private static Function luceneGetPageFunction = Mockito.spy(new LuceneGetPageFunction());
+
+ static {
+ Mockito.doNothing().when(luceneCreateIndexFunction).execute(any());
+ Mockito.doNothing().when(luceneDescribeIndexFunction).execute(any());
+ Mockito.doNothing().when(luceneDestroyIndexFunction).execute(any());
+ Mockito.doNothing().when(luceneListIndexFunction).execute(any());
+ Mockito.doNothing().when(luceneSearchIndexFunction).execute(any());
+ Mockito.doNothing().when(dumpDirectoryFiles).execute(any());
+ Mockito.doNothing().when(luceneQueryFunction).execute(any());
+ Mockito.doNothing().when(waitUntilFlushedFunction).execute(any());
+ Mockito.doNothing().when(luceneGetPageFunction).execute(any());
+ }
+
+ @ClassRule
+ public static ServerStarterRule server =
+ new ServerStarterRule().withJMXManager().withSecurityManager(SimpleSecurityManager.class)
+ .withRegion(RegionShortcut.PARTITION, regionName).withAutoStart();
+
+ @Rule
+ public GfshCommandRule gfsh =
+ new GfshCommandRule(server::getJmxPort, GfshCommandRule.PortType.jmxManager);
+
+ @BeforeClass
+ public static void setupClass() {
+ FunctionService.registerFunction(luceneCreateIndexFunction);
+ FunctionService.registerFunction(luceneDescribeIndexFunction);
+ FunctionService.registerFunction(luceneDestroyIndexFunction);
+ FunctionService.registerFunction(luceneListIndexFunction);
+ FunctionService.registerFunction(luceneSearchIndexFunction);
+ FunctionService.registerFunction(dumpDirectoryFiles);
+ FunctionService.registerFunction(luceneQueryFunction);
+ FunctionService.registerFunction(waitUntilFlushedFunction);
+ FunctionService.registerFunction(luceneGetPageFunction);
+ }
+
+ /* Command authorized tests */
+ @Test
+ @ConnectionConfiguration(user = "clusterManageLucene", password = "clusterManageLucene")
+ public void testValidPermissionsForLuceneCreateIndexFunction() throws Exception {
+ Function thisFunction = luceneCreateIndexFunction;
+
+ gfsh.executeAndAssertThat("execute function --id=" + thisFunction.getId())
+ .doesNotContainOutput("not authorized for").statusIsSuccess();
+ }
+
+ @Test
+ @ConnectionConfiguration(user = "clusterReadLucene", password = "clusterReadLucene")
+ public void testValidPermissionsForLuceneDescribeIndexFunction() throws Exception {
+ Function thisFunction = luceneDescribeIndexFunction;
+
+ gfsh.executeAndAssertThat("execute function --id=" + thisFunction.getId())
+ .doesNotContainOutput("not authorized for").statusIsSuccess();
+ }
+
+ @Test
+ @ConnectionConfiguration(user = "clusterManageLucene", password = "clusterManageLucene")
+ public void testValidPermissionsForLuceneDestroyIndexFunction() throws Exception {
+ Function thisFunction = luceneDestroyIndexFunction;
+
+ gfsh.executeAndAssertThat("execute function --id=" + thisFunction.getId())
+ .doesNotContainOutput("not authorized for").statusIsSuccess();
+ }
+
+ @Test
+ @ConnectionConfiguration(user = "clusterReadLucene", password = "clusterReadLucene")
+ public void testValidPermissionsForLuceneListIndexFunction() throws Exception {
+ Function thisFunction = luceneListIndexFunction;
+
+ gfsh.executeAndAssertThat("execute function --id=" + thisFunction.getId())
+ .doesNotContainOutput("not authorized for").statusIsSuccess();
+ }
+
+ @Test
+ @ConnectionConfiguration(user = "dataReadThis_test_region,clusterManage",
+ password = "dataReadThis_test_region,clusterManage")
+ public void testValidPermissionsForDumpDirectoryFilesWithRegionParameter() throws Exception {
+ Function thisFunction = dumpDirectoryFiles;
+
+ gfsh.executeAndAssertThat(
+ "execute function --region=" + regionName + " --id=" + thisFunction.getId())
+ .doesNotContainOutput("not authorized for").statusIsSuccess();
+ }
+
+ @Test
+ @ConnectionConfiguration(user = "dataRead,clusterManage", password = "dataRead,clusterManage")
+ public void testValidPermissionsForDumpDirectoryFilesWithoutRegionParameter() throws Exception {
+ Function thisFunction = dumpDirectoryFiles;
+
+ gfsh.executeAndAssertThat("execute function --id=" + thisFunction.getId())
+ .doesNotContainOutput("not authorized for").statusIsSuccess();
+ }
+
+
+ @Test
+ @ConnectionConfiguration(user = "dataRead", password = "dataRead")
+ public void testValidPermissionsForLuceneSearchIndexFunctionWithoutRegionParameter()
+ throws Exception {
+ Function thisFunction = luceneSearchIndexFunction;
+
+ gfsh.executeAndAssertThat("execute function --id=" + thisFunction.getId())
+ .doesNotContainOutput("not authorized for").statusIsSuccess();
+ }
+
+ @Test
+ @ConnectionConfiguration(user = "dataReadThis_test_region", password = "dataReadThis_test_region")
+ public void testValidPermissionsForLuceneSearchIndexFunctionWithRegionParameter()
+ throws Exception {
+ Function thisFunction = luceneSearchIndexFunction;
+
+ gfsh.executeAndAssertThat(
+ "execute function --region=" + regionName + " --id=" + thisFunction.getId())
+ .doesNotContainOutput("not authorized for").statusIsSuccess();
+ }
+
+ @Test
+ @ConnectionConfiguration(user = "dataRead", password = "dataRead")
+ public void testValidPermissionsForLuceneQueryFunctionWithoutRegionParameter() throws Exception {
+ Function thisFunction = luceneQueryFunction;
+
+ gfsh.executeAndAssertThat("execute function --id=" + thisFunction.getId())
+ .doesNotContainOutput("not authorized for").statusIsSuccess();
+ }
+
+ @Test
+ @ConnectionConfiguration(user = "dataReadThis_test_region", password = "dataReadThis_test_region")
+ public void testValidPermissionsForLuceneQueryFunctionWithRegionParameter() throws Exception {
+ Function thisFunction = luceneQueryFunction;
+
+ gfsh.executeAndAssertThat(
+ "execute function --region=" + regionName + " --id=" + thisFunction.getId())
+ .doesNotContainOutput("not authorized for").statusIsSuccess();
+ }
+
+ @Test
+ @ConnectionConfiguration(user = "dataRead", password = "dataRead")
+ public void testValidPermissionsForWaitUntilFlushedFunctionWithoutRegionParameter()
+ throws Exception {
+ Function thisFunction = waitUntilFlushedFunction;
+
+ gfsh.executeAndAssertThat("execute function --id=" + thisFunction.getId())
+ .doesNotContainOutput("not authorized for").statusIsSuccess();
+ }
+
+ @Test
+ @ConnectionConfiguration(user = "dataReadThis_test_region", password = "dataReadThis_test_region")
+ public void testValidPermissionsForWaitUntilFlushedFunctionWithRegionParameter()
+ throws Exception {
+ Function thisFunction = waitUntilFlushedFunction;
+
+ gfsh.executeAndAssertThat(
+ "execute function --region=" + regionName + " --id=" + thisFunction.getId())
+ .doesNotContainOutput("not authorized for").statusIsSuccess();
+ }
+
+ @Test
+ @ConnectionConfiguration(user = "dataRead", password = "dataRead")
+ public void testValidPermissionsForLuceneGetPageFunctionWithoutRegionParameter()
+ throws Exception {
+ Function thisFunction = luceneGetPageFunction;
+
+ gfsh.executeAndAssertThat("execute function --id=" + thisFunction.getId())
+ .doesNotContainOutput("not authorized for").statusIsSuccess();
+ }
+
+ @Test
+ @ConnectionConfiguration(user = "dataReadThis_test_region", password = "dataReadThis_test_region")
+ public void testValidPermissionsForLuceneGetPageFunctionWithRegionParameter() throws Exception {
+ Function thisFunction = luceneGetPageFunction;
+
+ gfsh.executeAndAssertThat(
+ "execute function --region=" + regionName + " --id=" + thisFunction.getId())
+ .doesNotContainOutput("not authorized for").statusIsSuccess();
+ }
+
+
+ /* Command refused tests */
+ @Test
+ @ConnectionConfiguration(user = "noPermissions", password = "noPermissions")
+ public void testInvalidPermissionsForLuceneCreateIndexFunction() throws Exception {
+ Function thisFunction = luceneCreateIndexFunction;
+ ResourcePermission thisRequiredPermission = CLUSTER_MANAGE_LUCENE;
+
+ gfsh.executeAndAssertThat("execute function --id=" + thisFunction.getId())
+ .containsOutput("not authorized for " + thisRequiredPermission.toString())
+ .statusIsSuccess();
+ }
+
+ @Test
+ @ConnectionConfiguration(user = "noPermissions", password = "noPermissions")
+ public void testInvalidPermissionsForLuceneDescribeIndexFunction() throws Exception {
+ Function thisFunction = luceneDescribeIndexFunction;
+ ResourcePermission thisRequiredPermission = CLUSTER_READ_LUCENE;
+
+ gfsh.executeAndAssertThat("execute function --id=" + thisFunction.getId())
+ .containsOutput("not authorized for " + thisRequiredPermission.toString())
+ .statusIsSuccess();
+ }
+
+ @Test
+ @ConnectionConfiguration(user = "noPermissions", password = "noPermissions")
+ public void testInvalidPermissionsForLuceneDestroyIndexFunction() throws Exception {
+ Function thisFunction = luceneDestroyIndexFunction;
+ ResourcePermission thisRequiredPermission = CLUSTER_MANAGE_LUCENE;
+
+ gfsh.executeAndAssertThat("execute function --id=" + thisFunction.getId())
+ .containsOutput("not authorized for " + thisRequiredPermission.toString())
+ .statusIsSuccess();
+ }
+
+ @Test
+ @ConnectionConfiguration(user = "noPermissions", password = "noPermissions")
+ public void testInvalidPermissionsForLuceneListIndexFunction() throws Exception {
+ Function thisFunction = luceneListIndexFunction;
+ ResourcePermission thisRequiredPermission = CLUSTER_READ_LUCENE;
+
+ gfsh.executeAndAssertThat("execute function --id=" + thisFunction.getId())
+ .containsOutput("not authorized for " + thisRequiredPermission.toString())
+ .statusIsSuccess();
+ }
+
+ @Test
+ @ConnectionConfiguration(user = "noPermissions", password = "noPermissions")
+ public void testInvalidPermissionsForDumpDirectoryFilesWithoutRegionParameter_noPermission()
+ throws Exception {
+ Function thisFunction = dumpDirectoryFiles;
+
+ Predicate<String> notAuthForDataRead =
+ s -> s.contains("not authorized for " + DATA_READ.toString());
+ Predicate<String> notAuthForClusterManage =
+ s -> s.contains("not authorized for " + CLUSTER_MANAGE.toString());
+ Predicate<String> notAuthForSomePermission =
+ s -> notAuthForDataRead.test(s) || notAuthForClusterManage.test(s);
+
+ String output = gfsh.execute("execute function --id=" + thisFunction.getId());
+
+ Condition<String> containsSomeAuthFailure = new Condition<>(notAuthForSomePermission,
+ "not authorized for for [DATA:MANAGE|CLUSTER:MANAGE]", output);
+ assertThat(output).has(containsSomeAuthFailure);
+ }
+
+ @Test
+ @ConnectionConfiguration(user = "dataRead", password = "dataRead")
+ public void testInvalidPermissionsForDumpDirectoryFilesWithoutRegionParameter_withDataRead()
+ throws Exception {
+ Function thisFunction = dumpDirectoryFiles;
+ ResourcePermission thisMissingPermission = CLUSTER_MANAGE;
+
+ gfsh.executeAndAssertThat("execute function --id=" + thisFunction.getId())
+ .containsOutput("not authorized for " + thisMissingPermission.toString()).statusIsSuccess();
+ }
+
+ @Test
+ @ConnectionConfiguration(user = "clusterManage", password = "clusterManage")
+ public void testInvalidPermissionsForDumpDirectoryFilesWithoutRegionParameter_withClusterManage()
+ throws Exception {
+ Function thisFunction = dumpDirectoryFiles;
+ ResourcePermission thisMissingPermission = DATA_READ;
+
+ gfsh.executeAndAssertThat("execute function --id=" + thisFunction.getId())
+ .containsOutput("not authorized for " + thisMissingPermission.toString()).statusIsSuccess();
+ }
+
+ @Test
+ @ConnectionConfiguration(user = "noPermissions", password = "noPermissions")
+ public void testInvalidPermissionsForDumpDirectoryFilesWithRegionParameter_noPermission()
+ throws Exception {
+ Function thisFunction = dumpDirectoryFiles;
+
+ Predicate<String> notAuthForDataReadRegion =
+ s -> s.contains("not authorized for " + DATA_READ_REGION.toString());
+ Predicate<String> notAuthForClusterManage =
+ s -> s.contains("not authorized for " + CLUSTER_MANAGE.toString());
+ Predicate<String> notAuthForSomePermission =
+ s -> notAuthForDataReadRegion.test(s) || notAuthForClusterManage.test(s);
+
+ String output =
+ gfsh.execute("execute function --region=" + regionName + " --id=" + thisFunction.getId());
+
+ Condition<String> containsSomeAuthFailure =
+ new Condition<>(notAuthForSomePermission, "D:R or C:M:L auth failure", output);
+ assertThat(output).has(containsSomeAuthFailure);
+ }
+
+ @Test
+ @ConnectionConfiguration(user = "dataReadThis_test_region", password = "dataReadThis_test_region")
+ public void testInvalidPermissionsForDumpDirectoryFilesWithRegionParameter_withDataReadRegion()
+ throws Exception {
+ Function thisFunction = dumpDirectoryFiles;
+ ResourcePermission thisMissingPermission = CLUSTER_MANAGE;
+
+ gfsh.executeAndAssertThat(
+ "execute function --region=" + regionName + " --id=" + thisFunction.getId())
+ .containsOutput("not authorized for " + thisMissingPermission.toString()).statusIsSuccess();
+ }
+
+ @Test
+ @ConnectionConfiguration(user = "clusterManage", password = "clusterManage")
+ public void testInvalidPermissionsForDumpDirectoryFilesWithRegionParameter_withClusterManage()
+ throws Exception {
+ Function thisFunction = dumpDirectoryFiles;
+ ResourcePermission thisMissingPermission = DATA_READ;
+
+ gfsh.executeAndAssertThat(
+ "execute function --region=" + regionName + " --id=" + thisFunction.getId())
+ .containsOutput("not authorized for " + thisMissingPermission.toString()).statusIsSuccess();
+ }
+
+
+ @Test
+ @ConnectionConfiguration(user = "noPermissions", password = "noPermissions")
+ public void testInvalidPermissionsForLuceneSearchIndexFunctionWithoutRegionParameter()
+ throws Exception {
+ Function thisFunction = luceneSearchIndexFunction;
+ ResourcePermission thisRequiredPermission = DATA_READ;
+
+ gfsh.executeAndAssertThat("execute function --id=" + thisFunction.getId())
+ .containsOutput("not authorized for " + thisRequiredPermission.toString())
+ .statusIsSuccess();
+ }
+
+ @Test
+ @ConnectionConfiguration(user = "noPermissions", password = "noPermissions")
+ public void testInvalidPermissionsForLuceneSearchIndexFunctionWithRegionParameter()
+ throws Exception {
+ Function thisFunction = luceneSearchIndexFunction;
+ ResourcePermission thisRequiredPermission = DATA_READ_REGION;
+
+ gfsh.executeAndAssertThat(
+ "execute function --region=" + regionName + " --id=" + thisFunction.getId())
+ .containsOutput("not authorized for " + thisRequiredPermission.toString())
+ .statusIsSuccess();
+ }
+
+ @Test
+ @ConnectionConfiguration(user = "noPermissions", password = "noPermissions")
+ public void testInvalidPermissionsForLuceneQueryFunctionWithoutRegionParameter()
+ throws Exception {
+ Function thisFunction = luceneQueryFunction;
+ ResourcePermission thisRequiredPermission = DATA_READ;
+
+ gfsh.executeAndAssertThat("execute function --id=" + thisFunction.getId())
+ .containsOutput("not authorized for " + thisRequiredPermission.toString())
+ .statusIsSuccess();
+ }
+
+ @Test
+ @ConnectionConfiguration(user = "noPermissions", password = "noPermissions")
+ public void testInvalidPermissionsForLuceneQueryFunctionWithRegionParameter() throws Exception {
+ Function thisFunction = luceneQueryFunction;
+ ResourcePermission thisRequiredPermission = DATA_READ_REGION;
+
+ gfsh.executeAndAssertThat(
+ "execute function --region=" + regionName + " --id=" + thisFunction.getId())
+ .containsOutput("not authorized for " + thisRequiredPermission.toString())
+ .statusIsSuccess();
+ }
+
+ @Test
+ @ConnectionConfiguration(user = "noPermissions", password = "noPermissions")
+ public void testInvalidPermissionsForWaitUntilFlushedFunctionWithoutRegionParameter()
+ throws Exception {
+ Function thisFunction = waitUntilFlushedFunction;
+ ResourcePermission thisRequiredPermission = DATA_READ;
+
+ gfsh.executeAndAssertThat("execute function --id=" + thisFunction.getId())
+ .containsOutput("not authorized for " + thisRequiredPermission.toString())
+ .statusIsSuccess();
+ }
+
+ @Test
+ @ConnectionConfiguration(user = "noPermissions", password = "noPermissions")
+ public void testInvalidPermissionsForWaitUntilFlushedFunctionWithRegionParameter()
+ throws Exception {
+ Function thisFunction = waitUntilFlushedFunction;
+ ResourcePermission thisRequiredPermission = DATA_READ_REGION;
+
+ gfsh.executeAndAssertThat(
+ "execute function --region=" + regionName + " --id=" + thisFunction.getId())
+ .containsOutput("not authorized for " + thisRequiredPermission.toString())
+ .statusIsSuccess();
+ }
+
+ @Test
+ @ConnectionConfiguration(user = "noPermissions", password = "noPermissions")
+ public void testInvalidPermissionsForLuceneGetPageFunctionWithoutRegionParameter()
+ throws Exception {
+ Function thisFunction = luceneGetPageFunction;
+ ResourcePermission thisRequiredPermission = DATA_READ;
+
+ gfsh.executeAndAssertThat("execute function --id=" + thisFunction.getId())
+ .containsOutput("not authorized for " + thisRequiredPermission.toString())
+ .statusIsSuccess();
+ }
+
+ @Test
+ @ConnectionConfiguration(user = "noPermissions", password = "noPermissions")
+ public void testInvalidPermissionsForLuceneGetPageFunctionWithRegionParameter() throws Exception {
+ Function thisFunction = luceneGetPageFunction;
+ ResourcePermission thisRequiredPermission = DATA_READ_REGION;
+
+ gfsh.executeAndAssertThat(
+ "execute function --region=" + regionName + " --id=" + thisFunction.getId())
+ .containsOutput("not authorized for " + thisRequiredPermission.toString())
+ .statusIsSuccess();
+ }
+}
| 1
|
57a41d6b8d65069a9d6dd7c0639e24343b78b2dd
|
https://github.com/ServiceStack/ServiceStack/commit/57a41d6b8d65069a9d6dd7c0639e24343b78b2dd
|
Implemented ICustomUserAuth and fixed custom UserAuth and UserAuthDetails support
Registration feature support was fixed by implementing ICustomUserAuth. Custom UserAuth and UserAuthDetails was fixed by reintroducing reflexion.
|
diff --git a/src/ServiceStack.Authentication.RavenDb/RavenDbIndexes.cs b/src/ServiceStack.Authentication.RavenDb/RavenDbIndexes.cs
deleted file mode 100644
index 42d30684eb8..00000000000
--- a/src/ServiceStack.Authentication.RavenDb/RavenDbIndexes.cs
+++ /dev/null
@@ -1,56 +0,0 @@
-using Raven.Client.Documents.Indexes;
-using System;
-using System.Linq;
-
-namespace ServiceStack.Authentication.RavenDb
-{
- public class UserAuth_By_UserNameOrEmail : AbstractIndexCreationTask<RavenUserAuth, UserAuth_By_UserNameOrEmail.Result>
- {
- //ncrunch: no coverage start
- public class Result
- {
- public string UserName { get; set; }
- public string Email { get; set; }
- public string[] Search { get; set; }
- }
- //ncrunch: no coverage end
-
- public UserAuth_By_UserNameOrEmail()
- {
- Map = users => from user in users
- select new Result
- {
- UserName = user.UserName,
- Email = user.Email,
- Search = new[] { user.UserName, user.Email }
- };
-
- Index(x => x.Search, FieldIndexing.Exact);
- }
- }
-
- public class UserAuth_By_UserAuthDetails : AbstractIndexCreationTask<RavenUserAuthDetails, UserAuth_By_UserAuthDetails.Result>
- {
- //ncrunch: no coverage start
- public class Result
- {
- public string Provider { get; set; }
- public string UserId { get; set; }
- public string UserAuthId { get; set; }
- public DateTime ModifiedDate { get; set; }
- }
- //ncrunch: no coverage end
-
- public UserAuth_By_UserAuthDetails()
- {
- Map = userDetails => from userDetail in userDetails
- select new Result
- {
- Provider = userDetail.Provider,
- UserId = userDetail.UserId,
- ModifiedDate = userDetail.ModifiedDate,
- UserAuthId = userDetail.RefIdStr,
- };
- }
- }
-}
diff --git a/src/ServiceStack.Authentication.RavenDb/RavenDbUserAuthRepository.cs b/src/ServiceStack.Authentication.RavenDb/RavenDbUserAuthRepository.cs
index 10d0886ef86..0823e6de2a1 100644
--- a/src/ServiceStack.Authentication.RavenDb/RavenDbUserAuthRepository.cs
+++ b/src/ServiceStack.Authentication.RavenDb/RavenDbUserAuthRepository.cs
@@ -12,7 +12,7 @@ public class RavenDbUserAuthRepository : RavenDbUserAuthRepository<RavenUserAuth
public static Func<MemberInfo, bool> FindIdentityProperty { get; set; } = DefaultFindIdentityProperty;
- public static bool DefaultFindIdentityProperty(MemberInfo p) =>
+ public static bool DefaultFindIdentityProperty(MemberInfo p) =>
p.Name == (p.DeclaringType.FirstAttribute<IndexAttribute>()?.Name ?? "Id");
}
}
\ No newline at end of file
diff --git a/src/ServiceStack.Authentication.RavenDb/RavenDbUserAuthRepositoryAsync.cs b/src/ServiceStack.Authentication.RavenDb/RavenDbUserAuthRepositoryAsync.cs
index 6c6b3eab281..87ede5d0070 100644
--- a/src/ServiceStack.Authentication.RavenDb/RavenDbUserAuthRepositoryAsync.cs
+++ b/src/ServiceStack.Authentication.RavenDb/RavenDbUserAuthRepositoryAsync.cs
@@ -14,32 +14,33 @@ public partial class RavenDbUserAuthRepository<TUserAuth, TUserAuthDetails> : IU
where TUserAuth : class, IUserAuth
where TUserAuthDetails : class, IUserAuthDetails
{
- public static async Task CreateOrUpdateUserAuthIndexAsync(IDocumentStore store, CancellationToken token=default)
+ public static async Task CreateOrUpdateUserAuthIndexAsync(IDocumentStore store, CancellationToken token = default)
{
// put this index into the ravendb database
await new UserAuth_By_UserNameOrEmail().ExecuteAsync(store, token: token).ConfigAwait();
await new UserAuth_By_UserAuthDetails().ExecuteAsync(store, token: token).ConfigAwait();
- UserAuthIndexCreated = true;
+ IsInitialized = true;
}
#region IUserAuthRepositoryAsync
public async Task<IUserAuth> CreateUserAuthAsync(IUserAuth newUser, string password, CancellationToken token = default)
{
- var nu = ((UserAuth)newUser).ToRavenUserAuth();
- nu.ValidateNewUser(password);
- await AssertNoExistingUserAsync(nu, token: token).ConfigAwait();
+ newUser.ValidateNewUser(password);
+
+ await AssertNoExistingUserAsync(newUser, token: token).ConfigAwait();
- nu.PopulatePasswordHashes(password);
- nu.CreatedDate = DateTime.UtcNow;
- nu.ModifiedDate = nu.CreatedDate;
+ newUser.PopulatePasswordHashes(password);
+ newUser.CreatedDate = DateTime.UtcNow;
+ newUser.ModifiedDate = newUser.CreatedDate;
using var session = documentStore.OpenAsyncSession();
- await session.StoreAsync(nu, token);
+ await session.StoreAsync(newUser, token);
+ UpdateIntKey(newUser);
await session.SaveChangesAsync(token);
- return nu;
+ return newUser;
}
public async Task DeleteUserAuthAsync(string ravenUserAuthId, CancellationToken token = default)
@@ -102,7 +103,7 @@ public async Task<IUserAuth> UpdateUserAuthAsync(IUserAuth existingUser, IUserAu
return newUser;
}
-
+
#endregion
#region IAuthRepositoryAsync
@@ -135,13 +136,10 @@ public async Task<IUserAuthDetails> CreateOrMergeAuthSessionAsync(IAuthSession a
userAuth.CreatedDate = userAuth.ModifiedDate;
await session.StoreAsync(userAuth, token);
+ UpdateIntKey(userAuth);
await session.SaveChangesAsync(token);
- var key = ((RavenUserAuth)userAuth).Key;
-
- if (userAuth.Id == default)
- userAuth.Id = RavenIdConverter.ToInt(key);
-
+ var key = GetKey(userAuth);
authDetails.UserAuthId = userAuth.Id; // Partial FK int Id
authDetails.RefIdStr = key; // FK
@@ -182,7 +180,7 @@ public async Task<IUserAuth> GetUserAuthAsync(IAuthSession authSession, IAuthTok
if (oAuthProvider != null)
{
- var userAuth = await session.LoadAsync<TUserAuth>(RavenIdConverter.ToString(RavenIdConverter.RavenUserAuthsIdPrefix, oAuthProvider.UserAuthId), token);
+ var userAuth = await session.LoadAsync<TUserAuth>(RavenIdConverter.ToString(UserAuthCollectionName, oAuthProvider.UserAuthId), token);
return userAuth;
}
return null;
@@ -196,7 +194,7 @@ public async Task<IUserAuth> GetUserAuthByUserNameAsync(string userNameOrEmail,
.Where(x => x.Search.Contains(userNameOrEmail))
.OfType<TUserAuth>()
.FirstOrDefaultAsync(token).ConfigAwait();
-
+
return userAuth;
}
@@ -221,11 +219,11 @@ public async Task LoadUserAuthAsync(IAuthSession session, IAuthTokens tokens, Ca
await LoadUserAuthAsync(session, (TUserAuth)userAuth, token).ConfigAwait();
}
- async Task LoadUserAuthAsync(IAuthSession session, TUserAuth userAuth, CancellationToken token = default)
- {
- UpdateSessionKey(session, userAuth);
- await session.PopulateSessionAsync(userAuth, this, token).ConfigAwait();
- }
+ async Task LoadUserAuthAsync(IAuthSession session, TUserAuth userAuth, CancellationToken token = default)
+ {
+ UpdateSessionKey(session, userAuth);
+ await session.PopulateSessionAsync(userAuth, this, token).ConfigAwait();
+ }
public async Task SaveUserAuthAsync(IAuthSession authSession, CancellationToken token = default)
{
@@ -240,18 +238,18 @@ public async Task SaveUserAuthAsync(IAuthSession authSession, CancellationToken
await session.SaveChangesAsync(token);
}
- static async Task<TUserAuth> LoadOrCreateFromSessionAsync(IAuthSession authSession, Raven.Client.Documents.Session.IAsyncDocumentSession session)
+ static async Task<TUserAuth> LoadOrCreateFromSessionAsync(IAuthSession authSession, Raven.Client.Documents.Session.IAsyncDocumentSession session)
+ {
+ TUserAuth userAuth;
+ if (!authSession.UserAuthId.IsNullOrEmpty())
{
- TUserAuth userAuth;
- if (!authSession.UserAuthId.IsNullOrEmpty())
- {
- var ravenKey = RavenIdConverter.ToString(RavenIdConverter.RavenUserAuthsIdPrefix, int.Parse(authSession.UserAuthId));
- userAuth = await session.LoadAsync<TUserAuth>(ravenKey);
- }
- else
- userAuth = authSession.ConvertTo<TUserAuth>();
- return userAuth;
+ var ravenKey = RavenIdConverter.ToString(UserAuthCollectionName, int.Parse(authSession.UserAuthId));
+ userAuth = await session.LoadAsync<TUserAuth>(ravenKey);
}
+ else
+ userAuth = authSession.ConvertTo<TUserAuth>();
+ return userAuth;
+ }
public async Task SaveUserAuthAsync(IUserAuth userAuth, CancellationToken token = default)
{
@@ -296,7 +294,7 @@ public async Task<IUserAuth> TryAuthenticateAsync(Dictionary<string, string> dig
return null;
}
-
+
async Task AssertNoExistingUserAsync(IUserAuth newUser, IUserAuth exceptForExistingUser = null, CancellationToken token = default)
{
if (newUser.UserName != null)
@@ -332,7 +330,7 @@ public async Task<List<IUserAuth>> SearchUserAuthsAsync(string query, string ord
using var session = documentStore.OpenAsyncSession();
// RavenDB cant query string Contains/IndexOf
var q = session.Query<TUserAuth>()
- .Where(x => x.UserName.StartsWith(query) || x.UserName.EndsWith(query) ||
+ .Where(x => x.UserName.StartsWith(query) || x.UserName.EndsWith(query) ||
x.Email.StartsWith(query) || x.Email.EndsWith(query))
.Customize(x => x.WaitForNonStaleResults());
diff --git a/src/ServiceStack.Authentication.RavenDb/RavenDbUserAuthRepositorySync.cs b/src/ServiceStack.Authentication.RavenDb/RavenDbUserAuthRepositorySync.cs
index a4b0c625152..b96b099334d 100644
--- a/src/ServiceStack.Authentication.RavenDb/RavenDbUserAuthRepositorySync.cs
+++ b/src/ServiceStack.Authentication.RavenDb/RavenDbUserAuthRepositorySync.cs
@@ -1,4 +1,5 @@
using Raven.Client.Documents;
+using Raven.Client.Documents.Indexes;
using Raven.Client.Documents.Linq;
using ServiceStack.Auth;
using System;
@@ -7,20 +8,44 @@
namespace ServiceStack.Authentication.RavenDb
{
- public partial class RavenDbUserAuthRepository<TUserAuth, TUserAuthDetails> : IUserAuthRepository, IQueryUserAuth
+ public partial class RavenDbUserAuthRepository<TUserAuth, TUserAuthDetails> : IUserAuthRepository, IQueryUserAuth, ICustomUserAuth
where TUserAuth : class, IUserAuth
where TUserAuthDetails : class, IUserAuthDetails
{
readonly IDocumentStore documentStore;
- public static bool UserAuthIndexCreated { get; private set; } = false;
+ public static bool IsInitialized { get; private set; } = false;
+ static TypeProperties UserAuthProps = TypeProperties<TUserAuth>.Instance;
+ static TypeProperties UserAuthDetailsProps = TypeProperties<TUserAuthDetails>.Instance;
+ static string UserAuthCollectionName { get; set; }
+
+ static RavenDbUserAuthRepository()
+ {
+ var typeName = typeof(TUserAuth).Name;
+ UserAuthCollectionName = typeName.ToLower().EndsWith("s") ? typeName : typeName + "s";
+ }
+
+ public string UserAuthIdentifier { get; set; } = nameof(RavenUserAuth.Key);
+ public string UserAuthDetailsIdentifier { get; set; } = nameof(RavenUserAuthDetails.Key);
public static void CreateOrUpdateUserAuthIndex(IDocumentStore store)
{
new UserAuth_By_UserNameOrEmail().Execute(store);
new UserAuth_By_UserAuthDetails().Execute(store);
- UserAuthIndexCreated = true;
+ IsInitialized = true;
}
+ private PropertyAccessor userAuthKeyProp;
+ private PropertyAccessor UserAuthKeyProp => userAuthKeyProp
+ ??= UserAuthProps.GetAccessor(UserAuthIdentifier)
+ ?? throw new NotSupportedException($"{typeof(TUserAuth).Name} does not contain '{UserAuthIdentifier}' property, add property or specify alternate Raven Identifier in UserAuthIdentifier");
+
+
+ private PropertyAccessor userAuthDetailsKeyProp;
+ private PropertyAccessor UserAuthDetailsKeyProp => userAuthDetailsKeyProp
+ ??= UserAuthDetailsProps.GetAccessor(UserAuthDetailsIdentifier)
+ ?? throw new NotSupportedException(typeof(TUserAuthDetails).Name +
+ $" does not contain '{UserAuthDetailsIdentifier}' property, add property or specify alternate Raven Identifier in UserAuthDetailsIdentifier");
+
public RavenDbUserAuthRepository(IDocumentStore documentStore)
{
this.documentStore = documentStore;
@@ -30,39 +55,95 @@ public RavenDbUserAuthRepository(IDocumentStore documentStore)
RegisterPopulator();
}
- static void EnsureThatUniqueIndexesAreCreated(IDocumentStore documentStore)
+ static void EnsureThatUniqueIndexesAreCreated(IDocumentStore documentStore)
+ {
+ if (!IsInitialized)
+ CreateOrUpdateUserAuthIndex(documentStore);
+ }
+
+ void RegisterPopulator()
+ {
+ var existingPopulator = AutoMappingUtils.GetPopulator(typeof(IAuthSession), typeof(IUserAuth));
+ AutoMapping.RegisterPopulator((IAuthSession session, IUserAuth userAuth) =>
+ {
+ existingPopulator?.Invoke(session, userAuth);
+ UpdateSessionKey(session, userAuth);
+ });
+ }
+
+ public class UserAuth_By_UserNameOrEmail : AbstractIndexCreationTask<TUserAuth, UserAuth_By_UserNameOrEmail.Result>
+ {
+ public class Result
{
- if (!UserAuthIndexCreated)
- CreateOrUpdateUserAuthIndex(documentStore);
+ public string UserName { get; set; }
+ public string Email { get; set; }
+ public string[] Search { get; set; }
}
- void RegisterPopulator()
+ public UserAuth_By_UserNameOrEmail()
{
- var existingPopulator = AutoMappingUtils.GetPopulator(typeof(IAuthSession), typeof(IUserAuth));
- AutoMapping.RegisterPopulator((IAuthSession session, IUserAuth userAuth) =>
- {
- existingPopulator?.Invoke(session, userAuth);
- UpdateSessionKey(session, userAuth);
- });
+ Map = users => from user in users
+ select new Result
+ {
+ UserName = user.UserName,
+ Email = user.Email,
+ Search = new[] { user.UserName, user.Email }
+ };
+
+ Index(x => x.Search, FieldIndexing.Exact);
}
+ }
+
+ public class UserAuth_By_UserAuthDetails : AbstractIndexCreationTask<TUserAuthDetails, UserAuth_By_UserAuthDetails.Result>
+ {
+ public class Result
+ {
+ public string Provider { get; set; }
+ public string UserId { get; set; }
+ public string UserAuthId { get; set; }
+ public DateTime ModifiedDate { get; set; }
+ }
+
+ public UserAuth_By_UserAuthDetails()
+ {
+ Map = userDetails => from userDetail in userDetails
+ select new Result
+ {
+ Provider = userDetail.Provider,
+ UserId = userDetail.UserId,
+ ModifiedDate = userDetail.ModifiedDate,
+ UserAuthId = userDetail.RefIdStr,
+ };
+ }
+ }
#region IUserAuthRepository
public IUserAuth CreateUserAuth(IUserAuth newUser, string password)
{
- var nu = ((UserAuth)newUser).ToRavenUserAuth();
- nu.ValidateNewUser(password);
+ newUser.ValidateNewUser(password);
- AssertNoExistingUser(nu);
+ AssertNoExistingUser(newUser);
- nu.PopulatePasswordHashes(password);
- nu.CreatedDate = DateTime.UtcNow;
- nu.ModifiedDate = nu.CreatedDate;
+ newUser.PopulatePasswordHashes(password);
+ newUser.CreatedDate = DateTime.UtcNow;
+ newUser.ModifiedDate = newUser.CreatedDate;
using var session = documentStore.OpenSession();
- session.Store(nu);
+ session.Store(newUser);
+ UpdateIntKey(newUser);
session.SaveChanges();
+ return newUser;
+ }
- return nu;
+ void UpdateIntKey(IUserAuth newUser)
+ {
+ var key = (string)UserAuthKeyProp.PublicGetter(newUser);
+ newUser.Id = RavenIdConverter.ToInt(key);
+ }
+
+ string GetKey(IUserAuth newUser)
+ {
+ return (string)UserAuthKeyProp.PublicGetter(newUser);
}
public void DeleteUserAuth(string ravenUserAuthId)
@@ -155,9 +236,10 @@ public IUserAuthDetails CreateOrMergeAuthSession(IAuthSession authSession, IAuth
userAuth.CreatedDate = (userAuth.CreatedDate == default) ? userAuth.ModifiedDate : userAuth.CreatedDate;
session.Store(userAuth);
+ UpdateIntKey(userAuth);
session.SaveChanges();
- var key = ((RavenUserAuth)userAuth).Key;
+ var key = GetKey(userAuth);
authDetails.UserAuthId = userAuth.Id; // Partial FK int Id
authDetails.RefIdStr = key; // FK
@@ -200,7 +282,7 @@ public IUserAuth GetUserAuth(IAuthSession authSession, IAuthTokens tokens)
.FirstOrDefault();
if (oAuthProvider != null)
- return session.Load<TUserAuth>(RavenIdConverter.ToString(RavenIdConverter.RavenUserAuthsIdPrefix, oAuthProvider.UserAuthId));
+ return session.Load<TUserAuth>(RavenIdConverter.ToString(UserAuthCollectionName, oAuthProvider.UserAuthId));
return null;
}
@@ -238,11 +320,11 @@ public void LoadUserAuth(IAuthSession session, IAuthTokens tokens)
LoadUserAuth(session, (TUserAuth)userAuth);
}
- void LoadUserAuth(IAuthSession session, TUserAuth userAuth)
- {
- UpdateSessionKey(session, userAuth);
- session.PopulateSession(userAuth, this);
- }
+ void LoadUserAuth(IAuthSession session, TUserAuth userAuth)
+ {
+ UpdateSessionKey(session, userAuth);
+ session.PopulateSession(userAuth, this);
+ }
public void SaveUserAuth(IAuthSession authSession)
{
@@ -257,18 +339,18 @@ public void SaveUserAuth(IAuthSession authSession)
session.SaveChanges();
}
- static TUserAuth LoadOrCreateFromSession(IAuthSession authSession, Raven.Client.Documents.Session.IDocumentSession session)
+ static TUserAuth LoadOrCreateFromSession(IAuthSession authSession, Raven.Client.Documents.Session.IDocumentSession session)
+ {
+ TUserAuth userAuth = null;
+ if (!authSession.UserAuthId.IsNullOrEmpty())
{
- TUserAuth userAuth = null;
- if (!authSession.UserAuthId.IsNullOrEmpty())
- {
- var ravenKey = RavenIdConverter.ToString(RavenIdConverter.RavenUserAuthsIdPrefix, int.Parse(authSession.UserAuthId));
- userAuth = session.Load<TUserAuth>(ravenKey);
- }
- else
- userAuth = authSession.ConvertTo<TUserAuth>();
- return userAuth;
+ var ravenKey = RavenIdConverter.ToString(UserAuthCollectionName, int.Parse(authSession.UserAuthId));
+ userAuth = session.Load<TUserAuth>(ravenKey);
}
+ else
+ userAuth = authSession.ConvertTo<TUserAuth>();
+ return userAuth;
+ }
public void SaveUserAuth(IUserAuth userAuth)
{
@@ -318,15 +400,17 @@ public bool TryAuthenticate(Dictionary<string, string> digestHeaders, string pri
void UpdateSessionKey(IAuthSession session, IUserAuth userAuth)
{
- var ra = userAuth.ConvertTo<RavenUserAuth>();
- if (ra.Id != default)
- ra.Key = RavenIdConverter.ToString(RavenIdConverter.RavenUserAuthsIdPrefix, ra.Id);
- session.UserAuthId = ra.Key;
+ var keyProp = UserAuthProps.GetAccessor(UserAuthIdentifier);
+ if (keyProp != null)
+ {
+ session.UserAuthId = (string)keyProp.PublicGetter(userAuth);
+ }
}
void UpdateKey(IUserAuth existingUser, IUserAuth newUser)
{
- ((RavenUserAuth)newUser).Key = ((RavenUserAuth)existingUser).Key;
+ var keyProp = UserAuthKeyProp;
+ keyProp.PublicSetter(newUser, keyProp.PublicGetter(existingUser));
}
void AssertNoExistingUser(IUserAuth newUser, IUserAuth exceptForExistingUser = null)
@@ -389,5 +473,17 @@ static IQueryable<TUserAuth> SortAndPage(IRavenQueryable<TUserAuth> q, string or
return qEnum;
}
#endregion
+
+ #region ICustomUserAuth
+ IUserAuth ICustomUserAuth.CreateUserAuth()
+ {
+ return Activator.CreateInstance<TUserAuth>();
+ }
+
+ IUserAuthDetails ICustomUserAuth.CreateUserAuthDetails()
+ {
+ return Activator.CreateInstance<TUserAuthDetails>();
+ }
+ #endregion
}
}
\ No newline at end of file
diff --git a/src/ServiceStack.Authentication.RavenDb/RavenIdConverter.cs b/src/ServiceStack.Authentication.RavenDb/RavenIdConverter.cs
index 4b47cb5eece..cb69b0b2d88 100644
--- a/src/ServiceStack.Authentication.RavenDb/RavenIdConverter.cs
+++ b/src/ServiceStack.Authentication.RavenDb/RavenIdConverter.cs
@@ -8,7 +8,6 @@ namespace ServiceStack.Authentication.RavenDb
/// </summary>
public static class RavenIdConverter
{
- public const string RavenUserAuthsIdPrefix = "RavenUserAuths";
const int ClusterTagOffset = 100;
const int ASCIIOffset = 65;
@@ -19,10 +18,10 @@ public static int ToInt(string ravenId)
return Convert.ToInt32(idParts[0]) * ClusterTagOffset + ClusterTagToInt(idParts[1]);
}
- static int ClusterTagToInt(string tag)
- {
- return tag[0] - ASCIIOffset;
- }
+ static int ClusterTagToInt(string tag)
+ {
+ return tag[0] - ASCIIOffset;
+ }
public static string ToString(string prefix, int id)
{
diff --git a/src/ServiceStack.Authentication.RavenDb/RavenUserAuth.cs b/src/ServiceStack.Authentication.RavenDb/RavenUserAuth.cs
index 99539898e13..176f99925dd 100644
--- a/src/ServiceStack.Authentication.RavenDb/RavenUserAuth.cs
+++ b/src/ServiceStack.Authentication.RavenDb/RavenUserAuth.cs
@@ -1,24 +1,12 @@
using ServiceStack.Auth;
using ServiceStack.DataAnnotations;
using System;
-using System.Linq;
namespace ServiceStack.Authentication.RavenDb
{
[Index(Name = nameof(Key))]
public class RavenUserAuth : UserAuth
{
- string key;
-
- public string Key
- {
- get => key;
-
- set
- {
- key = value;
- Id = RavenIdConverter.ToInt(key);
- }
- }
+ public string Key { get; set; }
}
}
\ No newline at end of file
diff --git a/src/ServiceStack.Authentication.RavenDb/RavenUserAuthDetails.cs b/src/ServiceStack.Authentication.RavenDb/RavenUserAuthDetails.cs
index fa5604a8944..e7ab1ead9c5 100644
--- a/src/ServiceStack.Authentication.RavenDb/RavenUserAuthDetails.cs
+++ b/src/ServiceStack.Authentication.RavenDb/RavenUserAuthDetails.cs
@@ -1,24 +1,12 @@
using ServiceStack.Auth;
using ServiceStack.DataAnnotations;
using System;
-using System.Linq;
namespace ServiceStack.Authentication.RavenDb
{
[Index(Name = nameof(Key))]
public class RavenUserAuthDetails : UserAuthDetails
{
- string key;
-
- public string Key
- {
- get => key;
-
- set
- {
- key = value;
- Id = RavenIdConverter.ToInt(key);
- }
- }
+ public string Key { get; set; }
}
}
\ No newline at end of file
diff --git a/src/ServiceStack.Authentication.RavenDb/UserAuthExtensions.cs b/src/ServiceStack.Authentication.RavenDb/UserAuthExtensions.cs
deleted file mode 100644
index f72aa4d5745..00000000000
--- a/src/ServiceStack.Authentication.RavenDb/UserAuthExtensions.cs
+++ /dev/null
@@ -1,15 +0,0 @@
-using ServiceStack.Auth;
-
-namespace ServiceStack.Authentication.RavenDb
-{
- public static class UserAuthExtensions
- {
- public static RavenUserAuth ToRavenUserAuth(this UserAuth ua)
- {
- var ra = ua.ConvertTo<RavenUserAuth>();
- if (ua.Id > 0)
- ra.Key = RavenIdConverter.ToString(RavenIdConverter.RavenUserAuthsIdPrefix, ua.Id);
- return ra;
- }
- }
-}
\ No newline at end of file
| 0
|
f260b975e5007ea8a32bb1a76d77a6144cc11e16
|
https://github.com/PHP-DI/PHP-DI/commit/f260b975e5007ea8a32bb1a76d77a6144cc11e16
|
Fix version requirements
|
diff --git a/tests/UnitTest/Definition/Source/AnnotationBasedAutowiringTest.php b/tests/UnitTest/Definition/Source/AnnotationBasedAutowiringTest.php
index 12e6c1e1..f42fe98a 100644
--- a/tests/UnitTest/Definition/Source/AnnotationBasedAutowiringTest.php
+++ b/tests/UnitTest/Definition/Source/AnnotationBasedAutowiringTest.php
@@ -66,7 +66,8 @@ public function testUnguessableProperty()
}
/**
- * @requires PHP >= 7.4 Typed properties support requires PHP7.4
+ * Typed properties support requires PHP 7.4
+ * @requires PHP 7.4
*/
public function testTypedProperty()
{
@@ -79,7 +80,8 @@ public function testTypedProperty()
}
/**
- * @requires PHP >= 7.4 Typed properties support requires PHP7.4
+ * Typed properties support requires PHP 7.4
+ * @requires PHP 7.4
*/
public function testScalarTypedPropertiesFail()
{
| 0
|
13356a7ee2240f740737c5c83bdccdacc30603a
|
https://github.com/spring-projects/spring-framework/commit/13356a7ee2240f740737c5c83bdccdacc30603a
|
Consistent encoded path evaluation in reactive ResourceWebHandler and co
Issue: SPR-16616
|
diff --git a/spring-webflux/src/main/java/org/springframework/web/reactive/resource/PathResourceResolver.java b/spring-webflux/src/main/java/org/springframework/web/reactive/resource/PathResourceResolver.java
index 5fa5a20692a0..37bcff4b2348 100644
--- a/spring-webflux/src/main/java/org/springframework/web/reactive/resource/PathResourceResolver.java
+++ b/spring-webflux/src/main/java/org/springframework/web/reactive/resource/PathResourceResolver.java
@@ -1,5 +1,5 @@
/*
- * Copyright 2002-2017 the original author or authors.
+ * Copyright 2002-2018 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@@ -17,6 +17,7 @@
package org.springframework.web.reactive.resource;
import java.io.IOException;
+import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;
import java.util.Arrays;
import java.util.List;
@@ -184,21 +185,21 @@ else if (resource instanceof ClassPathResource) {
return true;
}
locationPath = (locationPath.endsWith("/") || locationPath.isEmpty() ? locationPath : locationPath + "/");
- if (!resourcePath.startsWith(locationPath)) {
- return false;
- }
+ return (resourcePath.startsWith(locationPath) && !isInvalidEncodedPath(resourcePath));
+ }
+ private boolean isInvalidEncodedPath(String resourcePath) {
if (resourcePath.contains("%")) {
// Use URLDecoder (vs UriUtils) to preserve potentially decoded UTF-8 chars...
- if (URLDecoder.decode(resourcePath, "UTF-8").contains("../")) {
- if (logger.isTraceEnabled()) {
- logger.trace("Resolved resource path contains \"../\" after decoding: " + resourcePath);
- }
- return false;
+ try {
+ String decodedPath = URLDecoder.decode(resourcePath, "UTF-8");
+ return (decodedPath.contains("../") || decodedPath.contains("..\\"));
+ }
+ catch (UnsupportedEncodingException ex) {
+ // Should never happen...
}
}
-
- return true;
+ return false;
}
}
diff --git a/spring-webflux/src/main/java/org/springframework/web/reactive/resource/ResourceWebHandler.java b/spring-webflux/src/main/java/org/springframework/web/reactive/resource/ResourceWebHandler.java
index 215a50f6c8d6..1d1782a392c4 100644
--- a/spring-webflux/src/main/java/org/springframework/web/reactive/resource/ResourceWebHandler.java
+++ b/spring-webflux/src/main/java/org/springframework/web/reactive/resource/ResourceWebHandler.java
@@ -28,7 +28,6 @@
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
-import reactor.core.Exceptions;
import reactor.core.publisher.Mono;
import org.springframework.beans.factory.InitializingBean;
@@ -314,9 +313,9 @@ protected void initAllowedLocations() {
}
protected Mono<Resource> getResource(ServerWebExchange exchange) {
-
String name = HandlerMapping.PATH_WITHIN_HANDLER_MAPPING_ATTRIBUTE;
PathContainer pathWithinHandler = exchange.getRequiredAttribute(name);
+
String path = processPath(pathWithinHandler.value());
if (!StringUtils.hasText(path) || isInvalidPath(path)) {
if (logger.isTraceEnabled()) {
@@ -324,31 +323,11 @@ protected void initAllowedLocations() {
}
return Mono.empty();
}
-
- if (path.contains("%")) {
- try {
- // Use URLDecoder (vs UriUtils) to preserve potentially decoded UTF-8 chars
- String decodedPath = URLDecoder.decode(path, "UTF-8");
- if (isInvalidPath(decodedPath)) {
- if (logger.isTraceEnabled()) {
- logger.trace("Ignoring invalid resource path with escape sequences [" + path + "].");
- }
- return Mono.empty();
- }
- decodedPath = processPath(decodedPath);
- if (isInvalidPath(decodedPath)) {
- if (logger.isTraceEnabled()) {
- logger.trace("Ignoring invalid resource path with escape sequences [" + path + "].");
- }
- return Mono.empty();
- }
- }
- catch (IllegalArgumentException ex) {
- // ignore
- }
- catch (UnsupportedEncodingException ex) {
- return Mono.error(Exceptions.propagate(ex));
+ if (isInvalidEncodedPath(path)) {
+ if (logger.isTraceEnabled()) {
+ logger.trace("Ignoring invalid resource path with escape sequences [" + path + "]");
}
+ return Mono.empty();
}
ResourceResolverChain resolveChain = createResolverChain();
@@ -420,6 +399,31 @@ else if (path.charAt(i) > ' ' && path.charAt(i) != 127) {
return (slash ? "/" : "");
}
+ /**
+ * Check whether the given path contains invalid escape sequences.
+ * @param path the path to validate
+ * @return {@code true} if the path is invalid, {@code false} otherwise
+ */
+ private boolean isInvalidEncodedPath(String path) {
+ if (path.contains("%")) {
+ try {
+ // Use URLDecoder (vs UriUtils) to preserve potentially decoded UTF-8 chars
+ String decodedPath = URLDecoder.decode(path, "UTF-8");
+ if (isInvalidPath(decodedPath)) {
+ return true;
+ }
+ decodedPath = processPath(decodedPath);
+ if (isInvalidPath(decodedPath)) {
+ return true;
+ }
+ }
+ catch (IllegalArgumentException | UnsupportedEncodingException ex) {
+ // Should never happen...
+ }
+ }
+ return false;
+ }
+
/**
* Identifies invalid resource paths. By default rejects:
* <ul>
| 1
|
3c054726596c81459acf4c4c6be057f81d7924b1
|
https://github.com/apache/commons-compress/commit/3c054726596c81459acf4c4c6be057f81d7924b1
|
Remove unused import.
|
diff --git a/src/main/java/org/apache/commons/compress/archivers/examples/Archiver.java b/src/main/java/org/apache/commons/compress/archivers/examples/Archiver.java
index d87fa2dd4..835875353 100644
--- a/src/main/java/org/apache/commons/compress/archivers/examples/Archiver.java
+++ b/src/main/java/org/apache/commons/compress/archivers/examples/Archiver.java
@@ -34,7 +34,6 @@
import java.nio.file.attribute.BasicFileAttributes;
import java.util.EnumSet;
import java.util.Objects;
-import java.util.function.BiConsumer;
import org.apache.commons.compress.archivers.ArchiveEntry;
import org.apache.commons.compress.archivers.ArchiveException;
| 0
|
4b8fa410e5d0b2ba642ea7bc0a68e528ad7f8d06
|
https://github.com/Sigil-Ebook/Sigil/commit/4b8fa410e5d0b2ba642ea7bc0a68e528ad7f8d06
|
move to qCSSParser and add line no to token plus some cleanups
|
diff --git a/src/CMakeLists.txt b/src/CMakeLists.txt
index 18479c576..047c664dc 100644
--- a/src/CMakeLists.txt
+++ b/src/CMakeLists.txt
@@ -336,12 +336,12 @@ set( MISC_FILES
Misc/CSSHighlighter.h
Misc/CSSInfo.cpp
Misc/CSSInfo.h
- Misc/CSSParser.cpp
- Misc/CSSParser.h
- Misc/CSSUtils.cpp
- Misc/CSSUtils.h
- Misc/CSSProperties.cpp
- Misc/CSSProperties.h
+ Misc/qCSSParser.cpp
+ Misc/qCSSParser.h
+ Misc/qCSSUtils.cpp
+ Misc/qCSSUtils.h
+ Misc/qCSSProperties.cpp
+ Misc/qCSSProperties.h
Misc/DiffRec.h
Misc/HTMLEncodingResolver.cpp
Misc/HTMLEncodingResolver.h
diff --git a/src/Misc/CSSParser.h b/src/Misc/CSSParser.h
deleted file mode 100644
index e64e408a4..000000000
--- a/src/Misc/CSSParser.h
+++ /dev/null
@@ -1,188 +0,0 @@
-/************************************************************************
- **
- ** Copyright (C) 2021 Kevin B. Hendricks, Stratford, Ontario, Canada
- **
- ** This file is part of Sigil.
- **
- ** Sigil is free software: you can redistribute it and/or modify
- ** it under the terms of the GNU General Public License as published by
- ** the Free Software Foundation, either version 3 of the License, or
- ** (at your option) any later version.
- **
- ** Sigil is distributed in the hope that it will be useful,
- ** but WITHOUT ANY WARRANTY; without even the implied warranty of
- ** MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
- ** GNU General Public License for more details.
- **
- ** You should have received a copy of the GNU General Public License
- ** along with Sigil. If not, see <http://www.gnu.org/licenses/>.
- **
- ** Extracted and modified from:
- ** CSSTidy Copyright 2005-2007 Florian Schmitz
- ** Available under the LGPL 2.1
- ** You should have received a copy of the GNU Lesser General Public License
- ** along with this program. If not, see <http://www.gnu.org/licenses/>.
- **
- *************************************************************************/
-
-#ifndef HEADER_CSSPARSER
-#define HEADER_CSSPARSER
-
-#include <cstdlib>
-#include <utility>
-#include <string>
-#include <iterator>
-#include <vector>
-#include <assert.h>
-#include <math.h>
-#include <time.h>
-#include <sstream>
-#include <iostream>
-#include <fstream>
-#include <map>
-#include <algorithm>
-
-class CSSParser
-{
-
-public:
-
- enum parse_status
- {
- PIS, PIP, PIV, PINSTR, PIC, PAT
- };
-
- enum message_type
- {
- Information,Warning,Error
- };
-
- enum token_type
- {
- CHARSET, IMPORT, NAMESP, AT_START, AT_END, SEL_START, SEL_END, PROPERTY, VALUE, COMMENT, CSS_END
- };
-
- struct token
- {
- token_type type;
- int pos;
- std::string data;
- };
-
- struct message
- {
- std::string m;
- message_type t;
- };
-
- CSSParser();
-
- // valid levels are "CSS1.0", "CSS2.0", "CSS2.1", "CSS3.0"
- void set_level(std::string level = "CSS3.0");
-
- void parse_css(std::string css_input);
-
- void reset_parser();
-
- // serialize the current list of csstokens back to css
- std::string serialize_css(std::string filename = "", bool tostdout = true);
-
- // access charset, namespace and imports without having to walk csstokens
- std::string get_charset();
- std::vector<std::string> get_import();
- std::string get_namespace();
-
- // walk the csstokens list, token by token
- // set start_ptr to the position you woud like to start at in the list
- // leaving it as -1 will simply start at 0 and increment
- // last token is a dummy token with type set to CSS_END
- token get_next_token(int start_ptr = -1);
-
- // covert token type enum value to a descriptive string
- std::string get_type_name(token_type t);
-
- // this routine allows external modifications to the csstokens
- // to be brought back into CSSParser in order to serialize them
- // with serialize_css
- void set_csstokens(const std::vector<token> &ntokens);
-
- // get errors, warnings, and information
- std::vector<std::string> get_parse_errors();
- std::vector<std::string> get_parse_warnings();
- std::vector<std::string> get_parse_info();
-
-
-private:
-
- void parseInAtBlock(std::string& css_input, int& i, parse_status& astatus, parse_status& afrom);
-
- void parseInSelector(std::string& css_input, int& i, parse_status& astatus, parse_status& afrom,
- bool& invalid_at, char& str_char, int str_size);
-
- void parseInProperty(std::string& css_input, int& i, parse_status& astatus, parse_status& afrom,
- bool& invalid_at);
-
- void parseInValue(std::string& css_input, int& i, parse_status& astatus, parse_status& afrom,
- bool& invalid_at, char& str_char, bool& pn, int str_size );
-
- void parseInComment(std::string& css_input, int& i, parse_status& astatus, parse_status& afrom,
- std::string& cur_comment);
-
- void parseInString(std::string& css_input, int& i, parse_status& astatus, parse_status& afrom,
- char& str_char, bool& str_in_str);
-
-
- // filter the logs by message type
- std::vector<std::string> get_logs(message_type t);
-
- // parses unicode notations
- std::string unicode(std::string& istring, int& i);
-
- // checks if the chat in istring at i is a token
- bool is_token(std::string& istring, const int i);
-
- void add_token(const token_type ttype, const std::string data, const bool force = false);
-
- // Add a message to the message log
- void log(const std::string msg, const message_type type, int iline = 0);
-
- // records token position information
- void record_position(parse_status old_status, parse_status new_status,
- std::string &css_input, int i, bool force=false);
-
- int _seeknocomment(const int key, const int move);
-
- void explode_selectors();
-
- static bool property_is_next(std::string istring, int pos);
-
- // private member variables
- std::vector<std::string> token_type_names;
- std::map<std::string, parse_status> at_rules;
- std::vector<std::string> csstemplate;
- std::string css_level;
- std::string tokens;
- int token_ptr;
-
- std::map<int, std::vector<message> > logs;
- int line;
- int spos;
-
- std::string charset;
- std::string namesp;
- std::vector<std::string> import;
- std::vector<token> csstokens;
- std::string cur_selector;
- std::string cur_at;
- std::string cur_property;
- std::string cur_function;
- std::string cur_sub_value;
- std::string cur_value;
- std::string cur_string;
- std::vector<int> sel_separate;
- std::vector<std::string> cur_sub_value_arr;
- std::vector<std::string> cur_function_arr;
-
-};
-
-#endif // HEADER_CSSPARSER
diff --git a/src/Misc/CSSProperties.h b/src/Misc/CSSProperties.h
deleted file mode 100644
index ceb26a94e..000000000
--- a/src/Misc/CSSProperties.h
+++ /dev/null
@@ -1,56 +0,0 @@
-/************************************************************************
-**
-** Copyright (C) 2021 Kevin B. Hendricks, Stratford, ON, Canada
-**
-** This file is part of Sigil.
-**
-** Sigil is free software: you can redistribute it and/or modify
-** it under the terms of the GNU General Public License as published by
-** the Free Software Foundation, either version 3 of the License, or
-** (at your option) any later version.
-**
-** Sigil is distributed in the hope that it will be useful,
-** but WITHOUT ANY WARRANTY; without even the implied warranty of
-** MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
-** GNU General Public License for more details.
-**
-** You should have received a copy of the GNU General Public License
-** along with Sigil. If not, see <http://www.gnu.org/licenses/>.
-**
-*************************************************************************/
-
-#pragma once
-#ifndef CSS_PROPERTIES_H
-#define CSS_PROPERTIES_H
-
-#include <cstdlib>
-#include <string>
-#include <map>
-
-/**
- * Singleton.
- *
- * CSSProperties
- */
-
-
-class CSSProperties
-{
-
-public:
-
- static CSSProperties *instance();
-
- bool contains(std::string pname);
-
- std::string levels(std::string pname);
-
-private:
-
- CSSProperties();
-
- std::map<std::string, std::string> m_all_properties;
- static CSSProperties *m_instance;
-};
-
-#endif // CSS_PROPERTIES_H
diff --git a/src/Misc/CSSUtils.cpp b/src/Misc/CSSUtils.cpp
deleted file mode 100644
index 332fd49cc..000000000
--- a/src/Misc/CSSUtils.cpp
+++ /dev/null
@@ -1,397 +0,0 @@
-/************************************************************************
- **
- ** Copyright (C) 2021 Kevin B. Hendricks, Stratford, Ontario, Canada
- **
- ** This file is part of Sigil.
- **
- ** Sigil is free software: you can redistribute it and/or modify
- ** it under the terms of the GNU General Public License as published by
- ** the Free Software Foundation, either version 3 of the License, or
- ** (at your option) any later version.
- **
- ** Sigil is distributed in the hope that it will be useful,
- ** but WITHOUT ANY WARRANTY; without even the implied warranty of
- ** MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
- ** GNU General Public License for more details.
- **
- ** You should have received a copy of the GNU General Public License
- ** along with Sigil. If not, see <http://www.gnu.org/licenses/>.
- **
- ** Extracted and modified from:
- ** CSSTidy Copyright 2005-2007 Florian Schmitz
- ** Available under the LGPL 2.1
- ** You should have received a copy of the GNU Lesser General Public License
- ** along with this program. If not, see <http://www.gnu.org/licenses/>.
- **
- *************************************************************************/
-
-#include <cstring>
-#include "Misc/CSSUtils.h"
-
-std::string CSSUtils::strtolower(std::string istring)
-{
- int str_size = istring.length();
- for(int i = 0; i < str_size; i++)
- {
- istring[i] = chartolower(istring[i]);
- }
- return istring;
-}
-
-
-char CSSUtils::chartolower(const char c)
-{
- switch(c)
- {
- case 'A': return 'a';
- case 'B': return 'b';
- case 'C': return 'c';
- case 'D': return 'd';
- case 'E': return 'e';
- case 'F': return 'f';
- case 'G': return 'g';
- case 'H': return 'h';
- case 'I': return 'i';
- case 'J': return 'j';
- case 'K': return 'k';
- case 'L': return 'l';
- case 'M': return 'm';
- case 'N': return 'n';
- case 'O': return 'o';
- case 'P': return 'p';
- case 'Q': return 'q';
- case 'R': return 'r';
- case 'S': return 's';
- case 'T': return 't';
- case 'U': return 'u';
- case 'V': return 'v';
- case 'W': return 'w';
- case 'X': return 'x';
- case 'Y': return 'y';
- case 'Z': return 'z';
- default: return c;
- }
-}
-
-
-std::string CSSUtils::strtoupper(std::string istring)
-{
- int str_size = istring.length();
- for(int i = 0; i < str_size; i++)
- {
- istring[i] = chartoupper(istring[i]);
- }
- return istring;
-}
-
-
-char CSSUtils::chartoupper(const char c)
-{
- switch(c)
- {
- case 'a': return 'A';
- case 'b': return 'B';
- case 'c': return 'C';
- case 'd': return 'D';
- case 'e': return 'E';
- case 'f': return 'F';
- case 'g': return 'G';
- case 'h': return 'H';
- case 'i': return 'I';
- case 'j': return 'J';
- case 'k': return 'K';
- case 'l': return 'L';
- case 'm': return 'M';
- case 'n': return 'N';
- case 'o': return 'O';
- case 'p': return 'P';
- case 'q': return 'Q';
- case 'r': return 'R';
- case 's': return 'S';
- case 't': return 'T';
- case 'u': return 'U';
- case 'v': return 'V';
- case 'w': return 'W';
- case 'x': return 'X';
- case 'y': return 'Y';
- case 'z': return 'Z';
- default: return c;
- }
-}
-
-
-double CSSUtils::hexdec(std::string istring)
-{
- double ret = 0;
- istring = trim(istring);
- for(int i = istring.length()-1; i >= 0; --i)
- {
- int num = 0;
- switch(tolower(istring[i]))
- {
- case 'a': num = 10; break;
- case 'b': num = 11; break;
- case 'c': num = 12; break;
- case 'd': num = 13; break;
- case 'e': num = 14; break;
- case 'f': num = 15; break;
- case '1': num = 1; break;
- case '2': num = 2; break;
- case '3': num = 3; break;
- case '4': num = 4; break;
- case '5': num = 5; break;
- case '6': num = 6; break;
- case '7': num = 7; break;
- case '8': num = 8; break;
- case '9': num = 9; break;
- case '0': num = 0; break;
- }
- ret += num*pow((double) 16, (double) istring.length()-i-1);
- }
- return ret;
-}
-
-
-std::string CSSUtils::char2str(const char c)
-{
- std::string ret = "";
- ret += c;
- return ret;
-}
-
-
-std::string CSSUtils::char2str(const char *c)
-{
- std::stringstream sstream;
- sstream << c;
- return sstream.str();
-}
-
-
-std::string CSSUtils::file_get_contents(const std::string filename)
-{
- std::ifstream file_input(filename.c_str(),std::ios::binary);
- std::string line, file_contents = "";
-
- if(file_input.bad())
- {
- return "";
- }
- else
- {
- while(file_input.good())
- {
- getline(file_input,line);
- file_contents += (line + "\n");
- }
- }
- file_input.close();
-
- return file_contents;
-}
-
-
-bool CSSUtils::file_exists(const char *filename)
-{
- std::ifstream file_input(filename);
-
- if(file_input.is_open())
- {
- file_input.close();
- return true;
- }
-
- file_input.close();
- return false;
-}
-
-
-bool CSSUtils::escaped(const std::string &istring, const int pos)
-{
- return !(s_at(istring,pos-1) != '\\' || escaped(istring,pos-1));
-}
-
-
-// Safe replacement for .at()
-char CSSUtils::s_at(const std::string &istring, const int pos)
-{
- if(pos > (istring.length()-1) || pos < 0)
- {
- return 0;
- }
- else
- {
- return istring[pos];
- }
-}
-
-
-std::vector<std::string> CSSUtils::explode(const std::string e, std::string s, const bool check)
-{
- std::vector<std::string> ret;
- int iPos = s.find(e, 0);
- int iPit = e.length();
-
- while(iPos > -1)
- {
- if(iPos != 0 || check)
- {
- ret.push_back(s.substr(0,iPos));
- }
- s.erase(0,iPos+iPit);
- iPos = s.find(e, 0);
- }
-
- if(s != "" || check)
- {
- ret.push_back(s);
- }
- return ret;
-}
-
-
-std::string CSSUtils::implode(const std::string e, const std::vector<std::string> s)
-{
- std::string ret;
- for(int i = 0; i < s.size(); i++)
- {
- ret += s[i];
- if(i != (s.size()-1)) ret += e;
- }
- return ret;
-}
-
-
-std::string CSSUtils::build_value(const std::vector<std::string> subvalues)
-{
- std::string ret;
- for(int i = 0; i < subvalues.size(); i++)
- {
- ret += subvalues[i];
- if(i != (subvalues.size()-1))
- {
- char last = s_at(subvalues[i], subvalues[i].length()-1);
- char next = s_at(subvalues[i+1], 0);
- if (strchr("(,=:", last) != NULL || strchr("),=:", next) != NULL)
- {
- continue;
- }
- ret += " ";
- }
- }
- return ret;
-}
-
-
-std::string CSSUtils::str_replace(const std::string find, const std::string replace, std::string str)
-{
- int len = find.length();
- int replace_len = replace.length();
- int pos = str.find(find);
-
- while(pos != std::string::npos)
- {
- str.replace(pos, len, replace);
- pos = str.find(find, pos + replace_len);
- }
- return str;
-}
-
-
-
-bool CSSUtils::in_char_arr(const char* haystack, const char needle)
-{
- for(int i = 0; i < strlen(haystack); ++i)
- {
- if(haystack[i] == needle)
- {
- return true;
- }
- }
- return false;
-}
-
-
-bool CSSUtils::in_str_array(const std::string& haystack, const char needle)
-{
- return (haystack.find_first_of(needle,0) != std::string::npos);
-}
-
-
-bool CSSUtils::ctype_space(const char c)
-{
- return (c == ' ' || c == '\t' || c == '\r' || c == '\n' || c == 11);
-}
-
-
-bool CSSUtils::ctype_digit(const char c)
-{
- return (c == '0' || c == '1' || c == '2' || c == '3' || c == '4' || c == '5' || c == '6' || c == '7' || c == '8' || c == '9');
-}
-
-
-bool CSSUtils::ctype_xdigit(char c)
-{
- c = chartolower(c);
- return (ctype_digit(c) || c == 'a' || c == 'b' || c == 'c' || c == 'd' || c == 'e' || c == 'f');
-}
-
-bool CSSUtils::ctype_alpha(char c)
-{
- c = chartolower(c);
- return (c == 'a' || c == 'b' || c == 'c' || c == 'd' || c == 'e' || c == 'f' ||
- c == 'g' || c == 'h' || c == 'i' || c == 'j' || c == 'k' || c == 'l' ||
- c == 'm' || c == 'n' || c == 'o' || c == 'p' || c == 'q' || c == 'r' ||
- c == 's' || c == 't' || c == 'u' || c == 'v' || c == 'w' || c == 'x' ||
- c == 'y' || c == 'z');
-}
-
-
-const std::string CSSUtils::trim(const std::string istring)
-{
- std::string::size_type first = istring.find_first_not_of(" \n\t\r\0xb");
- if (first == std::string::npos) {
- return std::string();
- }
- else
- {
- std::string::size_type last = istring.find_last_not_of(" \n\t\r\0xb");
- return istring.substr( first, last - first + 1);
- }
-}
-
-
-const std::string CSSUtils::ltrim(const std::string istring)
-{
- std::string::size_type first = istring.find_first_not_of(" \n\t\r\0xb");
- if (first == std::string::npos) {
- return std::string();
- }
- else
- {
- return istring.substr( first );
- }
-}
-
-
-const std::string CSSUtils::rtrim(const std::string istring)
-{
- std::string::size_type last = istring.find_last_not_of(" \n\t\r\0xb"); /// must succeed
- return istring.substr( 0, last + 1);
-}
-
-
-const std::string CSSUtils::rtrim(const std::string istring, const std::string chars)
-{
- std::string::size_type last = istring.find_last_not_of(chars); /// must succeed
- return istring.substr( 0, last + 1);
-}
-
-const std::string CSSUtils::indent(int lvl, const std::string &base)
-{
- std::string ind = "";
- for (int i = 0; i < lvl; i++) {
- ind = ind + base;
- }
- return ind;
-}
diff --git a/src/Misc/CSSUtils.h b/src/Misc/CSSUtils.h
deleted file mode 100644
index 6308466da..000000000
--- a/src/Misc/CSSUtils.h
+++ /dev/null
@@ -1,109 +0,0 @@
-/************************************************************************
- **
- ** Copyright (C) 2021 Kevin B. Hendricks, Stratford, Ontario, Canada
- **
- ** This file is part of Sigil.
- **
- ** Sigil is free software: you can redistribute it and/or modify
- ** it under the terms of the GNU General Public License as published by
- ** the Free Software Foundation, either version 3 of the License, or
- ** (at your option) any later version.
- **
- ** Sigil is distributed in the hope that it will be useful,
- ** but WITHOUT ANY WARRANTY; without even the implied warranty of
- ** MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
- ** GNU General Public License for more details.
- **
- ** You should have received a copy of the GNU General Public License
- ** along with Sigil. If not, see <http://www.gnu.org/licenses/>.
- **
- ** Extracted and modified from:
- ** CSSTidy Copyright 2005-2007 Florian Schmitz
- ** Available under the LGPL 2.1
- ** You should have received a copy of the GNU Lesser General Public License
- ** along with this program. If not, see <http://www.gnu.org/licenses/>.
- **
- *************************************************************************/
-
-#ifndef HEADER_CSSUTILS
-#define HEADER_CSSUTILS
-
-#include <cstdlib>
-#include <string>
-#include <iterator>
-#include <vector>
-#include <assert.h>
-#include <math.h>
-#include <sstream>
-#include <iostream>
-#include <fstream>
-#include <algorithm>
-
-class CSSUtils
-{
-
-public:
-
- // Returns the lowercase version of a string
- static std::string strtolower(std::string istring);
-
- // Apparently faster replacement for tolower
- static char chartolower(const char c);
-
- // Returns the uppercase version of a string
- static std::string strtoupper(std::string istring);
- static char chartoupper(const char c);
-
- // Converts a hexadecimal number (string) to a decimal number
- static double hexdec(std::string istring);
-
- // Converts a char to a string
- static std::string char2str(const char c);
-
- // Converts a char to a string
- static std::string char2str(const char* c);
-
- // Get contents of a file
- static std::string file_get_contents(const std::string filename);
-
- // Checks if a file exists
- static bool file_exists(const char *filename);
-
- // Checks if a charcter is escaped
- static bool escaped(const std::string &istring, int pos);
-
- // Returns a char of a std::string at pos but checks the std::string-length before
- static char s_at(const std::string &istring, int pos);
-
- // Implodes a vector of std::string e (string join with e as seprator))
- static std::string implode(const std::string e, const std::vector<std::string> s);
-
- // Explodes a std::string into a vector of std::strings, splitting at s
- static std::vector<std::string> explode(const std::string e, std::string s, const bool check);
-
- // Builds a compact value std::string, inserting spaces only where necessary
- static std::string build_value(const std::vector<std::string> subvalues);
-
- // Replaces <find> with <replace> in <str>
- static std::string str_replace(const std::string find, const std::string replace, std::string str);
-
- // Checks if a std::string exists in a std::string-array
- static bool in_char_arr(const char* haystack, const char needle);
- static bool in_str_array(const std::string& haystack, const char needle);
-
- // isspace() and isdigit() do not work correctly with UTF-8 std::strings
- static bool ctype_space(const char c);
- static bool ctype_digit(const char c);
- static bool ctype_xdigit(char c);
- static bool ctype_alpha(char c);
-
- // trims whitespace at the specific or both ends of a std::string
- static const std::string trim(const std::string istring);
- static const std::string rtrim(const std::string istring);
- static const std::string rtrim(const std::string istring, const std::string chars);
- static const std::string ltrim(const std::string istring);
-
- // creates proper indent level
- static const std::string indent(int lvl, const std::string &base);
-};
-#endif // HEADER_CSSUTILS
diff --git a/src/Misc/CSSParser.cpp b/src/Misc/qCSSParser.cpp
similarity index 78%
rename from src/Misc/CSSParser.cpp
rename to src/Misc/qCSSParser.cpp
index fed053bb4..1c639eaf8 100644
--- a/src/Misc/CSSParser.cpp
+++ b/src/Misc/qCSSParser.cpp
@@ -18,16 +18,30 @@
** along with Sigil. If not, see <http://www.gnu.org/licenses/>.
**
** Extracted and modified from:
- ** CSSTidy Copyright 2005-2007 Florian Schmitz
- ** Available under the LGPL 2.1
+ ** CSSTidy (https://github.com/csstidy-c/csstidy)
+ **
+ ** CSSTidy Portions Copyright:
+ ** Florian Schmitz <[email protected]>
+ ** Thierry Charbonnel
+ ** Will Mitchell <[email protected]>
+ ** Brett Zamir <[email protected]>
+ ** sined_ <[email protected]>
+ ** Dmitry Leskov <[email protected]>
+ ** Kevin Coyner <[email protected]>
+ ** Tuukka Pasanen <[email protected]>
+ ** Frank W. Bergmann <[email protected]>
+ ** Frank Dana <[email protected]>
+ **
+ ** CSSTidy us Available under the LGPL 2.1
** You should have received a copy of the GNU Lesser General Public License
** along with this program. If not, see <http://www.gnu.org/licenses/>.
**
*************************************************************************/
-
-#include "Misc/CSSProperties.h"
-#include "Misc/CSSUtils.h"
-#include "Misc/CSSParser.h"
+
+#include <QTextStream>
+#include "Misc/qCSSProperties.h"
+#include "Misc/qCSSUtils.h"
+#include "Misc/qCSSParser.h"
/* PIS = in selector
* PIP = in property
@@ -47,7 +61,7 @@ CSSParser::CSSParser()
csstemplate.push_back(""); // 2 - unused
csstemplate.push_back(" {\n"); // 3 - bracket after selector was "\n{\n"
csstemplate.push_back(""); // 4 - unused
- csstemplate.push_back(""); // 5 - string after property before value
+ csstemplate.push_back(" "); // 5 - string after property before value
csstemplate.push_back(";\n"); // 6 - string after value
csstemplate.push_back("}"); // 7 - closing bracket - selector
csstemplate.push_back("\n\n"); // 8 - space between blocks {...}
@@ -87,7 +101,7 @@ CSSParser::CSSParser()
}
-void CSSParser::set_level(std::string level)
+void CSSParser::set_level(QString level)
{
if ((level == "CSS1.0") || (level == "CSS2.0") ||
(level == "CSS2.1") || (level == "CSS3.0"))
@@ -103,6 +117,7 @@ void CSSParser::reset_parser()
charset = "";
namesp = "";
line = 1;
+ selector_nest_level = 0;
import.clear();
csstokens.clear();
cur_selector.clear();
@@ -117,17 +132,17 @@ void CSSParser::reset_parser()
}
-std::string CSSParser::get_charset()
+QString CSSParser::get_charset()
{
return charset;
}
-std::string CSSParser::get_namespace()
+QString CSSParser::get_namespace()
{
return namesp;
}
-std::vector<std::string> CSSParser::get_import()
+QVector<QString> CSSParser::get_import()
{
return import;
}
@@ -153,22 +168,25 @@ CSSParser::token CSSParser::get_next_token(int start_ptr)
}
-std::string CSSParser::get_type_name(CSSParser::token_type t)
+QString CSSParser::get_type_name(CSSParser::token_type t)
{
return token_type_names[t];
}
-void CSSParser::add_token(const token_type ttype, const std::string data, const bool force)
+void CSSParser::add_token(const token_type ttype, const QString data)
{
token temp;
temp.type = ttype;
temp.pos = spos;
+ temp.line = sline;
temp.data = (ttype == COMMENT) ? data : CSSUtils::trim(data);
csstokens.push_back(temp);
+ if (ttype == SEL_START) selector_nest_level++;
+ if (ttype == SEL_END) selector_nest_level++;
}
-void CSSParser::log(const std::string msg, const message_type type, int iline)
+void CSSParser::log(const QString msg, const message_type type, int iline)
{
message new_msg;
new_msg.m = msg;
@@ -190,10 +208,10 @@ void CSSParser::log(const std::string msg, const message_type type, int iline)
logs[line].push_back(new_msg);
}
-std::string CSSParser::unicode(std::string& istring, int& i)
+QString CSSParser::unicode(QString& istring, int& i)
{
++i;
- std::string add = "";
+ QString add = "";
bool replaced = false;
while(i < istring.length() && (CSSUtils::ctype_xdigit(istring[i]) ||
@@ -211,7 +229,7 @@ std::string CSSParser::unicode(std::string& istring, int& i)
(CSSUtils::hexdec(add) > 64 && CSSUtils::hexdec(add) < 91) ||
(CSSUtils::hexdec(add) > 96 && CSSUtils::hexdec(add) < 123))
{
- std::string msg = "Replaced unicode notation: Changed \\" + CSSUtils::rtrim(add) + " to ";
+ QString msg = "Replaced unicode notation: Changed \\" + CSSUtils::rtrim(add) + " to ";
add = static_cast<int>(CSSUtils::hexdec(add));
msg += add;
log(msg,Information);
@@ -233,15 +251,15 @@ std::string CSSParser::unicode(std::string& istring, int& i)
}
-bool CSSParser::is_token(std::string& istring, const int i)
+bool CSSParser::is_token(QString& istring, const int i)
{
- return (CSSUtils::in_str_array(tokens, istring[i]) && !CSSUtils::escaped(istring,i));
+ return (tokens.contains(istring[i]) && !CSSUtils::escaped(istring,i));
}
void CSSParser::explode_selectors()
{
- sel_separate = std::vector<int>();
+ sel_separate = QVector<int>();
}
@@ -259,32 +277,17 @@ int CSSParser::_seeknocomment(const int key, int move)
}
return csstokens[i].type;
}
- // FIXME: control can reach end of non-void function
return -1;
}
-std::string CSSParser::serialize_css(std::string filename, bool tostdout)
+QString CSSParser::serialize_css(bool tostdout)
{
- if(charset == "" && namesp == "" && import.empty() && csstokens.empty())
- {
- std::cout << "Warning: empty CSS output!" << std::endl;
- }
-
- std::ofstream file_output;
- if(filename != "")
- {
- file_output.open(filename.c_str(),std::ios::binary);
- if(file_output.bad())
- {
- std::cout << "Error when trying to save the output file!" << std::endl;
- return "";
- }
- }
+ QString output_string;
+ QTextStream output(&output_string);
- std::stringstream output;
int lvl = 0;
- std::string indent = "";
+ QString indent = "";
for (int i = 0; i < csstokens.size(); ++i)
{
@@ -327,7 +330,7 @@ std::string CSSParser::serialize_css(std::string filename, bool tostdout)
case SEL_END:
lvl--; if (lvl < 0) lvl = 0;
indent = CSSUtils::indent(lvl, csstemplate[0]);
- output << indent + csstemplate[7];
+ output << indent << csstemplate[7];
if(_seeknocomment(i, 1) != AT_END) output << csstemplate[8];
break;
@@ -346,22 +349,18 @@ std::string CSSParser::serialize_css(std::string filename, bool tostdout)
}
}
- std::string output_string = CSSUtils::trim(output.str());
+ output_string = CSSUtils::trim(output_string);
if(tostdout)
{
- std::cout << output_string << "\n";
- }
- if(filename != "")
- {
- file_output << output_string;
- file_output.close();
+ QTextStream out(stdout, QIODevice::WriteOnly);
+ out << output_string << "\n";
}
return output_string;
}
-void CSSParser::parseInAtBlock(std::string& css_input, int& i, parse_status& astatus, parse_status& afrom)
+void CSSParser::parseInAtBlock(QString& css_input, int& i, parse_status& astatus, parse_status& afrom)
{
if(is_token(css_input,i))
{
@@ -385,10 +384,10 @@ void CSSParser::parseInAtBlock(std::string& css_input, int& i, parse_status& ast
}
else /*if((css_input[i] == '(') || (css_input[i] == ':') || (css_input[i] == ')') || (css_input[i] == '.'))*/
{
- if(!CSSUtils::in_char_arr("():/.", css_input[i]))
+ if(!QString("():/.").contains(css_input[i]))
{
// Strictly speaking, these are only permitted in @media rules
- log("Unexpected symbol '" + std::string(css_input, i, 1) + "' in @-rule", Warning);
+ log("Unexpected symbol '" + css_input[i] + "' in @-rule", Warning);
}
cur_at += css_input[i]; /* append tokens after media selector */
}
@@ -407,13 +406,11 @@ void CSSParser::parseInAtBlock(std::string& css_input, int& i, parse_status& ast
}
-void CSSParser::parseInSelector(std::string& css_input, int& i, parse_status& astatus, parse_status& afrom,
- bool& invalid_at, char& str_char, int str_size)
+void CSSParser::parseInSelector(QString& css_input, int& i, parse_status& astatus, parse_status& afrom,
+ bool& invalid_at, QChar& str_char, int str_size)
{
if(is_token(css_input,i))
{
- // if(css_input[i] == '/' && CSSUtils::s_at(css_input,i+1) == '*' &&
- // trim(cur_selector) == "") selector as dep doesn't make any sense here, huh?
if(css_input[i] == '/' && CSSUtils::s_at(css_input,i+1) == '*')
{
astatus = PIC; ++i;
@@ -423,20 +420,20 @@ void CSSParser::parseInSelector(std::string& css_input, int& i, parse_status& as
{
// Check for at-rule
invalid_at = true;
- for(std::map<std::string,parse_status>::iterator j = at_rules.begin(); j != at_rules.end(); ++j )
+ for(QMap<QString,parse_status>::iterator j = at_rules.begin(); j != at_rules.end(); ++j )
{
- if(CSSUtils::strtolower(css_input.substr(i+1,j->first.length())) == j->first)
+ if(CSSUtils::strtolower(css_input.mid(i+1,j.key().length())) == j.key())
{
- (j->second == PAT) ? cur_at = "@" + j->first : cur_selector = "@" + j->first;
- astatus = j->second;
- i += j->first.length();
+ (j.value() == PAT) ? cur_at = "@" + j.key() : cur_selector = "@" + j.key();
+ astatus = j.value();
+ i += j.key().length();
invalid_at = false;
}
}
if (invalid_at)
{
cur_selector = "@";
- std::string invalid_at_name = "";
+ QString invalid_at_name = "";
for(int j = i+1; j < str_size; ++j)
{
if(!CSSUtils::ctype_alpha(css_input[j]))
@@ -470,7 +467,7 @@ void CSSParser::parseInSelector(std::string& css_input, int& i, parse_status& as
add_token(AT_END, cur_at);
cur_at = "";
cur_selector = "";
- sel_separate = std::vector<int>();
+ sel_separate = QVector<int>();
}
else if(css_input[i] == ',')
{
@@ -490,9 +487,7 @@ void CSSParser::parseInSelector(std::string& css_input, int& i, parse_status& as
else
{
int lastpos = cur_selector.length()-1;
- if((lastpos == -1) || !( (CSSUtils::ctype_space(cur_selector[lastpos]) ||
- (is_token(cur_selector,lastpos) && cur_selector[lastpos] == ',')) &&
- CSSUtils::ctype_space(css_input[i])))
+ if( (lastpos == -1) || !( (CSSUtils::ctype_space(cur_selector[lastpos]) || (is_token(cur_selector,lastpos) && cur_selector[lastpos] == ',')) && CSSUtils::ctype_space(css_input[i])))
{
cur_selector += css_input[i];
}
@@ -500,7 +495,7 @@ void CSSParser::parseInSelector(std::string& css_input, int& i, parse_status& as
}
-void CSSParser::parseInProperty(std::string& css_input, int& i, parse_status& astatus, parse_status& afrom,
+void CSSParser::parseInProperty(QString& css_input, int& i, parse_status& astatus, parse_status& afrom,
bool& invalid_at)
{
@@ -510,7 +505,7 @@ void CSSParser::parseInProperty(std::string& css_input, int& i, parse_status& as
{
astatus = PIV;
bool valid = true || (CSSProperties::instance()->contains(cur_property) &&
- CSSProperties::instance()->levels(cur_property).find(css_level,0) != std::string::npos);
+ CSSProperties::instance()->levels(cur_property).indexOf(css_level,0) != -1);
if(valid) {
add_token(PROPERTY, cur_property);
}
@@ -548,7 +543,7 @@ void CSSParser::parseInProperty(std::string& css_input, int& i, parse_status& as
}
else
{
- log("Unexpected character '" + std::string(1, css_input[i]) + "'in property name", Error);
+ log("Unexpected character '" + QString(1, css_input[i]) + "'in property name", Error);
}
}
else if(!CSSUtils::ctype_space(css_input[i]))
@@ -565,8 +560,8 @@ void CSSParser::parseInProperty(std::string& css_input, int& i, parse_status& as
}
-void CSSParser::parseInValue(std::string& css_input, int& i, parse_status& astatus, parse_status& afrom,
- bool& invalid_at, char& str_char, bool& pn, int str_size)
+void CSSParser::parseInValue(QString& css_input, int& i, parse_status& astatus, parse_status& afrom,
+ bool& invalid_at, QChar& str_char, bool& pn, int str_size)
{
pn = (((css_input[i] == '\n' || css_input[i] == '\r') && property_is_next(css_input,i+1)) || i == str_size-1);
if(pn)
@@ -579,7 +574,7 @@ void CSSParser::parseInValue(std::string& css_input, int& i, parse_status& astat
cur_selector == "@charset" ||
cur_selector == "@namespace"))
{
- log("Unexpected character '" + std::string(1, css_input[i]) + "' in " + cur_selector, Error);
+ log("Unexpected character '" + QString(1, css_input[i]) + "' in " + cur_selector, Error);
}
if(css_input[i] == '/' && CSSUtils::s_at(css_input,i+1) == '*')
{
@@ -589,7 +584,7 @@ void CSSParser::parseInValue(std::string& css_input, int& i, parse_status& astat
else if(css_input[i] == '"' || css_input[i] == '\'' ||
(css_input[i] == '(' && cur_sub_value == "url") )
{
- str_char = (css_input[i] == '(') ? ')' : css_input[i];
+ str_char = (css_input[i] == QChar('(')) ? QChar(')') : css_input[i];
cur_string = css_input[i];
astatus = PINSTR;
afrom = PIV;
@@ -614,9 +609,9 @@ void CSSParser::parseInValue(std::string& css_input, int& i, parse_status& astat
}
else if(css_input[i] == ';' || pn)
{
- if(cur_selector.substr(0,1) == "@" &&
- at_rules.count(cur_selector.substr(1)) > 0 &&
- at_rules[cur_selector.substr(1)] == PIV)
+ if(cur_selector.mid(0,1) == "@" &&
+ at_rules.count(cur_selector.mid(1)) > 0 &&
+ at_rules[cur_selector.mid(1)] == PIV)
{
cur_sub_value_arr.push_back(CSSUtils::trim(cur_sub_value));
astatus = PIS;
@@ -628,7 +623,7 @@ void CSSParser::parseInValue(std::string& css_input, int& i, parse_status& astat
}
else if(cur_selector == "@import")
{
- std::string aimport = CSSUtils::build_value(cur_sub_value_arr);
+ QString aimport = CSSUtils::build_value(cur_sub_value_arr);
add_token(IMPORT, aimport);
import.push_back(aimport);
}
@@ -640,7 +635,7 @@ void CSSParser::parseInValue(std::string& css_input, int& i, parse_status& astat
cur_sub_value_arr.clear();
cur_sub_value = "";
cur_selector = "";
- sel_separate = std::vector<int>();
+ sel_separate = QVector<int>();
}
else
{
@@ -664,7 +659,7 @@ void CSSParser::parseInValue(std::string& css_input, int& i, parse_status& astat
bool drop = false;
if (css_input[i] == ')')
{
- if (cur_function_arr.empty())
+ if (cur_function_arr.isEmpty())
{
// No matching open parenthesis, drop this closing one
log("Unexpected closing parenthesis, dropping", Warning);
@@ -674,19 +669,19 @@ void CSSParser::parseInValue(std::string& css_input, int& i, parse_status& astat
{
// Pop function from the stack
cur_function_arr.pop_back();
- cur_function = cur_function_arr.empty() ? "" : cur_function_arr.back();
+ cur_function = cur_function_arr.isEmpty() ? "" : cur_function_arr.back();
}
}
if (!drop) {
- cur_sub_value_arr.push_back(std::string(1,css_input[i]));
+ cur_sub_value_arr.push_back(QString(1,css_input[i]));
}
}
else if(css_input[i] != '}')
{
cur_sub_value += css_input[i];
}
- if( (css_input[i] == '}' || css_input[i] == ';' || pn) && !cur_selector.empty())
+ if( (css_input[i] == '}' || css_input[i] == ';' || pn) && !cur_selector.isEmpty())
{
// End of value: normalize, optimize and store property
if(cur_at == "")
@@ -710,9 +705,9 @@ void CSSParser::parseInValue(std::string& css_input, int& i, parse_status& astat
}
// Check for leftover open parentheses
- if (!cur_function_arr.empty())
+ if (!cur_function_arr.isEmpty())
{
- std::vector<std::string>::reverse_iterator rit;
+ QVector<QString>::reverse_iterator rit;
for (rit = cur_function_arr.rbegin(); rit != cur_function_arr.rend(); ++rit)
{
log("Closing parenthesis missing for '" + *rit + "', inserting", Warning);
@@ -724,7 +719,7 @@ void CSSParser::parseInValue(std::string& css_input, int& i, parse_status& astat
bool valid = (CSSProperties::instance()->contains(cur_property) &&
- CSSProperties::instance()->levels(cur_property).find(css_level,0) != std::string::npos);
+ CSSProperties::instance()->levels(cur_property).indexOf(css_level,0) != -1);
if(1)
{
//add(cur_at,cur_selector,cur_property,cur_value);
@@ -765,8 +760,8 @@ void CSSParser::parseInValue(std::string& css_input, int& i, parse_status& astat
}
-void CSSParser::parseInComment(std::string& css_input, int& i, parse_status& astatus, parse_status& afrom,
- std::string& cur_comment)
+void CSSParser::parseInComment(QString& css_input, int& i, parse_status& astatus, parse_status& afrom,
+ QString& cur_comment)
{
if(css_input[i] == '*' && CSSUtils::s_at(css_input,i+1) == '/')
@@ -783,8 +778,8 @@ void CSSParser::parseInComment(std::string& css_input, int& i, parse_status& ast
}
-void CSSParser::parseInString(std::string& css_input, int& i, parse_status& astatus, parse_status& afrom,
- char& str_char, bool& str_in_str)
+void CSSParser::parseInString(QString& css_input, int& i, parse_status& astatus, parse_status& afrom,
+ QChar& str_char, bool& str_in_str)
{
if(str_char == ')' && (css_input[i] == '"' || css_input[i] == '\'') &&
@@ -797,23 +792,24 @@ void CSSParser::parseInString(std::string& css_input, int& i, parse_status& asta
{
str_in_str = false;
}
- std::string temp_add = ""; temp_add += css_input[i];
+ QString temp_add = ""; temp_add += css_input[i];
if( (css_input[i] == '\n' || css_input[i] == '\r') &&
!(css_input[i-1] == '\\' && !CSSUtils::escaped(css_input,i-1)) )
{
temp_add = "\\A ";
log("Fixed incorrect newline in string",Warning);
}
- if (!(str_char == ')' &&
- CSSUtils::char2str(css_input[i]).find_first_of(" \n\t\r\0xb") != std::string::npos && !str_in_str))
+ if (!(str_char == ')' && QString(" \n\t\r\0xb").contains(css_input[i]) && !str_in_str))
{
cur_string += temp_add;
}
if(css_input[i] == str_char && !CSSUtils::escaped(css_input,i) && str_in_str == false)
{
astatus = afrom;
+ // Quotes are optional so leave them alone (ie. act like a parser not an optimizer)
+#if 0
if (cur_function == "" &&
- cur_string.find_first_of(" \n\t\r\0xb") == std::string::npos &&
+ CSSUtils::find_first_of(cur_string, " \n\t\r\0xb") == -1 &&
cur_property != "content" && cur_sub_value != "format")
{
// If the string is not inside a function call, contains no whitespace,
@@ -824,12 +820,13 @@ void CSSParser::parseInString(std::string& css_input, int& i, parse_status& asta
{
// If the string is in double or single quotes, remove them
// FIXME: once url() is handled separately, this may always be the case.
- cur_string = cur_string.substr(1, cur_string.length() - 2);
+ cur_string = cur_string.mid(1, cur_string.length() - 2);
} else if (cur_string.length() > 3 && (cur_string[1] == '"' || cur_string[1] == '\'')) /* () */
{
- cur_string = cur_string[0] + cur_string.substr(2, cur_string.length() - 4) + cur_string[cur_string.length()-1];
+ cur_string = cur_string[0] + cur_string.mid(2, cur_string.length() - 4) + cur_string[cur_string.length()-1];
}
}
+#endif
if(afrom == PIV)
{
cur_sub_value += cur_string;
@@ -842,19 +839,19 @@ void CSSParser::parseInString(std::string& css_input, int& i, parse_status& asta
}
-void CSSParser::parse_css(std::string css_input)
+void CSSParser::parse_css(QString css_input)
{
reset_parser();
- css_input = CSSUtils::str_replace("\r\n","\n",css_input); // Replace newlines
+ css_input = css_input.replace("\r\n","\n"); // Replace newlines
css_input += "\n";
parse_status astatus = PIS, afrom;
parse_status old_status = PIS;
record_position(PIS, PIS, css_input, 0, true);
- std::string cur_comment;
+ QString cur_comment;
cur_sub_value_arr.clear();
cur_function_arr.clear(); // Stack of nested function calls
- char str_char;
+ QChar str_char;
bool str_in_str = false;
bool invalid_at = false;
bool pn = false;
@@ -862,11 +859,8 @@ void CSSParser::parse_css(std::string css_input)
int str_size = css_input.length();
for(int i = 0; i < str_size; ++i)
{
- if(css_input[i] == '\n' || css_input[i] == '\r')
- {
- ++line;
- }
-
+ // track line number
+ if(css_input[i] == '\n') ++line;
// record current position for selected state transitions
if (old_status != astatus)
@@ -909,51 +903,56 @@ void CSSParser::parse_css(std::string css_input)
break;
}
}
+ // validate that every selector start had its own selector end
+ if (selector_nest_level != 0)
+ {
+ log("Unbalanced selector braces in style sheet", Error, line);
+ }
}
-bool CSSParser::property_is_next(std::string istring, int pos)
+bool CSSParser::property_is_next(QString istring, int pos)
{
- istring = istring.substr(pos,istring.length()-pos);
- pos = istring.find_first_of(':',0);
- if(pos == std::string::npos)
+ istring = istring.mid(pos,istring.length()-pos);
+ pos = CSSUtils::find_first_of(istring, ":");
+ if(pos == -1)
{
return false;
}
- istring = CSSUtils::strtolower(CSSUtils::trim(istring.substr(0,pos)));
+ istring = CSSUtils::strtolower(CSSUtils::trim(istring.mid(0,pos)));
return CSSProperties::instance()->contains(istring);
}
-std::vector<std::string> CSSParser::get_parse_errors()
+QVector<QString> CSSParser::get_parse_errors()
{
return get_logs(CSSParser::Error);
}
-std::vector<std::string> CSSParser::get_parse_warnings()
+QVector<QString> CSSParser::get_parse_warnings()
{
return get_logs(CSSParser::Warning);
}
-std::vector<std::string> CSSParser::get_parse_info()
+QVector<QString> CSSParser::get_parse_info()
{
return get_logs(CSSParser::Information);
}
-std::vector<std::string> CSSParser::get_logs(CSSParser::message_type mt)
+QVector<QString> CSSParser::get_logs(CSSParser::message_type mt)
{
- std::vector<std::string> res;
+ QVector<QString> res;
if(logs.size() > 0)
{
- for(std::map<int, std::vector<message> >::iterator j = logs.begin(); j != logs.end(); j++ )
+ for(QMap<int, QVector<message> >::iterator j = logs.begin(); j != logs.end(); j++ )
{
- for(int i = 0; i < j->second.size(); ++i)
+ for(int i = 0; i < j.value().size(); ++i)
{
- if (j->second[i].t == mt) {
- res.push_back(std::to_string(j->first) + ": " + j->second[i].m);
+ if (j.value()[i].t == mt) {
+ res.push_back(QString::number(j.key()) + ": " + j.value()[i].m);
}
}
}
@@ -963,7 +962,7 @@ std::vector<std::string> CSSParser::get_logs(CSSParser::message_type mt)
// allow a new set of csstokens to be loaded and then serialized
-void CSSParser::set_csstokens(const std::vector<CSSParser::token> &ntokens)
+void CSSParser::set_csstokens(const QVector<CSSParser::token> &ntokens)
{
csstokens.clear();
for(int i = 0; i < ntokens.size(); i++)
@@ -976,7 +975,7 @@ void CSSParser::set_csstokens(const std::vector<CSSParser::token> &ntokens)
// update the position only for selected state transitions
void CSSParser::record_position(parse_status old_status, parse_status new_status,
- std::string &css_input, int i, bool force)
+ QString &css_input, int i, bool force)
{
// to reach here old_status must be != new_status
bool record = false;
@@ -998,6 +997,10 @@ void CSSParser::record_position(parse_status old_status, parse_status new_status
if ((old_status == PIP) && (new_status == PIS)) record = true;
if (record || force) {
- spos = css_input.find_first_not_of(" \n\t\r\0xb", i);
+ spos = CSSUtils::find_first_not_of(css_input, " \n\t\r\0xb", i);
+ sline = line;
+ for(int j = i+1; j <= spos; j++) {
+ if (css_input[j] == '\n') sline++;
+ }
}
}
diff --git a/src/Misc/qCSSParser.h b/src/Misc/qCSSParser.h
new file mode 100644
index 000000000..a63428226
--- /dev/null
+++ b/src/Misc/qCSSParser.h
@@ -0,0 +1,198 @@
+/************************************************************************
+ **
+ ** Copyright (C) 2021 Kevin B. Hendricks, Stratford, Ontario, Canada
+ **
+ ** This file is part of Sigil.
+ **
+ ** Sigil is free software: you can redistribute it and/or modify
+ ** it under the terms of the GNU General Public License as published by
+ ** the Free Software Foundation, either version 3 of the License, or
+ ** (at your option) any later version.
+ **
+ ** Sigil is distributed in the hope that it will be useful,
+ ** but WITHOUT ANY WARRANTY; without even the implied warranty of
+ ** MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ ** GNU General Public License for more details.
+ **
+ ** You should have received a copy of the GNU General Public License
+ ** along with Sigil. If not, see <http://www.gnu.org/licenses/>.
+ **
+ ** Extracted and modified from:
+ ** CSSTidy (https://github.com/csstidy-c/csstidy)
+ **
+ ** CSSTidy Portions Copyright:
+ ** Florian Schmitz <[email protected]>
+ ** Thierry Charbonnel
+ ** Will Mitchell <[email protected]>
+ ** Brett Zamir <[email protected]>
+ ** sined_ <[email protected]>
+ ** Dmitry Leskov <[email protected]>
+ ** Kevin Coyner <[email protected]>
+ ** Tuukka Pasanen <[email protected]>
+ ** Frank W. Bergmann <[email protected]>
+ ** Frank Dana <[email protected]>
+ **
+ ** CSSTidy us Available under the LGPL 2.1
+ ** You should have received a copy of the GNU Lesser General Public License
+ ** along with this program. If not, see <http://www.gnu.org/licenses/>.
+ **
+ *************************************************************************/
+
+#ifndef HEADER_CSSPARSER
+#define HEADER_CSSPARSER
+
+#include <assert.h>
+#include <QChar>
+#include <QString>
+#include <QVector>
+#include <QMap>
+#include "Misc/qCSSProperties.h"
+#include "Misc/qCSSUtils.h"
+
+class CSSParser
+{
+
+public:
+
+ enum parse_status
+ {
+ PIS, PIP, PIV, PINSTR, PIC, PAT
+ };
+
+ enum message_type
+ {
+ Information,Warning,Error
+ };
+
+ enum token_type
+ {
+ CHARSET, IMPORT, NAMESP, AT_START, AT_END, SEL_START, SEL_END, PROPERTY, VALUE, COMMENT, CSS_END
+ };
+
+ struct token
+ {
+ token_type type;
+ int pos;
+ int line;
+ QString data;
+ };
+
+ struct message
+ {
+ QString m;
+ message_type t;
+ };
+
+ CSSParser();
+
+ // valid levels are "CSS1.0", "CSS2.0", "CSS2.1", "CSS3.0"
+ void set_level(QString level = "CSS3.0");
+
+ void parse_css(QString css_input);
+
+ void reset_parser();
+
+ // serialize the current list of csstokens back to css
+ QString serialize_css(bool tostdout = true);
+
+ // access charset, namespace and imports without having to walk csstokens
+ QString get_charset();
+ QVector<QString> get_import();
+ QString get_namespace();
+
+ // walk the csstokens list, token by token
+ // set start_ptr to the position you woud like to start at in the list
+ // leaving it as -1 will simply start at 0 and increment
+ // last token is a dummy token with type set to CSS_END
+ token get_next_token(int start_ptr = -1);
+
+ // covert token type enum value to a descriptive string
+ QString get_type_name(token_type t);
+
+ // this routine allows external modifications to the csstokens
+ // to be brought back into CSSParser in order to serialize them
+ // with serialize_css
+ void set_csstokens(const QVector<token> &ntokens);
+
+ // get errors, warnings, and information
+ QVector<QString> get_parse_errors();
+ QVector<QString> get_parse_warnings();
+ QVector<QString> get_parse_info();
+
+
+private:
+
+ void parseInAtBlock(QString& css_input, int& i, parse_status& astatus, parse_status& afrom);
+
+ void parseInSelector(QString& css_input, int& i, parse_status& astatus, parse_status& afrom,
+ bool& invalid_at, QChar& str_char, int str_size);
+
+ void parseInProperty(QString& css_input, int& i, parse_status& astatus, parse_status& afrom,
+ bool& invalid_at);
+
+ void parseInValue(QString& css_input, int& i, parse_status& astatus, parse_status& afrom,
+ bool& invalid_at, QChar& str_char, bool& pn, int str_size );
+
+ void parseInComment(QString& css_input, int& i, parse_status& astatus, parse_status& afrom,
+ QString& cur_comment);
+
+ void parseInString(QString& css_input, int& i, parse_status& astatus, parse_status& afrom,
+ QChar& str_char, bool& str_in_str);
+
+
+ // filter the logs by message type
+ QVector<QString> get_logs(message_type t);
+
+ // Pparses unicode notations
+ QString unicode(QString& istring, int& i);
+
+ // checks if the chat in istring at i is a token
+ bool is_token(QString& istring, const int i);
+
+ void add_token(const token_type ttype, const QString data);
+
+ // Add a message to the message log
+ void log(const QString msg, const message_type type, int iline = 0);
+
+ // records token position information
+ void record_position(parse_status old_status, parse_status new_status,
+ QString &css_input, int i, bool force=false);
+
+ int _seeknocomment(const int key, const int move);
+
+ void explode_selectors();
+
+ static bool property_is_next(QString istring, int pos);
+
+ // private member variables
+ QVector<QString> token_type_names;
+ QMap<QString, parse_status> at_rules;
+ QVector<QString> csstemplate;
+ QString css_level;
+ QString tokens;
+ int token_ptr;
+
+ QMap<int, QVector<message> > logs;
+ int line;
+ int spos;
+ int sline;
+ int selector_nest_level;
+
+ QString charset;
+ QString namesp;
+ QVector<QString> import;
+ QVector<token> csstokens;
+ QString cur_selector;
+ QString cur_at;
+ QString cur_property;
+ QString cur_function;
+ QString cur_sub_value;
+ QString cur_value;
+ QString cur_string;
+ QVector<int> sel_separate;
+ QVector<QString> cur_sub_value_arr;
+ QVector<QString> cur_function_arr;
+
+};
+
+#endif // HEADER_CSSPARSER
diff --git a/src/Misc/CSSProperties.cpp b/src/Misc/qCSSProperties.cpp
similarity index 87%
rename from src/Misc/CSSProperties.cpp
rename to src/Misc/qCSSProperties.cpp
index 5f0dfa6bb..b2414f8cb 100644
--- a/src/Misc/CSSProperties.cpp
+++ b/src/Misc/qCSSProperties.cpp
@@ -1,32 +1,45 @@
/************************************************************************
-**
-** Copyright (C) 2021 Kevin B. Hendricks, Stratford, Ontario, Canada
-**
-** This file is part of Sigil.
-**
-** Sigil is free software: you can redistribute it and/or modify
-** it under the terms of the GNU General Public License as published by
-** the Free Software Foundation, either version 3 of the License, or
-** (at your option) any later version.
-**
-** Sigil is distributed in the hope that it will be useful,
-** but WITHOUT ANY WARRANTY; without even the implied warranty of
-** MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
-** GNU General Public License for more details.
-**
-** You should have received a copy of the GNU General Public License
-** along with Sigil. If not, see <http://www.gnu.org/licenses/>.
-**
-** Extracted and modified from:
-** CSSTidy Copyright 2005-2007 Florian Schmitz
-** Available under the LGPL 2.1
-** You should have received a copy of the GNU Lesser General Public License
-** along with this program. If not, see <http://www.gnu.org/licenses/>.
-**
-*************************************************************************/
+ **
+ ** Copyright (C) 2021 Kevin B. Hendricks, Stratford, Ontario, Canada
+ **
+ ** This file is part of Sigil.
+ **
+ ** Sigil is free software: you can redistribute it and/or modify
+ ** it under the terms of the GNU General Public License as published by
+ ** the Free Software Foundation, either version 3 of the License, or
+ ** (at your option) any later version.
+ **
+ ** Sigil is distributed in the hope that it will be useful,
+ ** but WITHOUT ANY WARRANTY; without even the implied warranty of
+ ** MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ ** GNU General Public License for more details.
+ **
+ ** You should have received a copy of the GNU General Public License
+ ** along with Sigil. If not, see <http://www.gnu.org/licenses/>.
+ **
+ ** Extracted and modified from:
+ ** CSSTidy (https://github.com/csstidy-c/csstidy)
+ **
+ ** CSSTidy Portions Copyright:
+ ** Florian Schmitz <[email protected]>
+ ** Thierry Charbonnel
+ ** Will Mitchell <[email protected]>
+ ** Brett Zamir <[email protected]>
+ ** sined_ <[email protected]>
+ ** Dmitry Leskov <[email protected]>
+ ** Kevin Coyner <[email protected]>
+ ** Tuukka Pasanen <[email protected]>
+ ** Frank W. Bergmann <[email protected]>
+ ** Frank Dana <[email protected]>
+ **
+ ** CSSTidy us Available under the LGPL 2.1
+ ** You should have received a copy of the GNU Lesser General Public License
+ ** along with this program. If not, see <http://www.gnu.org/licenses/>.
+ **
+ *************************************************************************/
-#include <string>
-#include "Misc/CSSProperties.h"
+#include <QString>
+#include "Misc/qCSSProperties.h"
CSSProperties *CSSProperties::m_instance = 0;
@@ -39,13 +52,13 @@ CSSProperties *CSSProperties::instance()
}
-bool CSSProperties::contains(std::string pname)
+bool CSSProperties::contains(QString pname)
{
- return m_all_properties.count(pname) == 1;
+ return m_all_properties.contains(pname);
}
-std::string CSSProperties::levels(std::string pname)
+QString CSSProperties::levels(QString pname)
{
if (contains(pname)) {
return m_all_properties[pname];
@@ -339,5 +352,16 @@ CSSProperties::CSSProperties()
m_all_properties["word-wrap"] = "CSS3.0";
m_all_properties["z-index"] = "CSS2.0,CSS2.1,CSS3.0";
m_all_properties["zoom"] = "CSS3.0";
+ m_all_properties["-epub-text-orientation"] = "CSS3.0";
+ m_all_properties["-epub-writing-mode"] = "CSS3.0";
+ m_all_properties["-epub-text-combine"] = "CSS3.0";
+ m_all_properties["-epub-hyphens"] = "CSS3.0";
+ m_all_properties["-epub-line-break"] = "CSS3.0";
+ m_all_properties["-epub-text-align-last"] = "CSS3.0";
+ m_all_properties["-epub-word-break"] = "CSS3.0";
+ m_all_properties["-epub-text-emphasis-color"] = "CSS3.0";
+ m_all_properties["-epub-text-emphasis-position"] = "CSS3.0";
+ m_all_properties["-epub-text-emphasis-style"] = "CSS3.0";
+ m_all_properties["-epub-text-underline-position"] = "CSS3.0";
}
}
diff --git a/src/Misc/qCSSProperties.h b/src/Misc/qCSSProperties.h
new file mode 100644
index 000000000..bdb660228
--- /dev/null
+++ b/src/Misc/qCSSProperties.h
@@ -0,0 +1,72 @@
+/************************************************************************
+ **
+ ** Copyright (C) 2021 Kevin B. Hendricks, Stratford, ON, Canada
+ **
+ ** This file is part of Sigil.
+ **
+ ** Sigil is free software: you can redistribute it and/or modify
+ ** it under the terms of the GNU General Public License as published by
+ ** the Free Software Foundation, either version 3 of the License, or
+ ** (at your option) any later version.
+ **
+ ** Sigil is distributed in the hope that it will be useful,
+ ** but WITHOUT ANY WARRANTY; without even the implied warranty of
+ ** MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ ** GNU General Public License for more details.
+ **
+ ** You should have received a copy of the GNU General Public License
+ ** along with Sigil. If not, see <http://www.gnu.org/licenses/>.
+ **
+ ** Extracted and modified from:
+ ** CSSTidy (https://github.com/csstidy-c/csstidy)
+ **
+ ** CSSTidy Portions Copyright:
+ ** Florian Schmitz <[email protected]>
+ ** Thierry Charbonnel
+ ** Will Mitchell <[email protected]>
+ ** Brett Zamir <[email protected]>
+ ** sined_ <[email protected]>
+ ** Dmitry Leskov <[email protected]>
+ ** Kevin Coyner <[email protected]>
+ ** Tuukka Pasanen <[email protected]>
+ ** Frank W. Bergmann <[email protected]>
+ ** Frank Dana <[email protected]>
+ **
+ ** CSSTidy us Available under the LGPL 2.1
+ *************************************************************************/
+
+#pragma once
+#ifndef CSS_PROPERTIES_H
+#define CSS_PROPERTIES_H
+
+#include <QChar>
+#include <QString>
+#include <QHash>
+
+/**
+ * Singleton.
+ *
+ * CSSProperties
+ */
+
+
+class CSSProperties
+{
+
+public:
+
+ static CSSProperties *instance();
+
+ bool contains(QString pname);
+
+ QString levels(QString pname);
+
+private:
+
+ CSSProperties();
+
+ QHash<QString, QString> m_all_properties;
+ static CSSProperties *m_instance;
+};
+
+#endif // CSS_PROPERTIES_H
diff --git a/src/Misc/qCSSUtils.cpp b/src/Misc/qCSSUtils.cpp
new file mode 100644
index 000000000..c12d46f61
--- /dev/null
+++ b/src/Misc/qCSSUtils.cpp
@@ -0,0 +1,270 @@
+/************************************************************************
+ **
+ ** Copyright (C) 2021 Kevin B. Hendricks, Stratford, Ontario, Canada
+ **
+ ** This file is part of Sigil.
+ **
+ ** Sigil is free software: you can redistribute it and/or modify
+ ** it under the terms of the GNU General Public License as published by
+ ** the Free Software Foundation, either version 3 of the License, or
+ ** (at your option) any later version.
+ **
+ ** Sigil is distributed in the hope that it will be useful,
+ ** but WITHOUT ANY WARRANTY; without even the implied warranty of
+ ** MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ ** GNU General Public License for more details.
+ **
+ ** You should have received a copy of the GNU General Public License
+ ** along with Sigil. If not, see <http://www.gnu.org/licenses/>.
+ **
+ ** Extracted and modified from:
+ ** CSSTidy (https://github.com/csstidy-c/csstidy)
+ **
+ ** CSSTidy Portions Copyright:
+ ** Florian Schmitz <[email protected]>
+ ** Thierry Charbonnel
+ ** Will Mitchell <[email protected]>
+ ** Brett Zamir <[email protected]>
+ ** sined_ <[email protected]>
+ ** Dmitry Leskov <[email protected]>
+ ** Kevin Coyner <[email protected]>
+ ** Tuukka Pasanen <[email protected]>
+ ** Frank W. Bergmann <[email protected]>
+ ** Frank Dana <[email protected]>
+ **
+ ** CSSTidy us Available under the LGPL 2.1
+ ** You should have received a copy of the GNU Lesser General Public License
+ ** along with this program. If not, see <http://www.gnu.org/licenses/>.
+ **
+ *************************************************************************/
+
+#include "Misc/qCSSUtils.h"
+
+QString CSSUtils::strtolower(QString istring)
+{
+ int str_size = istring.length();
+ for(int i = 0; i < str_size; i++)
+ {
+ istring[i] = chartolower(istring[i]);
+ }
+ return istring;
+}
+
+
+QChar CSSUtils::chartolower(const QChar c)
+{
+ if ((c.unicode() >= 'A') && (c.unicode() <= 'Z')) return c.toLower();
+ return c;
+}
+
+
+QString CSSUtils::strtoupper(QString istring)
+{
+ int str_size = istring.length();
+ for(int i = 0; i < str_size; i++)
+ {
+ istring[i] = chartoupper(istring[i]);
+ }
+ return istring;
+}
+
+
+QChar CSSUtils::chartoupper(const QChar c)
+{
+ if ((c.unicode() >= 'a') && (c.unicode() <= 'z')) return c.toUpper();
+ return c;
+}
+
+
+unsigned int CSSUtils::hexdec(QString istring)
+{
+ unsigned int res = 0;
+ bool okay = false;
+ istring = trim(istring);
+ res = istring.toUInt(&okay, 16);
+ if (okay) return res;
+ return 0;
+}
+
+
+bool CSSUtils::escaped(const QString &istring, const int pos)
+{
+ return !(s_at(istring,pos-1) != '\\' || escaped(istring,pos-1));
+}
+
+
+// Safe replacement for .at()
+QChar CSSUtils::s_at(const QString &istring, const int pos)
+{
+ if(pos > (istring.length()-1) || pos < 0)
+ {
+ return 0;
+ }
+ else
+ {
+ return istring[pos];
+ }
+}
+
+
+QVector<QString> CSSUtils::explode(const QString e, QString s, const bool check)
+{
+ QVector<QString> ret;
+ int iPos = s.indexOf(e, 0);
+ int iPit = e.length();
+
+ while(iPos > -1)
+ {
+ if(iPos != 0 || check)
+ {
+ ret.push_back(s.mid(0,iPos));
+ }
+ s = s.remove(0,iPos+iPit);
+ iPos = s.indexOf(e, 0);
+ }
+
+ if(s != "" || check)
+ {
+ ret.push_back(s);
+ }
+ return ret;
+}
+
+
+QString CSSUtils::implode(const QString e, const QVector<QString> s)
+{
+ QString ret;
+ for(int i = 0; i < s.size(); i++)
+ {
+ ret += s[i];
+ if(i != (s.size()-1)) ret += e;
+ }
+ return ret;
+}
+
+
+QString CSSUtils::build_value(const QVector<QString> subvalues)
+{
+ QString ret;
+ for(int i = 0; i < subvalues.size(); i++)
+ {
+ ret += subvalues[i];
+ if(i != (subvalues.size()-1))
+ {
+ QChar last = s_at(subvalues[i], subvalues[i].length()-1);
+ QChar next = s_at(subvalues[i+1], 0);
+ // allow a space after a comma in a values list. next line was:
+ // if (QString("(,=:").contains(last) || QString("),=:").contains(next))
+ if (QString("(=:").contains(last) || QString("),=:").contains(next))
+ {
+ continue;
+ }
+ ret += " ";
+ }
+ }
+ return ret;
+}
+
+
+bool CSSUtils::ctype_space(const QChar c)
+{
+ return (c == ' ' || c == '\t' || c == '\r' || c == '\n' || c == 11);
+}
+
+
+bool CSSUtils::ctype_digit(const QChar c)
+{
+ if ((c.unicode() >= '0') && (c.unicode() <= '9')) return true;
+ return false;
+}
+
+
+bool CSSUtils::ctype_xdigit(QChar c)
+{
+ c = chartolower(c);
+ return (ctype_digit(c) || c == 'a' || c == 'b' || c == 'c' || c == 'd' || c == 'e' || c == 'f');
+}
+
+
+bool CSSUtils::ctype_alpha(QChar c)
+{
+ c = chartolower(c);
+ if ((c.unicode() >= 'a') && (c.unicode() <= 'z')) return true;
+ return false;
+}
+
+
+const QString CSSUtils::trim(const QString istring)
+{
+ int first = find_first_not_of(istring, " \n\t\r\0xb");
+ if (first == -1) {
+ return QString();
+ }
+ else
+ {
+ int last = find_last_not_of(istring, " \n\t\r\0xb");
+ return istring.mid( first, last - first + 1);
+ }
+}
+
+
+const QString CSSUtils::ltrim(const QString istring)
+{
+ int first = find_first_not_of(istring, " \n\t\r\0xb");
+ if (first == -1) {
+ return QString();
+ }
+ else
+ {
+ return istring.mid(first);
+ }
+}
+
+
+const QString CSSUtils::rtrim(const QString istring)
+{
+ int last = find_last_not_of(istring, " \n\t\r\0xb"); /// must succeed
+ return istring.mid(0, last + 1);
+}
+
+
+const QString CSSUtils::rtrim(const QString istring, const QString chars)
+{
+ int last = find_last_not_of(istring, chars); /// must succeed
+ return istring.mid( 0, last + 1);
+}
+
+
+const QString CSSUtils::indent(int lvl, const QString &base)
+{
+ QString ind = "";
+ for (int i = 0; i < lvl; i++) {
+ ind = ind + base;
+ }
+ return ind;
+}
+
+
+int CSSUtils::find_first_of(const QString &tgt, const QString& stopchars, int p)
+{
+ while((p < tgt.length()) && !stopchars.contains(tgt.at(p))) p++;
+ if (p < tgt.length()) return p;
+ return -1;
+}
+
+
+int CSSUtils::find_first_not_of(const QString &tgt, const QString& skipchars, int p)
+{
+ while((p < tgt.length()) && skipchars.contains(tgt.at(p))) p++;
+ if (p < tgt.length()) return p;
+ return -1;
+}
+
+
+int CSSUtils::find_last_not_of(const QString &tgt, const QString& skipchars)
+{
+ int p = tgt.length() - 1;
+ while((p >= 0) && skipchars.contains(tgt.at(p))) p--;
+ if (p < 0) return -1;
+ return p;
+}
diff --git a/src/Misc/qCSSUtils.h b/src/Misc/qCSSUtils.h
new file mode 100644
index 000000000..5bf683ef7
--- /dev/null
+++ b/src/Misc/qCSSUtils.h
@@ -0,0 +1,104 @@
+/************************************************************************
+ **
+ ** Copyright (C) 2021 Kevin B. Hendricks, Stratford, Ontario, Canada
+ **
+ ** This file is part of Sigil.
+ **
+ ** Sigil is free software: you can redistribute it and/or modify
+ ** it under the terms of the GNU General Public License as published by
+ ** the Free Software Foundation, either version 3 of the License, or
+ ** (at your option) any later version.
+ **
+ ** Sigil is distributed in the hope that it will be useful,
+ ** but WITHOUT ANY WARRANTY; without even the implied warranty of
+ ** MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ ** GNU General Public License for more details.
+ **
+ ** You should have received a copy of the GNU General Public License
+ ** along with Sigil. If not, see <http://www.gnu.org/licenses/>.
+ **
+ ** Extracted and modified from:
+ ** CSSTidy (https://github.com/csstidy-c/csstidy)
+ **
+ ** CSSTidy Portions Copyright:
+ ** Florian Schmitz <[email protected]>
+ ** Thierry Charbonnel
+ ** Will Mitchell <[email protected]>
+ ** Brett Zamir <[email protected]>
+ ** sined_ <[email protected]>
+ ** Dmitry Leskov <[email protected]>
+ ** Kevin Coyner <[email protected]>
+ ** Tuukka Pasanen <[email protected]>
+ ** Frank W. Bergmann <[email protected]>
+ ** Frank Dana <[email protected]>
+ **
+ ** CSSTidy us Available under the LGPL 2.1
+ ** Available under the LGPL 2.1
+ ** You should have received a copy of the GNU Lesser General Public License
+ ** along with this program. If not, see <http://www.gnu.org/licenses/>.
+ **
+ *************************************************************************/
+
+#ifndef HEADER_CSSUTILS
+#define HEADER_CSSUTILS
+
+#include <QChar>
+#include <QString>
+#include <QVector>
+#include <QFile>
+#include <QFileInfo>
+
+class CSSUtils
+{
+
+public:
+
+ // Returns the lowercase version of a string
+ static QString strtolower(QString istring);
+
+ // Apparently faster replacement for tolower
+ static QChar chartolower(const QChar c);
+
+ // Returns the uppercase version of a string
+ static QString strtoupper(QString istring);
+ static QChar chartoupper(const QChar c);
+
+ // Converts a hexadecimal number (string) to a decimal number
+ static unsigned int hexdec(QString istring);
+
+ // Checks if a charcter is escaped
+ static bool escaped(const QString &istring, int pos);
+
+ // Returns a QChar of a QString at pos but checks the QString-length before
+ static QChar s_at(const QString &istring, int pos);
+
+ // Implodes a vector of QString e (string join with e as seprator))
+ static QString implode(const QString e, const QVector<QString> s);
+
+ // Explodes a QString into a vector of QStrings, splitting at s
+ static QVector<QString> explode(const QString e, QString s, const bool check);
+
+ // Builds a compact value QString, inserting spaces only where necessary
+ static QString build_value(const QVector<QString> subvalues);
+
+ // isspace() and isdigit() do not work correctly with UTF-8 QStrings
+ static bool ctype_space(const QChar c);
+ static bool ctype_digit(const QChar c);
+ static bool ctype_xdigit(QChar c);
+ static bool ctype_alpha(QChar c);
+
+ // trims whitespace at the specific or both ends of a QString
+ static const QString trim(const QString istring);
+ static const QString rtrim(const QString istring);
+ static const QString rtrim(const QString istring, const QString chars);
+ static const QString ltrim(const QString istring);
+
+ // creates proper indent level
+ static const QString indent(int lvl, const QString &base);
+
+ // make std::string find_* equivalents for QString
+ static int find_first_of(const QString &tgt, const QString& stopchars, int p = 0);
+ static int find_first_not_of(const QString &tgt, const QString& skipchars, int p = 0);
+ static int find_last_not_of(const QString &tgt, const QString& skipchars);
+};
+#endif // HEADER_CSSUTILS
| 0
|
dda55aa50db95a25f0d919c3a0d5871827cdc40f
|
https://github.com/fedora-selinux/setroubleshoot/commit/dda55aa50db95a25f0d919c3a0d5871827cdc40f
|
framework: Use subprocess.check_output() with a sequence of program arguments
All subprocess.get*output() should be replaced with either
subprocess.Popen or subprocess.check_output now.
String args were converted to sequences of program arguments.
|
diff --git a/framework/src/SetroubleshootFixit.py b/framework/src/SetroubleshootFixit.py
index a810151..aef1dd0 100644
--- a/framework/src/SetroubleshootFixit.py
+++ b/framework/src/SetroubleshootFixit.py
@@ -14,9 +14,9 @@ def __init__ (self, *p, **k):
@dbus.service.method ("org.fedoraproject.SetroubleshootFixit", in_signature='ss', out_signature='s')
def run_fix(self, local_id, analysis_id):
- import commands
- command = "sealert -f %s -P %s" % ( local_id, analysis_id)
- return commands.getoutput(command)
+ import subprocess
+ command = ["sealert", "-f", local_id, "-P", analysis_id]
+ return subprocess.check_output(command, universal_newlines=True)
if __name__ == "__main__":
mainloop = gobject.MainLoop ()
| 1
|
4155bfe068bf211b49a0b3ffd06e78cbaf1b40fa
|
https://github.com/omphalos/crud-file-server/commit/4155bfe068bf211b49a0b3ffd06e78cbaf1b40fa
|
Fix not sanitizing file names rendered in html
|
diff --git a/crud-file-server.js b/crud-file-server.js
index ad8ae00..c6147c2 100644
--- a/crud-file-server.js
+++ b/crud-file-server.js
@@ -140,7 +140,9 @@ exports.handleRequest = function(vpath, path, req, res, readOnly, logHeadRequest
var name = results[f].name;
var normalized = url + '/' + name;
while(normalized[0] == '/') { normalized = normalized.slice(1, normalized.length); }
- res.write('\r\n<p><a href="/' + normalized + '">' + name + '</a></p>');
+ if(normalized.indexOf('"') >= 0) throw new Error('unsupported file name')
+ name = name.replace(/&/g, '&').replace(/</g, '<').replace(/>/g, '>');
+ res.write('\r\n<p><a href="/' + normalized + '"><span>' + name + '</span></a></p>');
}
res.end('\r\n</body></html>');
}
| 1
|
efad4cca2d7d461f5f8c08a0d7b51fabeb82d0a
|
https://github.com/apache/storm/commit/efad4cca2d7d461f5f8c08a0d7b51fabeb82d0a
|
STORM-3052: Allow for blobs to be unzipped/untarred
|
diff --git a/storm-core/src/jvm/org/apache/storm/localizer/Localizer.java b/storm-core/src/jvm/org/apache/storm/localizer/Localizer.java
index 616406f7dc1..549f3576d8b 100644
--- a/storm-core/src/jvm/org/apache/storm/localizer/Localizer.java
+++ b/storm-core/src/jvm/org/apache/storm/localizer/Localizer.java
@@ -543,7 +543,7 @@ private LocalizedResource downloadBlob(Map conf, String key, File localFile,
out.close();
in.close();
if (uncompress) {
- Utils.unpack(new File(downloadFile), new File(localFileWithVersion));
+ Utils.unpack(new File(downloadFile), new File(localFileWithVersion), (boolean)OR(_conf.get(Config.DISABLE_SYMLINKS), false));
LOG.debug("uncompressed " + downloadFile + " to: " + localFileWithVersion);
}
diff --git a/storm-core/src/jvm/org/apache/storm/utils/Utils.java b/storm-core/src/jvm/org/apache/storm/utils/Utils.java
index 7aa1a3930f7..8892ba93365 100644
--- a/storm-core/src/jvm/org/apache/storm/utils/Utils.java
+++ b/storm-core/src/jvm/org/apache/storm/utils/Utils.java
@@ -861,52 +861,9 @@ public static long secureRandomLong() {
* @param jarFile the .jar file to unpack
* @param toDir the destination directory into which to unpack the jar
*/
- public static void unJar(File jarFile, File toDir)
- throws IOException {
- JarFile jar = new JarFile(jarFile);
- try {
- Enumeration<JarEntry> entries = jar.entries();
- while (entries.hasMoreElements()) {
- final JarEntry entry = entries.nextElement();
- if (!entry.isDirectory()) {
- InputStream in = jar.getInputStream(entry);
- try {
- File file = new File(toDir, entry.getName());
- ensureDirectory(file.getParentFile());
- OutputStream out = new FileOutputStream(file);
- try {
- copyBytes(in, out, 8192);
- } finally {
- out.close();
- }
- } finally {
- in.close();
- }
- }
- }
- } finally {
- jar.close();
- }
- }
-
- /**
- * Copies from one stream to another.
- *
- * @param in InputStream to read from
- * @param out OutputStream to write to
- * @param buffSize the size of the buffer
- */
- public static void copyBytes(InputStream in, OutputStream out, int buffSize)
- throws IOException {
- PrintStream ps = out instanceof PrintStream ? (PrintStream)out : null;
- byte buf[] = new byte[buffSize];
- int bytesRead = in.read(buf);
- while (bytesRead >= 0) {
- out.write(buf, 0, bytesRead);
- if ((ps != null) && ps.checkError()) {
- throw new IOException("Unable to write to output stream.");
- }
- bytesRead = in.read(buf);
+ public static void unJar(File jarFile, File toDir) throws IOException {
+ try (JarFile jar = new JarFile(jarFile)) {
+ extractZipFile(jar, toDir, null);
}
}
@@ -930,20 +887,17 @@ private static void ensureDirectory(File dir) throws IOException {
*
* @param inFile The tar file as input.
* @param untarDir The untar directory where to untar the tar file.
+ * @param symlinksDisabled true if symlinks should be disabled, else false.
* @throws IOException
*/
- public static void unTar(File inFile, File untarDir) throws IOException {
- if (!untarDir.mkdirs()) {
- if (!untarDir.isDirectory()) {
- throw new IOException("Mkdirs failed to create " + untarDir);
- }
- }
+ public static void unTar(File inFile, File untarDir, boolean symlinksDisabled) throws IOException {
+ ensureDirectory(untarDir);
boolean gzipped = inFile.toString().endsWith("gz");
- if (isOnWindows()) {
+ if (Utils.isOnWindows() || symlinksDisabled) {
// Tar is not native to Windows. Use simple Java based implementation for
// tests and simple tar archives
- unTarUsingJava(inFile, untarDir, gzipped);
+ unTarUsingJava(inFile, untarDir, gzipped, symlinksDisabled);
} else {
// spawn tar utility to untar archive for full fledged unix behavior such
// as resolving symlinks in tar archives
@@ -980,7 +934,9 @@ private static void unTarUsingTar(File inFile, File untarDir,
}
private static void unTarUsingJava(File inFile, File untarDir,
- boolean gzipped) throws IOException {
+ boolean gzipped, boolean symlinksDisabled) throws IOException {
+ final String base = untarDir.getCanonicalPath();
+ LOG.trace("java untar {} to {}", inFile, base);
InputStream inputStream = null;
try {
if (gzipped) {
@@ -991,7 +947,7 @@ private static void unTarUsingJava(File inFile, File untarDir,
}
try (TarArchiveInputStream tis = new TarArchiveInputStream(inputStream)) {
for (TarArchiveEntry entry = tis.getNextTarEntry(); entry != null; ) {
- unpackEntries(tis, entry, untarDir);
+ unpackEntries(tis, entry, untarDir, base, symlinksDisabled);
entry = tis.getNextTarEntry();
}
}
@@ -1003,35 +959,82 @@ private static void unTarUsingJava(File inFile, File untarDir,
}
private static void unpackEntries(TarArchiveInputStream tis,
- TarArchiveEntry entry, File outputDir) throws IOException {
+ TarArchiveEntry entry, File outputDir, final String base,
+ boolean symlinksDisabled) throws IOException {
+ File target = new File(outputDir, entry.getName());
+ String found = target.getCanonicalPath();
+ if (!found.startsWith(base)) {
+ LOG.error("Invalid location {} is outside of {}", found, base);
+ return;
+ }
if (entry.isDirectory()) {
- File subDir = new File(outputDir, entry.getName());
- if (!subDir.mkdirs() && !subDir.isDirectory()) {
- throw new IOException("Mkdirs failed to create tar internal dir "
- + outputDir);
- }
+ LOG.trace("Extracting dir {}", target);
+ ensureDirectory(target);
for (TarArchiveEntry e : entry.getDirectoryEntries()) {
- unpackEntries(tis, e, subDir);
+ unpackEntries(tis, e, target, base, symlinksDisabled);
}
- return;
+ } else if (entry.isSymbolicLink()) {
+ if (symlinksDisabled) {
+ LOG.info("Symlinks disabled skipping {}", target);
+ } else {
+ Path src = target.toPath();
+ Path dest = Paths.get(entry.getLinkName());
+ LOG.trace("Extracting sym link {} to {}", target, dest);
+ // Create symbolic link relative to tar parent dir
+ Files.createSymbolicLink(src, dest);
+ }
+ } else if (entry.isFile()) {
+ LOG.trace("Extracting file {}", target);
+ ensureDirectory(target.getParentFile());
+ try (BufferedOutputStream outputStream = new BufferedOutputStream(new FileOutputStream(target))) {
+ IOUtils.copy(tis, outputStream);
+ }
+ } else {
+ LOG.error("{} is not a currently supported tar entry type.", entry);
}
- File outputFile = new File(outputDir, entry.getName());
- if (!outputFile.getParentFile().exists()) {
- if (!outputFile.getParentFile().mkdirs()) {
- throw new IOException("Mkdirs failed to create tar internal dir "
- + outputDir);
+
+ Path p = target.toPath();
+ if (Files.exists(p)) {
+ try {
+ //We created it so lets chmod it properly
+ int mode = entry.getMode();
+ Files.setPosixFilePermissions(p, parsePerms(mode));
+ } catch (UnsupportedOperationException e) {
+ //Ignored the file system we are on does not support this, so don't do it.
}
}
- int count;
- byte data[] = new byte[2048];
- BufferedOutputStream outputStream = new BufferedOutputStream(
- new FileOutputStream(outputFile));
+ }
- while ((count = tis.read(data)) != -1) {
- outputStream.write(data, 0, count);
+ private static Set<PosixFilePermission> parsePerms(int mode) {
+ Set<PosixFilePermission> ret = new HashSet<>();
+ if ((mode & 0001) > 0) {
+ ret.add(PosixFilePermission.OTHERS_EXECUTE);
+ }
+ if ((mode & 0002) > 0) {
+ ret.add(PosixFilePermission.OTHERS_WRITE);
+ }
+ if ((mode & 0004) > 0) {
+ ret.add(PosixFilePermission.OTHERS_READ);
+ }
+ if ((mode & 0010) > 0) {
+ ret.add(PosixFilePermission.GROUP_EXECUTE);
+ }
+ if ((mode & 0020) > 0) {
+ ret.add(PosixFilePermission.GROUP_WRITE);
}
- outputStream.flush();
- outputStream.close();
+ if ((mode & 0040) > 0) {
+ ret.add(PosixFilePermission.GROUP_READ);
+ }
+ if ((mode & 0100) > 0) {
+ ret.add(PosixFilePermission.OWNER_EXECUTE);
+ }
+ if ((mode & 0200) > 0) {
+ ret.add(PosixFilePermission.OWNER_WRITE);
+ }
+ if ((mode & 0400) > 0) {
+ ret.add(PosixFilePermission.OWNER_READ);
+ }
+ return ret;
}
public static boolean isOnWindows() {
@@ -1045,16 +1048,21 @@ public static boolean isAbsolutePath(String path) {
return Paths.get(path).isAbsolute();
}
- public static void unpack(File localrsrc, File dst) throws IOException {
+ public static void unpack(File localrsrc, File dst, boolean symLinksDisabled) throws IOException {
String lowerDst = localrsrc.getName().toLowerCase();
- if (lowerDst.endsWith(".jar")) {
+ if (lowerDst.endsWith(".jar") ||
+ lowerDst.endsWith("_jar")) {
unJar(localrsrc, dst);
- } else if (lowerDst.endsWith(".zip")) {
+ } else if (lowerDst.endsWith(".zip") ||
+ lowerDst.endsWith("_zip")) {
unZip(localrsrc, dst);
} else if (lowerDst.endsWith(".tar.gz") ||
- lowerDst.endsWith(".tgz") ||
- lowerDst.endsWith(".tar")) {
- unTar(localrsrc, dst);
+ lowerDst.endsWith("_tar_gz") ||
+ lowerDst.endsWith(".tgz") ||
+ lowerDst.endsWith("_tgz") ||
+ lowerDst.endsWith(".tar") ||
+ lowerDst.endsWith("_tar")) {
+ unTar(localrsrc, dst, symLinksDisabled);
} else {
LOG.warn("Cannot unpack " + localrsrc);
if (!localrsrc.renameTo(dst)) {
@@ -1067,6 +1075,35 @@ public static void unpack(File localrsrc, File dst) throws IOException {
}
}
+ private static void extractZipFile(ZipFile zipFile, File toDir, String prefix) throws IOException {
+ ensureDirectory(toDir);
+ final String base = toDir.getCanonicalPath();
+
+ Enumeration<? extends ZipEntry> entries = zipFile.entries();
+ while (entries.hasMoreElements()) {
+ ZipEntry entry = entries.nextElement();
+ if (!entry.isDirectory()) {
+ if (prefix != null && !entry.getName().startsWith(prefix)) {
+ //No need to extract it, it is not what we are looking for.
+ continue;
+ }
+ File file = new File(toDir, entry.getName());
+ String found = file.getCanonicalPath();
+ if (!found.startsWith(base)) {
+ LOG.error("Invalid location {} is outside of {}", found, base);
+ continue;
+ }
+
+ try (InputStream in = zipFile.getInputStream(entry)) {
+ ensureDirectory(file.getParentFile());
+ try (OutputStream out = new FileOutputStream(file)) {
+ IOUtils.copy(in, out);
+ }
+ }
+ }
+ }
+ }
+
public static boolean canUserReadBlob(ReadableBlobMeta meta, String user) {
SettableBlobMeta settable = meta.get_settable();
for (AccessControl acl : settable.get_acl()) {
@@ -1398,45 +1435,12 @@ public static void validateTopologyBlobStoreMap(Map<String, ?> stormConf, Set<St
* Given a File input it will unzip the file in a the unzip directory
* passed as the second parameter
* @param inFile The zip file as input
- * @param unzipDir The unzip directory where to unzip the zip file.
+ * @param toDir The unzip directory where to unzip the zip file.
* @throws IOException
*/
- public static void unZip(File inFile, File unzipDir) throws IOException {
- Enumeration<? extends ZipEntry> entries;
- ZipFile zipFile = new ZipFile(inFile);
-
- try {
- entries = zipFile.entries();
- while (entries.hasMoreElements()) {
- ZipEntry entry = entries.nextElement();
- if (!entry.isDirectory()) {
- InputStream in = zipFile.getInputStream(entry);
- try {
- File file = new File(unzipDir, entry.getName());
- if (!file.getParentFile().mkdirs()) {
- if (!file.getParentFile().isDirectory()) {
- throw new IOException("Mkdirs failed to create " +
- file.getParentFile().toString());
- }
- }
- OutputStream out = new FileOutputStream(file);
- try {
- byte[] buffer = new byte[8192];
- int i;
- while ((i = in.read(buffer)) != -1) {
- out.write(buffer, 0, i);
- }
- } finally {
- out.close();
- }
- } finally {
- in.close();
- }
- }
- }
- } finally {
- zipFile.close();
- }
+ public static void unZip(File inFile, File toDir) throws IOException {
+ try (ZipFile zipFile = new ZipFile(inFile)) {
+ extractZipFile(zipFile, toDir, null); }
}
/**
@@ -1910,21 +1914,10 @@ public static int execCommand(String... command) throws ExecuteException, IOExce
public static void extractDirFromJar(String jarpath, String dir, File destdir) {
_instance.extractDirFromJarImpl(jarpath, dir, destdir);
}
-
+
public void extractDirFromJarImpl(String jarpath, String dir, File destdir) {
try (JarFile jarFile = new JarFile(jarpath)) {
- Enumeration<JarEntry> jarEnums = jarFile.entries();
- while (jarEnums.hasMoreElements()) {
- JarEntry entry = jarEnums.nextElement();
- if (!entry.isDirectory() && entry.getName().startsWith(dir)) {
- File aFile = new File(destdir, entry.getName());
- aFile.getParentFile().mkdirs();
- try (FileOutputStream out = new FileOutputStream(aFile);
- InputStream in = jarFile.getInputStream(entry)) {
- IOUtils.copy(in, out);
- }
- }
- }
+ extractZipFile(jarFile, destdir, dir);
} catch (IOException e) {
LOG.info("Could not extract {} from {}", dir, jarpath);
}
| 1
|
8244394cc4efcfd1c7e179f18e2292d1d32b7fad
|
https://github.com/webbukkit/dynmap/commit/8244394cc4efcfd1c7e179f18e2292d1d32b7fad
|
Zap warning for lack of webp tools - confusing support headache
|
diff --git a/DynmapCore/src/main/java/org/dynmap/DynmapCore.java b/DynmapCore/src/main/java/org/dynmap/DynmapCore.java
index 8b7901f70..93a0a5e10 100644
--- a/DynmapCore/src/main/java/org/dynmap/DynmapCore.java
+++ b/DynmapCore/src/main/java/org/dynmap/DynmapCore.java
@@ -503,7 +503,6 @@ public boolean enableCore(EnableCoreCallbacks cb) {
Log.info("Found cwebp at " + cwebpPath + " and dwebp at " + dwebpPath + ": webp format enabled");
}
else {
- Log.warning("cwebp or dwebp not found, or cwebpPath or dwebpPath is invalid: webp format disabled");
cwebpPath = dwebpPath = null;
}
/* Get default image format */
| 0
|
230076f1f4df9c861eeb080198a909429d48c269
|
https://github.com/apache/commons-collections/commit/230076f1f4df9c861eeb080198a909429d48c269
|
[COLLECTIONS-780] Use assertThrows V2
|
diff --git a/src/test/java/org/apache/commons/collections4/FactoryUtilsTest.java b/src/test/java/org/apache/commons/collections4/FactoryUtilsTest.java
index d57cfa8b15..df8e9a796f 100644
--- a/src/test/java/org/apache/commons/collections4/FactoryUtilsTest.java
+++ b/src/test/java/org/apache/commons/collections4/FactoryUtilsTest.java
@@ -23,6 +23,7 @@
import static org.junit.Assert.assertSame;
import static org.junit.Assert.assertTrue;
import static org.junit.Assert.fail;
+import static org.junit.jupiter.api.Assertions.assertThrows;
import java.io.IOException;
import java.io.Serializable;
@@ -31,7 +32,7 @@
import org.apache.commons.collections4.functors.ConstantFactory;
import org.apache.commons.collections4.functors.ExceptionFactory;
-import org.junit.Test;
+import org.junit.jupiter.api.Test;
/**
* Tests the org.apache.commons.collections.FactoryUtils class.
@@ -214,9 +215,9 @@ public int getValue() {
// instantiateFactory
//------------------------------------------------------------------
- @Test(expected=NullPointerException.class)
+ @Test
public void instantiateFactoryNull() {
- FactoryUtils.instantiateFactory(null);
+ assertThrows(NullPointerException.class, () -> FactoryUtils.instantiateFactory(null));
}
@Test
@@ -229,14 +230,14 @@ public void instantiateFactorySimple() {
assertEquals(1, created.getValue());
}
- @Test(expected=IllegalArgumentException.class)
+ @Test
public void instantiateFactoryMismatch() {
- FactoryUtils.instantiateFactory(Date.class, null, new Object[] {null});
+ assertThrows(IllegalArgumentException.class, () -> FactoryUtils.instantiateFactory(Date.class, null, new Object[] {null}));
}
- @Test(expected=IllegalArgumentException.class)
+ @Test
public void instantiateFactoryNoConstructor() {
- FactoryUtils.instantiateFactory(Date.class, new Class[] {Long.class}, new Object[] {null});
+ assertThrows(IllegalArgumentException.class, () -> FactoryUtils.instantiateFactory(Date.class, new Class[] {Long.class}, new Object[] {null}));
}
@Test
diff --git a/src/test/java/org/apache/commons/collections4/PredicateUtilsTest.java b/src/test/java/org/apache/commons/collections4/PredicateUtilsTest.java
index af558a6731..087fa748e0 100644
--- a/src/test/java/org/apache/commons/collections4/PredicateUtilsTest.java
+++ b/src/test/java/org/apache/commons/collections4/PredicateUtilsTest.java
@@ -36,7 +36,7 @@
import org.apache.commons.collections4.functors.NotNullPredicate;
import org.apache.commons.collections4.functors.NullPredicate;
import org.apache.commons.collections4.functors.TruePredicate;
-import org.junit.Test;
+import org.junit.jupiter.api.Test;
/**
* Tests the PredicateUtils class.
@@ -130,9 +130,9 @@ public void testNotPredicate() {
assertFalse(PredicateUtils.notPredicate(truePredicate()).evaluate(cInteger));
}
- @Test(expected=NullPointerException.class)
+ @Test
public void testNotPredicateEx() {
- PredicateUtils.notPredicate(null);
+ assertThrows(NullPointerException.class, () -> PredicateUtils.notPredicate(null));
}
// andPredicate
@@ -146,9 +146,9 @@ public void testAndPredicate() {
assertFalse(PredicateUtils.andPredicate(FalsePredicate.falsePredicate(), FalsePredicate.falsePredicate()).evaluate(null));
}
- @Test(expected=NullPointerException.class)
+ @Test
public void testAndPredicateEx() {
- PredicateUtils.andPredicate(null, null);
+ assertThrows(NullPointerException.class, () -> PredicateUtils.andPredicate(null, null));
}
// allPredicate
@@ -192,25 +192,25 @@ public void testAllPredicate() {
assertPredicateTrue(AllPredicate.allPredicate(coll), null);
}
- @Test(expected=NullPointerException.class)
+ @Test
public void testAllPredicateEx1() {
- AllPredicate.allPredicate((Predicate<Object>[]) null);
+ assertThrows(NullPointerException.class, () -> AllPredicate.allPredicate((Predicate<Object>[]) null));
}
@SuppressWarnings("unchecked")
- @Test(expected=NullPointerException.class)
+ @Test
public void testAllPredicateEx2() {
- AllPredicate.<Object>allPredicate(new Predicate[] { null });
+ assertThrows(NullPointerException.class, () -> AllPredicate.<Object>allPredicate(new Predicate[] { null }));
}
- @Test(expected=NullPointerException.class)
+ @Test
public void testAllPredicateEx3() {
- AllPredicate.allPredicate(null, null);
+ assertThrows(NullPointerException.class, () -> AllPredicate.allPredicate(null, null));
}
- @Test(expected=NullPointerException.class)
+ @Test
public void testAllPredicateEx4() {
- AllPredicate.allPredicate((Collection<Predicate<Object>>) null);
+ assertThrows(NullPointerException.class, () -> AllPredicate.allPredicate((Collection<Predicate<Object>>) null));
}
@Test
@@ -218,12 +218,12 @@ public void testAllPredicateEx5() {
AllPredicate.allPredicate(Collections.emptyList());
}
- @Test(expected=NullPointerException.class)
+ @Test
public void testAllPredicateEx6() {
final Collection<Predicate<Object>> coll = new ArrayList<>();
coll.add(null);
coll.add(null);
- AllPredicate.allPredicate(coll);
+ assertThrows(NullPointerException.class, () -> AllPredicate.allPredicate(coll));
}
// orPredicate
@@ -237,9 +237,9 @@ public void testOrPredicate() {
assertFalse(PredicateUtils.orPredicate(FalsePredicate.falsePredicate(), FalsePredicate.falsePredicate()).evaluate(null));
}
- @Test(expected=NullPointerException.class)
+ @Test
public void testOrPredicateEx() {
- PredicateUtils.orPredicate(null, null);
+ assertThrows(NullPointerException.class, () -> PredicateUtils.orPredicate(null, null));
}
// anyPredicate
@@ -284,25 +284,25 @@ public void testAnyPredicate() {
assertPredicateFalse(PredicateUtils.anyPredicate(coll), null);
}
- @Test(expected=NullPointerException.class)
+ @Test
public void testAnyPredicateEx1() {
- PredicateUtils.anyPredicate((Predicate<Object>[]) null);
+ assertThrows(NullPointerException.class, () -> PredicateUtils.anyPredicate((Predicate<Object>[]) null));
}
@SuppressWarnings("unchecked")
- @Test(expected=NullPointerException.class)
+ @Test
public void testAnyPredicateEx2() {
- PredicateUtils.anyPredicate(new Predicate[] {null});
+ assertThrows(NullPointerException.class, () -> PredicateUtils.anyPredicate(new Predicate[] {null}));
}
- @Test(expected=NullPointerException.class)
+ @Test
public void testAnyPredicateEx3() {
- PredicateUtils.anyPredicate(null, null);
+ assertThrows(NullPointerException.class, () -> PredicateUtils.anyPredicate(null, null));
}
- @Test(expected=NullPointerException.class)
+ @Test
public void testAnyPredicateEx4() {
- PredicateUtils.anyPredicate((Collection<Predicate<Object>>) null);
+ assertThrows(NullPointerException.class, () -> PredicateUtils.anyPredicate((Collection<Predicate<Object>>) null));
}
@Test
@@ -310,12 +310,12 @@ public void testAnyPredicateEx5() {
PredicateUtils.anyPredicate(Collections.emptyList());
}
- @Test(expected=NullPointerException.class)
+ @Test
public void testAnyPredicateEx6() {
final Collection<Predicate<Object>> coll = new ArrayList<>();
coll.add(null);
coll.add(null);
- PredicateUtils.anyPredicate(coll);
+ assertThrows(NullPointerException.class, () -> PredicateUtils.anyPredicate(coll));
}
// eitherPredicate
@@ -329,9 +329,9 @@ public void testEitherPredicate() {
assertFalse(PredicateUtils.eitherPredicate(FalsePredicate.falsePredicate(), FalsePredicate.falsePredicate()).evaluate(null));
}
- @Test(expected=NullPointerException.class)
+ @Test
public void testEitherPredicateEx() {
- PredicateUtils.eitherPredicate(null, null);
+ assertThrows(NullPointerException.class, () -> PredicateUtils.eitherPredicate(null, null));
}
// onePredicate
@@ -377,25 +377,25 @@ public void testOnePredicate() {
assertPredicateFalse(PredicateUtils.onePredicate(coll), null);
}
- @Test(expected=NullPointerException.class)
+ @Test
public void testOnePredicateEx1() {
- PredicateUtils.onePredicate((Predicate<Object>[]) null);
+ assertThrows(NullPointerException.class, () -> PredicateUtils.onePredicate((Predicate<Object>[]) null));
}
@SuppressWarnings("unchecked")
- @Test(expected=NullPointerException.class)
+ @Test
public void testOnePredicateEx2() {
- PredicateUtils.onePredicate(new Predicate[] {null});
+ assertThrows(NullPointerException.class, () -> PredicateUtils.onePredicate(new Predicate[] {null}));
}
- @Test(expected=NullPointerException.class)
+ @Test
public void testOnePredicateEx3() {
- PredicateUtils.onePredicate(null, null);
+ assertThrows(NullPointerException.class, () -> PredicateUtils.onePredicate(null, null));
}
- @Test(expected=NullPointerException.class)
+ @Test
public void testOnePredicateEx4() {
- PredicateUtils.onePredicate((Collection<Predicate<Object>>) null);
+ assertThrows(NullPointerException.class, () -> PredicateUtils.onePredicate((Collection<Predicate<Object>>) null));
}
@SuppressWarnings("unchecked")
@@ -404,9 +404,9 @@ public void testOnePredicateEx5() {
PredicateUtils.onePredicate(Collections.EMPTY_LIST);
}
- @Test(expected=NullPointerException.class)
+ @Test
public void testOnePredicateEx6() {
- PredicateUtils.onePredicate(Arrays.asList(null, null));
+ assertThrows(NullPointerException.class, () -> PredicateUtils.onePredicate(Arrays.asList(null, null)));
}
// neitherPredicate
@@ -420,9 +420,9 @@ public void testNeitherPredicate() {
assertTrue(PredicateUtils.neitherPredicate(FalsePredicate.falsePredicate(), FalsePredicate.falsePredicate()).evaluate(null));
}
- @Test(expected=NullPointerException.class)
+ @Test
public void testNeitherPredicateEx() {
- PredicateUtils.neitherPredicate(null, null);
+ assertThrows(NullPointerException.class, () -> PredicateUtils.neitherPredicate(null, null));
}
// nonePredicate
@@ -466,26 +466,26 @@ public void testNonePredicate() {
assertPredicateTrue(PredicateUtils.nonePredicate(coll), null);
}
- @Test(expected=NullPointerException.class)
+ @Test
public void testNonePredicateEx1() {
- PredicateUtils.nonePredicate((Predicate<Object>[]) null);
+ assertThrows(NullPointerException.class, () -> PredicateUtils.nonePredicate((Predicate<Object>[]) null));
}
@SuppressWarnings("unchecked")
- @Test(expected=NullPointerException.class)
+ @Test
public void testNonePredicateEx2() {
- PredicateUtils.nonePredicate(new Predicate[] {null});
+ assertThrows(NullPointerException.class, () -> PredicateUtils.nonePredicate(new Predicate[] {null}));
}
@SuppressWarnings("unchecked")
- @Test(expected=NullPointerException.class)
+ @Test
public void testNonePredicateEx3() {
- PredicateUtils.nonePredicate(null, null);
+ assertThrows(NullPointerException.class, () -> PredicateUtils.nonePredicate(null, null));
}
- @Test(expected=NullPointerException.class)
+ @Test
public void testNonePredicateEx4() {
- PredicateUtils.nonePredicate((Collection<Predicate<Object>>) null);
+ assertThrows(NullPointerException.class, () -> PredicateUtils.nonePredicate((Collection<Predicate<Object>>) null));
}
@Test
@@ -493,12 +493,12 @@ public void testNonePredicateEx5() {
PredicateUtils.nonePredicate(Collections.emptyList());
}
- @Test(expected=NullPointerException.class)
+ @Test
public void testNonePredicateEx6() {
final Collection<Predicate<Object>> coll = new ArrayList<>();
coll.add(null);
coll.add(null);
- PredicateUtils.nonePredicate(coll);
+ assertThrows(NullPointerException.class, () -> PredicateUtils.nonePredicate(coll));
}
// instanceofPredicate
@@ -536,14 +536,14 @@ public void testAsPredicateTransformer() {
assertTrue(PredicateUtils.asPredicate(TransformerUtils.nopTransformer()).evaluate(true));
}
- @Test(expected=NullPointerException.class)
+ @Test
public void testAsPredicateTransformerEx1() {
- PredicateUtils.asPredicate(null);
+ assertThrows(NullPointerException.class, () -> PredicateUtils.asPredicate(null));
}
- @Test(expected=FunctorException.class)
+ @Test
public void testAsPredicateTransformerEx2() {
- PredicateUtils.asPredicate(TransformerUtils.nopTransformer()).evaluate(null);
+ assertThrows(FunctorException.class, () -> PredicateUtils.asPredicate(TransformerUtils.nopTransformer()).evaluate(null));
}
// invokerPredicate
@@ -557,19 +557,19 @@ public void testInvokerPredicate() {
assertFalse(PredicateUtils.invokerPredicate("isEmpty").evaluate(list));
}
- @Test(expected=NullPointerException.class)
+ @Test
public void testInvokerPredicateEx1() {
- PredicateUtils.invokerPredicate(null);
+ assertThrows(NullPointerException.class, () -> PredicateUtils.invokerPredicate(null));
}
- @Test(expected=FunctorException.class)
+ @Test
public void testInvokerPredicateEx2() {
- PredicateUtils.invokerPredicate("isEmpty").evaluate(null);
+ assertThrows(FunctorException.class, () -> PredicateUtils.invokerPredicate("isEmpty").evaluate(null));
}
- @Test(expected=FunctorException.class)
+ @Test
public void testInvokerPredicateEx3() {
- PredicateUtils.invokerPredicate("noSuchMethod").evaluate(new Object());
+ assertThrows(FunctorException.class, () -> PredicateUtils.invokerPredicate("noSuchMethod").evaluate(new Object()));
}
// invokerPredicate2
@@ -585,34 +585,35 @@ public void testInvokerPredicate2() {
"contains", new Class[]{Object.class}, new Object[]{cString}).evaluate(list));
}
- @Test(expected=NullPointerException.class)
+ @Test
public void testInvokerPredicate2Ex1() {
- PredicateUtils.invokerPredicate(null, null, null);
+ assertThrows(NullPointerException.class, () -> PredicateUtils.invokerPredicate(null, null, null));
}
- @Test(expected=FunctorException.class)
+ @Test
public void testInvokerPredicate2Ex2() {
- PredicateUtils.invokerPredicate("contains", new Class[] {Object.class}, new Object[] {cString}).evaluate(null);
+ assertThrows(FunctorException.class, () -> PredicateUtils.
+ invokerPredicate("contains", new Class[] {Object.class}, new Object[] {cString}).evaluate(null));
}
- @Test(expected=FunctorException.class)
+ @Test
public void testInvokerPredicate2Ex3() {
- PredicateUtils.invokerPredicate(
- "noSuchMethod", new Class[] {Object.class}, new Object[] {cString}).evaluate(new Object());
+ assertThrows(FunctorException.class, () -> PredicateUtils.invokerPredicate(
+ "noSuchMethod", new Class[] {Object.class}, new Object[] {cString}).evaluate(new Object()));
}
// nullIsException
//------------------------------------------------------------------
- @Test(expected=FunctorException.class)
+ @Test
public void testNullIsExceptionPredicate() {
assertTrue(PredicateUtils.nullIsExceptionPredicate(truePredicate()).evaluate(new Object()));
- PredicateUtils.nullIsExceptionPredicate(TruePredicate.truePredicate()).evaluate(null);
+ assertThrows(FunctorException.class, () -> PredicateUtils.nullIsExceptionPredicate(TruePredicate.truePredicate()).evaluate(null));
}
- @Test(expected=NullPointerException.class)
+ @Test
public void testNullIsExceptionPredicateEx1() {
- PredicateUtils.nullIsExceptionPredicate(null);
+ assertThrows(NullPointerException.class, () -> PredicateUtils.nullIsExceptionPredicate(null));
}
// nullIsTrue
@@ -625,9 +626,9 @@ public void testNullIsTruePredicate() {
assertFalse(PredicateUtils.nullIsTruePredicate(FalsePredicate.falsePredicate()).evaluate(new Object()));
}
- @Test(expected=NullPointerException.class)
+ @Test
public void testNullIsTruePredicateEx1() {
- PredicateUtils.nullIsTruePredicate(null);
+ assertThrows(NullPointerException.class, () -> PredicateUtils.nullIsTruePredicate(null));
}
// nullIsFalse
@@ -640,9 +641,9 @@ public void testNullIsFalsePredicate() {
assertFalse(PredicateUtils.nullIsFalsePredicate(FalsePredicate.falsePredicate()).evaluate(new Object()));
}
- @Test(expected=NullPointerException.class)
+ @Test
public void testNullIsFalsePredicateEx1() {
- PredicateUtils.nullIsFalsePredicate(null);
+ assertThrows(NullPointerException.class, () -> PredicateUtils.nullIsFalsePredicate(null));
}
// transformed
@@ -696,3 +697,5 @@ public void testSingletonPatternInSerialization() {
return truePredicate(); //Just return something to satisfy super class.
}
}
+
+
diff --git a/src/test/java/org/apache/commons/collections4/bloomfilter/hasher/HashFunctionValidatorTest.java b/src/test/java/org/apache/commons/collections4/bloomfilter/hasher/HashFunctionValidatorTest.java
index 625cb645ec..bd9532a237 100644
--- a/src/test/java/org/apache/commons/collections4/bloomfilter/hasher/HashFunctionValidatorTest.java
+++ b/src/test/java/org/apache/commons/collections4/bloomfilter/hasher/HashFunctionValidatorTest.java
@@ -17,11 +17,12 @@
package org.apache.commons.collections4.bloomfilter.hasher;
import static org.junit.Assert.assertFalse;
+import static org.junit.Assert.assertThrows;
import static org.junit.Assert.assertTrue;
import org.apache.commons.collections4.bloomfilter.hasher.HashFunctionIdentity.ProcessType;
import org.apache.commons.collections4.bloomfilter.hasher.HashFunctionIdentity.Signedness;
-import org.junit.Test;
+import org.junit.jupiter.api.Test;
/**
* Tests of the {@link HashFunctionValidator}.
@@ -108,12 +109,12 @@ public void testSignedness() {
/**
* Test the check method throws when the two hash functions are not equal.
*/
- @Test(expected=IllegalArgumentException.class)
+ @Test
public void testCheckThrows() {
final HashFunctionIdentityImpl impl1 = new HashFunctionIdentityImpl("Testing Suite", "impl1", Signedness.SIGNED,
ProcessType.CYCLIC, 300L);
final HashFunctionIdentityImpl impl2 = new HashFunctionIdentityImpl("Testing Suite", "impl1", Signedness.UNSIGNED,
ProcessType.CYCLIC, 300L);
- HashFunctionValidator.checkAreEqual(impl1, impl2);
+ assertThrows(IllegalArgumentException.class, () -> HashFunctionValidator.checkAreEqual(impl1, impl2));
}
}
diff --git a/src/test/java/org/apache/commons/collections4/functors/AbstractPredicateTest.java b/src/test/java/org/apache/commons/collections4/functors/AbstractPredicateTest.java
index e26564ca05..68e46e9ae0 100644
--- a/src/test/java/org/apache/commons/collections4/functors/AbstractPredicateTest.java
+++ b/src/test/java/org/apache/commons/collections4/functors/AbstractPredicateTest.java
@@ -18,15 +18,15 @@
import org.apache.commons.collections4.Predicate;
import org.junit.Assert;
-import org.junit.Before;
-import org.junit.Test;
+import org.junit.jupiter.api.BeforeEach;
+import org.junit.jupiter.api.Test;
public abstract class AbstractPredicateTest {
protected Object cObject;
protected String cString;
protected Integer cInteger;
- @Before
+ @BeforeEach
public void initializeTestObjects() throws Exception {
cObject = new Object();
cString = "Hello";
diff --git a/src/test/java/org/apache/commons/collections4/functors/NullPredicateTest.java b/src/test/java/org/apache/commons/collections4/functors/NullPredicateTest.java
index 652f7c8bb7..15abe48406 100644
--- a/src/test/java/org/apache/commons/collections4/functors/NullPredicateTest.java
+++ b/src/test/java/org/apache/commons/collections4/functors/NullPredicateTest.java
@@ -20,7 +20,7 @@
import static org.junit.Assert.assertSame;
import org.apache.commons.collections4.Predicate;
-import org.junit.Test;
+import org.junit.jupiter.api.Test;
public class NullPredicateTest extends AbstractPredicateTest {
@Test
| 0
|
44952c14d0307113415e0a56cce7610d1a50976c
|
https://github.com/boonebgorges/buddypress-docs/commit/44952c14d0307113415e0a56cce7610d1a50976c
|
Version bumps for 2.1.4.
|
diff --git a/composer.json b/composer.json
index f74d09ec..e7fc8dba 100644
--- a/composer.json
+++ b/composer.json
@@ -1,6 +1,7 @@
{
"name": "boonebgorges/buddypress-docs",
"description": "Collaborative document editing for BuddyPress",
+ "version": "2.1.4",
"type": "project",
"license": "GPLv3",
"require": {},
diff --git a/loader.php b/loader.php
index 00bc118c..b149a0e7 100644
--- a/loader.php
+++ b/loader.php
@@ -3,7 +3,7 @@
Plugin Name: BuddyPress Docs
Plugin URI: http://github.com/boonebgorges/buddypress-docs
Description: Adds collaborative Docs to BuddyPress
-Version: 2.1.3
+Version: 2.1.4
Author: Boone B Gorges, David Cavins
Author URI: http://boone.gorg.es
Text Domain: buddypress-docs
@@ -15,7 +15,7 @@
It's on like Donkey Kong
*/
-define( 'BP_DOCS_VERSION', '2.1.3' );
+define( 'BP_DOCS_VERSION', '2.1.4' );
/*
* BuddyPress Docs introduces a lot of overhead. Unless otherwise specified,
diff --git a/package.json b/package.json
index 5afd2e86..0b94648b 100644
--- a/package.json
+++ b/package.json
@@ -17,5 +17,5 @@
"matchdep": "latest"
},
"license": "GPL-2.0+",
- "version": "2.0.1"
+ "version": "2.1.4"
}
diff --git a/readme.txt b/readme.txt
index fbd881eb..4a27962e 100755
--- a/readme.txt
+++ b/readme.txt
@@ -3,8 +3,8 @@ Contributors: boonebgorges, cuny-academic-commons, dcavins
Donate link: http://teleogistic.net/donate
Tags: buddypress, docs, wiki, documents, collaboration
Requires at least: 3.3
-Tested up to: 5.2
-Stable tag: 2.1.3
+Tested up to: 5.5
+Stable tag: 2.1.4
Adds collaborative Docs to BuddyPress.
| 0
|
4287c1c2a043f3f0447730ced74e0ddb1b6004eb
|
https://github.com/moodle/moodle/commit/4287c1c2a043f3f0447730ced74e0ddb1b6004eb
|
MDL-24058 fixed sql injection, addslashes must not be used any more
|
diff --git a/admin/report/spamcleaner/index.php b/admin/report/spamcleaner/index.php
index 37815460e358a..d069d9318f8c1 100755
--- a/admin/report/spamcleaner/index.php
+++ b/admin/report/spamcleaner/index.php
@@ -148,19 +148,21 @@ function search_spammers($keywords) {
$keywords = array($keywords); // Make it into an array
}
- $like = $DB->sql_ilike();
+ $like = $DB->sql_ilike();
+ $params = array('userid'=>$USER->id);
$keywordfull = array();
foreach ($keywords as $keyword) {
- $keyword = addslashes($keyword); // Just to be safe
- $keywordfull[] = " description $like '%$keyword%' ";
- $keywordfull2[] = " p.summary $like '%$keyword%' ";
+ $keywordfull[] = " description $like :descpat ";
+ $params['descpat'] = "%$keyword%";
+ $keywordfull2[] = " p.summary $like :sumpat ";
+ $params['sumpat'] = "%$keyword%";
}
$conditions = '( '.implode(' OR ', $keywordfull).' )';
$conditions2 = '( '.implode(' OR ', $keywordfull2).' )';
- $sql = "SELECT * FROM {user} WHERE deleted = 0 AND id <> {$USER->id} AND $conditions"; // Exclude oneself
- $sql2= "SELECT u.*, p.summary FROM {user} AS u, {post} AS p WHERE $conditions2 AND u.deleted = 0 AND u.id=p.userid AND u.id <> {$USER->id}";
+ $sql = "SELECT * FROM {user} WHERE deleted = 0 AND id <> :userid AND $conditions"; // Exclude oneself
+ $sql2 = "SELECT u.*, p.summary FROM {user} AS u, {post} AS p WHERE $conditions2 AND u.deleted = 0 AND u.id=p.userid AND u.id <> :userid";
$spamusers_desc = $DB->get_recordset_sql($sql);
$spamusers_blog = $DB->get_recordset_sql($sql2);
| 1
|
3273cc76b33cae568d22d5e70b773d2e3f757a1c
|
https://github.com/MailCleaner/MailCleaner/commit/3273cc76b33cae568d22d5e70b773d2e3f757a1c
|
Translated using Weblate (Korean)
Currently translated at 100.0% (342 of 342 strings)
Translation: MailCleaner Anti Spam/User interface
Translate-URL: https://hosted.weblate.org/projects/mailcleaner/user-interface/ko/
|
diff --git a/www/user/htdocs/lang/ko/texts.php b/www/user/htdocs/lang/ko/texts.php
index e81ecc98..4853e3e8 100644
--- a/www/user/htdocs/lang/ko/texts.php
+++ b/www/user/htdocs/lang/ko/texts.php
@@ -500,3 +500,4 @@
$txt['ADDANEWSENTRY'] = "리스트에 주소 추가";
$txt['NEWSLISTENTRYTOADD'] = "뉴스레터 목록에 추가하고 싶은 주소를 입력하세요. 설명을 추가할 수도 있습니다.";
$txt['REMOVEANEWSENTRYSHORTHELP'] = "수정하고 싶은 주소를 하나이상 선택하고 원하는 버튼을 누르세요.";
+$txt['ADDTOGROUP'] = "그룹의 모든 주소에 추가";
| 0
|
e1456c4134ed54ff2fa4f9a83831c141f667b084
|
https://github.com/mybb/mybb/commit/e1456c4134ed54ff2fa4f9a83831c141f667b084
|
Update template version to 1.8.25
|
diff --git a/admin/modules/user/users.php b/admin/modules/user/users.php
index 7026afb1d3..bba7f27c5c 100644
--- a/admin/modules/user/users.php
+++ b/admin/modules/user/users.php
@@ -930,7 +930,7 @@
<link rel="stylesheet" href="../jscripts/sceditor/themes/mybb.css" type="text/css" media="all" />
<script type="text/javascript" src="../jscripts/sceditor/jquery.sceditor.bbcode.min.js?ver=1822"></script>
- <script type="text/javascript" src="../jscripts/bbcodes_sceditor.js?ver=1824"></script>
+ <script type="text/javascript" src="../jscripts/bbcodes_sceditor.js?ver=1825"></script>
<script type="text/javascript" src="../jscripts/sceditor/plugins/undo.js?ver=1805"></script>
EOF;
$page->output_header($lang->edit_user);
diff --git a/install/resources/mybb_theme.xml b/install/resources/mybb_theme.xml
index 804ac2a8af..5cb6e9ec60 100644
--- a/install/resources/mybb_theme.xml
+++ b/install/resources/mybb_theme.xml
@@ -14140,9 +14140,9 @@ if(use_xmlhttprequest == "1")
<td class="trow1" width="20%"><strong>{$lang->username}</strong></td>
<td class="trow1">{$mybb->user['username']} <span class="smalltext">[<strong><a href="member.php?action=logout&logoutkey={$mybb->user['logoutkey']}">{$lang->change_user}</a></strong>]</span></td>
</tr>]]></template>
- <template name="codebuttons" version="1824"><![CDATA[<link rel="stylesheet" href="{$mybb->asset_url}/jscripts/sceditor/themes/{$theme['editortheme']}" type="text/css" media="all" />
+ <template name="codebuttons" version="1825"><![CDATA[<link rel="stylesheet" href="{$mybb->asset_url}/jscripts/sceditor/themes/{$theme['editortheme']}" type="text/css" media="all" />
<script type="text/javascript" src="{$mybb->asset_url}/jscripts/sceditor/jquery.sceditor.bbcode.min.js?ver=1822"></script>
-<script type="text/javascript" src="{$mybb->asset_url}/jscripts/bbcodes_sceditor.js?ver=1824"></script>
+<script type="text/javascript" src="{$mybb->asset_url}/jscripts/bbcodes_sceditor.js?ver=1825"></script>
<script type="text/javascript" src="{$mybb->asset_url}/jscripts/sceditor/plugins/undo.js?ver=1821"></script>
<script type="text/javascript">
var partialmode = {$mybb->settings['partialmode']},
@@ -14361,7 +14361,7 @@ $(function() {
</tr>]]></template>
<template name="task_image" version="1800"><![CDATA[<img src="{$mybb->settings['bburl']}/task.php" width="1" height="1" alt="" />]]></template>
<template name="smilie" version="1800"><![CDATA[<img src="{$smilie['image']}" alt="{$smilie['name']}" title="{$smilie['name']}" class="smilie smilie_{$smilie['sid']}{$extra_class}"{$onclick} />]]></template>
- <template name="delete_attachments_button" version="1825"><![CDATA[
+ <template name="delete_attachments_button" version="1825"><![CDATA[
<div align="center">
<input type="hidden" name="action" value="do_attachments" />
<input type="submit" class="button" value="{$lang->delete_attachments}" />
| 0
|
66607a56749339d50620b049701ad4d6a4dafbd7
|
https://github.com/flarum/core/commit/66607a56749339d50620b049701ad4d6a4dafbd7
|
Always invalidate all user email tokens
Reported by B. Dhiyaneshwaran of Geek Freak.
|
diff --git a/src/User/Command/ConfirmEmailHandler.php b/src/User/Command/ConfirmEmailHandler.php
index cef9f70b81..feb80a11fd 100644
--- a/src/User/Command/ConfirmEmailHandler.php
+++ b/src/User/Command/ConfirmEmailHandler.php
@@ -53,7 +53,8 @@ public function handle(ConfirmEmail $command)
$user->save();
$this->dispatchEventsFor($user);
- $token->delete();
+ // Delete *all* tokens for the user, in case other ones were sent first
+ $user->emailTokens()->delete();
return $user;
}
diff --git a/src/User/User.php b/src/User/User.php
index 13d55dd1ad..3fc2f21106 100644
--- a/src/User/User.php
+++ b/src/User/User.php
@@ -614,6 +614,16 @@ public function notifications()
return $this->hasMany('Flarum\Notification\Notification');
}
+ /**
+ * Define the relationship with the user's email tokens.
+ *
+ * @return \Illuminate\Database\Eloquent\Relations\HasMany
+ */
+ public function emailTokens()
+ {
+ return $this->hasMany(EmailToken::class);
+ }
+
/**
* Define the relationship with the permissions of all of the groups that
* the user is in.
| 1
|
5ede4ce188d29aef94af78f27d89169ac4ee54cd
|
https://github.com/josh/rails/commit/5ede4ce188d29aef94af78f27d89169ac4ee54cd
|
Fixed session related memory leak [#1558 state:resolved]
Signed-off-by: Joshua Peek <[email protected]>
|
diff --git a/actionpack/lib/action_controller/base.rb b/actionpack/lib/action_controller/base.rb
index c2f0c1c4f6fd9..13f2e9072e79e 100644
--- a/actionpack/lib/action_controller/base.rb
+++ b/actionpack/lib/action_controller/base.rb
@@ -1160,6 +1160,9 @@ def expires_now #:doc:
def reset_session #:doc:
request.reset_session
@_session = request.session
+ #http://rails.lighthouseapp.com/projects/8994/tickets/1558-memory-problem-on-reset_session-in-around_filter#ticket-1558-1
+ #MRI appears to have a GC related memory leak to do with the finalizer that is defined on CGI::Session
+ ObjectSpace.undefine_finalizer(@_session)
response.session = @_session
end
| 1
|
d4184aa26cfa4e99b6e36502aee7f685e122facc
|
https://github.com/realm/realm-cocoa/commit/d4184aa26cfa4e99b6e36502aee7f685e122facc
|
Merge pull request #1200 from realm/tg-circular-add
Fix a memory leak when circularly linked objects are added to a Realm
|
diff --git a/CHANGELOG.md b/CHANGELOG.md
index d4270bfeb1..6984cfd900 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -7,7 +7,7 @@ x.x.x Release notes (yyyy-MM-dd)
### Enhancements
-* None.
+* Fix a memory leak when circularly linked objects are added to a Realm.
### Bugfixes
diff --git a/Realm/RLMObjectStore.mm b/Realm/RLMObjectStore.mm
index 63d620d0e9..45c5da874b 100644
--- a/Realm/RLMObjectStore.mm
+++ b/Realm/RLMObjectStore.mm
@@ -25,7 +25,7 @@
#import "RLMQueryUtil.hpp"
#import "RLMUtil.hpp"
-#import <objc/runtime.h>
+#import <objc/message.h>
static void RLMVerifyAndAlignColumns(RLMObjectSchema *tableSchema, RLMObjectSchema *objectSchema) {
NSMutableArray *properties = [NSMutableArray arrayWithCapacity:objectSchema.properties.count];
@@ -309,6 +309,15 @@ void RLMAddObjectToRealm(RLMObject *object, RLMRealm *realm, RLMSetFlag options)
if (created || !prop.isPrimary) {
RLMDynamicSet(object, prop, value, options | (prop.isPrimary ? RLMSetFlagEnforceUnique : 0));
}
+
+ // set the ivars for object and array properties to nil as otherwise the
+ // accessors retain objects that are no longer accessible via the properties
+ // this is mainly an issue when the object graph being added has cycles,
+ // as it's not obvious that the user has to set the *ivars* to nil to
+ // avoid leaking memory
+ if (prop.type == RLMPropertyTypeObject || prop.type == RLMPropertyTypeArray) {
+ ((void(*)(id, SEL, id))objc_msgSend)(object, prop.setterSel, nil);
+ }
}
// switch class to use table backed accessor
diff --git a/Realm/Tests/LinkTests.m b/Realm/Tests/LinkTests.m
index 9e29e60524..8c664c56eb 100644
--- a/Realm/Tests/LinkTests.m
+++ b/Realm/Tests/LinkTests.m
@@ -169,10 +169,29 @@ - (void)testBidirectionalRelationship {
XCTAssertEqualObjects(@"b", [results[1] data]);
}
-// FIXME - disabled until we fix commit log issue which break transacions when leaking realm objects
-/*
-- (void)testCircularLinks
- {
+- (void)testAddingCircularReferenceDoesNotLeakSourceObjects {
+ CircleObject __weak *weakObj0, __weak *weakObj1;
+ @autoreleasepool {
+ CircleObject *obj0 = [[CircleObject alloc] initWithObject:@[@"a", NSNull.null]];
+ CircleObject *obj1 = [[CircleObject alloc] initWithObject:@[@"b", obj0]];
+ obj0.next = obj1;
+
+ weakObj0 = obj0;
+ weakObj1 = obj1;
+
+ RLMRealm *realm = [RLMRealm defaultRealm];
+ [realm beginWriteTransaction];
+ [realm addObject:obj0];
+ obj0.next = nil;
+ obj1.next = nil;
+ [realm commitWriteTransaction];
+ }
+
+ XCTAssertNil(weakObj0);
+ XCTAssertNil(weakObj1);
+}
+
+- (void)testCircularLinks {
RLMRealm *realm = [self realmWithTestPath];
CircleObject *obj = [[CircleObject alloc] init];
@@ -184,10 +203,10 @@ - (void)testCircularLinks
obj.next.data = @"b";
[realm commitWriteTransaction];
- CircleObject *obj1 = [realm allObjects:CircleObject.className].firstObject;
+ CircleObject *obj1 = [CircleObject allObjectsInRealm:realm].firstObject;
XCTAssertEqualObjects(obj1.data, @"b", @"data should be 'b'");
XCTAssertEqualObjects(obj1.data, obj.next.data, @"objects should be equal");
-}*/
+ }
@end
| 1
|
2ae973a0b568b5de149bf20b7db2495a8d02494f
|
https://github.com/thorsten/phpMyFAQ/commit/2ae973a0b568b5de149bf20b7db2495a8d02494f
|
fix: added missing support for options in ext/filter functions
This commit is needed for a fix for #1750
|
diff --git a/phpmyfaq/src/phpMyFAQ/Filter.php b/phpmyfaq/src/phpMyFAQ/Filter.php
index 8dbdcbeb8b..b21bb5f47b 100644
--- a/phpmyfaq/src/phpMyFAQ/Filter.php
+++ b/phpmyfaq/src/phpMyFAQ/Filter.php
@@ -36,7 +36,7 @@ class Filter
*/
public static function filterInput($type, $variableName, $filter, $default = null)
{
- $return = filter_input($type, $variableName, $filter);
+ $return = filter_input($type, $variableName, $filter, $default);
return (is_null($return) || $return === false) ? $default : $return;
}
@@ -65,7 +65,7 @@ public static function filterInputArray($type, array $definition)
*/
public static function filterVar($variable, $filter, $default = null)
{
- $return = filter_var($variable, $filter);
+ $return = filter_var($variable, $filter, $default);
return ($return === false) ? $default : $return;
}
| 0
|
37c2ceb737cb40377346c63a05f407da1c119ba0
|
https://github.com/apache/thrift/commit/37c2ceb737cb40377346c63a05f407da1c119ba0
|
THRIFT-5322: Guard against large string/binary lengths in Go
Client: go
In TBinaryProtocol.ReadString, TBinaryProtocol.ReadBinary,
TCompactProtocol.ReadString, and TCompactProtocol.ReadBinary, use
safeReadBytes to prevent from large allocation on malformed sizes.
$ go test -bench=SafeReadBytes -benchmem
BenchmarkSafeReadBytes/normal-12 625057 1789 ns/op 2176 B/op 5 allocs/op
BenchmarkSafeReadBytes/max-askedSize-12 545271 2236 ns/op 14464 B/op 7 allocs/op
PASS
|
diff --git a/lib/go/thrift/binary_protocol.go b/lib/go/thrift/binary_protocol.go
index c87d23a1bb1..58956f67320 100644
--- a/lib/go/thrift/binary_protocol.go
+++ b/lib/go/thrift/binary_protocol.go
@@ -432,6 +432,15 @@ func (p *TBinaryProtocol) ReadString(ctx context.Context) (value string, err err
err = invalidDataLength
return
}
+ if size == 0 {
+ return "", nil
+ }
+ if size < int32(len(p.buffer)) {
+ // Avoid allocation on small reads
+ buf := p.buffer[:size]
+ read, e := io.ReadFull(p.trans, buf)
+ return string(buf[:read]), NewTProtocolException(e)
+ }
return p.readStringBody(size)
}
@@ -445,9 +454,7 @@ func (p *TBinaryProtocol) ReadBinary(ctx context.Context) ([]byte, error) {
return nil, invalidDataLength
}
- isize := int(size)
- buf := make([]byte, isize)
- _, err := io.ReadFull(p.trans, buf)
+ buf, err := safeReadBytes(size, p.trans)
return buf, NewTProtocolException(err)
}
@@ -479,38 +486,21 @@ func (p *TBinaryProtocol) readAll(ctx context.Context, buf []byte) (err error) {
return NewTProtocolException(err)
}
-const readLimit = 32768
-
func (p *TBinaryProtocol) readStringBody(size int32) (value string, err error) {
- if size < 0 {
- return "", nil
- }
-
- var (
- buf bytes.Buffer
- e error
- b []byte
- )
+ buf, err := safeReadBytes(size, p.trans)
+ return string(buf), NewTProtocolException(err)
+}
- switch {
- case int(size) <= len(p.buffer):
- b = p.buffer[:size] // avoids allocation for small reads
- case int(size) < readLimit:
- b = make([]byte, size)
- default:
- b = make([]byte, readLimit)
+// This function is shared between TBinaryProtocol and TCompactProtocol.
+//
+// It tries to read size bytes from trans, in a way that prevents large
+// allocations when size is insanely large (mostly caused by malformed message).
+func safeReadBytes(size int32, trans io.Reader) ([]byte, error) {
+ if size < 0 {
+ return nil, nil
}
- for size > 0 {
- _, e = io.ReadFull(p.trans, b)
- buf.Write(b)
- if e != nil {
- break
- }
- size -= readLimit
- if size < readLimit && size > 0 {
- b = b[:size]
- }
- }
- return buf.String(), NewTProtocolException(e)
+ buf := new(bytes.Buffer)
+ _, err := io.CopyN(buf, trans, int64(size))
+ return buf.Bytes(), err
}
diff --git a/lib/go/thrift/binary_protocol_test.go b/lib/go/thrift/binary_protocol_test.go
index 0462cc79dee..88bfd26b7ea 100644
--- a/lib/go/thrift/binary_protocol_test.go
+++ b/lib/go/thrift/binary_protocol_test.go
@@ -20,9 +20,162 @@
package thrift
import (
+ "bytes"
+ "math"
+ "strings"
"testing"
)
func TestReadWriteBinaryProtocol(t *testing.T) {
ReadWriteProtocolTest(t, NewTBinaryProtocolFactoryDefault())
}
+
+const (
+ safeReadBytesSource = `
+Lorem ipsum dolor sit amet, consectetur adipiscing elit. Integer sit amet
+tincidunt nibh. Phasellus vel convallis libero, sit amet posuere quam. Nullam
+blandit velit at nibh fringilla, sed egestas erat dapibus. Sed hendrerit
+tincidunt accumsan. Curabitur consectetur bibendum dui nec hendrerit. Fusce quis
+turpis nec magna efficitur volutpat a ut nibh. Vestibulum odio risus, tristique
+a nisi et, congue mattis mi. Vivamus a nunc justo. Mauris molestie sagittis
+magna, hendrerit auctor lectus egestas non. Phasellus pretium, odio sit amet
+bibendum feugiat, velit nunc luctus erat, ac bibendum mi dui molestie nulla.
+Nullam fermentum magna eu elit vehicula tincidunt. Etiam ornare laoreet
+dignissim. Ut sed nunc ac neque vulputate fermentum. Morbi volutpat dapibus
+magna, at porttitor quam facilisis a. Donec eget fermentum risus. Aliquam erat
+volutpat.
+
+Phasellus molestie id ante vel iaculis. Fusce eget quam nec quam viverra laoreet
+vitae a dui. Mauris blandit blandit dui, iaculis interdum diam mollis at. Morbi
+vel sem et.
+`
+ safeReadBytesSourceLen = len(safeReadBytesSource)
+)
+
+func TestSafeReadBytes(t *testing.T) {
+ srcData := []byte(safeReadBytesSource)
+
+ for _, c := range []struct {
+ label string
+ askedSize int32
+ dataSize int
+ }{
+ {
+ label: "normal",
+ askedSize: 100,
+ dataSize: 100,
+ },
+ {
+ label: "max-askedSize",
+ askedSize: math.MaxInt32,
+ dataSize: safeReadBytesSourceLen,
+ },
+ } {
+ t.Run(c.label, func(t *testing.T) {
+ data := bytes.NewReader(srcData[:c.dataSize])
+ buf, err := safeReadBytes(c.askedSize, data)
+ if len(buf) != c.dataSize {
+ t.Errorf(
+ "Expected to read %d bytes, got %d",
+ c.dataSize,
+ len(buf),
+ )
+ }
+ if !strings.HasPrefix(safeReadBytesSource, string(buf)) {
+ t.Errorf("Unexpected read data: %q", buf)
+ }
+ if int32(c.dataSize) < c.askedSize {
+ // We expect error in this case
+ if err == nil {
+ t.Errorf(
+ "Expected error when dataSize %d < askedSize %d, got nil",
+ c.dataSize,
+ c.askedSize,
+ )
+ }
+ } else {
+ // We expect no error in this case
+ if err != nil {
+ t.Errorf(
+ "Expected no error when dataSize %d >= askedSize %d, got: %v",
+ c.dataSize,
+ c.askedSize,
+ err,
+ )
+ }
+ }
+ })
+ }
+}
+
+func generateSafeReadBytesBenchmark(askedSize int32, dataSize int) func(b *testing.B) {
+ return func(b *testing.B) {
+ data := make([]byte, dataSize)
+ b.ResetTimer()
+ for i := 0; i < b.N; i++ {
+ safeReadBytes(askedSize, bytes.NewReader(data))
+ }
+ }
+}
+
+func TestSafeReadBytesAlloc(t *testing.T) {
+ if testing.Short() {
+ // NOTE: Since this test runs a benchmark test, it takes at
+ // least 1 second.
+ //
+ // In general we try to avoid unit tests taking that long to run,
+ // but it's to verify a security issue so we made an exception
+ // here:
+ // https://issues.apache.org/jira/browse/THRIFT-5322
+ t.Skip("skipping test in short mode.")
+ }
+
+ const (
+ askedSize = int32(math.MaxInt32)
+ dataSize = 4096
+ )
+
+ // The purpose of this test is that in the case a string header says
+ // that it has a string askedSize bytes long, the implementation should
+ // not just allocate askedSize bytes upfront. So when there're actually
+ // not enough data to be read (dataSize), the actual allocated bytes
+ // should be somewhere between dataSize and askedSize.
+ //
+ // Different approachs could have different memory overheads, so this
+ // target is arbitrary in nature. But when dataSize is small enough
+ // compare to askedSize, half the askedSize is a good and safe target.
+ const target = int64(askedSize) / 2
+
+ bm := testing.Benchmark(generateSafeReadBytesBenchmark(askedSize, dataSize))
+ actual := bm.AllocedBytesPerOp()
+ if actual > target {
+ t.Errorf(
+ "Expected allocated bytes per op to be <= %d, got %d",
+ target,
+ actual,
+ )
+ } else {
+ t.Logf("Allocated bytes: %d B/op", actual)
+ }
+}
+
+func BenchmarkSafeReadBytes(b *testing.B) {
+ for _, c := range []struct {
+ label string
+ askedSize int32
+ dataSize int
+ }{
+ {
+ label: "normal",
+ askedSize: 100,
+ dataSize: 100,
+ },
+ {
+ label: "max-askedSize",
+ askedSize: math.MaxInt32,
+ dataSize: 4096,
+ },
+ } {
+ b.Run(c.label, generateSafeReadBytesBenchmark(c.askedSize, c.dataSize))
+ }
+}
diff --git a/lib/go/thrift/compact_protocol.go b/lib/go/thrift/compact_protocol.go
index a0161959c8c..424906d616b 100644
--- a/lib/go/thrift/compact_protocol.go
+++ b/lib/go/thrift/compact_protocol.go
@@ -579,17 +579,17 @@ func (p *TCompactProtocol) ReadString(ctx context.Context) (value string, err er
if length < 0 {
return "", invalidDataLength
}
-
if length == 0 {
return "", nil
}
- var buf []byte
- if length <= int32(len(p.buffer)) {
- buf = p.buffer[0:length]
- } else {
- buf = make([]byte, length)
+ if length < int32(len(p.buffer)) {
+ // Avoid allocation on small reads
+ buf := p.buffer[:length]
+ read, e := io.ReadFull(p.trans, buf)
+ return string(buf[:read]), NewTProtocolException(e)
}
- _, e = io.ReadFull(p.trans, buf)
+
+ buf, e := safeReadBytes(length, p.trans)
return string(buf), NewTProtocolException(e)
}
@@ -606,8 +606,7 @@ func (p *TCompactProtocol) ReadBinary(ctx context.Context) (value []byte, err er
return nil, invalidDataLength
}
- buf := make([]byte, length)
- _, e = io.ReadFull(p.trans, buf)
+ buf, e := safeReadBytes(length, p.trans)
return buf, NewTProtocolException(e)
}
| 0
|
da5916311fb9bce40979d4ceee3095be19d3a821
|
https://github.com/seccomp/libseccomp-golang/commit/da5916311fb9bce40979d4ceee3095be19d3a821
|
golang: Fix unit test failures on 32-bit systems
Add the setreuid32 syscall to the test filter as well as setreuid.
On most 64-bit systems the syscall does not exist, but this should
be handled by libseccomp, and actually slightly increases test
coverage.
Signed-off-by: Matthew Heon <[email protected]>
|
diff --git a/seccomp_test.go b/seccomp_test.go
index 92e9eba..52174a0 100644
--- a/seccomp_test.go
+++ b/seccomp_test.go
@@ -465,6 +465,11 @@ func TestRuleAddAndLoad(t *testing.T) {
t.Errorf("Error getting syscall number of setreuid: %s", err)
}
+ call3, err := GetSyscallFromName("setreuid32")
+ if err != nil {
+ t.Errorf("Error getting syscall number of setreuid32: %s", err)
+ }
+
uid := syscall.Getuid()
euid := syscall.Geteuid()
@@ -490,6 +495,11 @@ func TestRuleAddAndLoad(t *testing.T) {
t.Errorf("Error adding conditional rule: %s", err)
}
+ err = filter1.AddRuleConditional(call3, ActErrno.SetReturnCode(0x3), conditions)
+ if err != nil {
+ t.Errorf("Error adding second conditional rule: %s", err)
+ }
+
err = filter1.Load()
if err != nil {
t.Errorf("Error loading filter: %s", err)
@@ -503,7 +513,9 @@ func TestRuleAddAndLoad(t *testing.T) {
// Try making a Geteuid syscall that should normally succeed
err = syscall.Setreuid(uid, euid)
- if err != syscall.Errno(2) {
+ if err == nil {
t.Errorf("Syscall should have returned error code!")
+ } else if err != syscall.Errno(2) && err != syscall.Errno(3) {
+ t.Errorf("Syscall returned incorrect error code - likely not blocked by Seccomp!")
}
}
| 0
|
470aaf23f768264e117461af215e5ee429ae1d67
|
https://github.com/GNOME/nautilus/commit/470aaf23f768264e117461af215e5ee429ae1d67
|
file-operations: Set "skipped" flag on error
During a move operation the "skipped" flag was not being set when there
was an error deleting the source directory after copying the source
directory to the new location if "skip-all-error" was selected during a
previous user interaction in the same operation.
|
diff --git a/src/nautilus-file-operations.c b/src/nautilus-file-operations.c
index 43ed339415..b5af920f4f 100644
--- a/src/nautilus-file-operations.c
+++ b/src/nautilus-file-operations.c
@@ -5011,6 +5011,7 @@ copy_move_directory (CopyMoveJob *copy_job,
if (job->skip_all_error)
{
+ local_skipped_file = TRUE;
goto skip;
}
basename = get_basename (src);
| 0
|
bc919205bf774f6af3fa7154506c46039af5a69b
|
https://github.com/GNOME/nautilus/commit/bc919205bf774f6af3fa7154506c46039af5a69b
|
release: prepare for 3.23.90
|
diff --git a/NEWS b/NEWS
index 70dc2abcaa..d9ef21ea72 100644
--- a/NEWS
+++ b/NEWS
@@ -1,3 +1,26 @@
+Major changes in 3.23.90:
+* Add <ctrl> Return as shortcut to open selected folder in new window (Felipe Borges)
+* <ctrl> N now opens the window in the same location as the current view (Felibe Borges)
+* Fixes on managing menus with keyboard (djb)
+* Remove unused <ctrl> B shortcut (Jeremy Bicha)
+* Use a better empty state for trash (Mohammed Sadiq)
+* Fix floating bar hide on hover when using tabs (Ernestas Kulik)
+* Syncronize gtk+ and Nautilus setting for sorting the folder first (Felipe Borges)
+* Select entire names for folder when renaming (Razvan Chitu)
+* Support to open folders withouth permission using polkit and the admin backend (Carlos Soriano)
+* Fix trash operations progress report (Carlos Soriano)
+* Improve performance setting metadata only when necesary (Carlos Soriano)
+* Fix progress reporting when copying (rpm-build)
+* Prevent toolbar menu dissapearing when "Hidden files" menu item is toggled (Neil Herald)
+* Update app icon (Jakub Steiner, Lapo Calamandrei)
+* Fix icon scale computation when changing DPI (Lionel Landwerlin)
+* Add <ctrl> M as alternate shortcut for renaming for those laptops withouth "f" keys (Cristian Nancu)
+* Fix crash when pressing enter on search (Alexandru Pandelea)
+* Fix failed build with tracker disabled (Ernestas Kulik)
+* Ask the user for using desktop files from unknown sources (Carlos Soriano)
+* Improve the operations button animation in order to not need to show the operations popover (Carlos Soriano)
+* Add an experimental icon view based on flow box with extra niceties under a gsetting preference (Carlos Soriano)
+
Major changes in 3.22.1:
* Multiple batch renaming fixes (Alex Pandelea, Carlos Soriano)
* Multiple compression integration fixes (Razvan Chitu, Carlos Soriano)
diff --git a/configure.ac b/configure.ac
index 2f2289a882..77464b3658 100644
--- a/configure.ac
+++ b/configure.ac
@@ -19,7 +19,7 @@ dnl Interface break is not allowed.
m4_define(nautilus_extension_current, 5)
m4_define(nautilus_extension_revision, 0)
-AC_INIT([nautilus],[3.22.1],[http://bugzilla.gnome.org/enter_bug.cgi?product=nautilus])
+AC_INIT([nautilus],[3.23.90],[http://bugzilla.gnome.org/enter_bug.cgi?product=nautilus])
dnl ===========================================================================
| 1
|
717df38fd8509bf883b70d680c9b1b3cf36732ee
|
https://github.com/GNOME/evince/commit/717df38fd8509bf883b70d680c9b1b3cf36732ee
|
comics: Remove support for tar and tar-like commands
When handling tar files, or using a command with tar-compatible syntax,
to open comic-book archives, both the archive name (the name of the
comics file) and the filename (the name of a page within the archive)
are quoted to not be interpreted by the shell.
But the filename is completely with the attacker's control and can start
with "--" which leads to tar interpreting it as a command line flag.
This can be exploited by creating a CBT file (a tar archive with the
.cbt suffix) with an embedded file named something like this:
"--checkpoint-action=exec=bash -c 'touch ~/hacked;'.jpg"
CBT files are infinitely rare (CBZ is usually used for DRM-free
commercial releases, CBR for those from more dubious provenance), so
removing support is the easiest way to avoid the bug triggering. All
this code was rewritten in the development release for GNOME 3.26 to not
shell out to any command, closing off this particular attack vector.
This also removes the ability to use libarchive's bsdtar-compatible
binary for CBZ (ZIP), CB7 (7zip), and CBR (RAR) formats. The first two
are already supported by unzip and 7zip respectively. libarchive's RAR
support is limited, so unrar is a requirement anyway.
Discovered by Felix Wilhelm from the Google Security Team.
https://bugzilla.gnome.org/show_bug.cgi?id=784630
|
diff --git a/backend/comics/comics-document.c b/backend/comics/comics-document.c
index 4c7473104..641d78563 100644
--- a/backend/comics/comics-document.c
+++ b/backend/comics/comics-document.c
@@ -56,8 +56,7 @@ typedef enum
RARLABS,
GNAUNRAR,
UNZIP,
- P7ZIP,
- TAR
+ P7ZIP
} ComicBookDecompressType;
typedef struct _ComicsDocumentClass ComicsDocumentClass;
@@ -117,9 +116,6 @@ static const ComicBookDecompressCommand command_usage_def[] = {
/* 7zip */
{NULL , "%s l -- %s" , "%s x -y %s -o%s", FALSE, OFFSET_7Z},
-
- /* tar */
- {"%s -xOf" , "%s -tf %s" , NULL , FALSE, NO_OFFSET}
};
static GSList* get_supported_image_extensions (void);
@@ -364,13 +360,6 @@ comics_check_decompress_command (gchar *mime_type,
comics_document->command_usage = GNAUNRAR;
return TRUE;
}
- comics_document->selected_command =
- g_find_program_in_path ("bsdtar");
- if (comics_document->selected_command) {
- comics_document->command_usage = TAR;
- return TRUE;
- }
-
} else if (g_content_type_is_a (mime_type, "application/x-cbz") ||
g_content_type_is_a (mime_type, "application/zip")) {
/* InfoZIP's unzip program */
@@ -396,12 +385,6 @@ comics_check_decompress_command (gchar *mime_type,
comics_document->command_usage = P7ZIP;
return TRUE;
}
- comics_document->selected_command =
- g_find_program_in_path ("bsdtar");
- if (comics_document->selected_command) {
- comics_document->command_usage = TAR;
- return TRUE;
- }
} else if (g_content_type_is_a (mime_type, "application/x-cb7") ||
g_content_type_is_a (mime_type, "application/x-7z-compressed")) {
@@ -425,27 +408,6 @@ comics_check_decompress_command (gchar *mime_type,
comics_document->command_usage = P7ZIP;
return TRUE;
}
- comics_document->selected_command =
- g_find_program_in_path ("bsdtar");
- if (comics_document->selected_command) {
- comics_document->command_usage = TAR;
- return TRUE;
- }
- } else if (g_content_type_is_a (mime_type, "application/x-cbt") ||
- g_content_type_is_a (mime_type, "application/x-tar")) {
- /* tar utility (Tape ARchive) */
- comics_document->selected_command =
- g_find_program_in_path ("tar");
- if (comics_document->selected_command) {
- comics_document->command_usage = TAR;
- return TRUE;
- }
- comics_document->selected_command =
- g_find_program_in_path ("bsdtar");
- if (comics_document->selected_command) {
- comics_document->command_usage = TAR;
- return TRUE;
- }
} else {
g_set_error (error,
EV_DOCUMENT_ERROR,
diff --git a/configure.ac b/configure.ac
index 9e9f8316e..7eb0f1f3c 100644
--- a/configure.ac
+++ b/configure.ac
@@ -795,7 +795,7 @@ AC_SUBST(TIFF_MIME_TYPES)
AC_SUBST(APPDATA_TIFF_MIME_TYPES)
AM_SUBST_NOTMAKE(APPDATA_TIFF_MIME_TYPES)
if test "x$enable_comics" = "xyes"; then
- COMICS_MIME_TYPES="application/x-cbr;application/x-cbz;application/x-cb7;application/x-cbt;application/x-ext-cbr;application/x-ext-cbz;application/vnd.comicbook+zip;application/x-ext-cb7;application/x-ext-cbt"
+ COMICS_MIME_TYPES="application/x-cbr;application/x-cbz;application/x-cb7;application/x-ext-cbr;application/x-ext-cbz;application/vnd.comicbook+zip;application/x-ext-cb7;"
APPDATA_COMICS_MIME_TYPES=$(echo "<mimetype>$COMICS_MIME_TYPES</mimetype>" | sed -e 's/;/<\/mimetype>\n <mimetype>/g')
if test -z "$EVINCE_MIME_TYPES"; then
EVINCE_MIME_TYPES="${COMICS_MIME_TYPES}"
| 1
|
7c2499fc060ab574611ec3e666ddbaac0de7f69d
|
https://github.com/cesanta/mongoose/commit/7c2499fc060ab574611ec3e666ddbaac0de7f69d
|
-D -> -v
|
diff --git a/examples/http-server/main.c b/examples/http-server/main.c
index e4956785f..80f114fcd 100644
--- a/examples/http-server/main.c
+++ b/examples/http-server/main.c
@@ -21,11 +21,11 @@ static void usage(const char *prog) {
fprintf(stderr,
"Mongoose v.%s, built " __DATE__ " " __TIME__
"\nUsage: %s OPTIONS\n"
- " -D LEVEL - debug level, from 0 to 4, default: '%s'\n"
" -H yes|no - enable traffic hexdump, default: '%s'\n"
" -S GLOB - glob pattern for SSI files, default: '%s'\n"
" -d DIR - directory to serve, default: '%s'\n"
- " -l ADDR - listening address, default: '%s'\n",
+ " -l ADDR - listening address, default: '%s'\n"
+ " -v LEVEL - debug level, from 0 to 4, default: '%s'\n",
MG_VERSION, prog, s_debug_level, s_enable_hexdump, s_ssi_pattern,
s_root_dir, s_listening_address);
exit(EXIT_FAILURE);
@@ -40,14 +40,14 @@ int main(int argc, char *argv[]) {
for (i = 1; i < argc; i++) {
if (strcmp(argv[i], "-d") == 0) {
s_root_dir = argv[++i];
- } else if (strcmp(argv[i], "-D") == 0) {
- s_debug_level = argv[++i];
} else if (strcmp(argv[i], "-H") == 0) {
s_enable_hexdump = argv[++i];
} else if (strcmp(argv[i], "-S") == 0) {
s_ssi_pattern = argv[++i];
} else if (strcmp(argv[i], "-l") == 0) {
s_listening_address = argv[++i];
+ } else if (strcmp(argv[i], "-v") == 0) {
+ s_debug_level = argv[++i];
} else {
usage(argv[0]);
}
| 0
|
ae43073fbf38db8371ff4f8bf2a966ee3b5f7e92
|
https://github.com/jkuhnert/ognl/commit/ae43073fbf38db8371ff4f8bf2a966ee3b5f7e92
|
Merge pull request #12 from danielfernandez/cachekey
Improved performance of getter/setter method caching in OgnlRuntime
|
diff --git a/src/java/ognl/OgnlRuntime.java b/src/java/ognl/OgnlRuntime.java
index ebaef116..4ef71546 100644
--- a/src/java/ognl/OgnlRuntime.java
+++ b/src/java/ognl/OgnlRuntime.java
@@ -148,8 +148,8 @@
static final ConcurrentHashMap<Integer, Boolean> _methodAccessCache = new ConcurrentHashMap<Integer, Boolean>();
static final ConcurrentHashMap<Integer, Boolean> _methodPermCache = new ConcurrentHashMap<Integer, Boolean>();
- static final Map cacheSetMethod = new HashMap();
- static final Map cacheGetMethod = new HashMap();
+ static final ClassPropertyMethodCache cacheSetMethod = new ClassPropertyMethodCache();
+ static final ClassPropertyMethodCache cacheGetMethod = new ClassPropertyMethodCache();
static ClassCacheInspector _cacheInspector;
@@ -1922,46 +1922,22 @@ static boolean isMethodCallable(Method m)
/**
* cache get methods
*/
- public static Method getGetMethod(OgnlContext context, Class targetClass, String propertyName) throws IntrospectionException, OgnlException {
- Object cacheKey = buildCacheKey(targetClass, propertyName);
- if (cacheGetMethod.containsKey(cacheKey)) {
- return (Method) cacheGetMethod.get(cacheKey);
- } else {
- Method result = null;
- synchronized (cacheGetMethod) {
- if (!cacheGetMethod.containsKey(cacheKey)) {
- result = _getGetMethod(context, targetClass, propertyName);
- cacheGetMethod.put(cacheKey, result);
- } else {
- result = (Method) cacheGetMethod.get(cacheKey);
- }
- }
- return result;
- }
- }
-
- private static Object buildCacheKey(Class targetClass, String propertyName) {
- return new CacheKey(targetClass, propertyName);
- }
-
- private static final class CacheKey {
- private final Class clazz;
- private final String propertyName;
+ public static Method getGetMethod(OgnlContext context, Class targetClass, String propertyName)
+ throws IntrospectionException, OgnlException
+ {
+ // Cache is a map in two levels, so we provide two keys (see comments in ClassPropertyMethodCache below)
+ Method method = cacheGetMethod.get(targetClass, propertyName);
+ if (method != null)
+ return method;
- public CacheKey(Class clazz, String propertyName) {
- this.clazz = clazz;
- this.propertyName = propertyName;
- }
+ // By checking key existence now and not before calling 'get', we will save a map resolution 90% of the times
+ if (cacheGetMethod.containsKey(targetClass, propertyName))
+ return null;
- public boolean equals(Object obj) {
- CacheKey cacheKey = (CacheKey) obj;
- return clazz.equals(cacheKey.clazz)
- && propertyName.equals(cacheKey.propertyName);
- }
+ method = _getGetMethod(context, targetClass, propertyName); // will be null if not found - will cache it anyway
+ cacheGetMethod.put(targetClass, propertyName, method);
- public int hashCode() {
- return clazz.hashCode() * 31 + propertyName.hashCode();
- }
+ return method;
}
private static Method _getGetMethod(OgnlContext context, Class targetClass, String propertyName)
@@ -2004,22 +1980,22 @@ public static boolean hasGetMethod(OgnlContext context, Object target, Class tar
/**
* cache set methods method
*/
- public static Method getSetMethod(OgnlContext context, Class targetClass, String propertyName) throws IntrospectionException, OgnlException {
- Object cacheKey = buildCacheKey(targetClass, propertyName);
- if (cacheSetMethod.containsKey(cacheKey)) {
- return (Method) cacheSetMethod.get(cacheKey);
- } else {
- Method result = null;
- synchronized (cacheSetMethod) { //PATCHED
- if (!cacheSetMethod.containsKey(cacheKey)) {
- result = _getSetMethod(context, targetClass, propertyName);
- cacheSetMethod.put(cacheKey, result);
- } else {
- result = (Method) cacheSetMethod.get(cacheKey);
- }
- }
- return result;
- }
+ public static Method getSetMethod(OgnlContext context, Class targetClass, String propertyName)
+ throws IntrospectionException, OgnlException
+ {
+ // Cache is a map in two levels, so we provide two keys (see comments in ClassPropertyMethodCache below)
+ Method method = cacheSetMethod.get(targetClass, propertyName);
+ if (method != null)
+ return method;
+
+ // By checking key existence now and not before calling 'get', we will save a map resolution 90% of the times
+ if (cacheSetMethod.containsKey(targetClass, propertyName))
+ return null;
+
+ method = _getSetMethod(context, targetClass, propertyName); // will be null if not found - will cache it anyway
+ cacheSetMethod.put(targetClass, propertyName, method);
+
+ return method;
}
private static Method _getSetMethod(OgnlContext context, Class targetClass, String propertyName)
@@ -2976,4 +2952,84 @@ public static String getChildSource(OgnlContext context, Object target, Node chi
return source;
}
+
+
+
+ /*
+ * The idea behind this class is to provide a very fast way to cache getter/setter methods indexed by their class
+ * and property name.
+ *
+ * Instead of creating any kind of complex key object (or a String key by appending class name and property), this
+ * class directly uses the Class clazz and the String propertyName as keys of two levels of ConcurrentHashMaps,
+ * so that it takes advantage of the fact that these two classes are immutable and that their respective hashCode()
+ * and equals() methods are extremely fast and optimized. These two aspects should improve Map access performance.
+ *
+ * Also, using these structure instead of any other kind of key on a single-level map should save a lot of memory
+ * given no specialized cache objects (be them of a specific CacheKey class or mere Strings) ever have to be created
+ * for simply accessing the cache in search for a getter/setter method.
+ *
+ */
+ private static final class ClassPropertyMethodCache {
+
+ // ConcurrentHashMaps do not allow null keys or values, so we will use one of this class's own methods as
+ // a replacement for signaling when the true cached value is 'null'
+ private static final Method NULL_REPLACEMENT;
+
+ private final ConcurrentHashMap<Class<?>,ConcurrentHashMap<String,Method>> cache =
+ new ConcurrentHashMap<Class<?>,ConcurrentHashMap<String,Method>>();
+
+ static
+ {
+ try
+ {
+ NULL_REPLACEMENT =
+ ClassPropertyMethodCache.class.getDeclaredMethod("get", new Class[] {Class.class,String.class});
+ } catch (NoSuchMethodException e)
+ {
+ throw new RuntimeException(e); // Will never happen, it's our own method, we know it exists
+ }
+ }
+
+ ClassPropertyMethodCache()
+ {
+ super();
+ }
+
+ Method get(Class clazz, String propertyName)
+ {
+ ConcurrentHashMap<String,Method> methodsByPropertyName = this.cache.get(clazz);
+ if (methodsByPropertyName == null)
+ {
+ methodsByPropertyName = new ConcurrentHashMap<String, Method>();
+ this.cache.put(clazz, methodsByPropertyName);
+ }
+ Method method = methodsByPropertyName.get(propertyName);
+ if (method == NULL_REPLACEMENT)
+ return null;
+ return method;
+ }
+
+ void put(Class clazz, String propertyName, Method method)
+ {
+ ConcurrentHashMap<String,Method> methodsByPropertyName = this.cache.get(clazz);
+ if (methodsByPropertyName == null)
+ {
+ methodsByPropertyName = new ConcurrentHashMap<String, Method>();
+ this.cache.put(clazz, methodsByPropertyName);
+ }
+ methodsByPropertyName.put(propertyName, (method == null? NULL_REPLACEMENT : method));
+ }
+
+ boolean containsKey(Class clazz, String propertyName)
+ {
+ ConcurrentHashMap<String,Method> methodsByPropertyName = this.cache.get(clazz);
+ if (methodsByPropertyName == null)
+ return false;
+
+ return methodsByPropertyName.containsKey(propertyName);
+ }
+
+ }
+
+
}
| 1
|
dc8f256848b4863dc633cfab0929927ef06d549d
|
https://github.com/zxing/zxing/commit/dc8f256848b4863dc633cfab0929927ef06d549d
|
[iphone] Memory leak fixed. Widget does not crash anymore after a few seconds. No more memory warning either
git-svn-id: https://zxing.googlecode.com/svn/trunk@1396 59b500cc-1b3d-0410-9834-0bbf25fbcc57
|
diff --git a/iphone/ScanTest/Classes/RootViewController.m b/iphone/ScanTest/Classes/RootViewController.m
index a9ae9a2ef2..cec4693566 100644
--- a/iphone/ScanTest/Classes/RootViewController.m
+++ b/iphone/ScanTest/Classes/RootViewController.m
@@ -18,16 +18,20 @@ @implementation RootViewController
- (void)viewDidLoad {
[super viewDidLoad];
[self setTitle:@"ZXing"];
- scanController = [ZXingWidgetController alloc];
+
+ scanController = [[ZXingWidgetController alloc] initWithDelegate:self];
[scanController setOneDMode:NO];
[scanController setShowCancel:YES];
scanController = [scanController initWithDelegate:self];
NSBundle *mainBundle = [NSBundle mainBundle];
[scanController setSoundToPlay:[[NSURL fileURLWithPath:[mainBundle pathForResource:@"beep-beep" ofType:@"aiff"] isDirectory:NO] retain]];
+
}
- (IBAction)scanPressed:(id)sender {
- [self presentModalViewController:scanController animated:YES];
+ //UIImagePickerController *picker = [[UIImagePickerController alloc] init];
+ [self presentModalViewController:scanController
+ animated:YES];
// [self.navigationController pushViewController:scanController animated:true];
}
@@ -64,7 +68,7 @@ - (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interface
- (void)scanResult:(NSString *)result {
//[self.resultsView setText:result];
- [self dismissModalViewControllerAnimated:NO];
+ [self dismissModalViewControllerAnimated:YES];
self.resultsToDisplay = result;
}
@@ -78,7 +82,7 @@ - (void)viewWillAppear:(BOOL)animated {
}
- (void)cancelled {
- [self dismissModalViewControllerAnimated:true];
+ [self dismissModalViewControllerAnimated:YES];
}
#pragma mark -
diff --git a/iphone/ScanTest/ScanTest.xcodeproj/project.pbxproj b/iphone/ScanTest/ScanTest.xcodeproj/project.pbxproj
index 6081c748ac..2b043303de 100755
--- a/iphone/ScanTest/ScanTest.xcodeproj/project.pbxproj
+++ b/iphone/ScanTest/ScanTest.xcodeproj/project.pbxproj
@@ -297,6 +297,7 @@
ARCHS = "$(ARCHS_STANDARD_32_BIT)";
"CODE_SIGN_IDENTITY[sdk=iphoneos*]" = "iPhone Developer";
GCC_C_LANGUAGE_STANDARD = c99;
+ GCC_VERSION = 4.2;
GCC_WARN_ABOUT_RETURN_TYPE = YES;
GCC_WARN_UNUSED_VARIABLE = YES;
HEADER_SEARCH_PATHS = "../ZXingWidget/Classes/**";
@@ -316,7 +317,7 @@
HEADER_SEARCH_PATHS = "../ZXingWidget/Classes/**";
OTHER_CFLAGS = "-DNS_BLOCK_ASSERTIONS=1";
PREBINDING = NO;
- SDKROOT = iphoneos3.1.3;
+ SDKROOT = iphonesimulator3.1.3;
};
name = Release;
};
diff --git a/iphone/ZXingWidget/Classes/Decoder.h b/iphone/ZXingWidget/Classes/Decoder.h
index 4b28141f87..be2bf57f8e 100644
--- a/iphone/ZXingWidget/Classes/Decoder.h
+++ b/iphone/ZXingWidget/Classes/Decoder.h
@@ -32,6 +32,7 @@
size_t subsetHeight;
size_t subsetBytesPerRow;
id<DecoderDelegate> delegate;
+ NSOperationQueue *operationQueue;
}
@property(nonatomic, retain) UIImage *image;
@@ -42,6 +43,7 @@
@property(assign) size_t subsetHeight;
@property(assign) size_t subsetBytesPerRow;
@property(nonatomic, assign) id<DecoderDelegate> delegate;
+@property (nonatomic, retain) NSOperationQueue *operationQueue;
- (void) decodeImage:(UIImage *)image;
- (void) decodeImage:(UIImage *)image cropRect:(CGRect)cropRect;
diff --git a/iphone/ZXingWidget/Classes/Decoder.mm b/iphone/ZXingWidget/Classes/Decoder.mm
index d5ca9cfc93..edc6336a54 100644
--- a/iphone/ZXingWidget/Classes/Decoder.mm
+++ b/iphone/ZXingWidget/Classes/Decoder.mm
@@ -42,7 +42,17 @@ @implementation Decoder
@synthesize subsetHeight;
@synthesize subsetBytesPerRow;
@synthesize delegate;
+@synthesize operationQueue;
+
+- (id)init {
+ if (self = [super init]) {
+ NSOperationQueue *opQueue = [[NSOperationQueue alloc] init];
+ self.operationQueue = opQueue;
+ [opQueue release];
+ }
+ return self;
+}
- (void)willDecodeImage {
if ([self.delegate respondsToSelector:@selector(decoder:willDecodeImage:usingSubset:)]) {
[self.delegate decoder:self willDecodeImage:self.image usingSubset:self.subsetImage];
@@ -56,6 +66,7 @@ - (void)progressDecodingImage:(NSString *)progress {
}
- (void)didDecodeImage:(TwoDDecoderResult *)result {
+
if ([self.delegate respondsToSelector:@selector(decoder:didDecodeImage:usingSubset:withResult:)]) {
[self.delegate decoder:self didDecodeImage:self.image usingSubset:self.subsetImage withResult:result];
}
@@ -64,6 +75,7 @@ - (void)didDecodeImage:(TwoDDecoderResult *)result {
}
- (void)failedToDecodeImage:(NSString *)reason {
+
if ([self.delegate respondsToSelector:@selector(decoder:failedToDecodeImage:usingSubset:reason:)]) {
[self.delegate decoder:self failedToDecodeImage:self.image usingSubset:self.subsetImage reason:reason];
}
@@ -143,13 +155,13 @@ - (void) prepareSubset {
}
- (void)decode:(id)arg {
- NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];
+
+ NSAutoreleasePool* mainpool = [[NSAutoreleasePool alloc] init];
{
NSSet *formatReaders = [FormatReader formatReaders];
Ref<LuminanceSource> source (new GrayBytesMonochromeBitmapSource(subsetData, subsetWidth, subsetHeight, subsetBytesPerRow));
-
Ref<Binarizer> binarizer (new GlobalHistogramBinarizer(source));
Ref<BinaryBitmap> grayImage (new BinaryBitmap(binarizer));
#ifdef DEBUG
@@ -163,10 +175,11 @@ - (void)decode:(id)arg {
for (int i = 0; !decoderResult && i < 4; i++) {
#endif
for (FormatReader *reader in formatReaders) {
+ NSAutoreleasePool *secondarypool = [[NSAutoreleasePool alloc] init];
try {
#ifdef DEBUG
NSLog(@"decoding gray image");
- #endif
+ #endif
Ref<Result> result([reader decode:grayImage]);
#ifdef DEBUG
NSLog(@"gray image decoded");
@@ -198,6 +211,7 @@ - (void)decode:(id)arg {
} catch (...) {
NSLog(@"Caught unknown exception!");
}
+ [secondarypool release];
}
#ifdef TRY_ROTATIONS
@@ -226,15 +240,12 @@ - (void)decode:(id)arg {
waitUntilDone:NO];
}
}
- [pool drain];
+
+
#ifdef DEBUG
NSLog(@"finished decoding.");
#endif
-
- // if this is not the main thread, then we end it
- if (![NSThread isMainThread]) {
- [NSThread exit];
- }
+ [mainpool release];
}
- (void) decodeImage:(UIImage *)i {
@@ -249,17 +260,25 @@ - (void) decodeImage:(UIImage *)i cropRect:(CGRect)cr {
[self willDecodeImage];
[self performSelectorOnMainThread:@selector(progressDecodingImage:)
withObject:NSLocalizedString(@"Decoder MessageWhileDecoding", @"Decoding ...")
- waitUntilDone:NO];
-
- [NSThread detachNewThreadSelector:@selector(decode:)
+ waitUntilDone:NO];
+ NSInvocationOperation *op = [[NSInvocationOperation alloc] initWithTarget:self selector:@selector(decode:) object:nil];
+ [operationQueue addOperation:op];
+ [op release];
+ //[self performSelectorInBackground:@selector(decode:) withObject:nil];
+
+
+ //[self performSelector:@selector(decode:) onThread:decodingThread withObject:nil waitUntilDone:NO];
+ /*[NSThread detachNewThreadSelector:@selector(decode:)
toTarget:self
- withObject:nil];
+ withObject:nil];*/
}
- (void) dealloc {
+
[image release];
[subsetImage release];
if (subsetData) free(subsetData);
+ [operationQueue release];
[super dealloc];
}
diff --git a/iphone/ZXingWidget/Classes/ZXingWidgetController.h b/iphone/ZXingWidget/Classes/ZXingWidgetController.h
index 5a0cb0c54a..daf29b9d9c 100755
--- a/iphone/ZXingWidget/Classes/ZXingWidgetController.h
+++ b/iphone/ZXingWidget/Classes/ZXingWidgetController.h
@@ -23,15 +23,15 @@
@protocol ZXingDelegate;
@interface ZXingWidgetController : UIImagePickerController <DecoderDelegate, CancelDelegate> {
- ParsedResult *result;
- NSArray *actions;
- OverlayView *overlayView;
- SystemSoundID beepSound;
- BOOL showCancel;
- NSURL *soundToPlay;
- id<ZXingDelegate> delegate;
- BOOL wasCancelled;
- BOOL oneDMode;
+ ParsedResult *result;
+ NSArray *actions;
+ OverlayView *overlayView;
+ SystemSoundID beepSound;
+ BOOL showCancel;
+ NSURL *soundToPlay;
+ id<ZXingDelegate> delegate;
+ BOOL wasCancelled;
+ BOOL oneDMode;
}
@property (nonatomic, assign) id<ZXingDelegate> delegate;
@@ -48,4 +48,4 @@
@protocol ZXingDelegate
- (void)scanResult:(NSString *)result;
- (void)cancelled;
-@end
+@end
\ No newline at end of file
diff --git a/iphone/ZXingWidget/Classes/ZXingWidgetController.m b/iphone/ZXingWidget/Classes/ZXingWidgetController.m
index 1c52454fb0..173af15e73 100755
--- a/iphone/ZXingWidget/Classes/ZXingWidgetController.m
+++ b/iphone/ZXingWidget/Classes/ZXingWidgetController.m
@@ -33,192 +33,199 @@ @implementation ZXingWidgetController
@synthesize result, actions, showCancel, delegate, soundToPlay, oneDMode;
- (id)initWithDelegate:(id<ZXingDelegate>)scanDelegate {
- if (self = [super init]) {
- [self setDelegate:scanDelegate];
- beepSound = -1;
- self.wantsFullScreenLayout = YES;
- self.sourceType = UIImagePickerControllerSourceTypeCamera;
- float zoomFactor = CAMERA_SCALAR;
- if ([self fixedFocus]) {
- zoomFactor *= 2.0;
- }
- self.cameraViewTransform = CGAffineTransformScale(
- self.cameraViewTransform, zoomFactor, zoomFactor);
- overlayView = [OverlayView alloc];
- [overlayView setOneDMode:oneDMode];
- overlayView = [overlayView initWithCancelEnabled:showCancel frame:[UIScreen mainScreen].bounds];
- [overlayView setDelegate:self];
- self.sourceType = UIImagePickerControllerSourceTypeCamera;
- self.showsCameraControls = NO;
- self.cameraOverlayView = overlayView;
- self.allowsEditing = NO; // [[NSUserDefaults standardUserDefaults] boolForKey:@"allowEditing"];
- }
-
- return self;
+ if (self = [super init]) {
+ [self setDelegate:scanDelegate];
+ beepSound = -1;
+ self.wantsFullScreenLayout = YES;
+ if ([UIImagePickerController isSourceTypeAvailable:UIImagePickerControllerSourceTypeCamera])
+ self.sourceType = UIImagePickerControllerSourceTypeCamera;
+ float zoomFactor = CAMERA_SCALAR;
+ if ([self fixedFocus]) {
+ zoomFactor *= 2.0;
+ }
+ if ([UIImagePickerController isSourceTypeAvailable:UIImagePickerControllerSourceTypeCamera])
+ self.cameraViewTransform = CGAffineTransformScale(
+ self.cameraViewTransform, zoomFactor, zoomFactor);
+ overlayView = [OverlayView alloc];
+ [overlayView setOneDMode:oneDMode];
+ overlayView = [overlayView initWithCancelEnabled:showCancel frame:[UIScreen mainScreen].bounds];
+ [overlayView setDelegate:self];
+ if ([UIImagePickerController isSourceTypeAvailable:UIImagePickerControllerSourceTypeCamera])
+ {
+ self.showsCameraControls = NO;
+ self.cameraOverlayView = overlayView;
+ self.allowsEditing = NO; // [[NSUserDefaults standardUserDefaults] boolForKey:@"allowEditing"];
+ }
+ }
+
+ return self;
}
- (void)dealloc {
- if (beepSound != -1) {
- AudioServicesDisposeSystemSoundID(beepSound);
- }
- [overlayView dealloc];
- [super dealloc];
+ if (beepSound != -1) {
+ AudioServicesDisposeSystemSoundID(beepSound);
+ }
+ [overlayView dealloc];
+ [super dealloc];
}
- (void)cancelled {
- NSLog(@"cancelled called in ZXingWidgetController");
- wasCancelled = true;
- if (delegate != nil) {
- [delegate cancelled];
- }
+ NSLog(@"cancelled called in ZXingWidgetController");
+ wasCancelled = true;
+ if (delegate != nil) {
+ [delegate cancelled];
+ }
}
- (NSString *)getPlatform {
- size_t size;
- sysctlbyname("hw.machine", NULL, &size, NULL, 0);
- char *machine = malloc(size);
- sysctlbyname("hw.machine", machine, &size, NULL, 0);
- NSString *platform = [NSString stringWithCString:machine encoding:NSASCIIStringEncoding];
- free(machine);
- return platform;
+ size_t size;
+ sysctlbyname("hw.machine", NULL, &size, NULL, 0);
+ char *machine = malloc(size);
+ sysctlbyname("hw.machine", machine, &size, NULL, 0);
+ NSString *platform = [NSString stringWithCString:machine encoding:NSASCIIStringEncoding];
+ free(machine);
+ return platform;
}
- (BOOL)fixedFocus {
- NSString *platform = [self getPlatform];
- if ([platform isEqualToString:@"iPhone1,1"] ||
- [platform isEqualToString:@"iPhone1,2"]) return true;
- return false;
+ NSString *platform = [self getPlatform];
+ if ([platform isEqualToString:@"iPhone1,1"] ||
+ [platform isEqualToString:@"iPhone1,2"]) return true;
+ return false;
}
- (void)viewWillAppear:(BOOL)animated {
- [super viewWillAppear:animated];
- if ([self soundToPlay] != nil) {
- OSStatus error = AudioServicesCreateSystemSoundID((CFURLRef)[self soundToPlay], &beepSound);
- if (error != kAudioServicesNoError) {
- NSLog(@"Problem loading nearSound.caf");
- }
- }
+ [super viewWillAppear:animated];
+ if ([self soundToPlay] != nil) {
+ OSStatus error = AudioServicesCreateSystemSoundID((CFURLRef)[self soundToPlay], &beepSound);
+ if (error != kAudioServicesNoError) {
+ NSLog(@"Problem loading nearSound.caf");
+ }
+ }
}
- (void)viewDidAppear:(BOOL)animated {
- [super viewDidAppear:animated];
- [overlayView setPoints:nil];
- wasCancelled = false;
- [NSTimer scheduledTimerWithTimeInterval: FIRST_TAKE_DELAY
- target: self
- selector: @selector(takePicture:)
- userInfo: nil
- repeats: NO];
+ [super viewDidAppear:animated];
+ [overlayView setPoints:nil];
+ wasCancelled = false;
+ [NSTimer scheduledTimerWithTimeInterval: FIRST_TAKE_DELAY
+ target: self
+ selector: @selector(takePicture:)
+ userInfo: nil
+ repeats: NO];
}
- (CGImageRef)CGImageRotated90:(CGImageRef)imgRef
{
- CGFloat angleInRadians = -90 * (M_PI / 180);
- CGFloat width = CGImageGetWidth(imgRef);
- CGFloat height = CGImageGetHeight(imgRef);
-
- CGRect imgRect = CGRectMake(0, 0, width, height);
- CGAffineTransform transform = CGAffineTransformMakeRotation(angleInRadians);
- CGRect rotatedRect = CGRectApplyAffineTransform(imgRect, transform);
-
- CGColorSpaceRef colorSpace = CGColorSpaceCreateDeviceRGB();
- CGContextRef bmContext = CGBitmapContextCreate(NULL,
- rotatedRect.size.width,
- rotatedRect.size.height,
- 8,
- 0,
- colorSpace,
- kCGImageAlphaPremultipliedFirst);
- CGContextSetAllowsAntialiasing(bmContext, FALSE);
- CGContextSetInterpolationQuality(bmContext, kCGInterpolationNone);
- CGColorSpaceRelease(colorSpace);
-// CGContextTranslateCTM(bmContext,
-// +(rotatedRect.size.width/2),
-// +(rotatedRect.size.height/2));
- CGContextScaleCTM(bmContext, rotatedRect.size.width/rotatedRect.size.height, 1.0);
- CGContextTranslateCTM(bmContext, 0.0, rotatedRect.size.height);
- CGContextRotateCTM(bmContext, angleInRadians);
-// CGContextTranslateCTM(bmContext,
-// -(rotatedRect.size.width/2),
-// -(rotatedRect.size.height/2));
- CGContextDrawImage(bmContext, CGRectMake(0, 0,
- rotatedRect.size.width,
- rotatedRect.size.height),
- imgRef);
-
- CGImageRef rotatedImage = CGBitmapContextCreateImage(bmContext);
- CFRelease(bmContext);
- [(id)rotatedImage autorelease];
-
- return rotatedImage;
+ CGFloat angleInRadians = -90 * (M_PI / 180);
+ CGFloat width = CGImageGetWidth(imgRef);
+ CGFloat height = CGImageGetHeight(imgRef);
+
+ CGRect imgRect = CGRectMake(0, 0, width, height);
+ CGAffineTransform transform = CGAffineTransformMakeRotation(angleInRadians);
+ CGRect rotatedRect = CGRectApplyAffineTransform(imgRect, transform);
+
+ CGColorSpaceRef colorSpace = CGColorSpaceCreateDeviceRGB();
+ CGContextRef bmContext = CGBitmapContextCreate(NULL,
+ rotatedRect.size.width,
+ rotatedRect.size.height,
+ 8,
+ 0,
+ colorSpace,
+ kCGImageAlphaPremultipliedFirst);
+ CGContextSetAllowsAntialiasing(bmContext, FALSE);
+ CGContextSetInterpolationQuality(bmContext, kCGInterpolationNone);
+ CGColorSpaceRelease(colorSpace);
+ // CGContextTranslateCTM(bmContext,
+ // +(rotatedRect.size.width/2),
+ // +(rotatedRect.size.height/2));
+ CGContextScaleCTM(bmContext, rotatedRect.size.width/rotatedRect.size.height, 1.0);
+ CGContextTranslateCTM(bmContext, 0.0, rotatedRect.size.height);
+ CGContextRotateCTM(bmContext, angleInRadians);
+ // CGContextTranslateCTM(bmContext,
+ // -(rotatedRect.size.width/2),
+ // -(rotatedRect.size.height/2));
+ CGContextDrawImage(bmContext, CGRectMake(0, 0,
+ rotatedRect.size.width,
+ rotatedRect.size.height),
+ imgRef);
+
+ CGImageRef rotatedImage = CGBitmapContextCreateImage(bmContext);
+ CFRelease(bmContext);
+ [(id)rotatedImage autorelease];
+
+ return rotatedImage;
}
- (CGImageRef)CGImageRotated180:(CGImageRef)imgRef
{
- CGFloat angleInRadians = M_PI;
- CGFloat width = CGImageGetWidth(imgRef);
- CGFloat height = CGImageGetHeight(imgRef);
-
- CGColorSpaceRef colorSpace = CGColorSpaceCreateDeviceRGB();
- CGContextRef bmContext = CGBitmapContextCreate(NULL,
- width,
- height,
- 8,
- 0,
- colorSpace,
- kCGImageAlphaPremultipliedFirst);
- CGContextSetAllowsAntialiasing(bmContext, FALSE);
- CGContextSetInterpolationQuality(bmContext, kCGInterpolationNone);
- CGColorSpaceRelease(colorSpace);
- CGContextTranslateCTM(bmContext,
- +(width/2),
- +(height/2));
- CGContextRotateCTM(bmContext, angleInRadians);
- CGContextTranslateCTM(bmContext,
- -(width/2),
- -(height/2));
- CGContextDrawImage(bmContext, CGRectMake(0, 0, width, height), imgRef);
-
- CGImageRef rotatedImage = CGBitmapContextCreateImage(bmContext);
- CFRelease(bmContext);
- [(id)rotatedImage autorelease];
-
- return rotatedImage;
+ CGFloat angleInRadians = M_PI;
+ CGFloat width = CGImageGetWidth(imgRef);
+ CGFloat height = CGImageGetHeight(imgRef);
+
+ CGColorSpaceRef colorSpace = CGColorSpaceCreateDeviceRGB();
+ CGContextRef bmContext = CGBitmapContextCreate(NULL,
+ width,
+ height,
+ 8,
+ 0,
+ colorSpace,
+ kCGImageAlphaPremultipliedFirst);
+ CGContextSetAllowsAntialiasing(bmContext, FALSE);
+ CGContextSetInterpolationQuality(bmContext, kCGInterpolationNone);
+ CGColorSpaceRelease(colorSpace);
+ CGContextTranslateCTM(bmContext,
+ +(width/2),
+ +(height/2));
+ CGContextRotateCTM(bmContext, angleInRadians);
+ CGContextTranslateCTM(bmContext,
+ -(width/2),
+ -(height/2));
+ CGContextDrawImage(bmContext, CGRectMake(0, 0, width, height), imgRef);
+
+ CGImageRef rotatedImage = CGBitmapContextCreateImage(bmContext);
+ CFRelease(bmContext);
+ [(id)rotatedImage autorelease];
+
+ return rotatedImage;
}
- (void)takePicture:(NSTimer*)theTimer {
- CGImageRef capture = UIGetScreenImage();
- CGRect cropRect = [overlayView cropRect];
- if (oneDMode) {
- // let's just give the decoder a vertical band right above the red line
- cropRect.origin.x = cropRect.origin.x + (cropRect.size.width / 2) - (ONE_D_BAND_HEIGHT + 1);
- cropRect.size.width = ONE_D_BAND_HEIGHT;
- // do a rotate
- CGImageRef croppedImg = CGImageCreateWithImageInRect(capture, cropRect);
- CGImageRelease(capture);
- capture = [self CGImageRotated90:croppedImg];
- capture = [self CGImageRotated180:capture];
-// UIImageWriteToSavedPhotosAlbum([UIImage imageWithCGImage:capture], nil, nil, nil);
- CGImageRelease(croppedImg);
- cropRect.origin.x = 0.0;
- cropRect.origin.y = 0.0;
- cropRect.size.width = CGImageGetWidth(capture);
- cropRect.size.height = CGImageGetHeight(capture);
- }
-
- UIImage *scrn = [UIImage imageWithCGImage:CGImageCreateWithImageInRect(capture, cropRect)];
- Decoder *d = [[Decoder alloc] init];
- d.delegate = self;
- cropRect.origin.x = 0.0;
- cropRect.origin.y = 0.0;
- [d decodeImage:scrn cropRect:cropRect];
+ CGImageRef capture = UIGetScreenImage();
+ CGRect cropRect = [overlayView cropRect];
+ if (oneDMode) {
+ // let's just give the decoder a vertical band right above the red line
+ cropRect.origin.x = cropRect.origin.x + (cropRect.size.width / 2) - (ONE_D_BAND_HEIGHT + 1);
+ cropRect.size.width = ONE_D_BAND_HEIGHT;
+ // do a rotate
+ CGImageRef croppedImg = CGImageCreateWithImageInRect(capture, cropRect);
+ capture = [self CGImageRotated90:croppedImg];
+ capture = [self CGImageRotated180:capture];
+ // UIImageWriteToSavedPhotosAlbum([UIImage imageWithCGImage:capture], nil, nil, nil);
+ CGImageRelease(croppedImg);
+ cropRect.origin.x = 0.0;
+ cropRect.origin.y = 0.0;
+ cropRect.size.width = CGImageGetWidth(capture);
+ cropRect.size.height = CGImageGetHeight(capture);
+ }
+ CGImageRef newImage = CGImageCreateWithImageInRect(capture, cropRect);
+ CGImageRelease(capture);
+ //UIImage *scrn = [UIImage imageWithCGImage:newImage];
+ UIImage *scrn = [[UIImage alloc] initWithCGImage:newImage];
+ CGImageRelease(newImage);
+ Decoder *d = [[Decoder alloc] init];
+ d.delegate = self;
+ cropRect.origin.x = 0.0;
+ cropRect.origin.y = 0.0;
+ [d decodeImage:scrn cropRect:cropRect];
+ [scrn release];
}
// DecoderDelegate methods
- (void)decoder:(Decoder *)decoder willDecodeImage:(UIImage *)image usingSubset:(UIImage *)subset{
#ifdef DEBUG
- NSLog(@"DecoderViewController MessageWhileDecodingWithDimensions: Decoding image (%.0fx%.0f) ...", image.size.width, image.size.height);
+ NSLog(@"DecoderViewController MessageWhileDecodingWithDimensions: Decoding image (%.0fx%.0f) ...", image.size.width, image.size.height);
#endif
}
@@ -229,48 +236,48 @@ - (void)decoder:(Decoder *)decoder
}
- (void)presentResultForString:(NSString *)resultString {
- self.result = [ResultParser parsedResultForString:resultString];
-
- if (beepSound != -1) {
- AudioServicesPlaySystemSound(beepSound);
- }
+ self.result = [ResultParser parsedResultForString:resultString];
+
+ if (beepSound != -1) {
+ AudioServicesPlaySystemSound(beepSound);
+ }
#ifdef DEBUG
- NSLog(@"result string = %@", resultString);
- NSLog(@"result has %d actions", actions ? 0 : actions.count);
+ NSLog(@"result string = %@", resultString);
+ NSLog(@"result has %d actions", actions ? 0 : actions.count);
#endif
- // [self updateToolbar];
+ // [self updateToolbar];
}
- (void)presentResultPoints:(NSArray *)resultPoints
forImage:(UIImage *)image
usingSubset:(UIImage *)subset {
- // simply add the points to the image view
- [overlayView setPoints:resultPoints];
+ // simply add the points to the image view
+ [overlayView setPoints:resultPoints];
}
- (void)decoder:(Decoder *)decoder didDecodeImage:(UIImage *)image usingSubset:(UIImage *)subset withResult:(TwoDDecoderResult *)twoDResult {
- [self presentResultForString:[twoDResult text]];
- [self presentResultPoints:[twoDResult points] forImage:image usingSubset:subset];
- // now, in a selector, call the delegate to give this overlay time to show the points
- [self performSelector:@selector(alertDelegate:) withObject:[[twoDResult text] copy] afterDelay:1.0];
- decoder.delegate = nil;
- [decoder release];
+ [self presentResultForString:[twoDResult text]];
+ [self presentResultPoints:[twoDResult points] forImage:image usingSubset:subset];
+ // now, in a selector, call the delegate to give this overlay time to show the points
+ [self performSelector:@selector(alertDelegate:) withObject:[[twoDResult text] copy] afterDelay:1.0];
+ decoder.delegate = nil;
+ [decoder release];
}
-- (void)alertDelegate:(id)text {
- if (delegate != nil) {
- [delegate scanResult:text];
- }
+- (void)alertDelegate:(id)text {
+ if (delegate != nil) {
+ [delegate scanResult:text];
+ }
}
- (void)decoder:(Decoder *)decoder failedToDecodeImage:(UIImage *)image usingSubset:(UIImage *)subset reason:(NSString *)reason {
- decoder.delegate = nil;
- [decoder release];
- [overlayView setPoints:nil];
- if (!wasCancelled) {
- [self takePicture:nil];
- }
- //[self updateToolbar];
+ decoder.delegate = nil;
+ [decoder release];
+ [overlayView setPoints:nil];
+ if (!wasCancelled) {
+ [self takePicture:nil];
+ }
+ //[self updateToolbar];
}
@end
diff --git a/iphone/ZXingWidget/Classes/parsedResults/EmailParsedResult.m b/iphone/ZXingWidget/Classes/parsedResults/EmailParsedResult.m
index d333cbac7d..7370d367ba 100644
--- a/iphone/ZXingWidget/Classes/parsedResults/EmailParsedResult.m
+++ b/iphone/ZXingWidget/Classes/parsedResults/EmailParsedResult.m
@@ -54,6 +54,7 @@ - (NSString *)stringForDisplay {
[parts addObject:[NSString stringWithFormat:NSLocalizedString(@"EmailParsedResult Display: Body", @"%@"), self.body]];
}
return [parts componentsJoinedByString:@"\n"];
+ [parts release];
}
+ (NSString *)typeName {
diff --git a/iphone/ZXingWidget/ZXingWidget.xcodeproj/project.pbxproj b/iphone/ZXingWidget/ZXingWidget.xcodeproj/project.pbxproj
index a0e5ebcbaf..86cc47f921 100644
--- a/iphone/ZXingWidget/ZXingWidget.xcodeproj/project.pbxproj
+++ b/iphone/ZXingWidget/ZXingWidget.xcodeproj/project.pbxproj
@@ -461,22 +461,6 @@
children = (
E53458B311987396000CB77F /* CoreSrc */,
08FB77AEFE84172EC02AAC07 /* Classes */,
- 1F027FB711A7BEBF006B06DE /* TwoDDecoderResult.h */,
- 1F027FB811A7BEBF006B06DE /* TwoDDecoderResult.m */,
- 1F027FB911A7BEBF006B06DE /* ZXingWidgetController.h */,
- 1F027FBA11A7BEBF006B06DE /* ZXingWidgetController.m */,
- 1F027F9F11A7BEAF006B06DE /* Decoder.h */,
- 1F027FA011A7BEAF006B06DE /* Decoder.mm */,
- 1F027FA111A7BEAF006B06DE /* DecoderDelegate.h */,
- 1F027FA211A7BEAF006B06DE /* FormatReader.h */,
- 1F027FA311A7BEAF006B06DE /* FormatReader.mm */,
- 1F027FA411A7BEAF006B06DE /* GrayBytesMonochromeBitmapSource.cpp */,
- 1F027FA511A7BEAF006B06DE /* GrayBytesMonochromeBitmapSource.h */,
- 1F027FA611A7BEAF006B06DE /* MultiFormatReader.mm */,
- 1F027FA711A7BEAF006B06DE /* NSString+HTML.h */,
- 1F027FA811A7BEAF006B06DE /* NSString+HTML.m */,
- 1F027FA911A7BEAF006B06DE /* OverlayView.h */,
- 1F027FAA11A7BEAF006B06DE /* OverlayView.m */,
32C88DFF0371C24200C91783 /* Other Sources */,
0867D69AFE84028FC02AAC07 /* Frameworks */,
E5345D2811999F53000CB77F /* Resources */,
@@ -499,6 +483,22 @@
08FB77AEFE84172EC02AAC07 /* Classes */ = {
isa = PBXGroup;
children = (
+ 1F027FB711A7BEBF006B06DE /* TwoDDecoderResult.h */,
+ 1F027FB811A7BEBF006B06DE /* TwoDDecoderResult.m */,
+ 1F027FB911A7BEBF006B06DE /* ZXingWidgetController.h */,
+ 1F027FBA11A7BEBF006B06DE /* ZXingWidgetController.m */,
+ 1F027F9F11A7BEAF006B06DE /* Decoder.h */,
+ 1F027FA011A7BEAF006B06DE /* Decoder.mm */,
+ 1F027FA111A7BEAF006B06DE /* DecoderDelegate.h */,
+ 1F027FA211A7BEAF006B06DE /* FormatReader.h */,
+ 1F027FA311A7BEAF006B06DE /* FormatReader.mm */,
+ 1F027FA411A7BEAF006B06DE /* GrayBytesMonochromeBitmapSource.cpp */,
+ 1F027FA511A7BEAF006B06DE /* GrayBytesMonochromeBitmapSource.h */,
+ 1F027FA611A7BEAF006B06DE /* MultiFormatReader.mm */,
+ 1F027FA711A7BEAF006B06DE /* NSString+HTML.h */,
+ 1F027FA811A7BEAF006B06DE /* NSString+HTML.m */,
+ 1F027FA911A7BEAF006B06DE /* OverlayView.h */,
+ 1F027FAA11A7BEAF006B06DE /* OverlayView.m */,
E5345A00119876A5000CB77F /* Actions */,
E53459EF119876A5000CB77F /* ParsedResults */,
E53459D4119876A5000CB77F /* ResultParsers */,
@@ -1144,7 +1144,7 @@
IPHONEOS_DEPLOYMENT_TARGET = 3.1.3;
OTHER_LDFLAGS = "-ObjC";
PREBINDING = NO;
- SDKROOT = iphoneos3.1.3;
+ SDKROOT = iphoneos4.0;
};
name = Debug;
};
@@ -1158,7 +1158,7 @@
IPHONEOS_DEPLOYMENT_TARGET = 3.1.3;
OTHER_LDFLAGS = "-ObjC";
PREBINDING = NO;
- SDKROOT = iphoneos3.1.3;
+ SDKROOT = iphoneos4.0;
};
name = Release;
};
| 1
|
45bf286b70a19f45cc931875564595b33cca63ac
|
https://github.com/denkGroot/Spina/commit/45bf286b70a19f45cc931875564595b33cca63ac
|
Bump rails from 5.2.2.1 to 5.2.3
Bumps [rails](https://github.com/rails/rails) from 5.2.2.1 to 5.2.3.
- [Release notes](https://github.com/rails/rails/releases)
- [Commits](https://github.com/rails/rails/compare/v5.2.2.1...v5.2.3)
Signed-off-by: dependabot[bot] <[email protected]>
|
diff --git a/Gemfile.lock b/Gemfile.lock
index fdf95f73f..2689b99f6 100644
--- a/Gemfile.lock
+++ b/Gemfile.lock
@@ -21,43 +21,43 @@ PATH
GEM
remote: https://rubygems.org/
specs:
- actioncable (5.2.2.1)
- actionpack (= 5.2.2.1)
+ actioncable (5.2.3)
+ actionpack (= 5.2.3)
nio4r (~> 2.0)
websocket-driver (>= 0.6.1)
- actionmailer (5.2.2.1)
- actionpack (= 5.2.2.1)
- actionview (= 5.2.2.1)
- activejob (= 5.2.2.1)
+ actionmailer (5.2.3)
+ actionpack (= 5.2.3)
+ actionview (= 5.2.3)
+ activejob (= 5.2.3)
mail (~> 2.5, >= 2.5.4)
rails-dom-testing (~> 2.0)
- actionpack (5.2.2.1)
- actionview (= 5.2.2.1)
- activesupport (= 5.2.2.1)
+ actionpack (5.2.3)
+ actionview (= 5.2.3)
+ activesupport (= 5.2.3)
rack (~> 2.0)
rack-test (>= 0.6.3)
rails-dom-testing (~> 2.0)
rails-html-sanitizer (~> 1.0, >= 1.0.2)
- actionview (5.2.2.1)
- activesupport (= 5.2.2.1)
+ actionview (5.2.3)
+ activesupport (= 5.2.3)
builder (~> 3.1)
erubi (~> 1.4)
rails-dom-testing (~> 2.0)
rails-html-sanitizer (~> 1.0, >= 1.0.3)
- activejob (5.2.2.1)
- activesupport (= 5.2.2.1)
+ activejob (5.2.3)
+ activesupport (= 5.2.3)
globalid (>= 0.3.6)
- activemodel (5.2.2.1)
- activesupport (= 5.2.2.1)
- activerecord (5.2.2.1)
- activemodel (= 5.2.2.1)
- activesupport (= 5.2.2.1)
+ activemodel (5.2.3)
+ activesupport (= 5.2.3)
+ activerecord (5.2.3)
+ activemodel (= 5.2.3)
+ activesupport (= 5.2.3)
arel (>= 9.0)
- activestorage (5.2.2.1)
- actionpack (= 5.2.2.1)
- activerecord (= 5.2.2.1)
+ activestorage (5.2.3)
+ actionpack (= 5.2.3)
+ activerecord (= 5.2.3)
marcel (~> 0.3.1)
- activesupport (5.2.2.1)
+ activesupport (5.2.3)
concurrent-ruby (~> 1.0, >= 1.0.2)
i18n (>= 0.7, < 2)
minitest (~> 5.1)
@@ -180,18 +180,18 @@ GEM
rack-rewrite (1.5.1)
rack-test (1.1.0)
rack (>= 1.0, < 3)
- rails (5.2.2.1)
- actioncable (= 5.2.2.1)
- actionmailer (= 5.2.2.1)
- actionpack (= 5.2.2.1)
- actionview (= 5.2.2.1)
- activejob (= 5.2.2.1)
- activemodel (= 5.2.2.1)
- activerecord (= 5.2.2.1)
- activestorage (= 5.2.2.1)
- activesupport (= 5.2.2.1)
+ rails (5.2.3)
+ actioncable (= 5.2.3)
+ actionmailer (= 5.2.3)
+ actionpack (= 5.2.3)
+ actionview (= 5.2.3)
+ activejob (= 5.2.3)
+ activemodel (= 5.2.3)
+ activerecord (= 5.2.3)
+ activestorage (= 5.2.3)
+ activesupport (= 5.2.3)
bundler (>= 1.3.0)
- railties (= 5.2.2.1)
+ railties (= 5.2.3)
sprockets-rails (>= 2.0.0)
rails-controller-testing (1.0.4)
actionpack (>= 5.0.1.x)
@@ -202,9 +202,9 @@ GEM
nokogiri (>= 1.6)
rails-html-sanitizer (1.0.4)
loofah (~> 2.2, >= 2.2.2)
- railties (5.2.2.1)
- actionpack (= 5.2.2.1)
- activesupport (= 5.2.2.1)
+ railties (5.2.3)
+ actionpack (= 5.2.3)
+ activesupport (= 5.2.3)
method_source
rake (>= 0.8.7)
thor (>= 0.19.0, < 2.0)
| 0
|
95df22248db483fbf80acbb9333a2c2dd4658fbb
|
https://github.com/WordPress/WordPress/commit/95df22248db483fbf80acbb9333a2c2dd4658fbb
|
nonce-protect comments by users with unfiltered_html cap to prevent xsrf/xss. fixes #3973 for trunk
git-svn-id: http://svn.automattic.com/wordpress/trunk@5039 1a063a9b-81f0-0310-95a4-ce76da25c4cd
|
diff --git a/wp-comments-post.php b/wp-comments-post.php
index 26b476bc9d46..5988fd5f8ba6 100644
--- a/wp-comments-post.php
+++ b/wp-comments-post.php
@@ -25,14 +25,20 @@
// If the user is logged in
$user = wp_get_current_user();
-if ( $user->ID ) :
+if ( $user->ID ) {
$comment_author = $wpdb->escape($user->display_name);
$comment_author_email = $wpdb->escape($user->user_email);
$comment_author_url = $wpdb->escape($user->user_url);
-else :
+ if ( current_user_can('unfiltered_html') ) {
+ if ( wp_create_nonce('unfiltered-html-comment_' . $comment_post_ID) != $_POST['_wp_unfiltered_html_comment'] ) {
+ kses_remove_filters(); // start with a clean slate
+ kses_init_filters(); // set up the filters
+ }
+ }
+} else {
if ( get_option('comment_registration') )
wp_die( __('Sorry, you must be logged in to post a comment.') );
-endif;
+}
$comment_type = '';
diff --git a/wp-includes/comment-template.php b/wp-includes/comment-template.php
index ba7c0cbebfba..6ab6bc3d266a 100644
--- a/wp-includes/comment-template.php
+++ b/wp-includes/comment-template.php
@@ -271,6 +271,12 @@ function pings_open() {
return false;
}
+function wp_comment_form_unfiltered_html_nonce() {
+ global $post;
+ if ( current_user_can('unfiltered_html') )
+ wp_nonce_field('unfiltered-html-comment_' . $post->ID, '_wp_unfiltered_html_comment', false);
+}
+
function comments_template( $file = '/comments.php' ) {
global $wp_query, $withcomments, $post, $wpdb, $id, $comment, $user_login, $user_ID, $user_identity;
diff --git a/wp-includes/default-filters.php b/wp-includes/default-filters.php
index d75f80d72a74..31cac9cacb75 100644
--- a/wp-includes/default-filters.php
+++ b/wp-includes/default-filters.php
@@ -31,6 +31,8 @@
add_filter('pre_comment_author_email', 'wp_filter_kses');
add_filter('pre_comment_author_url', 'wp_filter_kses');
+add_action('comment_form', 'wp_comment_form_unfiltered_html_nonce');
+
// Default filters for these functions
add_filter('comment_author', 'wptexturize');
add_filter('comment_author', 'convert_chars');
diff --git a/wp-includes/functions.php b/wp-includes/functions.php
index e00196ea61ee..084d1f45c513 100644
--- a/wp-includes/functions.php
+++ b/wp-includes/functions.php
@@ -1000,9 +1000,11 @@ function wp_nonce_url($actionurl, $action = -1) {
return wp_specialchars(add_query_arg('_wpnonce', wp_create_nonce($action), $actionurl));
}
-function wp_nonce_field($action = -1) {
- echo '<input type="hidden" name="_wpnonce" value="' . wp_create_nonce($action) . '" />';
- wp_referer_field();
+function wp_nonce_field($action = -1, $name = "_wpnonce", $referer = true) {
+ $name = attribute_escape($name);
+ echo '<input type="hidden" name="' . $name . '" value="' . wp_create_nonce($action) . '" />';
+ if ( $referer )
+ wp_referer_field();
}
function wp_referer_field() {
| 1
|
8dca25d26c7ca2caf6138267f6f17111212c156e
|
https://github.com/the-tcpdump-group/tcpdump/commit/8dca25d26c7ca2caf6138267f6f17111212c156e
|
CVE-2017-13690/IKEv2: Fix some bounds checks.
Use a pointer of the correct type in ND_TCHECK(), or use ND_TCHECK2()
and provide the correct length.
While we're at it, remove the blank line between some checks and the
UNALIGNED_MEMCPY()s they protect.
Also, note the places where we print the entire payload.
This fixes a buffer over-read discovered by Bhargava Shastry,
SecT/TU Berlin.
Add a test using the capture file supplied by the reporter(s).
|
diff --git a/print-isakmp.c b/print-isakmp.c
index fbc6c5420..04374b0b3 100644
--- a/print-isakmp.c
+++ b/print-isakmp.c
@@ -1313,6 +1313,7 @@ ikev1_ke_print(netdissect_options *ndo, u_char tpay _U_,
UNALIGNED_MEMCPY(&e, ext, sizeof(e));
ND_PRINT((ndo," key len=%d", ntohs(e.len) - 4));
if (2 < ndo->ndo_vflag && 4 < ntohs(e.len)) {
+ /* Print the entire payload in hex */
ND_PRINT((ndo," "));
if (!rawprint(ndo, (const uint8_t *)(ext + 1), ntohs(e.len) - 4))
goto trunc;
@@ -1515,6 +1516,7 @@ ikev1_cert_print(netdissect_options *ndo, u_char tpay _U_,
ND_PRINT((ndo," len=%d", item_len - 4));
ND_PRINT((ndo," type=%s", STR_OR_ID((cert.encode), certstr)));
if (2 < ndo->ndo_vflag && 4 < item_len) {
+ /* Print the entire payload in hex */
ND_PRINT((ndo," "));
if (!rawprint(ndo, (const uint8_t *)(ext + 1), item_len - 4))
goto trunc;
@@ -1547,6 +1549,7 @@ ikev1_cr_print(netdissect_options *ndo, u_char tpay _U_,
ND_PRINT((ndo," len=%d", item_len - 4));
ND_PRINT((ndo," type=%s", STR_OR_ID((cert.encode), certstr)));
if (2 < ndo->ndo_vflag && 4 < item_len) {
+ /* Print the entire payload in hex */
ND_PRINT((ndo," "));
if (!rawprint(ndo, (const uint8_t *)(ext + 1), item_len - 4))
goto trunc;
@@ -1571,6 +1574,7 @@ ikev1_hash_print(netdissect_options *ndo, u_char tpay _U_,
UNALIGNED_MEMCPY(&e, ext, sizeof(e));
ND_PRINT((ndo," len=%d", ntohs(e.len) - 4));
if (2 < ndo->ndo_vflag && 4 < ntohs(e.len)) {
+ /* Print the entire payload in hex */
ND_PRINT((ndo," "));
if (!rawprint(ndo, (const uint8_t *)(ext + 1), ntohs(e.len) - 4))
goto trunc;
@@ -1595,6 +1599,7 @@ ikev1_sig_print(netdissect_options *ndo, u_char tpay _U_,
UNALIGNED_MEMCPY(&e, ext, sizeof(e));
ND_PRINT((ndo," len=%d", ntohs(e.len) - 4));
if (2 < ndo->ndo_vflag && 4 < ntohs(e.len)) {
+ /* Print the entire payload in hex */
ND_PRINT((ndo," "));
if (!rawprint(ndo, (const uint8_t *)(ext + 1), ntohs(e.len) - 4))
goto trunc;
@@ -1850,6 +1855,7 @@ ikev1_vid_print(netdissect_options *ndo, u_char tpay _U_,
UNALIGNED_MEMCPY(&e, ext, sizeof(e));
ND_PRINT((ndo," len=%d", ntohs(e.len) - 4));
if (2 < ndo->ndo_vflag && 4 < ntohs(e.len)) {
+ /* Print the entire payload in hex */
ND_PRINT((ndo," "));
if (!rawprint(ndo, (const uint8_t *)(ext + 1), ntohs(e.len) - 4))
goto trunc;
@@ -1884,6 +1890,7 @@ ikev2_gen_print(netdissect_options *ndo, u_char tpay,
ND_PRINT((ndo," len=%d", ntohs(e.len) - 4));
if (2 < ndo->ndo_vflag && 4 < ntohs(e.len)) {
+ /* Print the entire payload in hex */
ND_PRINT((ndo," "));
if (!rawprint(ndo, (const uint8_t *)(ext + 1), ntohs(e.len) - 4))
goto trunc;
@@ -2022,7 +2029,6 @@ ikev2_p_print(netdissect_options *ndo, u_char tpay _U_, int pcount _U_,
if (prop_length < sizeof(*ext))
goto toolong;
ND_TCHECK(*ext);
-
UNALIGNED_MEMCPY(&e, ext, sizeof(e));
/*
@@ -2109,7 +2115,6 @@ ikev2_sa_print(netdissect_options *ndo, u_char tpay,
if (sa_length < sizeof(*ext))
goto toolong;
ND_TCHECK(*ext);
-
UNALIGNED_MEMCPY(&e, ext, sizeof(e));
/*
@@ -2170,7 +2175,7 @@ ikev2_ke_print(netdissect_options *ndo, u_char tpay,
const struct ikev2_ke *k;
k = (const struct ikev2_ke *)ext;
- ND_TCHECK(*ext);
+ ND_TCHECK(*k);
UNALIGNED_MEMCPY(&ke, ext, sizeof(ke));
ikev2_pay_print(ndo, NPSTR(tpay), ke.h.critical);
@@ -2195,12 +2200,14 @@ ikev2_ID_print(netdissect_options *ndo, u_char tpay,
uint32_t phase _U_, uint32_t doi _U_,
uint32_t proto _U_, int depth _U_)
{
+ const struct ikev2_id *idp;
struct ikev2_id id;
int id_len, idtype_len, i;
unsigned int dumpascii, dumphex;
const unsigned char *typedata;
- ND_TCHECK(*ext);
+ idp = (const struct ikev2_id *)ext;
+ ND_TCHECK(*idp);
UNALIGNED_MEMCPY(&id, ext, sizeof(id));
ikev2_pay_print(ndo, NPSTR(tpay), id.h.critical);
@@ -2208,6 +2215,7 @@ ikev2_ID_print(netdissect_options *ndo, u_char tpay,
ND_PRINT((ndo," len=%d", id_len - 4));
if (2 < ndo->ndo_vflag && 4 < id_len) {
+ /* Print the entire payload in hex */
ND_PRINT((ndo," "));
if (!rawprint(ndo, (const uint8_t *)(ext + 1), id_len - 4))
goto trunc;
@@ -2303,7 +2311,7 @@ ikev2_auth_print(netdissect_options *ndo, u_char tpay,
const u_char *authdata = (const u_char*)ext + sizeof(a);
unsigned int len;
- ND_TCHECK(*ext);
+ ND_TCHECK2(*ext, sizeof(a));
UNALIGNED_MEMCPY(&a, ext, sizeof(a));
ikev2_pay_print(ndo, NPSTR(tpay), a.h.critical);
len = ntohs(a.h.len);
@@ -2599,6 +2607,7 @@ ikev2_vid_print(netdissect_options *ndo, u_char tpay,
else ND_PRINT((ndo, "."));
}
if (2 < ndo->ndo_vflag && 4 < len) {
+ /* Print the entire payload in hex */
ND_PRINT((ndo," "));
if (!rawprint(ndo, (const uint8_t *)(ext + 1), ntohs(e.len) - 4))
goto trunc;
@@ -2764,7 +2773,6 @@ ikev1_sub_print(netdissect_options *ndo,
while (np) {
ND_TCHECK(*ext);
-
UNALIGNED_MEMCPY(&e, ext, sizeof(e));
ND_TCHECK2(*ext, ntohs(e.len));
@@ -2932,7 +2940,6 @@ ikev2_sub_print(netdissect_options *ndo,
cp = (const u_char *)ext;
while (np) {
ND_TCHECK(*ext);
-
UNALIGNED_MEMCPY(&e, ext, sizeof(e));
ND_TCHECK2(*ext, ntohs(e.len));
diff --git a/tests/TESTLIST b/tests/TESTLIST
index 0e7097210..bd6073d71 100644
--- a/tests/TESTLIST
+++ b/tests/TESTLIST
@@ -578,6 +578,7 @@ isis-extd-isreach-oobr isis-extd-isreach-oobr.pcap isis-extd-isreach-oobr.out -v
olsr-oobr-1 olsr-oobr-1.pcap olsr-oobr-1.out -v
olsr-oobr-2 olsr-oobr-2.pcap olsr-oobr-2.out -v
ikev1_id_ipv6_addr_subnet-oobr ikev1_id_ipv6_addr_subnet-oobr.pcap ikev1_id_ipv6_addr_subnet-oobr.out -v
+isakmp-various-oobr isakmp-various-oobr.pcap isakmp-various-oobr.out -v
# bad packets from Katie Holly
mlppp-oobr mlppp-oobr.pcap mlppp-oobr.out
diff --git a/tests/isakmp-various-oobr.out b/tests/isakmp-various-oobr.out
new file mode 100644
index 000000000..cf1b1e046
--- /dev/null
+++ b/tests/isakmp-various-oobr.out
@@ -0,0 +1,5 @@
+IP (tos 0xfb,CE, ttl 17, id 21263, offset 0, flags [+, DF, rsvd], proto UDP (17), length 296, bad cksum 1ff (->f67d)!)
+ 16.0.128.20.500 > 12.251.225.45.49152: isakmp 1.0 msgid 10101010: phase 2/others ? #16[]:
+ ( [|v2ke]) (len mismatch: isakmp 2130706432/ip 268)
+IP (tos 0x12,ECT(0), ttl 17, id 21263, offset 4096, flags [DF, rsvd], proto UDP (17), length 296, bad cksum 1ff (->939f)!)
+ 0.0.0.5 > 0.0.0.0: ip-proto-17
diff --git a/tests/isakmp-various-oobr.pcap b/tests/isakmp-various-oobr.pcap
new file mode 100644
index 000000000..b81d3f5d3
Binary files /dev/null and b/tests/isakmp-various-oobr.pcap differ
| 1
|
a45ae4e1011e08583cc2b80b2f17cf608d059d20
|
https://github.com/ansible/ansible-modules-extras/commit/a45ae4e1011e08583cc2b80b2f17cf608d059d20
|
ovirt_vms: Add new cloud_init_nics parameter (#3557)
|
diff --git a/cloud/ovirt/ovirt_vms.py b/cloud/ovirt/ovirt_vms.py
index 29cb2695cb9..0c1ea05388f 100644
--- a/cloud/ovirt/ovirt_vms.py
+++ b/cloud/ovirt/ovirt_vms.py
@@ -195,12 +195,26 @@
- "C(custom_script) - Cloud-init script which will be executed on Virtual Machine when deployed."
- "C(dns_servers) - DNS servers to be configured on Virtual Machine."
- "C(dns_search) - DNS search domains to be configured on Virtual Machine."
- - "C(nic_boot_protocol) - Set boot protocol of the network interface of Virtual Machine. Can be one of None, DHCP or Static."
+ - "C(nic_boot_protocol) - Set boot protocol of the network interface of Virtual Machine. Can be one of none, dhcp or static."
- "C(nic_ip_address) - If boot protocol is static, set this IP address to network interface of Virtual Machine."
- "C(nic_netmask) - If boot protocol is static, set this netmask to network interface of Virtual Machine."
- "C(nic_gateway) - If boot protocol is static, set this gateway to network interface of Virtual Machine."
- "C(nic_name) - Set name to network interface of Virtual Machine."
- "C(nic_on_boot) - If I(True) network interface will be set to start on boot."
+ cloud_init_nics:
+ description:
+ - "List of dictionaries representing network interafaces to be setup by cloud init."
+ - "This option is used, when user needs to setup more network interfaces via cloud init."
+ - "If one network interface is enough, user should use C(cloud_init) I(nic_*) parameters. C(cloud_init) I(nic_*) parameters
+ are merged with C(cloud_init_nics) parameters."
+ - "Dictionary can contain following values:"
+ - "C(nic_boot_protocol) - Set boot protocol of the network interface of Virtual Machine. Can be one of none, dhcp or static."
+ - "C(nic_ip_address) - If boot protocol is static, set this IP address to network interface of Virtual Machine."
+ - "C(nic_netmask) - If boot protocol is static, set this netmask to network interface of Virtual Machine."
+ - "C(nic_gateway) - If boot protocol is static, set this gateway to network interface of Virtual Machine."
+ - "C(nic_name) - Set name to network interface of Virtual Machine."
+ - "C(nic_on_boot) - If I(True) network interface will be set to start on boot."
+ version_added: "2.3"
notes:
- "If VM is in I(UNASSIGNED) or I(UNKNOWN) state before any operation, the module will fail.
If VM is in I(IMAGE_LOCKED) state before any operation, we try to wait for VM to be I(DOWN).
@@ -281,6 +295,22 @@
user_name: root
root_password: super_password
+# Run VM with cloud init, with multiple network interfaces:
+ovirt_vms:
+ name: rhel7_4
+ template: rhel7
+ cluster: mycluster
+ cloud_init_nics:
+ - nic_name: eth0
+ nic_boot_protocol: dhcp
+ nic_on_boot: true
+ - nic_name: eth1
+ nic_boot_protocol: static
+ nic_ip_address: 10.34.60.86
+ nic_netmask: 255.255.252.0
+ nic_gateway: 10.34.63.254
+ nic_on_boot: true
+
# Run VM with sysprep:
ovirt_vms:
name: windows2012R2_AD
@@ -609,34 +639,36 @@ def __attach_nics(self, entity):
self.changed = True
-def _get_initialization(sysprep, cloud_init):
+def _get_initialization(sysprep, cloud_init, cloud_init_nics):
initialization = None
- if cloud_init:
+ if cloud_init or cloud_init_nics:
initialization = otypes.Initialization(
nic_configurations=[
otypes.NicConfiguration(
boot_protocol=otypes.BootProtocol(
- cloud_init.pop('nic_boot_protocol').lower()
- ) if cloud_init.get('nic_boot_protocol') else None,
- name=cloud_init.pop('nic_name'),
- on_boot=cloud_init.pop('nic_on_boot'),
+ nic.pop('nic_boot_protocol').lower()
+ ) if nic.get('nic_boot_protocol') else None,
+ name=nic.pop('nic_name', None),
+ on_boot=nic.pop('nic_on_boot', None),
ip=otypes.Ip(
- address=cloud_init.pop('nic_ip_address'),
- netmask=cloud_init.pop('nic_netmask'),
- gateway=cloud_init.pop('nic_gateway'),
+ address=nic.pop('nic_ip_address', None),
+ netmask=nic.pop('nic_netmask', None),
+ gateway=nic.pop('nic_gateway', None),
) if (
- cloud_init.get('nic_gateway') is not None or
- cloud_init.get('nic_netmask') is not None or
- cloud_init.get('nic_ip_address') is not None
+ nic.get('nic_gateway') is not None or
+ nic.get('nic_netmask') is not None or
+ nic.get('nic_ip_address') is not None
) else None,
)
- ] if (
- cloud_init.get('nic_gateway') is not None or
- cloud_init.get('nic_netmask') is not None or
- cloud_init.get('nic_ip_address') is not None or
- cloud_init.get('nic_boot_protocol') is not None or
- cloud_init.get('nic_on_boot') is not None
- ) else None,
+ for nic in cloud_init_nics
+ if (
+ nic.get('nic_gateway') is not None or
+ nic.get('nic_netmask') is not None or
+ nic.get('nic_ip_address') is not None or
+ nic.get('nic_boot_protocol') is not None or
+ nic.get('nic_on_boot') is not None
+ )
+ ] if cloud_init_nics else None,
**cloud_init
)
elif sysprep:
@@ -730,6 +762,7 @@ def main():
force=dict(type='bool', default=False),
nics=dict(default=[], type='list'),
cloud_init=dict(type='dict'),
+ cloud_init_nics=dict(defaul=[], type='list'),
sysprep=dict(type='dict'),
host=dict(default=None),
clone=dict(type='bool', default=False),
@@ -755,8 +788,10 @@ def main():
control_state(vm, vms_service, module)
if state == 'present' or state == 'running' or state == 'next_run':
- cloud_init = module.params['cloud_init']
sysprep = module.params['sysprep']
+ cloud_init = module.params['cloud_init']
+ cloud_init_nics = module.params['cloud_init_nics']
+ cloud_init_nics.append(cloud_init)
# In case VM don't exist, wait for VM DOWN state,
# otherwise don't wait for any state, just update VM:
@@ -781,13 +816,13 @@ def main():
),
wait_condition=lambda vm: vm.status == otypes.VmStatus.UP,
# Start action kwargs:
- use_cloud_init=cloud_init is not None,
+ use_cloud_init=cloud_init is not None or len(cloud_init_nics) > 0,
use_sysprep=sysprep is not None,
vm=otypes.Vm(
placement_policy=otypes.VmPlacementPolicy(
hosts=[otypes.Host(name=module.params['host'])]
) if module.params['host'] else None,
- initialization=_get_initialization(sysprep, cloud_init),
+ initialization=_get_initialization(sysprep, cloud_init, cloud_init_nics),
),
)
| 0
|
de8ad232d45a65a783c1f90008d9359afecfb9d8
|
https://github.com/wesnoth/wesnoth/commit/de8ad232d45a65a783c1f90008d9359afecfb9d8
|
updated Portuguese (Brazil) translation
|
diff --git a/changelog.md b/changelog.md
index e10c21295c07..f1391ac5dfbf 100644
--- a/changelog.md
+++ b/changelog.md
@@ -9,7 +9,7 @@
### Packaging
### Terrain
### Translations
- * Updated translations: Catalan, Czech, French
+ * Updated translations: Catalan, Czech, French, Portuguese (Brazil)
### Units
### User interface
### WML Engine
diff --git a/po/wesnoth-help/pt_BR.po b/po/wesnoth-help/pt_BR.po
index e6d08deafe74..dd4f68ed7c6d 100644
--- a/po/wesnoth-help/pt_BR.po
+++ b/po/wesnoth-help/pt_BR.po
@@ -9,7 +9,7 @@ msgstr ""
"Project-Id-Version: Battle for Wesnoth 0.8.2-CVS\n"
"Report-Msgid-Bugs-To: https://bugs.wesnoth.org/\n"
"POT-Creation-Date: 2021-01-16 17:17+0300\n"
-"PO-Revision-Date: 2021-01-03 16:08-0300\n"
+"PO-Revision-Date: 2021-01-15 08:49-0300\n"
"Last-Translator: Andrei Machado <[email protected]>\n"
"Language-Team: Portuguese - Brasil\n"
"Language: pt_BR\n"
@@ -174,15 +174,6 @@ msgstr "medicar +12"
# File: data/core/macros/abilities.cfg, line: 31
#. [heals]: id=healing
#: data/campaigns/Under_the_Burning_Suns/utils/abilities.cfg:64
-#, fuzzy
-#| msgid ""
-#| "This unit combines herbal remedies with magic to heal units more quickly "
-#| "than is normally possible on the battlefield.\n"
-#| "\n"
-#| "A unit cared for by this healer may heal up to 8 HP per turn, or stop "
-#| "poison from taking effect for that turn.\n"
-#| "A poisoned unit cannot be cured of its poison by a healer, and must seek "
-#| "the care of a village or a unit that can cure."
msgid ""
"This unit combines herbal remedies with magic to heal units more quickly "
"than is normally possible on the battlefield.\n"
@@ -195,7 +186,7 @@ msgstr ""
"Esta unidade combina remédios a base de ervas com magia para curar unidades "
"mais rapidamente do que é normalmente possível no campo de batalha.\n"
"\n"
-"Uma unidade sob o tratamento deste curandeiro recuperará 8 de HP por turno "
+"Uma unidade sob o tratamento deste curandeiro recuperará 12 de HP por turno "
"ou não leva dano de veneno naquele turno.\n"
"Uma unidade envenenada não pode ter o seu veneno curado por um curandeiro "
"precisando, assim, ser tratado em uma aldeia ou por uma unidade que pode "
@@ -753,7 +744,7 @@ msgstr "Seleciona três hexágonos em linha."
#. [topic]: id=editor_tool_paste
#: data/core/editor/help.cfg:89
msgid "Clipboard and Paste Tool"
-msgstr ""
+msgstr "Área de tranferência e Ferramenta de Colagem"
#. [topic]: id=editor_tool_paste
#: data/core/editor/help.cfg:90
@@ -3162,15 +3153,6 @@ msgstr "Salvando-carregando"
#. [topic]: id=saveload
#: data/core/help.cfg:292
-#, fuzzy
-#| msgid ""
-#| "Random numbers are part of Wesnoth, attacks can fail and units can die "
-#| "due to bad luck. This is an expected part of the game, and one of the "
-#| "aims of the game is that a sufficiently skilled player should be able to "
-#| "complete all of the mainline campaigns, on hard, without needing to save-"
-#| "load. Going back to a previous turn to try a different strategy is a part "
-#| "of learning the game, but we recommend against reloading merely to try "
-#| "the same strategy again while hoping for better luck."
msgid ""
"Random numbers are part of Wesnoth, attacks can fail and units can die due "
"to bad luck — this is an expected part of the game. Going back to a previous "
@@ -3179,13 +3161,11 @@ msgid ""
"hoping for better luck."
msgstr ""
"Números aleatórios são uma parte de Wesnoth, ataques podem falhar e unidades "
-"podem morrer por causa de azar. Esta é uma parte normal do jogo, e um dos "
-"objetivos do jogo é que um jogador experiênte seja capaz de completar todas "
-"as campanhas que já vem com o jogo, na dificuldade difícil, sem precisar "
-"salvar e carregar no meio de um cenário. Carregar um turno anterior para "
-"tentar uma estratégia diferente faz parte da curva de aprendizado do jogo, "
-"mas nos recomendamos que não carregue um turno anterior com a intenção de "
-"tentar a mesma estratégia mas torcendo para ter mais sorte."
+"podem morrer devido à má sorte — esta é uma parte normal do jogo. Carregar "
+"um turno anterior para tentar uma estratégia diferente faz parte da curva de "
+"aprendizado do jogo, mas nos recomendamos que não carregue um turno anterior "
+"com a intenção de tentar a mesma estratégia e torcer para que a sorte esteja "
+"do seu ldo."
#. [topic]: id=saveload
#: data/core/help.cfg:294
@@ -10118,39 +10098,6 @@ msgstr ""
#~ msgid "Item Tool"
#~ msgstr "Ferramenta de Itens"
-#, fuzzy
-#~| msgid ""
-#~| "Named Areas are sets of gamefields which can be addressed during "
-#~| "scenario scripting by a given name.\n"
-#~| "\n"
-#~| "It can be used to abstract between the implementation of an effect and "
-#~| "the map specific setting.\n"
-#~| "This is a very powerful mechanism since it allows generic scenario "
-#~| "codings working with different maps providing the needed named locations."
-#~ msgid ""
-#~ "This tool can create [time_area]s, unlike the name suggests these do not "
-#~ "need to have a specific time zone assigned to them.\n"
-#~ " [time_area]s are sets of tiles which can be addressed during scenario "
-#~ "scripting by their id. [time_area]s can optionally have a custom\n"
-#~ " time zone assigned to them. The simplest way to address a [time_area] "
-#~ "via scenario scripting is the `area=` attribute in standard location "
-#~ "filters.\n"
-#~ "\n"
-#~ "This tool can be used to abstract between the implementation of an effect "
-#~ "and the map specific setting.\n"
-#~ "This is a very powerful mechanism since it allows generic scenario code "
-#~ "to work with different maps providing the needed named locations."
-#~ msgstr ""
-#~ "Áreas nomeadas são áreas pré-definidas que podem ser referidos por um "
-#~ "nome específico durante o script do cenário por meio de um nome "
-#~ "específico.\n"
-#~ "\n"
-#~ "Pode ser usado para abstrair entre a implementação de um efeito e a "
-#~ "configuração despecífica do mapa.\n"
-#~ "Este é um mecanismo muito poderoso, pois ele permite que o código "
-#~ "genérico de cenários funcione com diferentes mapas, desde que você tenha "
-#~ "as áreas nomeadas necessárias."
-
#~ msgid ""
#~ "Saves a list of music tracks defining a random playlist to the scenario.\n"
#~ "\n"
@@ -10161,15 +10108,6 @@ msgstr ""
#~ "Dê uma olhada no servidor de addon para encontrar músicas adicionais que "
#~ "podem ser adicionadas com facilidade."
-#, fuzzy
-#~| msgid ""
-#~| "\n"
-#~| "• <ref>dst='editor_modes' text='Editing Modes'</ref>\n"
-#~| "• <ref>dst='editor_toolkit' text='Editor Toolkit'</ref>\n"
-#~| "• <ref>dst='editor_palette' text='Editor Palette'</ref>\n"
-#~| "• <ref>dst='editor_brush' text='Editor Brushes'</ref> TODO: not sure if "
-#~| "it needs a topic on its own\n"
-#~| "• <ref>dst='editor_clipboard' text='Editor Clipboard'</ref>"
#~ msgid ""
#~ "<header>text='Basic Concepts'</header>\n"
#~ "• <ref>dst='editor_modes' text='Editing Modes'</ref>\n"
@@ -10178,14 +10116,12 @@ msgstr ""
#~ "• The clipboard is described in the <ref>dst='editor_tool_paste' "
#~ "text='Paste Tool'</ref>"
#~ msgstr ""
-#~ "\n"
+#~ "<header>text='Conceitos Básicos'</header>\n"
#~ "• <ref>dst='editor_modes' text='Modos de Edição'</ref>\n"
#~ "• <ref>dst='editor_toolkit' text='Toolkit do Editor'</ref>\n"
#~ "• <ref>dst='editor_palette' text='Paleta do Editor'</ref>\n"
-#~ "• <ref>dst='editor_brush' text='Pinceis do Editor'</ref> AFAZER: incerto "
-#~ "se precisa de um tópico próprio\n"
-#~ "• <ref>dst='editor_clipboard' text='Área de Transferência de Terreno'</"
-#~ "ref>"
+#~ "• A área de transferência é descrita em <ref>dst='editor_tool_paste' "
+#~ "text='Ferramenta de Colagem'</ref>"
#~ msgid "Editing Modes"
#~ msgstr "Modos de Edição"
@@ -10193,25 +10129,6 @@ msgstr ""
#~ msgid "Editor Tools"
#~ msgstr "Ferramentas do Editor"
-#, fuzzy
-#~| msgid ""
-#~| "The editor provides several tools for editing your maps and scenarios. "
-#~| "At all times, one of the editor tools is active. The active tool's "
-#~| "context determines the content of the editor palette and context menu.\n"
-#~| "\n"
-#~| "These following tools are provided:\n"
-#~| "\n"
-#~| "• <ref>dst='editor_tool_paint' text='Paint Tool'</ref>\n"
-#~| "• <ref>dst='editor_tool_fill' text='Fill Tool'</ref>\n"
-#~| "• <ref>dst='editor_tool_select' text='Select Tool'</ref>\n"
-#~| "• <ref>dst='editor_tool_paste' text='Paste Tool'</ref>\n"
-#~| "• <ref>dst='editor_tool_starting' text='Starting Tool'</ref>\n"
-#~| "• <ref>dst='editor_tool_label' text='Label Tool'</ref>\n"
-#~| "• <ref>dst='editor_tool_item' text='Item Tool'</ref>\n"
-#~| "• <ref>dst='editor_tool_soundsource' text='Soundsource Tool'</ref>\n"
-#~| "• <ref>dst='editor_tool_village' text='Village Tool'</ref>\n"
-#~| "• <ref>dst='editor_tool_unit' text='Unit Tool'</ref>\n"
-#~| "\n"
#~ msgid ""
#~ "The editor provides several tools for editing your maps and scenarios. At "
#~ "all times, one of the editor tools is active. The active tool’s context "
@@ -10237,20 +10154,22 @@ msgstr ""
#~ "ferramenta ativada determina o conteúdo da paleta do editor e do menu "
#~ "contextual.\n"
#~ "\n"
-#~ "As seguintes ferramentas são fornecidas:\n"
+#~ "Estas ferramentas estão disponíveis tanto no modo apenas-terreno quanto "
+#~ "no modo de cenário:\n"
+#~ "\n"
#~ "• <ref>dst='editor_tool_paint' text='Pincel'</ref>\n"
-#~ "• <ref>dst='editor_tool_fill' text='Balde'</ref>\n"
+#~ "• <ref>dst='editor_tool_fill' text='Balde'</ref>\n"
#~ "• <ref>dst='editor_tool_select' text='Ferramenta de Seleção'</ref>\n"
#~ "• <ref>dst='editor_tool_paste' text='Ferramenta de Colagem '</ref>\n"
#~ "• <ref>dst='editor_tool_starting' text='Ferramenta de Posição Inicial'</"
#~ "ref>\n"
+#~ "\n"
+#~ "Estas ferramentas só estão disponíveis no modo de cenário:\n"
+#~ "\n"
#~ "• <ref>dst='editor_tool_label' text='Ferramenta de Etiquetas'</ref>\n"
#~ "• <ref>dst='editor_tool_item' text='Ferramenta de Itens'</ref>\n"
-#~ "• <ref>dst='editor_tool_soundsource' text='Ferramenta de Fonte do Som'</"
-#~ "ref>\n"
#~ "• <ref>dst='editor_tool_village' text='Ferramento de Aldeias'</ref>\n"
-#~ "• <ref>dst='editor_tool_unit' text='Ferramenta de Unidades'</ref>\n"
-#~ "\n"
+#~ "• <ref>dst='editor_tool_unit' text='Ferramenta de Unidades'</ref>"
#~ msgid "Editor Brush"
#~ msgstr "Pincel do Editor"
diff --git a/po/wesnoth-sof/pt_BR.po b/po/wesnoth-sof/pt_BR.po
index aa1e75497971..f32b99919140 100644
--- a/po/wesnoth-sof/pt_BR.po
+++ b/po/wesnoth-sof/pt_BR.po
@@ -3,7 +3,7 @@ msgstr ""
"Project-Id-Version: pt_BR\n"
"Report-Msgid-Bugs-To: https://bugs.wesnoth.org/\n"
"POT-Creation-Date: 2021-01-16 14:18 UTC\n"
-"PO-Revision-Date: 2020-09-30 10:36-0300\n"
+"PO-Revision-Date: 2021-01-08 19:00-0300\n"
"Last-Translator: Andrei Machado <[email protected]>\n"
"Language-Team: Portuguese Brazilian\n"
"Language: pt_BR\n"
@@ -11,7 +11,7 @@ msgstr ""
"Content-Type: text/plain; charset=UTF-8\n"
"Content-Transfer-Encoding: 8bit\n"
"Plural-Forms: nplurals=2; plural=(n > 1);\n"
-"X-Generator: Poedit 2.4.1\n"
+"X-Generator: Poedit 2.4.2\n"
#. [campaign]: id=Sceptre_of_Fire
#: data/campaigns/Sceptre_of_Fire/_main.cfg:11
@@ -364,16 +364,12 @@ msgstr ""
#. [message]: speaker=Rugnur
#: data/campaigns/Sceptre_of_Fire/scenarios/1_A_Bargain_is_Struck.cfg:361
-#, fuzzy
-#| msgid ""
-#| "Well... I think we can make a deal, but I’m not sure. I’ll have to ask "
-#| "the tribal leaders."
msgid ""
"Well... I think we can make a deal, but I’m not sure. I’ll have to ask the "
"clan leaders."
msgstr ""
"Bem... Eu acho que nós podemos chegar a um acordo, mas eu não tenho certeza. "
-"Eu terei que perguntar aos líderes da tribo."
+"Eu terei que perguntar aos líderes do clã."
#. [message]: speaker=Haldric II
#: data/campaigns/Sceptre_of_Fire/scenarios/1_A_Bargain_is_Struck.cfg:365
@@ -395,15 +391,11 @@ msgstr ""
#. [message]: speaker=Haldric II
#: data/campaigns/Sceptre_of_Fire/scenarios/1_A_Bargain_is_Struck.cfg:374
-#, fuzzy
-#| msgid ""
-#| "I can always take my offer to another tribe more friendly to its "
-#| "potential patrons. You are not the only smiths in the Northlands!"
msgid ""
"I can always take my offer to another clan more friendly to its potential "
"patrons. You are not the only smiths in the Northlands!"
msgstr ""
-"Eu posso sempre levar minha oferta para uma outra tribo mais amigável com os "
+"Eu posso sempre levar minha oferta para uma outro clã mais amigável com os "
"seus clientes em potencial. Vocês não são os únicos ferreiros nas Terras do "
"Norte!"
@@ -460,12 +452,12 @@ msgstr ""
#. [message]: speaker=Haldric II
#: data/campaigns/Sceptre_of_Fire/scenarios/1_A_Bargain_is_Struck.cfg:409
-#, fuzzy
-#| msgid "I want you to make it into a sceptre, a sceptre of fire."
msgid ""
"I want you to make it into a sceptre. A gold and ruby sceptre to all "
"appearances. We shall call it the Sceptre of Fire."
-msgstr "Eu quero que vocês a transformem em um cetro, um cetro de fogo."
+msgstr ""
+"Eu quero que vocês a transformem em um cetro. Um cetro de ouro e rubi para "
+"todas as aparências. Ele será chamado de Cetro de Fogo."
#. [message]: speaker=Rugnur
#: data/campaigns/Sceptre_of_Fire/scenarios/1_A_Bargain_is_Struck.cfg:414
@@ -506,15 +498,11 @@ msgstr "Isso mesmo. Eu estou indo junto com a prata."
#. [message]: speaker=Glildur
#: data/campaigns/Sceptre_of_Fire/scenarios/1_A_Bargain_is_Struck.cfg:487
-#, fuzzy
-#| msgid ""
-#| "Hey! You can’t do that — this road is an elvish road. We’re not letting "
-#| "you transport gold and jewels on it without paying a toll."
msgid ""
"Hey! You can’t do that — this road is an elvish road. We’re not letting you "
"transport gold and jewels on it without paying a toll."
msgstr ""
-"Ei! Vocês não podem fazer isto — esta estrada é uma estrada élfica. Nós não "
+"Ei! Vocês não podem fazer isto — esta estrada é uma estrada élfica. Nós não "
"vamos permitir que vocês transportem ouro e jóias sem pagar pedágio."
#. [message]: speaker=Rugnur
@@ -589,20 +577,16 @@ msgstr ""
#. [message]: speaker=Glildur
#: data/campaigns/Sceptre_of_Fire/scenarios/1_A_Bargain_is_Struck.cfg:669
msgid "I told you this was our road."
-msgstr ""
+msgstr "Eu te disse que essa estrada é nossa."
#. [message]: speaker=Alanin
#: data/campaigns/Sceptre_of_Fire/scenarios/1_A_Bargain_is_Struck.cfg:689
-#, fuzzy
-#| msgid ""
-#| "Here’s the stone, for you dwarves! Now, if you’ll excuse me, I think I’ll "
-#| "be taking refuge in this castle here... I don’t much like fighting."
msgid ""
"Here’s the stone, for you dwarves! Now, if you’ll excuse me, I think I’ll be "
"taking refuge here... I don’t much like fighting."
msgstr ""
"Aqui está a pedra, para vocês, anões! Agora, se me dão licença, eu acho que "
-"vou me refugiar nesse castelo aqui... Eu não gosto muito de lutar."
+"vou me refugiar aqui... Eu não gosto muito de lutar."
#. [message]: speaker=Haldric II
#: data/campaigns/Sceptre_of_Fire/scenarios/1_A_Bargain_is_Struck.cfg:710
@@ -644,6 +628,8 @@ msgid ""
"Our reinforcements should be here soon. Send those caravans here, we might "
"let you walk away."
msgstr ""
+"Nossos reforços logo estarão aqui. Envie as caravanas para nós e talvez "
+"deixaremos que vocês saiam vivos."
#. [message]: speaker=Haldric II
#: data/campaigns/Sceptre_of_Fire/scenarios/1_A_Bargain_is_Struck.cfg:833
@@ -651,6 +637,8 @@ msgid ""
"That's a bluff, what sort of reinforcements can this little band of thieves "
"possibly count on?"
msgstr ""
+"Você está blefando. Mas que reforços esse pequeno bando de ladrões pode "
+"estar contando?"
#. [message]: speaker=Glildur
#: data/campaigns/Sceptre_of_Fire/scenarios/1_A_Bargain_is_Struck.cfg:865
@@ -708,7 +696,7 @@ msgstr "O seu precioso Landar pode beijar o meu machado."
#. [message]: speaker=unit
#: data/campaigns/Sceptre_of_Fire/scenarios/1_A_Bargain_is_Struck.cfg:941
msgid "This gains you nothing, we will not rest!"
-msgstr ""
+msgstr "Isso não lhes ajudará em nada, nós não descansaremos!"
#. [message]: speaker=Rugnur
#: data/campaigns/Sceptre_of_Fire/scenarios/1_A_Bargain_is_Struck.cfg:971
@@ -1036,15 +1024,13 @@ msgstr ""
#. [scenario]: id=2p5_Reaching_the_Runecrafter
#: data/campaigns/Sceptre_of_Fire/scenarios/2p5_Reaching_the_Runecrafter.cfg:3
-#, fuzzy
-#| msgid "Searching for the Runecrafter"
msgid "Reaching the Runecrafter"
-msgstr "Procurando pelo Criador de Runas"
+msgstr "Alcançando o Criador de Runas"
#. [side]: type=Orcish Warrior, id=Bragdash
#: data/campaigns/Sceptre_of_Fire/scenarios/2p5_Reaching_the_Runecrafter.cfg:31
msgid "Bragdash Gar"
-msgstr ""
+msgstr "Bragdash Gar"
#. [side]: type=Orcish Warrior, id=Bragdash
#. [side]
@@ -1058,12 +1044,12 @@ msgstr "Orcs"
#. [side]: type=Goblin Rouser, id=Pidmer
#: data/campaigns/Sceptre_of_Fire/scenarios/2p5_Reaching_the_Runecrafter.cfg:49
msgid "Pidmer Gar"
-msgstr ""
+msgstr "Pidmer Gar"
#. [side]: type=Goblin Rouser, id=Pidmer
#: data/campaigns/Sceptre_of_Fire/scenarios/2p5_Reaching_the_Runecrafter.cfg:56
msgid "Goblins"
-msgstr ""
+msgstr "Góblins"
#. [part]
#: data/campaigns/Sceptre_of_Fire/scenarios/2p5_Reaching_the_Runecrafter.cfg:66
@@ -1089,7 +1075,7 @@ msgstr ""
#. [message]: speaker=Rugnur
#: data/campaigns/Sceptre_of_Fire/scenarios/2p5_Reaching_the_Runecrafter.cfg:140
msgid "Those are orcs, aren't they?"
-msgstr ""
+msgstr "Isso dai são orcs, não é?"
#. [message]: speaker=Baglur
#: data/campaigns/Sceptre_of_Fire/scenarios/2p5_Reaching_the_Runecrafter.cfg:144
@@ -1101,7 +1087,7 @@ msgstr ""
#. [message]: speaker=Alanin
#: data/campaigns/Sceptre_of_Fire/scenarios/2p5_Reaching_the_Runecrafter.cfg:148
msgid "That's terrible, someone should stop them!"
-msgstr ""
+msgstr "Isso é péssimo. Alguém precisa pará-los!"
#. [message]: speaker=Rugnur
#: data/campaigns/Sceptre_of_Fire/scenarios/2p5_Reaching_the_Runecrafter.cfg:152
@@ -1109,16 +1095,19 @@ msgid ""
"Do orcs always stink so bad? I've heard that they are stupid and messy, but "
"this is almost unbearable!"
msgstr ""
+"Por acaso orcs sempre fedem tanto? Eu ouvi dizer que eles são idiotas e "
+"sujos, mas esse cheiro é terrível!"
#. [message]: speaker=Bragdash
#: data/campaigns/Sceptre_of_Fire/scenarios/2p5_Reaching_the_Runecrafter.cfg:156
msgid "We see you, we hear you, sneaky little moles! Pidmer, go skewer them!"
msgstr ""
+"Nós vemos vocês, nós ouvimos vocês, suas toupeiras! Pidmer, vá espetar eles!"
#. [message]: speaker=Pidmer
#: data/campaigns/Sceptre_of_Fire/scenarios/2p5_Reaching_the_Runecrafter.cfg:160
msgid "Um... Aren't we needed for the salvage?"
-msgstr ""
+msgstr "Um... não precisam da gente pra ajudar com a sucata?"
#. [message]: speaker=Bragdash
#: data/campaigns/Sceptre_of_Fire/scenarios/2p5_Reaching_the_Runecrafter.cfg:164
@@ -1131,12 +1120,12 @@ msgstr ""
#. [message]: speaker=Rugnur
#: data/campaigns/Sceptre_of_Fire/scenarios/2p5_Reaching_the_Runecrafter.cfg:168
msgid "Uh, well, we're not getting through without a fight..."
-msgstr ""
+msgstr "É, bom, pelo visto não temos como passar daqui serm lutarmos..."
#. [message]: speaker=Rugnur
#: data/campaigns/Sceptre_of_Fire/scenarios/2p5_Reaching_the_Runecrafter.cfg:173
msgid "... Let's set up a base here."
-msgstr ""
+msgstr "... Vamos estabelecer uma base aqui."
#. [message]: speaker=unit
#: data/campaigns/Sceptre_of_Fire/scenarios/2p5_Reaching_the_Runecrafter.cfg:205
@@ -1159,11 +1148,13 @@ msgid ""
"(*gasp*) I think I've found the source of the terrible smell, it wasn't the "
"orcs..."
msgstr ""
+"(*surpreso*) Eu acho que descobri de onde está vindo esse cheiro terrível, e "
+"não foram os orcs..."
#. [message]: speaker=Bragdash
#: data/campaigns/Sceptre_of_Fire/scenarios/2p5_Reaching_the_Runecrafter.cfg:226
msgid "Of course it wasn't us, you worm!"
-msgstr ""
+msgstr "É claro que não fomos nós, seus vermes!"
#. [message]: speaker=unit
#: data/campaigns/Sceptre_of_Fire/scenarios/2p5_Reaching_the_Runecrafter.cfg:230
@@ -1175,7 +1166,7 @@ msgstr ""
#. [message]: speaker=Pidmer
#: data/campaigns/Sceptre_of_Fire/scenarios/2p5_Reaching_the_Runecrafter.cfg:263
msgid "Help! We can't swim!"
-msgstr ""
+msgstr "Socorro! Eu não sei nadar!"
#. [message]: speaker=Bragdash
#: data/campaigns/Sceptre_of_Fire/scenarios/2p5_Reaching_the_Runecrafter.cfg:276
@@ -1288,20 +1279,16 @@ msgstr ""
#. [message]: speaker=Durstorn
#: data/campaigns/Sceptre_of_Fire/scenarios/2t_In_the_Dwarven_City.cfg:136
msgid "... ?"
-msgstr ""
+msgstr "... ?"
#. [message]: speaker=Durstorn
#: data/campaigns/Sceptre_of_Fire/scenarios/2t_In_the_Dwarven_City.cfg:140
-#, fuzzy
-#| msgid ""
-#| "Where’s that fool Rugnur gotten to? It’s time for him to report on events "
-#| "in the surface world. He’s late!"
msgid ""
"Where's that fool Rugnur? He should be here to report on events in the "
"surface world. He’s late!"
msgstr ""
-"Onde será que aquele tolo do Rugnur foi se meter? Já está na hora dele "
-"relatar sobre os acontecimentos do mundo da superfície. Ele está atrasado!"
+"Onde está aquele tolo do Rugnur? Ele já deveria ter retornado para relatar "
+"os acontecimentos do mundo da superfície. Ele está atrasado!"
#. [message]: speaker=Noiraran
#: data/campaigns/Sceptre_of_Fire/scenarios/2t_In_the_Dwarven_City.cfg:144
@@ -1329,16 +1316,12 @@ msgstr "Boa, deixe que eles tentem pegá-lo! Ha!"
#. [message]: speaker=Rugnur
#: data/campaigns/Sceptre_of_Fire/scenarios/2t_In_the_Dwarven_City.cfg:165
-#, fuzzy
-#| msgid ""
-#| "Hey, Durstorn, have we started yet? King Haldric came by just now, wanted "
-#| "to talk to you..."
msgid ""
"(whew!) Sorry I'm late, but King Haldric came by just now, wanted to talk to "
"you..."
msgstr ""
-"Ei, Durstorn, nós já começamos? O Rei Haldric acabou de ir embora, ele "
-"queria falar com você..."
+"(Ufa!) Sinto muito estar atrasado, mas o Rei Haldric acabou de ir embora, "
+"ele queria falar com você..."
#. [message]: speaker=Durstorn
#: data/campaigns/Sceptre_of_Fire/scenarios/2t_In_the_Dwarven_City.cfg:169
@@ -1352,10 +1335,8 @@ msgstr "Hã? Um mensageiro não veio e lhe disse?"
#. [message]: speaker=Durstorn
#: data/campaigns/Sceptre_of_Fire/scenarios/2t_In_the_Dwarven_City.cfg:177
-#, fuzzy
-#| msgid "So what are you going to do?"
msgid "No, what are you talking about?"
-msgstr "Então o que você pretende fazer?"
+msgstr "Não, do que você está falando?"
#. [message]: speaker=Baglur
#: data/campaigns/Sceptre_of_Fire/scenarios/2t_In_the_Dwarven_City.cfg:181
@@ -1387,12 +1368,12 @@ msgstr ""
#. [message]: speaker=Kuhnar
#: data/campaigns/Sceptre_of_Fire/scenarios/2t_In_the_Dwarven_City.cfg:194
msgid "Why were the elves attacking?"
-msgstr ""
+msgstr "Por que os elfos atacaram?"
#. [message]: speaker=Noiraran
#: data/campaigns/Sceptre_of_Fire/scenarios/2t_In_the_Dwarven_City.cfg:198
msgid "More important than that, what'd the king offer for this sceptre, eh?"
-msgstr ""
+msgstr "Mais importante do que isso, o que o rei ofereceu por esse cetro?"
#. [message]: speaker=Rugnur
#: data/campaigns/Sceptre_of_Fire/scenarios/2t_In_the_Dwarven_City.cfg:202
@@ -1419,32 +1400,22 @@ msgstr ""
#. [message]: speaker=Rugnur
#: data/campaigns/Sceptre_of_Fire/scenarios/2t_In_the_Dwarven_City.cfg:210
-#, fuzzy
-#| msgid ""
-#| "Sorry, lord, but he said he would move on to another tribe if I left."
msgid "Sorry, lord, but he said he would move on to another clan if I left."
msgstr ""
-"Desculpe, lorde, mas ele disse que iria para outra tribo caso eu fosse "
-"embora."
+"Desculpe, lorde, mas ele disse que iria para outro clã caso eu fosse embora."
#. [message]: speaker=Durstorn
#: data/campaigns/Sceptre_of_Fire/scenarios/2t_In_the_Dwarven_City.cfg:214
-#, fuzzy
-#| msgid ""
-#| "Can’t you tell a bluff when you hear one?! He knows we’re the best "
-#| "craftsmen, and he wouldn’t have gone to another tribe if we stalled for a "
-#| "year. Oh well, what’s done is done. We’ll have to work for less than I "
-#| "would prefer..."
msgid ""
"Can’t you tell a bluff when you hear one?! He knows we’re the best "
"craftsmen, and he wouldn’t have gone to another clan if we stalled for a "
"year. Oh well, what’s done is done. We’ll have to work for less than I would "
"prefer..."
msgstr ""
-"Você não consegue distinguir um blefe?! Ele sabe que nós somos of melhores "
-"artesãos, e ele não teria ido para nenhuma outra tribo mesmo que tivessemos "
-"demorado um ano para aceitar a oferta. Fazer o que. O que está feito está "
-"feito. Teremos que trabalhar por menos do que eu gostaria..."
+"Você não reconhece um blefe quando vê um?! Ele sabe que nós somos of "
+"melhores artesãos, e ele não teria ido para nenhum outro clã mesmo que "
+"tivessemos demorado um ano para aceitar a oferta. Fazer o que. O que está "
+"feito está feito. Teremos que trabalhar por menos do que eu gostaria..."
#. [message]: speaker=Baglur
#: data/campaigns/Sceptre_of_Fire/scenarios/2t_In_the_Dwarven_City.cfg:218
@@ -1472,19 +1443,14 @@ msgstr "Você quer dizer aquele anão maluco que vive no extremo norte?!"
#. [message]: speaker=Durstorn
#: data/campaigns/Sceptre_of_Fire/scenarios/2t_In_the_Dwarven_City.cfg:230
-#, fuzzy
-#| msgid ""
-#| "Yes. He is the only one I know of who could craft the sceptre the way "
-#| "Haldric wants it. And he has nothing to do; he will be fine with wasting "
-#| "25 years of his life on this task."
msgid ""
"Yes. He is the only one I know of who could craft the sceptre the way "
"Haldric wants it, bad magic and all. And he has nothing to do; he will be "
"fine with wasting 25 years of his life on this insane task."
msgstr ""
-"Sim. Ele é o único que conheço que seria capaz de criar o cetro da maneira "
-"que Haldric quer. E ele não tem nada melhor para fazer; ele não se importará "
-"de desperdiçar 25 anos da vida dele nessa tarefa."
+"Sim. Ele é o único que conheço que seria capaz de criar o cetro do jeito que "
+"Haldric quer, com magia e tudo. E ele não tem nada melhor para fazer; ele "
+"não se importará de desperdiçar 25 anos da vida dele nesse projeto maluco."
#. [message]: speaker=Rugnur
#: data/campaigns/Sceptre_of_Fire/scenarios/2t_In_the_Dwarven_City.cfg:234
@@ -1506,8 +1472,9 @@ msgstr ""
#. [message]: speaker=Rugnur
#: data/campaigns/Sceptre_of_Fire/scenarios/2t_In_the_Dwarven_City.cfg:242
+#, fuzzy
msgid "Thank you, Lord. I'll find him and do us proud!"
-msgstr ""
+msgstr "Obrigado, Milorde. Eu vou encontrá-lo!"
#. [message]: speaker=Durstorn
#: data/campaigns/Sceptre_of_Fire/scenarios/2t_In_the_Dwarven_City.cfg:246
@@ -1523,14 +1490,14 @@ msgstr "O que eu perdi, hein?"
#. [message]: speaker=Rugnur
#: data/campaigns/Sceptre_of_Fire/scenarios/2t_In_the_Dwarven_City.cfg:263
msgid "Where have you been? Lord-"
-msgstr ""
+msgstr "Onde você estava? Lorde-"
#. [message]: speaker=Durstorn
#: data/campaigns/Sceptre_of_Fire/scenarios/2t_In_the_Dwarven_City.cfg:267
msgid ""
"A friend of Rugnur, huh? ... Follow him north. He needs all the help he can "
"get!"
-msgstr ""
+msgstr "Um amigo de Rugnur, é? ... Vá para o norte. Ele precisa de ajuda!"
#. [scenario]: id=3_Searching_for_the_Runecrafter
#: data/campaigns/Sceptre_of_Fire/scenarios/3_Searching_for_the_Runecrafter.cfg:3
@@ -1611,16 +1578,12 @@ msgstr ""
#. [message]: speaker=Baglur
#: data/campaigns/Sceptre_of_Fire/scenarios/3_Searching_for_the_Runecrafter.cfg:222
-#, fuzzy
-#| msgid ""
-#| "We need to find the mage Thursagan and convince him to return to the "
-#| "citadel with us. He’s somewhere up here."
msgid ""
"We need to find the sage Thursagan and convince him to return to the citadel "
"with us. He’s somewhere up here."
msgstr ""
-"Nós precisamos encotrar o mago Thursagan e convencê-lo a retornar à cidadela "
-"conosco. Ele está por aqui em algum lugar."
+"Nós precisamos encotrar o sábio Thursagan e convencê-lo a retornar à "
+"cidadela conosco. Ele está por aqui em algum lugar."
#. [message]: speaker=Rugnur
#: data/campaigns/Sceptre_of_Fire/scenarios/3_Searching_for_the_Runecrafter.cfg:226
@@ -1638,16 +1601,12 @@ msgstr ""
#. [message]: speaker=Alanin
#: data/campaigns/Sceptre_of_Fire/scenarios/3_Searching_for_the_Runecrafter.cfg:234
-#, fuzzy
-#| msgid ""
-#| "Except for trolls and ogres, right? They live in the far Northlands. "
-#| "They’re probably lurking around here somewhere."
msgid ""
"Except for trolls and ogres, right? I've heard they live in the far "
"Northlands. They’re probably lurking around here somewhere."
msgstr ""
-"Exceto por trolls e orcs, correto? Eles vivem no extremo norte. Eles "
-"provavelmente estão à espreita por aqui em algum lugar."
+"Exceto por trolls e orcs, correto? Ouvir dizer que eles vivem no extremo "
+"norte. Eles provavelmente estão à espreita por aqui em algum lugar."
#. [message]: speaker=Baglur
#: data/campaigns/Sceptre_of_Fire/scenarios/3_Searching_for_the_Runecrafter.cfg:238
@@ -1700,17 +1659,13 @@ msgstr ""
#. [message]: speaker=Krawg
#: data/campaigns/Sceptre_of_Fire/scenarios/3_Searching_for_the_Runecrafter.cfg:387
-#, fuzzy
-#| msgid "Thursagan"
msgid "Urrrsagan?"
-msgstr "Thursagan"
+msgstr "Urrrsagan?"
#. [message]: speaker=Rugnur
#: data/campaigns/Sceptre_of_Fire/scenarios/3_Searching_for_the_Runecrafter.cfg:391
-#, fuzzy
-#| msgid "Well, um, yes. Why, can you help us?"
msgid "Well, um, yes, Thursagan. Why, can you help us find him?"
-msgstr "Bem, é, sim. Porque? Você pode nos ajudar?"
+msgstr "Bem, é, sim, Thursagan. Porque? Você pode nos ajudar a encontrá-lo?"
#. [message]: speaker=Krawg
#: data/campaigns/Sceptre_of_Fire/scenarios/3_Searching_for_the_Runecrafter.cfg:395
@@ -1816,12 +1771,10 @@ msgstr ""
#. [message]: speaker=Thursagan
#: data/campaigns/Sceptre_of_Fire/scenarios/3_Searching_for_the_Runecrafter.cfg:548
-#, fuzzy
-#| msgid "The ruby of fire, what is that, some worthless Wesnothian gem?"
msgid ""
"Whoa, now! The Ruby of Fire, what is that, some worthless Wesnothian gem?"
msgstr ""
-"O rubi de fogo, e o que é isso, alguma gema sem valor dos Wesnothianos?"
+"O Rubi de Fogo, e o que é isso, alguma gema sem valor dos Wesnothianos?"
#. [message]: speaker=Baglur
#: data/campaigns/Sceptre_of_Fire/scenarios/3_Searching_for_the_Runecrafter.cfg:552
@@ -1836,10 +1789,8 @@ msgstr ""
#. [message]: speaker=Thursagan
#: data/campaigns/Sceptre_of_Fire/scenarios/3_Searching_for_the_Runecrafter.cfg:556
-#, fuzzy
-#| msgid "Oh, really? And what does Haldric want us to do with it?"
msgid "Oh, really? And what does the king of Wesnoth want us to do with it?"
-msgstr "Ah, sério? E o que Haldric quer que nós façamos com ele?"
+msgstr "Ah, sério? E o que é que o rei de Wesnoth quer que façamos com ele?"
#. [message]: speaker=Rugnur
#: data/campaigns/Sceptre_of_Fire/scenarios/3_Searching_for_the_Runecrafter.cfg:560
@@ -1852,6 +1803,8 @@ msgid ""
"I see. The king would cast fire like a mage. Well, good for him. Send him my "
"regards!"
msgstr ""
+"Entendo. O rei será capaz de lançar bolas de fogo, como um mago. Bim, bom "
+"pra ele. Mande minhas felicidades para ele!"
#. [message]: speaker=Rugnur
#: data/campaigns/Sceptre_of_Fire/scenarios/3_Searching_for_the_Runecrafter.cfg:568
@@ -1946,10 +1899,8 @@ msgstr "Sim, nós fizemos. E este é Krawg, que nos ajudou nas Terras do Norte."
#. [message]: speaker=Krawg
#: data/campaigns/Sceptre_of_Fire/scenarios/3t_The_Council_Regathers.cfg:140
-#, fuzzy
-#| msgid "Yaa! Mee Krawg!"
msgid "Yaa! Krawg!"
-msgstr "Siin! Eeu Krawg!"
+msgstr "Siin! Krawg!"
#. [message]: speaker=Thursagan
#: data/campaigns/Sceptre_of_Fire/scenarios/3t_The_Council_Regathers.cfg:144
@@ -1959,20 +1910,16 @@ msgstr "Agora, onde está o rubi com o qual eu vou trabalhar, hein, Durstorn?"
#. [message]: speaker=Durstorn
#: data/campaigns/Sceptre_of_Fire/scenarios/3t_The_Council_Regathers.cfg:148
msgid "Where I can keep an eye on it."
-msgstr ""
+msgstr "Num lugar bem seguro."
#. [message]: speaker=Durstorn
#: data/campaigns/Sceptre_of_Fire/scenarios/3t_The_Council_Regathers.cfg:161
-#, fuzzy
-#| msgid ""
-#| "In the treasury. And leave it there until you’re ready to work with it — "
-#| "I still don’t trust you."
msgid ""
"And leave it there until you’re ready to work with it — I still don’t trust "
"you."
msgstr ""
-"Na tesouraria. E deixe-o lá até que você esteja pronto para trabalhar com "
-"ele — Eu ainda não confio em você."
+"E ele vai ficar lá até que você esteja pronto para trabalhar com ele — Eu "
+"ainda não confio em você."
#. [message]: speaker=Thursagan
#: data/campaigns/Sceptre_of_Fire/scenarios/3t_The_Council_Regathers.cfg:165
@@ -1994,6 +1941,8 @@ msgid ""
"Hey, if you want me to work on this sceptre, you don’t dictate what I am to "
"do, Durstorn!"
msgstr ""
+"Ei, se você quer que eu trabalhe nestre cetro, não me diga o que fazer, "
+"Durstorn!"
#. [message]: speaker=Durstorn
#: data/campaigns/Sceptre_of_Fire/scenarios/3t_The_Council_Regathers.cfg:177
@@ -2002,16 +1951,12 @@ msgstr "O rubi é meu, não toque nele!"
#. [message]: speaker=Noiraran
#: data/campaigns/Sceptre_of_Fire/scenarios/3t_The_Council_Regathers.cfg:181
-#, fuzzy
-#| msgid ""
-#| "Uh, technically it’s Haldric’s, and I think that if Thursagan needs to "
-#| "see it to plan this sceptre, we must allow it."
msgid ""
"Uh, it belongs to King Haldric, my lord, and I think that if Thursagan needs "
"to see it to plan this sceptre, we must allow it."
msgstr ""
-"Uh, tecnicamente é de Haldric, e eu acho que se Thursagan precisa vê-lo para "
-"planejar o cetro, devemos permitir."
+"Uh, tecnicamente é do Rei Haldric, milorde, e eu acho que se Thursagan "
+"precisa vê-lo para planejar o cetro, devemos permitir."
#. [message]: speaker=Durstorn
#: data/campaigns/Sceptre_of_Fire/scenarios/3t_The_Council_Regathers.cfg:185
@@ -2019,6 +1964,8 @@ msgid ""
"Fine, so be it! Do what you have to, Thursagan, but don't try anything "
"sneaky..."
msgstr ""
+"Certo, que seja! Faça o que você precisar fazer, Thursagan, mas não dê uma "
+"de espertinho, se não..."
#. [message]: speaker=Thursagan
#: data/campaigns/Sceptre_of_Fire/scenarios/3t_The_Council_Regathers.cfg:194
@@ -2037,7 +1984,7 @@ msgstr "Agora, eu vou precisar de alguns materiais para fazer o cetro."
#. [message]: speaker=Durstorn
#: data/campaigns/Sceptre_of_Fire/scenarios/3t_The_Council_Regathers.cfg:208
msgid "And what would those be?"
-msgstr ""
+msgstr "Quais?"
#. [message]: speaker=Thursagan
#: data/campaigns/Sceptre_of_Fire/scenarios/3t_The_Council_Regathers.cfg:212
@@ -2093,18 +2040,13 @@ msgstr "Então, iremos para as minas orientais!"
#. [message]: speaker=Durstorn
#: data/campaigns/Sceptre_of_Fire/scenarios/3t_The_Council_Regathers.cfg:232
-#, fuzzy
-#| msgid ""
-#| "Fine. As for the jewels, I will have others obtain those. That will cost "
-#| "quite a bit of our payment, but it can’t be helped. Our people do not "
-#| "mine jewels."
msgid ""
"Fine. As for the crystals, I will have others obtain those. That will cost "
"quite a bit of our payment, but it can’t be helped. Our people do not mine "
"jewels."
msgstr ""
-"Certo. Quanto às jóias, vou pedir para outros obtê-las. Isso vai comer uma "
-"boa parte do nosso pagamente, mas quanto a isso não podemos fazer nada. "
+"Certo. Quanto aos cristais, vou pedir para outros obtê-los. Isso vai comer "
+"uma boa parte do nosso pagamente, mas não podemos fazer nada quanto a isso. "
"Nosso povo não minera jóias."
#. [message]: speaker=Thursagan
@@ -2179,17 +2121,17 @@ msgstr ""
#. [side]: type=Troll Warrior, type=Troll
#: data/campaigns/Sceptre_of_Fire/scenarios/4_Gathering_Materials.cfg:235
msgid "Resident Trolls"
-msgstr ""
+msgstr "Trolls Locais"
#. [side]: type=Troll Warrior, type=Troll
#: data/campaigns/Sceptre_of_Fire/scenarios/4_Gathering_Materials.cfg:262
msgid "Intruding Trolls"
-msgstr ""
+msgstr "Trolls Instrusos"
#. [side]: type=Direwolf Rider, type=Goblin Pillager
#: data/campaigns/Sceptre_of_Fire/scenarios/4_Gathering_Materials.cfg:291
msgid "Goblin Explorers"
-msgstr ""
+msgstr "Gónlins Exploradores"
#. [objective]: condition=win
#: data/campaigns/Sceptre_of_Fire/scenarios/4_Gathering_Materials.cfg:644
@@ -2374,17 +2316,13 @@ msgstr ""
#. [message]: speaker=Durstorn
#: data/campaigns/Sceptre_of_Fire/scenarios/4t_The_Jeweler.cfg:162
-#, fuzzy
-#| msgid "Oh... right, right. Fine. Theganli?"
msgid "Oh... right, right. Fine!"
-msgstr "Ah... certo, certo. Tudo bem. Theganli?"
+msgstr "Ah... certo, certo. Certo!"
#. [message]: speaker=Durstorn
#: data/campaigns/Sceptre_of_Fire/scenarios/4t_The_Jeweler.cfg:167
-#, fuzzy
-#| msgid "Theganli"
msgid "Theganli?"
-msgstr "Theganli"
+msgstr "Theganli?"
#. [message]: speaker=Kuhnar
#: data/campaigns/Sceptre_of_Fire/scenarios/4t_The_Jeweler.cfg:171
@@ -2411,10 +2349,8 @@ msgstr "Theganli"
#. [message]: speaker=Theganli
#: data/campaigns/Sceptre_of_Fire/scenarios/4t_The_Jeweler.cfg:193
-#, fuzzy
-#| msgid "I’m coming... coming... stop pounding on the door..."
msgid "Coming... coming... stop pounding on the door!"
-msgstr "Já vai... já vai... pare de bater na porta..."
+msgstr "Já vai... já vai... pare de bater na porta!"
#. [message]: speaker=Thursagan
#: data/campaigns/Sceptre_of_Fire/scenarios/4t_The_Jeweler.cfg:197
@@ -2427,10 +2363,8 @@ msgstr ""
#. [message]: speaker=Thursagan
#: data/campaigns/Sceptre_of_Fire/scenarios/4t_The_Jeweler.cfg:208
-#, fuzzy
-#| msgid "Well, Theganli, what do you think of this jewel?"
msgid "Well, Theganli, what do you think of this ruby?"
-msgstr "Bem, Theganli, o que você acha desta jóia?"
+msgstr "Bem, Theganli, o que você acha deste rubi?"
#. [message]: speaker=Theganli
#: data/campaigns/Sceptre_of_Fire/scenarios/4t_The_Jeweler.cfg:212
@@ -2447,10 +2381,8 @@ msgstr ""
#. [message]: speaker=Theganli
#: data/campaigns/Sceptre_of_Fire/scenarios/4t_The_Jeweler.cfg:220
-#, fuzzy
-#| msgid "Well, uh, um, maybe... maybe... it will be hard... let me see..."
msgid "Maybe... maybe... It will be hard, let me see..."
-msgstr "Bem, uh, hum, talvez... talvez... vai ser difícil... deixe-me ver..."
+msgstr "Talvez... talvez... vai ser difícil... deixe-me ver..."
#. [message]: speaker=Thursagan
#: data/campaigns/Sceptre_of_Fire/scenarios/4t_The_Jeweler.cfg:224
@@ -2500,10 +2432,8 @@ msgstr ""
#. [message]: speaker=Rugnur
#: data/campaigns/Sceptre_of_Fire/scenarios/4t_The_Jeweler.cfg:307
-#, fuzzy
-#| msgid "Who are they?"
msgid "Shorbear? Who are they?"
-msgstr "Quem são eles?"
+msgstr "Urso-Curto? Quem são eles?"
#. [message]: speaker=Theganli
#: data/campaigns/Sceptre_of_Fire/scenarios/4t_The_Jeweler.cfg:311
@@ -2541,17 +2471,13 @@ msgstr ""
#. [message]: speaker=Durstorn
#: data/campaigns/Sceptre_of_Fire/scenarios/4t_The_Jeweler.cfg:336
-#, fuzzy
-#| msgid "Fine. Go rent it from them."
msgid "Fine! Go rent it from them."
-msgstr "Tudo bem. Vá alugar as ferramentas deles."
+msgstr "Certo! Vá alugar as ferramentas deles."
#. [message]: speaker=Rugnur
#: data/campaigns/Sceptre_of_Fire/scenarios/4t_The_Jeweler.cfg:340
-#, fuzzy
-#| msgid "Very well. We’ll go south now."
msgid "Very well, sir. We’ll go south now."
-msgstr "Muito bem. Nós iremos para o sul agora."
+msgstr "Muito bem, senhor. Nós iremos para o sul agora."
#. [message]: speaker=Durstorn
#: data/campaigns/Sceptre_of_Fire/scenarios/4t_The_Jeweler.cfg:344
@@ -2569,16 +2495,13 @@ msgstr "Você tem certeza de que essa é uma boa ideia, milorde?"
#. [message]: speaker=Durstorn
#: data/campaigns/Sceptre_of_Fire/scenarios/4t_The_Jeweler.cfg:352
-#, fuzzy
-#| msgid ""
-#| "Of course! To be safe, though, you and Noiraran are going to come with us."
msgid "Of course it is! You and Noiraran are going to come with us!"
-msgstr "Claro! E, só para ter certeza, você e Noiraran também irão conosco."
+msgstr "Claro! Você e Noiraran também irão conosco!"
#. [message]: speaker=Kuhnar
#: data/campaigns/Sceptre_of_Fire/scenarios/4t_The_Jeweler.cfg:356
msgid "Yes sir..."
-msgstr ""
+msgstr "Sim senhor..."
#. [scenario]: id=5_Hills_of_the_Shorbear_Clan
#: data/campaigns/Sceptre_of_Fire/scenarios/5_Hills_of_the_Shorbear_Clan.cfg:3
@@ -2637,10 +2560,8 @@ msgstr "Morte de Durstorn"
#. [message]: speaker=Kuhnar
#: data/campaigns/Sceptre_of_Fire/scenarios/5_Hills_of_the_Shorbear_Clan.cfg:278
-#, fuzzy
-#| msgid "Hills of the Shorbear Clan"
msgid "Here we are! The hills of the Shorbear clan!"
-msgstr "Colinas do Clã Urso-Curto"
+msgstr "Aqui estamos nós! As Colinas do Clã Urso-Curto!"
#. [message]: speaker=Rugnur
#: data/campaigns/Sceptre_of_Fire/scenarios/5_Hills_of_the_Shorbear_Clan.cfg:282
@@ -2658,7 +2579,7 @@ msgstr ""
#. [message]: speaker=Thursagan
#: data/campaigns/Sceptre_of_Fire/scenarios/5_Hills_of_the_Shorbear_Clan.cfg:286
msgid "I could-"
-msgstr ""
+msgstr "Eu poderia-"
#. [message]: speaker=Durstorn
#: data/campaigns/Sceptre_of_Fire/scenarios/5_Hills_of_the_Shorbear_Clan.cfg:290
@@ -2814,7 +2735,7 @@ msgstr "Você está louco?!"
#. [message]: speaker=Durstorn
#: data/campaigns/Sceptre_of_Fire/scenarios/5_Hills_of_the_Shorbear_Clan.cfg:381
msgid "Of course not!"
-msgstr ""
+msgstr "Claro que não!"
#. [message]: speaker=Durstorn
#: data/campaigns/Sceptre_of_Fire/scenarios/5_Hills_of_the_Shorbear_Clan.cfg:385
@@ -2831,10 +2752,8 @@ msgstr ""
#. [message]: speaker=Glonoin
#: data/campaigns/Sceptre_of_Fire/scenarios/5_Hills_of_the_Shorbear_Clan.cfg:390
-#, fuzzy
-#| msgid "I’d like to see you try!"
msgid "Hah! I’d like to see you try!"
-msgstr "Eu gostaria de ver vocês tentarem!"
+msgstr "Hah! Eu gostaria de ver vocês tentarem!"
#. [message]: speaker=Thursagan
#: data/campaigns/Sceptre_of_Fire/scenarios/5_Hills_of_the_Shorbear_Clan.cfg:394
@@ -2849,13 +2768,13 @@ msgstr "Calem-se, todos vocês! Ataquem-nos!"
#. [message]: speaker=Rugnur
#: data/campaigns/Sceptre_of_Fire/scenarios/5_Hills_of_the_Shorbear_Clan.cfg:421
msgid "Look at him fly... If only we could move that fast."
-msgstr ""
+msgstr "Veja só como ele voa... se ao menos pudéssemos nos mover tão rápido."
#. [message]: speaker=Krawg
#: data/campaigns/Sceptre_of_Fire/scenarios/5_Hills_of_the_Shorbear_Clan.cfg:425
#: data/campaigns/Sceptre_of_Fire/scenarios/9_Caverns_of_Flame.cfg:1037
msgid "Krah!"
-msgstr ""
+msgstr "Krah!"
#. [message]: speaker=narrator
#: data/campaigns/Sceptre_of_Fire/scenarios/5_Hills_of_the_Shorbear_Clan.cfg:444
@@ -2915,10 +2834,8 @@ msgstr ""
#. [message]: speaker=Glildur
#: data/campaigns/Sceptre_of_Fire/scenarios/5_Hills_of_the_Shorbear_Clan.cfg:498
-#, fuzzy
-#| msgid "I see. So you don’t have the ruby?"
msgid "No reason? So you don’t have the ruby?"
-msgstr "Entendo. Então vocês não possuem o rubi?"
+msgstr "Sem nenhum motivo? Então vocês não possuem o rubi?"
#. [message]: speaker=Glonoin
#: data/campaigns/Sceptre_of_Fire/scenarios/5_Hills_of_the_Shorbear_Clan.cfg:502
@@ -3185,13 +3102,8 @@ msgstr ""
#. [message]: speaker=Rugnur
#: data/campaigns/Sceptre_of_Fire/scenarios/6_Towards_the_Caves.cfg:314
-#, fuzzy
-#| msgid ""
-#| "Yes, of course, let’s just all be cowards! What happened to your honor, "
-#| "Durstorn?!"
msgid "What happened to your honor, Durstorn?!"
-msgstr ""
-"Sim, claro, sejamos covardes! O que aconteceu com a sua honra, Durstorn?!"
+msgstr "O que aconteceu com a sua honra, Durstorn?!"
#. [message]: speaker=Durstorn
#: data/campaigns/Sceptre_of_Fire/scenarios/6_Towards_the_Caves.cfg:318
@@ -3272,10 +3184,8 @@ msgstr ""
#. [message]: speaker=Thursagan
#: data/campaigns/Sceptre_of_Fire/scenarios/6_Towards_the_Caves.cfg:422
-#, fuzzy
-#| msgid "Yes. So, see the area to the northeast of us?"
msgid "Yes. See the area to the northeast of us?"
-msgstr "Sim. Então, vê a área a nordeste de nós?"
+msgstr "Sim. Vê a área a nordeste de nós?"
#. [message]: speaker=Thursagan
#: data/campaigns/Sceptre_of_Fire/scenarios/6_Towards_the_Caves.cfg:439
@@ -3888,27 +3798,27 @@ msgstr "Cavernas de Chamas"
#. [time]: id=underground_SoF_volcano
#: data/campaigns/Sceptre_of_Fire/scenarios/9_Caverns_of_Flame.cfg:16
msgid "Underground"
-msgstr ""
+msgstr "Subterrâneo"
#. [unit]: id=Gathor, type=Orcish Warrior
#: data/campaigns/Sceptre_of_Fire/scenarios/9_Caverns_of_Flame.cfg:104
msgid "Bar'Gathor"
-msgstr ""
+msgstr "Bar'Gathor"
#. [side]: type=Troll Warrior, id=Harohk
#: data/campaigns/Sceptre_of_Fire/scenarios/9_Caverns_of_Flame.cfg:189
msgid "Harohk"
-msgstr ""
+msgstr "Harohk"
#. [unit]: id=Toomak, type=Troll Hero
#: data/campaigns/Sceptre_of_Fire/scenarios/9_Caverns_of_Flame.cfg:223
msgid "Toomak"
-msgstr ""
+msgstr "Harohk"
#. [side]
#: data/campaigns/Sceptre_of_Fire/scenarios/9_Caverns_of_Flame.cfg:243
msgid "Bats"
-msgstr ""
+msgstr "Morcegos"
#. [part]
#: data/campaigns/Sceptre_of_Fire/scenarios/9_Caverns_of_Flame.cfg:301
@@ -3972,7 +3882,7 @@ msgstr ""
#. [message]: speaker=Krawg
#: data/campaigns/Sceptre_of_Fire/scenarios/9_Caverns_of_Flame.cfg:636
msgid "Wha'?"
-msgstr ""
+msgstr "O qê?"
#. [message]: speaker=narrator
#: data/campaigns/Sceptre_of_Fire/scenarios/9_Caverns_of_Flame.cfg:640
@@ -4003,10 +3913,8 @@ msgstr ""
#. [message]: speaker=Krawg
#: data/campaigns/Sceptre_of_Fire/scenarios/9_Caverns_of_Flame.cfg:678
-#, fuzzy
-#| msgid "Krawg"
msgid "Krawg sad."
-msgstr "Krawg"
+msgstr "Krawg triste."
#. [message]: speaker=Thursagan
#: data/campaigns/Sceptre_of_Fire/scenarios/9_Caverns_of_Flame.cfg:682
@@ -4453,12 +4361,12 @@ msgstr ""
#. [message]: speaker=Krawg
#: data/campaigns/Sceptre_of_Fire/scenarios/Epilogue.cfg:198
msgid "Kraw! Lost!"
-msgstr ""
+msgstr "Kruá! Perdido!"
#. [message]: speaker=Haldric II
#: data/campaigns/Sceptre_of_Fire/scenarios/Epilogue.cfg:202
msgid "What the devil! I'm supposed to believe this?"
-msgstr ""
+msgstr "Mas o quê? E eu deveria acreditar nele?"
#. [message]: speaker=Alanin
#: data/campaigns/Sceptre_of_Fire/scenarios/Epilogue.cfg:206
@@ -4471,7 +4379,7 @@ msgstr ""
#. [message]: speaker=Krawg
#: data/campaigns/Sceptre_of_Fire/scenarios/Epilogue.cfg:210
msgid "Krah! Here!"
-msgstr ""
+msgstr "Krah! Aqui!"
#. [message]: speaker=narrator
#: data/campaigns/Sceptre_of_Fire/scenarios/Epilogue.cfg:214
@@ -4599,7 +4507,7 @@ msgstr ""
#. [attack]: type=impact
#: data/campaigns/Sceptre_of_Fire/units/Caravan.cfg:25
msgid "whip"
-msgstr ""
+msgstr "chicote"
#. [firststrike]: id=deterrentstrike
#: data/campaigns/Sceptre_of_Fire/units/Caravan.cfg:34
@@ -4646,10 +4554,8 @@ msgstr "Rei de Wesnoth."
#. [set_menu_item]: id=sof_minecart_boarding_{VAR}
#: data/campaigns/Sceptre_of_Fire/utils/cart-utils.cfg:221
-#, fuzzy
-#| msgid "Guard Captain"
msgid "Board Cart"
-msgstr "Capitão da Guarda"
+msgstr ""
#. [set_menu_item]: id=sof_minecart_unboarding_{VAR}
#: data/campaigns/Sceptre_of_Fire/utils/cart-utils.cfg:294
@@ -4682,12 +4588,12 @@ msgstr ""
#. [option]
#: data/campaigns/Sceptre_of_Fire/utils/rune-equip.cfg:289
msgid "Exit"
-msgstr ""
+msgstr "Sair"
#. [option]
#: data/campaigns/Sceptre_of_Fire/utils/rune-equip.cfg:290
msgid "Nothing for now."
-msgstr ""
+msgstr "Nada por enquanto."
#. [option]
#: data/campaigns/Sceptre_of_Fire/utils/rune-equip.cfg:297
@@ -4697,12 +4603,12 @@ msgstr ""
#. [option]
#: data/campaigns/Sceptre_of_Fire/utils/rune-equip.cfg:298
msgid "No thanks, don't ask again."
-msgstr ""
+msgstr "Não, obrigado, não pergunte novamente."
#. [option]
#: data/campaigns/Sceptre_of_Fire/utils/rune-equip.cfg:315
msgid "Adds 2 MP"
-msgstr ""
+msgstr "Adiciona 2 PdM"
#. [option]
#: data/campaigns/Sceptre_of_Fire/utils/rune-equip.cfg:315
@@ -4714,12 +4620,12 @@ msgstr ""
#: data/campaigns/Sceptre_of_Fire/utils/rune-equip.cfg:323
#: data/campaigns/Sceptre_of_Fire/utils/rune-equip.cfg:438
msgid "Accuracy"
-msgstr ""
+msgstr "Mira"
#. [option]
#: data/campaigns/Sceptre_of_Fire/utils/rune-equip.cfg:323
msgid "Increases ranged weapon accuracy 20%"
-msgstr ""
+msgstr "Aumenta a precisão de armas à distância em 20%"
#. [option]
#: data/campaigns/Sceptre_of_Fire/utils/rune-equip.cfg:332
@@ -4730,7 +4636,7 @@ msgstr ""
#. [option]
#: data/campaigns/Sceptre_of_Fire/utils/rune-equip.cfg:332
msgid "Increases melee weapon damage by 4"
-msgstr ""
+msgstr "Aumenta o dano de armas corpo-a-corpo em 2"
#. [message]: speaker=unit
#: data/campaigns/Sceptre_of_Fire/utils/rune-equip.cfg:378
@@ -4742,30 +4648,28 @@ msgstr ""
#. [option]
#: data/campaigns/Sceptre_of_Fire/utils/rune-equip.cfg:382
-#, fuzzy
-#| msgid "No."
msgid "No"
-msgstr "Não."
+msgstr "Não"
#. [option]
#: data/campaigns/Sceptre_of_Fire/utils/rune-equip.cfg:383
msgid "Not now."
-msgstr ""
+msgstr "Agora não."
#. [option]
#: data/campaigns/Sceptre_of_Fire/utils/rune-equip.cfg:400
msgid "Adds 1 MP"
-msgstr ""
+msgstr "Adiciona 1 PdM"
#. [option]
#: data/campaigns/Sceptre_of_Fire/utils/rune-equip.cfg:438
msgid "Increases ranged weapon accuracy 10%"
-msgstr ""
+msgstr "Aumenta a precisão de armas à distância em 10%"
#. [option]
#: data/campaigns/Sceptre_of_Fire/utils/rune-equip.cfg:477
msgid "Increases melee weapon damage by 2"
-msgstr ""
+msgstr "Aumenta o dano de armas corpo-a-corpo em 2"
#. [terrain_type]: id=sof_ancient_stone_floor
#: data/campaigns/Sceptre_of_Fire/utils/terrain.cfg:4
diff --git a/po/wesnoth-wc/pt_BR.po b/po/wesnoth-wc/pt_BR.po
index 41cd2e83e067..4ab0c9d7601a 100644
--- a/po/wesnoth-wc/pt_BR.po
+++ b/po/wesnoth-wc/pt_BR.po
@@ -3,7 +3,7 @@ msgstr ""
"Project-Id-Version: \n"
"Report-Msgid-Bugs-To: https://bugs.wesnoth.org/\n"
"POT-Creation-Date: 2021-01-16 14:18 UTC\n"
-"PO-Revision-Date: 2021-01-02 13:37-0300\n"
+"PO-Revision-Date: 2021-01-13 08:10-0300\n"
"Last-Translator: Andrei Machado <[email protected]>\n"
"Language-Team: none\n"
"Language: pt_BR\n"
@@ -3031,13 +3031,15 @@ msgstr ""
#: data/campaigns/World_Conquest/resources/strings/artifacts.cfg:202
msgid "Winter’s bloom"
-msgstr ""
+msgstr "Flor invernal"
#: data/campaigns/World_Conquest/resources/strings/artifacts.cfg:205
msgid ""
"This delicate blossom rarely found in snowy peaks, is strongly appreciated "
"for its beneficial effects on health."
msgstr ""
+"Uma delicada flor rara que é encontrada em picos nevados. É muito apreciada "
+"pelos seus efeitos benéficos para a saúde."
#: data/campaigns/World_Conquest/resources/strings/artifacts.cfg:208
msgid "Zephyr cloak"
@@ -3048,6 +3050,8 @@ msgid ""
"This lightweight cloak renders its wearer almost invisible in the darkness "
"and lets them move with fluid grace past enemies with ease."
msgstr ""
+"Este manto leve faz com que o seu usuário fique quase que completamente "
+"invisível nas trevas e mova-se com graça e fluidez por entre seus oponentes."
#: data/campaigns/World_Conquest/resources/strings/effects.cfg:4
msgid "staff of radiance"
@@ -3256,6 +3260,12 @@ msgid ""
"I’ll teach you how to break out of those dreary marching formations and step "
"light as a feather!"
msgstr ""
+"O que? Você quer que eu participe da batalha? Nem a pau, garotão! Sinto "
+"muito mas ficar na linha de frente não faz o meu estilo - não eixste drama, "
+"nem estilo e nem romance! Nem sutileza! Duvido que você entenda do que eu "
+"estou falando, então deixe-me lhe mostrar do que eu estou falando. Vou "
+"ensinar a vocês como sair dessas formações de marcha horríveis e se mover "
+"com a leveza de uma pluma!"
#: data/campaigns/World_Conquest/resources/strings/training.cfg:28
msgid "Combat Experience"
| 0
|
e272feaa8a3b84dfc4aa6df9e9cbefeabb4b16a5
|
https://github.com/rdesktop/rdesktop/commit/e272feaa8a3b84dfc4aa6df9e9cbefeabb4b16a5
|
Print the reason code for protocol errors
|
diff --git a/rdesktop.c b/rdesktop.c
index 895f4a41..d03ac044 100644
--- a/rdesktop.c
+++ b/rdesktop.c
@@ -390,18 +390,15 @@ handle_disconnect_reason(RD_BOOL deactivated, uint16 reason)
break;
default:
- if (reason > 0x1000 && reason < 0x7fff)
- {
- text = "Internal protocol error";
- }
- else
- {
- text = "Unknown reason";
- }
+ text = "Unknown reason";
retval = EXRD_UNKNOWN;
}
- if (reason != ERRINFO_NO_INFO)
+
+ if (reason > 0x1000 && reason < 0x7fff) {
+ fprintf(stderr, "Internal protocol error: %x", reason);
+ } else if (reason != ERRINFO_NO_INFO) {
fprintf(stderr, "disconnect: %s.\n", text);
+ }
return retval;
}
| 0
|
942e09b71eef5bd9fdb1c8711125c4bc1193bcdc
|
https://github.com/apache/hbase/commit/942e09b71eef5bd9fdb1c8711125c4bc1193bcdc
|
HBASE-13768 ZooKeeper znodes are bootstrapped with insecure ACLs in a secure configuration (Enis Soztutar)
|
diff --git a/hbase-client/src/main/java/org/apache/hadoop/hbase/zookeeper/RecoverableZooKeeper.java b/hbase-client/src/main/java/org/apache/hadoop/hbase/zookeeper/RecoverableZooKeeper.java
index b1b297c4c604..01124cafaffd 100644
--- a/hbase-client/src/main/java/org/apache/hadoop/hbase/zookeeper/RecoverableZooKeeper.java
+++ b/hbase-client/src/main/java/org/apache/hadoop/hbase/zookeeper/RecoverableZooKeeper.java
@@ -463,6 +463,70 @@ public Stat setData(String path, byte[] data, int version)
}
}
+ /**
+ * getAcl is an idempotent operation. Retry before throwing exception
+ * @return list of ACLs
+ */
+ public List<ACL> getAcl(String path, Stat stat)
+ throws KeeperException, InterruptedException {
+ TraceScope traceScope = null;
+ try {
+ traceScope = Trace.startSpan("RecoverableZookeeper.getAcl");
+ RetryCounter retryCounter = retryCounterFactory.create();
+ while (true) {
+ try {
+ return checkZk().getACL(path, stat);
+ } catch (KeeperException e) {
+ switch (e.code()) {
+ case CONNECTIONLOSS:
+ case SESSIONEXPIRED:
+ case OPERATIONTIMEOUT:
+ retryOrThrow(retryCounter, e, "getAcl");
+ break;
+
+ default:
+ throw e;
+ }
+ }
+ retryCounter.sleepUntilNextRetry();
+ }
+ } finally {
+ if (traceScope != null) traceScope.close();
+ }
+ }
+
+ /**
+ * setAcl is an idempotent operation. Retry before throwing exception
+ * @return list of ACLs
+ */
+ public Stat setAcl(String path, List<ACL> acls, int version)
+ throws KeeperException, InterruptedException {
+ TraceScope traceScope = null;
+ try {
+ traceScope = Trace.startSpan("RecoverableZookeeper.setAcl");
+ RetryCounter retryCounter = retryCounterFactory.create();
+ while (true) {
+ try {
+ return checkZk().setACL(path, acls, version);
+ } catch (KeeperException e) {
+ switch (e.code()) {
+ case CONNECTIONLOSS:
+ case SESSIONEXPIRED:
+ case OPERATIONTIMEOUT:
+ retryOrThrow(retryCounter, e, "setAcl");
+ break;
+
+ default:
+ throw e;
+ }
+ }
+ retryCounter.sleepUntilNextRetry();
+ }
+ } finally {
+ if (traceScope != null) traceScope.close();
+ }
+ }
+
/**
* <p>
* NONSEQUENTIAL create is idempotent operation.
diff --git a/hbase-client/src/main/java/org/apache/hadoop/hbase/zookeeper/ZKUtil.java b/hbase-client/src/main/java/org/apache/hadoop/hbase/zookeeper/ZKUtil.java
index 16357c1ed2e5..1575d55d7897 100644
--- a/hbase-client/src/main/java/org/apache/hadoop/hbase/zookeeper/ZKUtil.java
+++ b/hbase-client/src/main/java/org/apache/hadoop/hbase/zookeeper/ZKUtil.java
@@ -999,7 +999,11 @@ public static boolean isSecureZooKeeper(Configuration conf) {
try {
javax.security.auth.login.Configuration testConfig =
javax.security.auth.login.Configuration.getConfiguration();
- if(testConfig.getAppConfigurationEntry("Client") == null) {
+ if (testConfig.getAppConfigurationEntry("Client") == null
+ && testConfig.getAppConfigurationEntry(
+ JaasConfiguration.CLIENT_KEYTAB_KERBEROS_CONFIG_NAME) == null
+ && testConfig.getAppConfigurationEntry(
+ JaasConfiguration.SERVER_KEYTAB_KERBEROS_CONFIG_NAME) == null) {
return false;
}
} catch(Exception e) {
@@ -1008,16 +1012,15 @@ public static boolean isSecureZooKeeper(Configuration conf) {
}
// Master & RSs uses hbase.zookeeper.client.*
- return("kerberos".equalsIgnoreCase(conf.get("hbase.security.authentication")) &&
- conf.get("hbase.zookeeper.client.keytab.file") != null);
+ return "kerberos".equalsIgnoreCase(conf.get("hbase.security.authentication"));
}
private static ArrayList<ACL> createACL(ZooKeeperWatcher zkw, String node) {
return createACL(zkw, node, isSecureZooKeeper(zkw.getConfiguration()));
}
- protected static ArrayList<ACL> createACL(ZooKeeperWatcher zkw, String node,
- boolean isSecureZooKeeper) {
+ public static ArrayList<ACL> createACL(ZooKeeperWatcher zkw, String node,
+ boolean isSecureZooKeeper) {
if (!node.startsWith(zkw.baseZNode)) {
return Ids.OPEN_ACL_UNSAFE;
}
@@ -1030,13 +1033,7 @@ public static boolean isSecureZooKeeper(Configuration conf) {
}
// Certain znodes are accessed directly by the client,
// so they must be readable by non-authenticated clients
- if ((node.equals(zkw.baseZNode) == true) ||
- (zkw.isAnyMetaReplicaZnode(node)) ||
- (node.equals(zkw.getMasterAddressZNode()) == true) ||
- (node.equals(zkw.clusterIdZNode) == true) ||
- (node.equals(zkw.rsZNode) == true) ||
- (node.equals(zkw.backupMasterAddressesZNode) == true) ||
- (node.startsWith(zkw.tableZNode) == true)) {
+ if (zkw.isClientReadable(node)) {
acls.addAll(Ids.CREATOR_ALL_ACL);
acls.addAll(Ids.READ_ACL_UNSAFE);
} else {
diff --git a/hbase-client/src/main/java/org/apache/hadoop/hbase/zookeeper/ZooKeeperWatcher.java b/hbase-client/src/main/java/org/apache/hadoop/hbase/zookeeper/ZooKeeperWatcher.java
index b428d98d3580..d26874a17291 100644
--- a/hbase-client/src/main/java/org/apache/hadoop/hbase/zookeeper/ZooKeeperWatcher.java
+++ b/hbase-client/src/main/java/org/apache/hadoop/hbase/zookeeper/ZooKeeperWatcher.java
@@ -21,7 +21,6 @@
import java.io.Closeable;
import java.io.IOException;
import java.util.ArrayList;
-import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
@@ -36,11 +35,15 @@
import org.apache.hadoop.hbase.HRegionInfo;
import org.apache.hadoop.hbase.ZooKeeperConnectionException;
import org.apache.hadoop.hbase.classification.InterfaceAudience;
+import org.apache.hadoop.security.UserGroupInformation;
import org.apache.zookeeper.KeeperException;
import org.apache.zookeeper.WatchedEvent;
import org.apache.zookeeper.Watcher;
-import org.apache.zookeeper.ZooDefs;
+import org.apache.zookeeper.ZooDefs.Ids;
+import org.apache.zookeeper.ZooDefs.Perms;
import org.apache.zookeeper.data.ACL;
+import org.apache.zookeeper.data.Id;
+import org.apache.zookeeper.data.Stat;
/**
* Acts as the single ZooKeeper Watcher. One instance of this is instantiated
@@ -183,6 +186,109 @@ private void createBaseZNodes() throws ZooKeeperConnectionException {
}
}
+ /** Returns whether the znode is supposed to be readable by the client
+ * and DOES NOT contain sensitive information (world readable).*/
+ public boolean isClientReadable(String node) {
+ // Developer notice: These znodes are world readable. DO NOT add more znodes here UNLESS
+ // all clients need to access this data to work. Using zk for sharing data to clients (other
+ // than service lookup case is not a recommended design pattern.
+ return
+ node.equals(baseZNode) ||
+ isAnyMetaReplicaZnode(node) ||
+ node.equals(getMasterAddressZNode()) ||
+ node.equals(clusterIdZNode)||
+ node.equals(rsZNode) ||
+ // /hbase/table and /hbase/table/foo is allowed, /hbase/table-lock is not
+ node.equals(tableZNode) ||
+ node.startsWith(tableZNode + "/");
+ }
+
+ /**
+ * On master start, we check the znode ACLs under the root directory and set the ACLs properly
+ * if needed. If the cluster goes from an unsecure setup to a secure setup, this step is needed
+ * so that the existing znodes created with open permissions are now changed with restrictive
+ * perms.
+ */
+ public void checkAndSetZNodeAcls() {
+ if (!ZKUtil.isSecureZooKeeper(getConfiguration())) {
+ return;
+ }
+
+ // Check the base znodes permission first. Only do the recursion if base znode's perms are not
+ // correct.
+ try {
+ List<ACL> actualAcls = recoverableZooKeeper.getAcl(baseZNode, new Stat());
+
+ if (!isBaseZnodeAclSetup(actualAcls)) {
+ LOG.info("setting znode ACLs");
+ setZnodeAclsRecursive(baseZNode);
+ }
+ } catch(KeeperException.NoNodeException nne) {
+ return;
+ } catch(InterruptedException ie) {
+ interruptedException(ie);
+ } catch (IOException|KeeperException e) {
+ LOG.warn("Received exception while checking and setting zookeeper ACLs", e);
+ }
+ }
+
+ /**
+ * Set the znode perms recursively. This will do post-order recursion, so that baseZnode ACLs
+ * will be set last in case the master fails in between.
+ * @param znode
+ */
+ private void setZnodeAclsRecursive(String znode) throws KeeperException, InterruptedException {
+ List<String> children = recoverableZooKeeper.getChildren(znode, false);
+
+ for (String child : children) {
+ setZnodeAclsRecursive(ZKUtil.joinZNode(znode, child));
+ }
+ List<ACL> acls = ZKUtil.createACL(this, znode, true);
+ LOG.info("Setting ACLs for znode:" + znode + " , acl:" + acls);
+ recoverableZooKeeper.setAcl(znode, acls, -1);
+ }
+
+ /**
+ * Checks whether the ACLs returned from the base znode (/hbase) is set for secure setup.
+ * @param acls acls from zookeeper
+ * @return whether ACLs are set for the base znode
+ * @throws IOException
+ */
+ private boolean isBaseZnodeAclSetup(List<ACL> acls) throws IOException {
+ String superUser = conf.get("hbase.superuser");
+
+ // this assumes that current authenticated user is the same as zookeeper client user
+ // configured via JAAS
+ String hbaseUser = UserGroupInformation.getCurrentUser().getShortUserName();
+
+ if (acls.isEmpty()) {
+ return false;
+ }
+
+ for (ACL acl : acls) {
+ int perms = acl.getPerms();
+ Id id = acl.getId();
+ // We should only set at most 3 possible ACLs for 3 Ids. One for everyone, one for superuser
+ // and one for the hbase user
+ if (Ids.ANYONE_ID_UNSAFE.equals(id)) {
+ if (perms != Perms.READ) {
+ return false;
+ }
+ } else if (superUser != null && new Id("sasl", superUser).equals(id)) {
+ if (perms != Perms.ALL) {
+ return false;
+ }
+ } else if (new Id("sasl", hbaseUser).equals(id)) {
+ if (perms != Perms.ALL) {
+ return false;
+ }
+ } else {
+ return false;
+ }
+ }
+ return true;
+ }
+
@Override
public String toString() {
return this.identifier + ", quorum=" + quorum + ", baseZNode=" + baseZNode;
@@ -304,7 +410,7 @@ public int getMetaReplicaIdFromZnode(String znode) {
String pattern = conf.get("zookeeper.znode.metaserver","meta-region-server");
if (znode.equals(pattern)) return HRegionInfo.DEFAULT_REPLICA_ID;
// the non-default replicas are of the pattern meta-region-server-<replicaId>
- String nonDefaultPattern = pattern + "-";
+ String nonDefaultPattern = pattern + "-";
return Integer.parseInt(znode.substring(nonDefaultPattern.length()));
}
@@ -552,6 +658,7 @@ public void interruptedException(InterruptedException ie) {
*
* @throws InterruptedException
*/
+ @Override
public void close() {
try {
if (recoverableZooKeeper != null) {
diff --git a/hbase-client/src/test/java/org/apache/hadoop/hbase/zookeeper/TestZooKeeperWatcher.java b/hbase-client/src/test/java/org/apache/hadoop/hbase/zookeeper/TestZooKeeperWatcher.java
new file mode 100644
index 000000000000..29ea259426aa
--- /dev/null
+++ b/hbase-client/src/test/java/org/apache/hadoop/hbase/zookeeper/TestZooKeeperWatcher.java
@@ -0,0 +1,59 @@
+/**
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package org.apache.hadoop.hbase.zookeeper;
+
+import static org.junit.Assert.*;
+
+import java.io.IOException;
+
+import org.apache.hadoop.hbase.HBaseConfiguration;
+import org.apache.hadoop.hbase.ZooKeeperConnectionException;
+import org.apache.hadoop.hbase.testclassification.SmallTests;
+import org.junit.Test;
+import org.junit.experimental.categories.Category;
+
+@Category({SmallTests.class})
+public class TestZooKeeperWatcher {
+
+ @Test
+ public void testIsClientReadable() throws ZooKeeperConnectionException, IOException {
+ ZooKeeperWatcher watcher = new ZooKeeperWatcher(HBaseConfiguration.create(),
+ "testIsClientReadable", null, false);
+
+ assertTrue(watcher.isClientReadable(watcher.baseZNode));
+ assertTrue(watcher.isClientReadable(watcher.getZNodeForReplica(0)));
+ assertTrue(watcher.isClientReadable(watcher.getMasterAddressZNode()));
+ assertTrue(watcher.isClientReadable(watcher.clusterIdZNode));
+ assertTrue(watcher.isClientReadable(watcher.tableZNode));
+ assertTrue(watcher.isClientReadable(ZKUtil.joinZNode(watcher.tableZNode, "foo")));
+ assertTrue(watcher.isClientReadable(watcher.rsZNode));
+
+
+ assertFalse(watcher.isClientReadable(watcher.tableLockZNode));
+ assertFalse(watcher.isClientReadable(watcher.balancerZNode));
+ assertFalse(watcher.isClientReadable(watcher.clusterStateZNode));
+ assertFalse(watcher.isClientReadable(watcher.drainingZNode));
+ assertFalse(watcher.isClientReadable(watcher.recoveringRegionsZNode));
+ assertFalse(watcher.isClientReadable(watcher.splitLogZNode));
+ assertFalse(watcher.isClientReadable(watcher.backupMasterAddressesZNode));
+
+ watcher.close();
+ }
+
+}
diff --git a/hbase-it/src/test/java/org/apache/hadoop/hbase/test/IntegrationTestZKAndFSPermissions.java b/hbase-it/src/test/java/org/apache/hadoop/hbase/test/IntegrationTestZKAndFSPermissions.java
new file mode 100644
index 000000000000..c39056dd3e9f
--- /dev/null
+++ b/hbase-it/src/test/java/org/apache/hadoop/hbase/test/IntegrationTestZKAndFSPermissions.java
@@ -0,0 +1,232 @@
+/**
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package org.apache.hadoop.hbase.test;
+
+import static org.junit.Assert.assertEquals;
+import static org.junit.Assert.assertTrue;
+import static org.junit.Assert.fail;
+
+import java.io.IOException;
+import java.util.List;
+
+import org.apache.commons.cli.CommandLine;
+import org.apache.commons.logging.Log;
+import org.apache.commons.logging.LogFactory;
+import org.apache.hadoop.conf.Configuration;
+import org.apache.hadoop.fs.FileSystem;
+import org.apache.hadoop.fs.Path;
+import org.apache.hadoop.fs.permission.FsPermission;
+import org.apache.hadoop.hbase.HBaseConfiguration;
+import org.apache.hadoop.hbase.IntegrationTestingUtility;
+import org.apache.hadoop.hbase.testclassification.IntegrationTests;
+import org.apache.hadoop.hbase.util.AbstractHBaseTool;
+import org.apache.hadoop.hbase.util.FSUtils;
+import org.apache.hadoop.hbase.zookeeper.RecoverableZooKeeper;
+import org.apache.hadoop.hbase.zookeeper.ZKUtil;
+import org.apache.hadoop.hbase.zookeeper.ZooKeeperWatcher;
+import org.apache.hadoop.util.ToolRunner;
+import org.apache.zookeeper.KeeperException;
+import org.apache.zookeeper.KeeperException.Code;
+import org.apache.zookeeper.ZooDefs.Ids;
+import org.apache.zookeeper.ZooDefs.Perms;
+import org.apache.zookeeper.data.ACL;
+import org.apache.zookeeper.data.Id;
+import org.apache.zookeeper.data.Stat;
+import org.junit.experimental.categories.Category;
+
+/**
+ * An integration test which checks that the znodes in zookeeper and data in the FileSystem
+ * are protected for secure HBase deployments.
+ * This test is intended to be run on clusters with kerberos authorization for HBase and Zookeeper.
+ *
+ * If hbase.security.authentication is not set to kerberos, the test does not run unless -f is
+ * specified which bypasses the check. It is recommended to always run with -f on secure clusters
+ * so that the test checks the actual end result, not the configuration.
+ *
+ * The test should be run as hbase user with kinit / TGT cached since it accesses HDFS.
+ * <p>
+ * Example usage:
+ * hbase org.apache.hadoop.hbase.test.IntegrationTestZnodeACLs -h
+ */
+@Category(IntegrationTests.class)
+public class IntegrationTestZKAndFSPermissions extends AbstractHBaseTool {
+
+ private static final Log LOG = LogFactory.getLog(IntegrationTestZKAndFSPermissions.class);
+ private String superUser;
+ private String masterPrincipal;
+ private boolean isForce;
+ private String fsPerms;
+ private boolean skipFSCheck;
+ private boolean skipZKCheck;
+
+ public static final String FORCE_CHECK_ARG = "f";
+ public static final String PRINCIPAL_ARG = "p";
+ public static final String SUPERUSER_ARG = "s";
+ public static final String FS_PERMS = "fs_perms";
+ public static final String SKIP_CHECK_FS = "skip_fs_check";
+ public static final String SKIP_CHECK_ZK = "skip_zk_check";
+
+ @Override
+ public void setConf(Configuration conf) {
+ super.setConf(conf);
+ }
+
+ @Override
+ protected void addOptions() {
+ addOptNoArg(FORCE_CHECK_ARG, "Whether to skip configuration lookup and assume a secure setup");
+ addOptWithArg(PRINCIPAL_ARG, "The principal for zk authorization");
+ addOptWithArg(SUPERUSER_ARG, "The principal for super user");
+ addOptWithArg(FS_PERMS, "FS permissions, ex. 700, 750, etc. Defaults to 700");
+ addOptNoArg(SKIP_CHECK_FS, "Whether to skip checking FS permissions");
+ addOptNoArg(SKIP_CHECK_ZK, "Whether to skip checking ZK permissions");
+ }
+
+ @Override
+ protected void processOptions(CommandLine cmd) {
+ isForce = cmd.hasOption(FORCE_CHECK_ARG);
+ masterPrincipal = getShortUserName(conf.get("hbase.master.kerberos.principal"));
+ superUser = cmd.getOptionValue(SUPERUSER_ARG, conf.get("hbase.superuser"));
+ masterPrincipal = cmd.getOptionValue(PRINCIPAL_ARG, masterPrincipal);
+ fsPerms = cmd.getOptionValue(FS_PERMS, "700");
+ skipFSCheck = cmd.hasOption(SKIP_CHECK_FS);
+ skipZKCheck = cmd.hasOption(SKIP_CHECK_ZK);
+ }
+
+ private String getShortUserName(String principal) {
+ for (int i = 0; i < principal.length(); i++) {
+ if (principal.charAt(i) == '/' || principal.charAt(i) == '@') {
+ return principal.substring(0, i);
+ }
+ }
+ return principal;
+ }
+
+ @Override
+ protected int doWork() throws Exception {
+ if (!isForce) {
+ if (!"kerberos".equalsIgnoreCase(conf.get("hbase.security.authentication"))) {
+ LOG.warn("hbase.security.authentication is not kerberos, and -f is not supplied. Skip "
+ + "running the test");
+ return 0;
+ }
+ }
+
+ if (!skipZKCheck) {
+ testZNodeACLs();
+ } if (!skipFSCheck) {
+ testFSPerms();
+ }
+ return 0;
+ }
+
+ private void testZNodeACLs() throws IOException, KeeperException, InterruptedException {
+
+ ZooKeeperWatcher watcher = new ZooKeeperWatcher(conf, "IntegrationTestZnodeACLs", null);
+ RecoverableZooKeeper zk = ZKUtil.connect(this.conf, watcher);
+
+ String baseZNode = watcher.baseZNode;
+
+ LOG.info("");
+ LOG.info("***********************************************************************************");
+ LOG.info("Checking ZK permissions, root znode: " + baseZNode);
+ LOG.info("***********************************************************************************");
+ LOG.info("");
+
+ checkZnodePermsRecursive(watcher, zk, baseZNode);
+
+ LOG.info("Checking ZK permissions: SUCCESS");
+ }
+
+ private void checkZnodePermsRecursive(ZooKeeperWatcher watcher,
+ RecoverableZooKeeper zk, String znode) throws KeeperException, InterruptedException {
+
+ boolean expectedWorldReadable = watcher.isClientReadable(znode);
+
+ assertZnodePerms(zk, znode, expectedWorldReadable);
+
+ try {
+ List<String> children = zk.getChildren(znode, false);
+
+ for (String child : children) {
+ checkZnodePermsRecursive(watcher, zk, ZKUtil.joinZNode(znode, child));
+ }
+ } catch (KeeperException ke) {
+ // if we are not authenticated for listChildren, it is fine.
+ if (ke.code() != Code.NOAUTH) {
+ throw ke;
+ }
+ }
+ }
+
+ private void assertZnodePerms(RecoverableZooKeeper zk, String znode,
+ boolean expectedWorldReadable) throws KeeperException, InterruptedException {
+ Stat stat = new Stat();
+ List<ACL> acls = zk.getZooKeeper().getACL(znode, stat);
+
+ LOG.info("Checking ACLs for znode znode:" + znode + " acls:" + acls);
+
+ for (ACL acl : acls) {
+ int perms = acl.getPerms();
+ Id id = acl.getId();
+ // We should only set at most 3 possible ACL for 3 Ids. One for everyone, one for superuser
+ // and one for the hbase user
+ if (Ids.ANYONE_ID_UNSAFE.equals(id)) {
+ // everyone should be set only if we are expecting this znode to be world readable
+ assertTrue(expectedWorldReadable);
+ // assert that anyone can only read
+ assertEquals(perms, Perms.READ);
+ } else if (superUser != null && new Id("sasl", superUser).equals(id)) {
+ // assert that super user has all the permissions
+ assertEquals(perms, Perms.ALL);
+ } else if (new Id("sasl", masterPrincipal).equals(id)) {
+ // hbase.master.kerberos.principal?
+ assertEquals(perms, Perms.ALL);
+ } else {
+ fail("An ACL is found which is not expected for the znode:" + znode + " , ACL:" + acl);
+ }
+ }
+ }
+
+ private void testFSPerms() throws IOException {
+ Path rootDir = FSUtils.getRootDir(conf);
+
+ LOG.info("");
+ LOG.info("***********************************************************************************");
+ LOG.info("Checking FS permissions for root dir:" + rootDir);
+ LOG.info("***********************************************************************************");
+ LOG.info("");
+ FileSystem fs = rootDir.getFileSystem(conf);
+
+ short expectedPerms = Short.valueOf(fsPerms, 8);
+
+ assertEquals(
+ FsPermission.createImmutable(expectedPerms),
+ fs.getFileStatus(rootDir).getPermission());
+
+ LOG.info("Checking FS permissions: SUCCESS");
+ }
+
+ public static void main(String[] args) throws Exception {
+ Configuration configuration = HBaseConfiguration.create();
+ IntegrationTestingUtility.setUseDistributedCluster(configuration);
+ IntegrationTestZKAndFSPermissions tool = new IntegrationTestZKAndFSPermissions();
+ int ret = ToolRunner.run(configuration, tool, args);
+ System.exit(ret);
+ }
+}
diff --git a/hbase-server/src/main/java/org/apache/hadoop/hbase/master/HMaster.java b/hbase-server/src/main/java/org/apache/hadoop/hbase/master/HMaster.java
index ced669955132..be11acac9e55 100644
--- a/hbase-server/src/main/java/org/apache/hadoop/hbase/master/HMaster.java
+++ b/hbase-server/src/main/java/org/apache/hadoop/hbase/master/HMaster.java
@@ -781,6 +781,11 @@ private void finishActiveMasterInitialization(MonitoredTask status)
// master initialization. See HBASE-5916.
this.serverManager.clearDeadServersWithSameHostNameAndPortOfOnlineServer();
+ // Check and set the znode ACLs if needed in case we are overtaking a non-secure configuration
+ status.setStatus("Checking ZNode ACLs");
+ zooKeeper.checkAndSetZNodeAcls();
+
+ status.setStatus("Calling postStartMaster coprocessors");
if (this.cpHost != null) {
// don't let cp initialization errors kill the master
try {
| 1
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.