func_before,func_after,commit_msg,commit_url,cve_id,cwe_id,file_name,vulnerability_score,extension,is_test,date "@Override public void init(Context context, IWindowManager windowManager, WindowManagerFuncs windowManagerFuncs) { mContext = context; mWindowManager = windowManager; mWindowManagerFuncs = windowManagerFuncs; mWindowManagerInternal = LocalServices.getService(WindowManagerInternal.class); mActivityManagerInternal = LocalServices.getService(ActivityManagerInternal.class); mActivityTaskManagerInternal = LocalServices.getService(ActivityTaskManagerInternal.class); mInputManagerInternal = LocalServices.getService(InputManagerInternal.class); mDreamManagerInternal = LocalServices.getService(DreamManagerInternal.class); mPowerManagerInternal = LocalServices.getService(PowerManagerInternal.class); mAppOpsManager = mContext.getSystemService(AppOpsManager.class); mDisplayManager = mContext.getSystemService(DisplayManager.class); mDisplayManagerInternal = LocalServices.getService(DisplayManagerInternal.class); mPackageManager = mContext.getPackageManager(); mHasFeatureWatch = mPackageManager.hasSystemFeature(FEATURE_WATCH); mHasFeatureLeanback = mPackageManager.hasSystemFeature(FEATURE_LEANBACK); mHasFeatureAuto = mPackageManager.hasSystemFeature(FEATURE_AUTOMOTIVE); mHasFeatureHdmiCec = mPackageManager.hasSystemFeature(FEATURE_HDMI_CEC); mAccessibilityShortcutController = new AccessibilityShortcutController(mContext, new Handler(), mCurrentUserId); mLogger = new MetricsLogger(); mScreenOffSleepTokenAcquirer = mActivityTaskManagerInternal .createSleepTokenAcquirer(""ScreenOff""); Resources res = mContext.getResources(); mWakeOnDpadKeyPress = res.getBoolean(com.android.internal.R.bool.config_wakeOnDpadKeyPress); mWakeOnAssistKeyPress = res.getBoolean(com.android.internal.R.bool.config_wakeOnAssistKeyPress); mWakeOnBackKeyPress = res.getBoolean(com.android.internal.R.bool.config_wakeOnBackKeyPress); // Init display burn-in protection boolean burnInProtectionEnabled = context.getResources().getBoolean( com.android.internal.R.bool.config_enableBurnInProtection); // Allow a system property to override this. Used by developer settings. boolean burnInProtectionDevMode = SystemProperties.getBoolean(""persist.debug.force_burn_in"", false); if (burnInProtectionEnabled || burnInProtectionDevMode) { final int minHorizontal; final int maxHorizontal; final int minVertical; final int maxVertical; final int maxRadius; if (burnInProtectionDevMode) { minHorizontal = -8; maxHorizontal = 8; minVertical = -8; maxVertical = -4; maxRadius = (isRoundWindow()) ? 6 : -1; } else { Resources resources = context.getResources(); minHorizontal = resources.getInteger( com.android.internal.R.integer.config_burnInProtectionMinHorizontalOffset); maxHorizontal = resources.getInteger( com.android.internal.R.integer.config_burnInProtectionMaxHorizontalOffset); minVertical = resources.getInteger( com.android.internal.R.integer.config_burnInProtectionMinVerticalOffset); maxVertical = resources.getInteger( com.android.internal.R.integer.config_burnInProtectionMaxVerticalOffset); maxRadius = resources.getInteger( com.android.internal.R.integer.config_burnInProtectionMaxRadius); } mBurnInProtectionHelper = new BurnInProtectionHelper( context, minHorizontal, maxHorizontal, minVertical, maxVertical, maxRadius); } mHandler = new PolicyHandler(); mWakeGestureListener = new MyWakeGestureListener(mContext, mHandler); mSettingsObserver = new SettingsObserver(mHandler); mSettingsObserver.observe(); mModifierShortcutManager = new ModifierShortcutManager(context); mUiMode = context.getResources().getInteger( com.android.internal.R.integer.config_defaultUiModeType); mHomeIntent = new Intent(Intent.ACTION_MAIN, null); mHomeIntent.addCategory(Intent.CATEGORY_HOME); mHomeIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_RESET_TASK_IF_NEEDED); mEnableCarDockHomeCapture = context.getResources().getBoolean( com.android.internal.R.bool.config_enableCarDockHomeLaunch); mCarDockIntent = new Intent(Intent.ACTION_MAIN, null); mCarDockIntent.addCategory(Intent.CATEGORY_CAR_DOCK); mCarDockIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_RESET_TASK_IF_NEEDED); mDeskDockIntent = new Intent(Intent.ACTION_MAIN, null); mDeskDockIntent.addCategory(Intent.CATEGORY_DESK_DOCK); mDeskDockIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_RESET_TASK_IF_NEEDED); mVrHeadsetHomeIntent = new Intent(Intent.ACTION_MAIN, null); mVrHeadsetHomeIntent.addCategory(Intent.CATEGORY_VR_HOME); mVrHeadsetHomeIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_RESET_TASK_IF_NEEDED); mPowerManager = (PowerManager)context.getSystemService(Context.POWER_SERVICE); mBroadcastWakeLock = mPowerManager.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, ""PhoneWindowManager.mBroadcastWakeLock""); mPowerKeyWakeLock = mPowerManager.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, ""PhoneWindowManager.mPowerKeyWakeLock""); mEnableShiftMenuBugReports = ""1"".equals(SystemProperties.get(""ro.debuggable"")); mLidKeyboardAccessibility = mContext.getResources().getInteger( com.android.internal.R.integer.config_lidKeyboardAccessibility); mLidNavigationAccessibility = mContext.getResources().getInteger( com.android.internal.R.integer.config_lidNavigationAccessibility); mAllowTheaterModeWakeFromKey = mContext.getResources().getBoolean( com.android.internal.R.bool.config_allowTheaterModeWakeFromKey); mAllowTheaterModeWakeFromPowerKey = mAllowTheaterModeWakeFromKey || mContext.getResources().getBoolean( com.android.internal.R.bool.config_allowTheaterModeWakeFromPowerKey); mAllowTheaterModeWakeFromMotion = mContext.getResources().getBoolean( com.android.internal.R.bool.config_allowTheaterModeWakeFromMotion); mAllowTheaterModeWakeFromMotionWhenNotDreaming = mContext.getResources().getBoolean( com.android.internal.R.bool.config_allowTheaterModeWakeFromMotionWhenNotDreaming); mAllowTheaterModeWakeFromCameraLens = mContext.getResources().getBoolean( com.android.internal.R.bool.config_allowTheaterModeWakeFromCameraLens); mAllowTheaterModeWakeFromLidSwitch = mContext.getResources().getBoolean( com.android.internal.R.bool.config_allowTheaterModeWakeFromLidSwitch); mAllowTheaterModeWakeFromWakeGesture = mContext.getResources().getBoolean( com.android.internal.R.bool.config_allowTheaterModeWakeFromGesture); mGoToSleepOnButtonPressTheaterMode = mContext.getResources().getBoolean( com.android.internal.R.bool.config_goToSleepOnButtonPressTheaterMode); mSupportLongPressPowerWhenNonInteractive = mContext.getResources().getBoolean( com.android.internal.R.bool.config_supportLongPressPowerWhenNonInteractive); mLongPressOnBackBehavior = mContext.getResources().getInteger( com.android.internal.R.integer.config_longPressOnBackBehavior); mShortPressOnPowerBehavior = mContext.getResources().getInteger( com.android.internal.R.integer.config_shortPressOnPowerBehavior); mLongPressOnPowerBehavior = mContext.getResources().getInteger( com.android.internal.R.integer.config_longPressOnPowerBehavior); mLongPressOnPowerAssistantTimeoutMs = mContext.getResources().getInteger( com.android.internal.R.integer.config_longPressOnPowerDurationMs); mVeryLongPressOnPowerBehavior = mContext.getResources().getInteger( com.android.internal.R.integer.config_veryLongPressOnPowerBehavior); mDoublePressOnPowerBehavior = mContext.getResources().getInteger( com.android.internal.R.integer.config_doublePressOnPowerBehavior); mPowerDoublePressTargetActivity = ComponentName.unflattenFromString( mContext.getResources().getString( com.android.internal.R.string.config_doublePressOnPowerTargetActivity)); mTriplePressOnPowerBehavior = mContext.getResources().getInteger( com.android.internal.R.integer.config_triplePressOnPowerBehavior); mShortPressOnSleepBehavior = mContext.getResources().getInteger( com.android.internal.R.integer.config_shortPressOnSleepBehavior); mAllowStartActivityForLongPressOnPowerDuringSetup = mContext.getResources().getBoolean( com.android.internal.R.bool.config_allowStartActivityForLongPressOnPowerInSetup); mHapticTextHandleEnabled = mContext.getResources().getBoolean( com.android.internal.R.bool.config_enableHapticTextHandle); mUseTvRouting = AudioSystem.getPlatformType(mContext) == AudioSystem.PLATFORM_TELEVISION; mHandleVolumeKeysInWM = mContext.getResources().getBoolean( com.android.internal.R.bool.config_handleVolumeKeysInWindowManager); mPerDisplayFocusEnabled = mContext.getResources().getBoolean( com.android.internal.R.bool.config_perDisplayFocusEnabled); mWakeUpToLastStateTimeout = mContext.getResources().getInteger( com.android.internal.R.integer.config_wakeUpToLastStateTimeoutMillis); readConfigurationDependentBehaviors(); mDisplayFoldController = DisplayFoldController.create(context, DEFAULT_DISPLAY); mAccessibilityManager = (AccessibilityManager) context.getSystemService( Context.ACCESSIBILITY_SERVICE); // register for dock events IntentFilter filter = new IntentFilter(); filter.addAction(UiModeManager.ACTION_ENTER_CAR_MODE); filter.addAction(UiModeManager.ACTION_EXIT_CAR_MODE); filter.addAction(UiModeManager.ACTION_ENTER_DESK_MODE); filter.addAction(UiModeManager.ACTION_EXIT_DESK_MODE); filter.addAction(Intent.ACTION_DOCK_EVENT); Intent intent = context.registerReceiver(mDockReceiver, filter); if (intent != null) { // Retrieve current sticky dock event broadcast. mDefaultDisplayPolicy.setDockMode(intent.getIntExtra(Intent.EXTRA_DOCK_STATE, Intent.EXTRA_DOCK_STATE_UNDOCKED)); } // register for dream-related broadcasts filter = new IntentFilter(); filter.addAction(Intent.ACTION_DREAMING_STARTED); filter.addAction(Intent.ACTION_DREAMING_STOPPED); context.registerReceiver(mDreamReceiver, filter); // register for multiuser-relevant broadcasts filter = new IntentFilter(Intent.ACTION_USER_SWITCHED); context.registerReceiver(mMultiuserReceiver, filter); mVibrator = (Vibrator)context.getSystemService(Context.VIBRATOR_SERVICE); mSafeModeEnabledVibePattern = getLongIntArray(mContext.getResources(), com.android.internal.R.array.config_safeModeEnabledVibePattern); mGlobalKeyManager = new GlobalKeyManager(mContext); // Controls rotation and the like. initializeHdmiState(); // Match current screen state. if (!mPowerManager.isInteractive()) { startedGoingToSleep(PowerManager.GO_TO_SLEEP_REASON_TIMEOUT); finishedGoingToSleep(PowerManager.GO_TO_SLEEP_REASON_TIMEOUT); } mWindowManagerInternal.registerAppTransitionListener(new AppTransitionListener() { @Override public int onAppTransitionStartingLocked(boolean keyguardGoingAway, boolean keyguardOccluding, long duration, long statusBarAnimationStartTime, long statusBarAnimationDuration) { // When remote animation is enabled for KEYGUARD_GOING_AWAY transition, SysUI // receives IRemoteAnimationRunner#onAnimationStart to start animation, so we don't // need to call IKeyguardService#keyguardGoingAway here. return handleStartTransitionForKeyguardLw(keyguardGoingAway && !WindowManagerService.sEnableRemoteKeyguardGoingAwayAnimation, keyguardOccluding, duration); } @Override public void onAppTransitionCancelledLocked(boolean keyguardGoingAway) { handleStartTransitionForKeyguardLw( keyguardGoingAway, false /* keyguardOccludingStarted */, 0 /* duration */); } }); mKeyguardDelegate = new KeyguardServiceDelegate(mContext, new StateCallback() { @Override public void onTrustedChanged() { mWindowManagerFuncs.notifyKeyguardTrustedChanged(); } @Override public void onShowingChanged() { mWindowManagerFuncs.onKeyguardShowingAndNotOccludedChanged(); } }); initKeyCombinationRules(); initSingleKeyGestureRules(); mSideFpsEventHandler = new SideFpsEventHandler(mContext, mHandler, mPowerManager); }","@Override public void init(Context context, IWindowManager windowManager, WindowManagerFuncs windowManagerFuncs) { mContext = context; mWindowManager = windowManager; mWindowManagerFuncs = windowManagerFuncs; mWindowManagerInternal = LocalServices.getService(WindowManagerInternal.class); mActivityManagerInternal = LocalServices.getService(ActivityManagerInternal.class); mActivityTaskManagerInternal = LocalServices.getService(ActivityTaskManagerInternal.class); mInputManagerInternal = LocalServices.getService(InputManagerInternal.class); mDreamManagerInternal = LocalServices.getService(DreamManagerInternal.class); mPowerManagerInternal = LocalServices.getService(PowerManagerInternal.class); mAppOpsManager = mContext.getSystemService(AppOpsManager.class); mDisplayManager = mContext.getSystemService(DisplayManager.class); mDisplayManagerInternal = LocalServices.getService(DisplayManagerInternal.class); mPackageManager = mContext.getPackageManager(); mHasFeatureWatch = mPackageManager.hasSystemFeature(FEATURE_WATCH); mHasFeatureLeanback = mPackageManager.hasSystemFeature(FEATURE_LEANBACK); mHasFeatureAuto = mPackageManager.hasSystemFeature(FEATURE_AUTOMOTIVE); mHasFeatureHdmiCec = mPackageManager.hasSystemFeature(FEATURE_HDMI_CEC); mAccessibilityShortcutController = new AccessibilityShortcutController(mContext, new Handler(), mCurrentUserId); mLogger = new MetricsLogger(); mScreenOffSleepTokenAcquirer = mActivityTaskManagerInternal .createSleepTokenAcquirer(""ScreenOff""); Resources res = mContext.getResources(); mWakeOnDpadKeyPress = res.getBoolean(com.android.internal.R.bool.config_wakeOnDpadKeyPress); mWakeOnAssistKeyPress = res.getBoolean(com.android.internal.R.bool.config_wakeOnAssistKeyPress); mWakeOnBackKeyPress = res.getBoolean(com.android.internal.R.bool.config_wakeOnBackKeyPress); // Init display burn-in protection boolean burnInProtectionEnabled = context.getResources().getBoolean( com.android.internal.R.bool.config_enableBurnInProtection); // Allow a system property to override this. Used by developer settings. boolean burnInProtectionDevMode = SystemProperties.getBoolean(""persist.debug.force_burn_in"", false); if (burnInProtectionEnabled || burnInProtectionDevMode) { final int minHorizontal; final int maxHorizontal; final int minVertical; final int maxVertical; final int maxRadius; if (burnInProtectionDevMode) { minHorizontal = -8; maxHorizontal = 8; minVertical = -8; maxVertical = -4; maxRadius = (isRoundWindow()) ? 6 : -1; } else { Resources resources = context.getResources(); minHorizontal = resources.getInteger( com.android.internal.R.integer.config_burnInProtectionMinHorizontalOffset); maxHorizontal = resources.getInteger( com.android.internal.R.integer.config_burnInProtectionMaxHorizontalOffset); minVertical = resources.getInteger( com.android.internal.R.integer.config_burnInProtectionMinVerticalOffset); maxVertical = resources.getInteger( com.android.internal.R.integer.config_burnInProtectionMaxVerticalOffset); maxRadius = resources.getInteger( com.android.internal.R.integer.config_burnInProtectionMaxRadius); } mBurnInProtectionHelper = new BurnInProtectionHelper( context, minHorizontal, maxHorizontal, minVertical, maxVertical, maxRadius); } mHandler = new PolicyHandler(); mWakeGestureListener = new MyWakeGestureListener(mContext, mHandler); mSettingsObserver = new SettingsObserver(mHandler); mSettingsObserver.observe(); mModifierShortcutManager = new ModifierShortcutManager(context); mUiMode = context.getResources().getInteger( com.android.internal.R.integer.config_defaultUiModeType); mHomeIntent = new Intent(Intent.ACTION_MAIN, null); mHomeIntent.addCategory(Intent.CATEGORY_HOME); mHomeIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_RESET_TASK_IF_NEEDED); mEnableCarDockHomeCapture = context.getResources().getBoolean( com.android.internal.R.bool.config_enableCarDockHomeLaunch); mCarDockIntent = new Intent(Intent.ACTION_MAIN, null); mCarDockIntent.addCategory(Intent.CATEGORY_CAR_DOCK); mCarDockIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_RESET_TASK_IF_NEEDED); mDeskDockIntent = new Intent(Intent.ACTION_MAIN, null); mDeskDockIntent.addCategory(Intent.CATEGORY_DESK_DOCK); mDeskDockIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_RESET_TASK_IF_NEEDED); mVrHeadsetHomeIntent = new Intent(Intent.ACTION_MAIN, null); mVrHeadsetHomeIntent.addCategory(Intent.CATEGORY_VR_HOME); mVrHeadsetHomeIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_RESET_TASK_IF_NEEDED); mPowerManager = (PowerManager)context.getSystemService(Context.POWER_SERVICE); mBroadcastWakeLock = mPowerManager.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, ""PhoneWindowManager.mBroadcastWakeLock""); mPowerKeyWakeLock = mPowerManager.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, ""PhoneWindowManager.mPowerKeyWakeLock""); mEnableShiftMenuBugReports = ""1"".equals(SystemProperties.get(""ro.debuggable"")); mLidKeyboardAccessibility = mContext.getResources().getInteger( com.android.internal.R.integer.config_lidKeyboardAccessibility); mLidNavigationAccessibility = mContext.getResources().getInteger( com.android.internal.R.integer.config_lidNavigationAccessibility); mAllowTheaterModeWakeFromKey = mContext.getResources().getBoolean( com.android.internal.R.bool.config_allowTheaterModeWakeFromKey); mAllowTheaterModeWakeFromPowerKey = mAllowTheaterModeWakeFromKey || mContext.getResources().getBoolean( com.android.internal.R.bool.config_allowTheaterModeWakeFromPowerKey); mAllowTheaterModeWakeFromMotion = mContext.getResources().getBoolean( com.android.internal.R.bool.config_allowTheaterModeWakeFromMotion); mAllowTheaterModeWakeFromMotionWhenNotDreaming = mContext.getResources().getBoolean( com.android.internal.R.bool.config_allowTheaterModeWakeFromMotionWhenNotDreaming); mAllowTheaterModeWakeFromCameraLens = mContext.getResources().getBoolean( com.android.internal.R.bool.config_allowTheaterModeWakeFromCameraLens); mAllowTheaterModeWakeFromLidSwitch = mContext.getResources().getBoolean( com.android.internal.R.bool.config_allowTheaterModeWakeFromLidSwitch); mAllowTheaterModeWakeFromWakeGesture = mContext.getResources().getBoolean( com.android.internal.R.bool.config_allowTheaterModeWakeFromGesture); mGoToSleepOnButtonPressTheaterMode = mContext.getResources().getBoolean( com.android.internal.R.bool.config_goToSleepOnButtonPressTheaterMode); mSupportLongPressPowerWhenNonInteractive = mContext.getResources().getBoolean( com.android.internal.R.bool.config_supportLongPressPowerWhenNonInteractive); mLongPressOnBackBehavior = mContext.getResources().getInteger( com.android.internal.R.integer.config_longPressOnBackBehavior); mShortPressOnPowerBehavior = mContext.getResources().getInteger( com.android.internal.R.integer.config_shortPressOnPowerBehavior); mLongPressOnPowerBehavior = mContext.getResources().getInteger( com.android.internal.R.integer.config_longPressOnPowerBehavior); mLongPressOnPowerAssistantTimeoutMs = mContext.getResources().getInteger( com.android.internal.R.integer.config_longPressOnPowerDurationMs); mVeryLongPressOnPowerBehavior = mContext.getResources().getInteger( com.android.internal.R.integer.config_veryLongPressOnPowerBehavior); mDoublePressOnPowerBehavior = mContext.getResources().getInteger( com.android.internal.R.integer.config_doublePressOnPowerBehavior); mPowerDoublePressTargetActivity = ComponentName.unflattenFromString( mContext.getResources().getString( com.android.internal.R.string.config_doublePressOnPowerTargetActivity)); mTriplePressOnPowerBehavior = mContext.getResources().getInteger( com.android.internal.R.integer.config_triplePressOnPowerBehavior); mShortPressOnSleepBehavior = mContext.getResources().getInteger( com.android.internal.R.integer.config_shortPressOnSleepBehavior); mAllowStartActivityForLongPressOnPowerDuringSetup = mContext.getResources().getBoolean( com.android.internal.R.bool.config_allowStartActivityForLongPressOnPowerInSetup); mHapticTextHandleEnabled = mContext.getResources().getBoolean( com.android.internal.R.bool.config_enableHapticTextHandle); mUseTvRouting = AudioSystem.getPlatformType(mContext) == AudioSystem.PLATFORM_TELEVISION; mHandleVolumeKeysInWM = mContext.getResources().getBoolean( com.android.internal.R.bool.config_handleVolumeKeysInWindowManager); mPerDisplayFocusEnabled = mContext.getResources().getBoolean( com.android.internal.R.bool.config_perDisplayFocusEnabled); mWakeUpToLastStateTimeout = mContext.getResources().getInteger( com.android.internal.R.integer.config_wakeUpToLastStateTimeoutMillis); readConfigurationDependentBehaviors(); mDisplayFoldController = DisplayFoldController.create(context, DEFAULT_DISPLAY); mAccessibilityManager = (AccessibilityManager) context.getSystemService( Context.ACCESSIBILITY_SERVICE); // register for dock events IntentFilter filter = new IntentFilter(); filter.addAction(UiModeManager.ACTION_ENTER_CAR_MODE); filter.addAction(UiModeManager.ACTION_EXIT_CAR_MODE); filter.addAction(UiModeManager.ACTION_ENTER_DESK_MODE); filter.addAction(UiModeManager.ACTION_EXIT_DESK_MODE); filter.addAction(Intent.ACTION_DOCK_EVENT); Intent intent = context.registerReceiver(mDockReceiver, filter); if (intent != null) { // Retrieve current sticky dock event broadcast. mDefaultDisplayPolicy.setDockMode(intent.getIntExtra(Intent.EXTRA_DOCK_STATE, Intent.EXTRA_DOCK_STATE_UNDOCKED)); } // register for dream-related broadcasts filter = new IntentFilter(); filter.addAction(Intent.ACTION_DREAMING_STARTED); filter.addAction(Intent.ACTION_DREAMING_STOPPED); context.registerReceiver(mDreamReceiver, filter); // register for multiuser-relevant broadcasts filter = new IntentFilter(Intent.ACTION_USER_SWITCHED); context.registerReceiver(mMultiuserReceiver, filter); mVibrator = (Vibrator)context.getSystemService(Context.VIBRATOR_SERVICE); mSafeModeEnabledVibePattern = getLongIntArray(mContext.getResources(), com.android.internal.R.array.config_safeModeEnabledVibePattern); mGlobalKeyManager = new GlobalKeyManager(mContext); // Controls rotation and the like. initializeHdmiState(); // Match current screen state. if (!mPowerManager.isInteractive()) { startedGoingToSleep(PowerManager.GO_TO_SLEEP_REASON_TIMEOUT); finishedGoingToSleep(PowerManager.GO_TO_SLEEP_REASON_TIMEOUT); } mWindowManagerInternal.registerAppTransitionListener(new AppTransitionListener() { @Override public int onAppTransitionStartingLocked(boolean keyguardGoingAway, boolean keyguardOccluding, long duration, long statusBarAnimationStartTime, long statusBarAnimationDuration) { // When remote animation is enabled for KEYGUARD_GOING_AWAY transition, SysUI // receives IRemoteAnimationRunner#onAnimationStart to start animation, so we don't // need to call IKeyguardService#keyguardGoingAway here. return handleStartTransitionForKeyguardLw(keyguardGoingAway && !WindowManagerService.sEnableRemoteKeyguardGoingAwayAnimation, keyguardOccluding, duration); } @Override public void onAppTransitionCancelledLocked(boolean keyguardGoingAway) { handleStartTransitionForKeyguardLw( keyguardGoingAway, false /* keyguardOccludingStarted */, 0 /* duration */); } }); mKeyguardDelegate = new KeyguardServiceDelegate(mContext, new StateCallback() { @Override public void onTrustedChanged() { mWindowManagerFuncs.notifyKeyguardTrustedChanged(); } @Override public void onShowingChanged() { mWindowManagerFuncs.onKeyguardShowingAndNotOccludedChanged(); } }); initKeyCombinationRules(); initSingleKeyGestureRules(); mSideFpsEventHandler = new SideFpsEventHandler(mContext, mHandler, mPowerManager); final String[] deviceKeyHandlerLibs = res.getStringArray( com.android.internal.R.array.config_deviceKeyHandlerLibs); final String[] deviceKeyHandlerClasses = res.getStringArray( com.android.internal.R.array.config_deviceKeyHandlerClasses); for (int i = 0; i < deviceKeyHandlerLibs.length && i < deviceKeyHandlerClasses.length; i++) { try { PathClassLoader loader = new PathClassLoader( deviceKeyHandlerLibs[i], getClass().getClassLoader()); Class klass = loader.loadClass(deviceKeyHandlerClasses[i]); Constructor constructor = klass.getConstructor(Context.class); mDeviceKeyHandlers.add((DeviceKeyHandler) constructor.newInstance(mContext)); } catch (Exception e) { Slog.w(TAG, ""Could not instantiate device key handler "" + deviceKeyHandlerLibs[i] + "" from class "" + deviceKeyHandlerClasses[i], e); } } if (DEBUG_INPUT) { Slog.d(TAG, """" + mDeviceKeyHandlers.size() + "" device key handlers loaded""); } }","base: Support for device specific key handlers This is a squash commit of the following changes, only modified for the new SDK. Author: Alexander Hofbauer Date: Thu Apr 12 01:24:24 2012 +0200 Dispatch keys to a device specific key handler Injects a device key handler into the input path to handle additional keys (as found on some docks with a hardware keyboard). Configurable via overlay settings config_deviceKeyHandlerLib and config_deviceKeyHandlerClass. Change-Id: I6678c89c7530fdb1d4d516ba4f1d2c9e30ce79a4 Author: Jorge Ruesga Date: Thu Jan 24 02:34:49 2013 +0100 DeviceKeyHandle: The device should consume only known keys When the device receive the key, only should consume it if the device know about the key. Otherwise, the key must be handle by the active app. Also make mDeviceKeyHandler private (is not useful outside this class) Change-Id: I4b9ea57b802e8c8c88c8b93a63d510f5952b0700 Signed-off-by: Jorge Ruesga Author: Danesh Mondegarian Date: Sun Oct 20 00:34:48 2013 -0700 DeviceKeyHandler : Allow handling keyevents while screen off Some devices require the keyevents to be processed while the screen is off, this patchset addresses that by moving the filter up in the call hierarchy. Change-Id: If71beecc81aa5e453dcd08aba72b7bea5c210590 Author: Steve Kondik Date: Sun Sep 11 00:49:41 2016 -0700 policy: Use PathClassLoader for loading the keyhandler * Fix crash on start due to getCacheDir throwing an exception. * We can't do this anymore due to the new storage/crypto in N. Change-Id: I28426a5df824460ebc74aa19068192adb00d4f7c Author: Zhao Wei Liew Date: Sun Nov 20 08:20:15 2016 +0800 PhoneWindowManager: Support multiple key handlers Convert the string overlay to a string-array overlay to allow devices to specify an array of key handlers. Note that the keyhandlers towards the start of the array take precedence when loading. Change-Id: Iaaab737f1501a97d7016d8d519ccf127ca059218 Author: Paul Keith Date: Thu Nov 23 21:47:51 2017 +0100 fw/b: Return a KeyEvent instead of a boolean in KeyHandler * Allows handlers to modify the event before sending it off to another KeyHandler class, to handle things like rotation Change-Id: I481107e050f6323c5897260a5d241e64b4e031ac Change-Id: Ie65a89cd7efd645622d99d47699df847bc3ad96b",https://github.com/PixelExperience/frameworks_base/commit/fc508ab5003274d8b9e5ae8589b5e008054909a1,,,services/core/java/com/android/server/policy/PhoneWindowManager.java,3,java,False,2017-10-11T20:11:49Z "public static void reset() { for (Map map : BehaviorListenerLists.values()) { map.clear(); } BehaviorListenerLists.clear(); }","public static void reset() { for (Map map : BehaviorListenerLists.values()) { map.forEach((key, value) -> map.get(key).destroyAllBehaviors()); map.clear(); } BehaviorListenerLists.clear(); }","fixed a ton of concurrency issues New Additions - `Drawable#isDestroyed` -- boolean for checking if a given `Drawable` has been destroyed - This boolean also effects the outcome of `Drawable#shouldRender` -- if the `Drawable` is destroyed, then it will not be rendered - `ManagedList` -- a type of `List` with convenient managed actions via a `ScheduledExecutorService`, providing a safe and manageable way to start and stop important list actions at a moment's notice Bug Fixes - Fixed occasional crashes on null pointers with enemies in `GameScene` - Fixed occasional concurrent modification exceptions on `AfterUpdateList` and `AfterRenderList` in `FastJEngine` - Fixed double-`exit` situation on closing `SimpleDisplay` - Fixed occasional concurrenct modification exceptions on `behavior` lists from `GameObject` - Sensibly removed as many `null` values as possible from `Model2D/Polygon2D/Sprite2D/Text2D` - Fixed buggy threading code/occasional concurrent modification exceptions in `InputManager` Breaking Changes - `BehaviorManager#reset` now destroys all the behaviors in each of its behavior lists Other Changes - Moved transform resetting on `destroyTheRest` up from `GameObject` to `Drawable` - Changed `GameObjectTests#tryUpdateBehaviorWithoutInitializing_shouldThrowNullPointerException`'s exception throwing to match the underlying `behaviors` list's exception - added trace-level logging to unit tests",https://github.com/fastjengine/FastJ/commit/3cf252b71786d782a98fdfb976eba13154e57757,,,src/main/java/tech/fastj/systems/behaviors/BehaviorManager.java,3,java,False,2021-12-20T17:24:53Z "def _require_verified_user(self, request): user = request.user if not settings.WAGTAIL_2FA_REQUIRED: # If two factor authentication is disabled in the settings return False if not user.is_authenticated: return False # If the user has no access to the admin anyway then don't require a # verified user here if not ( user.is_staff or user.is_superuser or user.has_perms([""wagtailadmin.access_admin""]) ): return False # Allow the user to a fixed number of paths when not verified if request.path in self._allowed_paths: return False # For all other cases require that the user is verfied via otp return True","def _require_verified_user(self, request): user = request.user if not settings.WAGTAIL_2FA_REQUIRED: # If two factor authentication is disabled in the settings return False if not user.is_authenticated: return False # If the user has no access to the admin anyway then don't require a # verified user here if not ( user.is_staff or user.is_superuser or user.has_perms([""wagtailadmin.access_admin""]) ): return False # Allow the user to a fixed number of paths when not verified user_has_device = django_otp.user_has_device(user, confirmed=True) if request.path in self._get_allowed_paths(user_has_device): return False # For all other cases require that the user is verfied via otp return True","Allow a limited list of paths when user has device This prevents users from adding or listing devices while they are not yet verified and already have a registered device.",https://github.com/labd/wagtail-2fa/commit/a6711b29711729005770ff481b22675b35ff5c81,,,src/wagtail_2fa/middleware.py,3,py,False,2019-11-21T11:29:50Z "public void doNextAuthentication() throws IOException, SshException { if (canAuthenticate()) { currentAuthenticator = authenticators.get(authIndex++); currentAuthenticator.authenticate(transport, username); } else { if(authenticators.size() > 0) { transport.getConnection().getAuthenticatedFuture().done(false); } } }","public synchronized boolean doNextAuthentication() throws IOException, SshException { if(!authenticators.isEmpty()) { currentAuthenticator = authenticators.removeFirst(); if(Log.isDebugEnabled()) { Log.debug(""Starting {} authentication"", currentAuthenticator.getName()); } currentAuthenticator.authenticate(transport, username); return true; } return false; }","Added prefer keyboard-interactive over password setting. Fixed race condition with none authenticator.",https://github.com/sshtools/maverick-synergy/commit/5421a5cb4c6b5f5174bcfb2c15d78f3acd706d86,,,maverick-synergy-client/src/main/java/com/sshtools/client/AuthenticationProtocolClient.java,3,java,False,2021-03-07T16:54:01Z "@SuppressWarnings({""StringEquality"", ""StringConcatenationInsideStringBufferAppend""}) // Interned strings; readability private String importDimension(File worldDir, Dimension dimension, ProgressReceiver progressReceiver) throws ProgressReceiver.OperationCancelled { if (progressReceiver != null) { progressReceiver.setMessage(dimension.getName() + "" dimension""); } final int minHeight = dimension.getMinHeight(), maxHeight = dimension.getMaxHeight(); final int maxY = maxHeight - 1; final Set newChunks = synchronizedSet(new HashSet<>()); final Set manMadeBlockTypes = synchronizedSet(new HashSet<>()); final Set unknownBiomes = synchronizedSet(new HashSet<>()); final boolean importBiomes = platform.capabilities.contains(BIOMES) || platform.capabilities.contains(BIOMES_3D) || platform.capabilities.contains(NAMED_BIOMES); final Map customNamedBiomes = synchronizedMap(new HashMap<>()); final AtomicInteger nextCustomBiomeId = new AtomicInteger(FIRST_UNALLOCATED_ID); final Set allBiomes = synchronizedSet(new HashSet<>()); try (ChunkStore chunkStore = PlatformManager.getInstance().getChunkStore(platform, worldDir, dimension.getDim())) { final int total = chunkStore.getChunkCount(); final AtomicInteger count = new AtomicInteger(); final StringBuffer reportBuilder = new StringBuffer(); final Map nonNativePlatformsEncountered = synchronizedMap(new HashMap<>()); if (! chunkStore.visitChunks(new ChunkVisitor() { @Override public boolean visitChunk(Chunk chunk) { try { if (progressReceiver != null) { progressReceiver.setProgress((float) count.getAndIncrement() / total); } final MinecraftCoords chunkCoords = chunk.getCoords(); if ((chunksToSkip != null) && chunksToSkip.contains(chunkCoords)) { return true; } // Sanity checks if (skipChunk(chunk)) { return true; } final Set chunkNativePlatforms = determineNativePlatforms(chunk); if ((chunkNativePlatforms != null) && (! chunkNativePlatforms.contains(platform))) { chunkNativePlatforms.forEach(chunkNativePlatform -> nonNativePlatformsEncountered.computeIfAbsent(chunkNativePlatform, p -> new AtomicInteger()).incrementAndGet()); } final int chunkX = chunkCoords.x; final int chunkZ = chunkCoords.z; final int chunkMinHeight = Math.max(minHeight, chunk.getMinHeight()); final Point tileCoords = new Point(chunkX >> 3, chunkZ >> 3); Tile tile = dimension.getTile(tileCoords); if (tile == null) { tile = dimension.getTileFactory().createTile(tileCoords.x, tileCoords.y); for (int xx = 0; xx < 8; xx++) { for (int yy = 0; yy < 8; yy++) { newChunks.add(new Point((tileCoords.x << TILE_SIZE_BITS) | (xx << 4), (tileCoords.y << TILE_SIZE_BITS) | (yy << 4))); } } dimension.addTile(tile); } boolean manMadeStructuresBelowGround = false; boolean manMadeStructuresAboveGround = false; final boolean collectDebugInfo = logger.isDebugEnabled(); try { for (int xx = 0; xx < 16; xx++) { for (int zz = 0; zz < 16; zz++) { float height = Float.MIN_VALUE; int waterLevel = Integer.MIN_VALUE; boolean floodWithLava = false, frost = false; Terrain terrain = Terrain.BEDROCK; for (int y = Math.min(maxY, chunk.getHighestNonAirBlock(xx, zz)); y >= chunkMinHeight; y--) { Material material = chunk.getMaterial(xx, y, zz); if (! material.natural) { if (height == Float.MIN_VALUE) { manMadeStructuresAboveGround = true; } else { manMadeStructuresBelowGround = true; } if (collectDebugInfo) { manMadeBlockTypes.add(material.name); } } String name = material.name; if ((name == MC_SNOW) || (name == MC_ICE)) { frost = true; } if ((waterLevel == Integer.MIN_VALUE) && ((name == MC_ICE) || (name == MC_FROSTED_ICE) || (material.watery) || (((name == MC_WATER) || (name == MC_LAVA)) && (material.getProperty(LEVEL) == 0)) || material.is(WATERLOGGED))) { waterLevel = y; if (name == MC_LAVA) { floodWithLava = true; } } else if (height == Float.MIN_VALUE) { if (TERRAIN_MAPPING.containsKey(name)) { // Terrain found height = y - 0.4375f; // Value that falls in the middle of the lowest one eighth which will still round to the same integer value and will receive a one layer thick smooth snow block (principle of least surprise) terrain = TERRAIN_MAPPING.get(name); if (waterLevel == Integer.MIN_VALUE) { waterLevel = (y >= DEFAULT_WATER_LEVEL) ? DEFAULT_WATER_LEVEL : minHeight; } if (readOnlyOption != MAN_MADE) { // We only need to keep going if we're going to mark chunks with // underground man-made blocks as read-only break; } } } } // Use smooth snow, if present, to better approximate world height, so smooth snow will survive merge final int intHeight = Math.round(height); if ((height != Float.MIN_VALUE) && (intHeight < maxY)) { Material materialAbove = chunk.getMaterial(xx, intHeight + 1, zz); if (materialAbove.isNamed(MC_SNOW)) { int layers = materialAbove.getProperty(LAYERS); height += layers * 0.125; } } if (waterLevel == Integer.MIN_VALUE) { if (height >= 61.5f) { waterLevel = DEFAULT_WATER_LEVEL; } else { waterLevel = minHeight; } } final int blockX = (chunkX << 4) | xx; final int blockY = (chunkZ << 4) | zz; final Point coords = new Point(blockX, blockY); dimension.setTerrainAt(coords, terrain); dimension.setHeightAt(coords, Math.max(height, minHeight)); dimension.setWaterLevelAt(blockX, blockY, waterLevel); if (frost) { dimension.setBitLayerValueAt(Frost.INSTANCE, blockX, blockY, true); } if (floodWithLava) { dimension.setBitLayerValueAt(FloodWithLava.INSTANCE, blockX, blockY, true); } if (height == Float.MIN_VALUE) { dimension.setBitLayerValueAt(org.pepsoft.worldpainter.layers.Void.INSTANCE, blockX, blockY, true); } if (importBiomes) { int biome = 255; if (chunk.isBiomesAvailable()) { biome = chunk.getBiome(xx, zz); } else if (chunk.is3DBiomesAvailable()) { // We accept a reduction in resolution here, and we lose 3D biome // information // TODO make this clear to the user // TODO add way of editing 3D biomes biome = chunk.get3DBiome(xx >> 2, dimension.getIntHeightAt(blockX, blockY) >> 2, zz >> 2); } else if (chunk.isNamedBiomesAvailable()) { // We accept a reduction in resolution here, and we lose 3D biome // information // TODOMC118 make this clear to the user // TODOMC118 add way of editing 3D biomes String biomeStr = chunk.getNamedBiome(xx >> 2, dimension.getIntHeightAt(blockX, blockY) >> 2, zz >> 2); if (biomeStr != null) { if (collectDebugInfo) { allBiomes.add(biomeStr); } if (BIOMES_BY_MODERN_ID.containsKey(biomeStr)) { biome = BIOMES_BY_MODERN_ID.get(biomeStr); } else if (customNamedBiomes.containsKey(biomeStr)) { // This is a new biome that WorldPainter does not know about yet, or one // from a mod, but we have encountered it before and assigned it a // custom ID; reuse that biome = customNamedBiomes.get(biomeStr); } else { // This is a new biome that WorldPainter does not know about yet, or one // from a mod, that we have not yet encountered before. Choose a custom // ID for it and record it int customId; do { customId = nextCustomBiomeId.getAndIncrement(); } while ((MODERN_IDS[customId] != null) && (customId < 255)); if (customId >= 255) { throw new RuntimeException(""More unknown biomes in dimension than available custom biome ids""); } biome = customId; customNamedBiomes.put(biomeStr, biome); } } } if (collectDebugInfo && ((biome > 255) || (BIOME_NAMES[biome] == null)) && (biome != 255)) { unknownBiomes.add(biome); } // If the biome is set (around the edges of the map Minecraft sets it to // 255, presumably as a marker that it has yet to be calculated), copy // it to the dimension. However, if it matches what the automatic biome // would be, don't copy it, so that WorldPainter will automatically // adjust the biome when the user makes changes if ((biome != 255) && (biome != dimension.getAutoBiome(blockX, blockY))) { dimension.setLayerValueAt(Biome.INSTANCE, blockX, blockY, biome); } } } } newChunks.remove(new Point(chunkX << 4, chunkZ << 4)); } catch (NullPointerException e) { reportBuilder.append(""Null pointer exception while reading chunk "" + chunkX + "","" + chunkZ + ""; skipping chunk"" + EOL); logger.error(""Null pointer exception while reading chunk "" + chunkX + "","" + chunkZ + ""; skipping chunk"", e); return true; } catch (ArrayIndexOutOfBoundsException e) { reportBuilder.append(""Array index out of bounds while reading chunk "" + chunkX + "","" + chunkZ + "" (message: \"""" + e.getMessage() + ""\""); skipping chunk"" + EOL); logger.error(""Array index out of bounds while reading chunk "" + chunkX + "","" + chunkZ + ""; skipping chunk"", e); return true; } if (((readOnlyOption == MAN_MADE) && (manMadeStructuresBelowGround || manMadeStructuresAboveGround)) || ((readOnlyOption == MAN_MADE_ABOVE_GROUND) && manMadeStructuresAboveGround) || (readOnlyOption == ALL)) { dimension.setBitLayerValueAt(ReadOnly.INSTANCE, chunkX << 4, chunkZ << 4, true); } } catch (ProgressReceiver.OperationCancelled e) { return false; } return true; } @Override public boolean chunkError(MinecraftCoords coords, String message) { reportBuilder.append(""\"""" + message + ""\"" while reading chunk "" + coords.x + "","" + coords.z + ""; skipping chunk"" + EOL); return true; } })) { throw new ProgressReceiver.OperationCancelled(""Operation cancelled""); } if (! nonNativePlatformsEncountered.isEmpty()) { if (reportBuilder.length() > 0) { reportBuilder.insert(0, EOL + EOL); } reportBuilder.insert(0, ""This map contains chunks that belong to (an)other version(s) of Minecraft: "" + EOL + nonNativePlatformsEncountered.entrySet().stream() .map(e -> e.getKey().displayName + "" ("" + e.getValue().get() + "" chunk(s))"") .collect(joining("", "")) + EOL + ""It may therefore not be possible to Merge your changes back to this map."" + EOL + ""It is highly recommended to use the Optimize function of"" + EOL + platform + "" to bring the map fully up to date.""); } if (! customNamedBiomes.isEmpty()) { List customBiomes = new ArrayList<>(customNamedBiomes.size()); for (Map.Entry entry: customNamedBiomes.entrySet()) { customBiomes.add(new CustomBiome(entry.getKey(), entry.getValue(), 0xff00ff)); } dimension.setCustomBiomes(customBiomes); } // Process chunks that were only added to fill out a tile. This includes chunks that were skipped during // import due to an error final Map notPresentChunksCountPerTile = new HashMap<>(); for (Point newChunkCoords: newChunks) { dimension.setBitLayerValueAt(NotPresent.INSTANCE, newChunkCoords.x, newChunkCoords.y, true); final Point tileCoords = new Point(newChunkCoords.x >> 3, newChunkCoords.y >> 3); if (notPresentChunksCountPerTile.computeIfAbsent(tileCoords, k -> new AtomicInteger()).incrementAndGet() == 64) { // All the chunks in this tile are ""not present"" (this might happen if chunks were skipped due to // errors) dimension.removeTile(tileCoords); } } if (progressReceiver != null) { progressReceiver.setProgress(1.0f); } if (logger.isDebugEnabled()) { if (! manMadeBlockTypes.isEmpty()) { logger.debug(""Man-made block types encountered: {}"", String.join("", "", manMadeBlockTypes)); } if (! unknownBiomes.isEmpty()) { logger.debug(""Unknown biome IDs encountered: {}"", unknownBiomes.stream().map(Object::toString).collect(joining("", ""))); } if (! allBiomes.isEmpty()) { logger.debug(""All named biomes encountered: {}"", allBiomes); } } return reportBuilder.length() != 0 ? reportBuilder.toString() : null; } }","@SuppressWarnings({""StringEquality"", ""StringConcatenationInsideStringBufferAppend""}) // Interned strings; readability private String importDimension(File worldDir, Dimension dimension, ProgressReceiver progressReceiver) throws ProgressReceiver.OperationCancelled { if (progressReceiver != null) { progressReceiver.setMessage(dimension.getName() + "" dimension""); } final int minHeight = dimension.getMinHeight(), maxHeight = dimension.getMaxHeight(); final int maxY = maxHeight - 1; final Set newChunks = synchronizedSet(new HashSet<>()); final Set manMadeBlockTypes = synchronizedSet(new HashSet<>()); final Set unknownBiomes = synchronizedSet(new HashSet<>()); final boolean importBiomes = platform.capabilities.contains(BIOMES) || platform.capabilities.contains(BIOMES_3D) || platform.capabilities.contains(NAMED_BIOMES); final Map customNamedBiomes = synchronizedMap(new HashMap<>()); final AtomicInteger nextCustomBiomeId = new AtomicInteger(FIRST_UNALLOCATED_ID); final Set allBiomes = synchronizedSet(new HashSet<>()); final Set invalidBiomeIds = synchronizedSet(new HashSet<>()); try (ChunkStore chunkStore = PlatformManager.getInstance().getChunkStore(platform, worldDir, dimension.getDim())) { final int total = chunkStore.getChunkCount(); final AtomicInteger count = new AtomicInteger(); final StringBuffer reportBuilder = new StringBuffer(); final Map nonNativePlatformsEncountered = synchronizedMap(new HashMap<>()); if (! chunkStore.visitChunks(new ChunkVisitor() { @Override public boolean visitChunk(Chunk chunk) { try { if (progressReceiver != null) { progressReceiver.setProgress((float) count.getAndIncrement() / total); } final MinecraftCoords chunkCoords = chunk.getCoords(); if ((chunksToSkip != null) && chunksToSkip.contains(chunkCoords)) { return true; } // Sanity checks if (skipChunk(chunk)) { return true; } final Set chunkNativePlatforms = determineNativePlatforms(chunk); if ((chunkNativePlatforms != null) && (! chunkNativePlatforms.contains(platform))) { chunkNativePlatforms.forEach(chunkNativePlatform -> nonNativePlatformsEncountered.computeIfAbsent(chunkNativePlatform, p -> new AtomicInteger()).incrementAndGet()); } final int chunkX = chunkCoords.x; final int chunkZ = chunkCoords.z; final int chunkMinHeight = Math.max(minHeight, chunk.getMinHeight()); final Point tileCoords = new Point(chunkX >> 3, chunkZ >> 3); Tile tile = dimension.getTile(tileCoords); if (tile == null) { tile = dimension.getTileFactory().createTile(tileCoords.x, tileCoords.y); for (int xx = 0; xx < 8; xx++) { for (int yy = 0; yy < 8; yy++) { newChunks.add(new Point((tileCoords.x << TILE_SIZE_BITS) | (xx << 4), (tileCoords.y << TILE_SIZE_BITS) | (yy << 4))); } } dimension.addTile(tile); } boolean manMadeStructuresBelowGround = false; boolean manMadeStructuresAboveGround = false; final boolean collectDebugInfo = logger.isDebugEnabled(); boolean markReadOnly = false; try { for (int xx = 0; xx < 16; xx++) { for (int zz = 0; zz < 16; zz++) { float height = Float.MIN_VALUE; int waterLevel = Integer.MIN_VALUE; boolean floodWithLava = false, frost = false; Terrain terrain = Terrain.BEDROCK; for (int y = Math.min(maxY, chunk.getHighestNonAirBlock(xx, zz)); y >= chunkMinHeight; y--) { Material material = chunk.getMaterial(xx, y, zz); if (! material.natural) { if (height == Float.MIN_VALUE) { manMadeStructuresAboveGround = true; } else { manMadeStructuresBelowGround = true; } if (collectDebugInfo) { manMadeBlockTypes.add(material.name); } } String name = material.name; if ((name == MC_SNOW) || (name == MC_ICE)) { frost = true; } if ((waterLevel == Integer.MIN_VALUE) && ((name == MC_ICE) || (name == MC_FROSTED_ICE) || (material.watery) || (((name == MC_WATER) || (name == MC_LAVA)) && (material.getProperty(LEVEL) == 0)) || material.is(WATERLOGGED))) { waterLevel = y; if (name == MC_LAVA) { floodWithLava = true; } } else if (height == Float.MIN_VALUE) { if (TERRAIN_MAPPING.containsKey(name)) { // Terrain found height = y - 0.4375f; // Value that falls in the middle of the lowest one eighth which will still round to the same integer value and will receive a one layer thick smooth snow block (principle of least surprise) terrain = TERRAIN_MAPPING.get(name); if (waterLevel == Integer.MIN_VALUE) { waterLevel = (y >= DEFAULT_WATER_LEVEL) ? DEFAULT_WATER_LEVEL : minHeight; } if (readOnlyOption != MAN_MADE) { // We only need to keep going if we're going to mark chunks with // underground man-made blocks as read-only break; } } } } // Use smooth snow, if present, to better approximate world height, so smooth snow will survive merge final int intHeight = Math.round(height); if ((height != Float.MIN_VALUE) && (intHeight < maxY)) { Material materialAbove = chunk.getMaterial(xx, intHeight + 1, zz); if (materialAbove.isNamed(MC_SNOW)) { int layers = materialAbove.getProperty(LAYERS); height += layers * 0.125; } } if (waterLevel == Integer.MIN_VALUE) { if (height >= 61.5f) { waterLevel = DEFAULT_WATER_LEVEL; } else { waterLevel = minHeight; } } final int blockX = (chunkX << 4) | xx; final int blockY = (chunkZ << 4) | zz; final Point coords = new Point(blockX, blockY); dimension.setTerrainAt(coords, terrain); dimension.setHeightAt(coords, Math.max(height, minHeight)); dimension.setWaterLevelAt(blockX, blockY, waterLevel); if (frost) { dimension.setBitLayerValueAt(Frost.INSTANCE, blockX, blockY, true); } if (floodWithLava) { dimension.setBitLayerValueAt(FloodWithLava.INSTANCE, blockX, blockY, true); } if (height == Float.MIN_VALUE) { dimension.setBitLayerValueAt(org.pepsoft.worldpainter.layers.Void.INSTANCE, blockX, blockY, true); } if (importBiomes) { int biome = 255; if (chunk.isBiomesAvailable()) { biome = chunk.getBiome(xx, zz); } else if (chunk.is3DBiomesAvailable()) { // We accept a reduction in resolution here, and we lose 3D biome // information // TODO make this clear to the user // TODO add way of editing 3D biomes biome = chunk.get3DBiome(xx >> 2, dimension.getIntHeightAt(blockX, blockY) >> 2, zz >> 2); } else if (chunk.isNamedBiomesAvailable()) { // We accept a reduction in resolution here, and we lose 3D biome // information // TODOMC118 make this clear to the user // TODOMC118 add way of editing 3D biomes String biomeStr = chunk.getNamedBiome(xx >> 2, dimension.getIntHeightAt(blockX, blockY) >> 2, zz >> 2); if (biomeStr != null) { if (collectDebugInfo) { allBiomes.add(biomeStr); } if (BIOMES_BY_MODERN_ID.containsKey(biomeStr)) { biome = BIOMES_BY_MODERN_ID.get(biomeStr); } else if (customNamedBiomes.containsKey(biomeStr)) { // This is a new biome that WorldPainter does not know about yet, or one // from a mod, but we have encountered it before and assigned it a // custom ID; reuse that biome = customNamedBiomes.get(biomeStr); } else { // This is a new biome that WorldPainter does not know about yet, or one // from a mod, that we have not yet encountered before. Choose a custom // ID for it and record it int customId; do { customId = nextCustomBiomeId.getAndIncrement(); } while ((MODERN_IDS[customId] != null) && (customId < 255)); if (customId >= 255) { throw new RuntimeException(""More unknown biomes in dimension than available custom biome ids""); } biome = customId; customNamedBiomes.put(biomeStr, biome); } } } if (collectDebugInfo && ((biome > 255) || (BIOME_NAMES[biome] == null)) && (biome != 255)) { unknownBiomes.add(biome); } // If the biome is set (around the edges of the map Minecraft sets it to 255, // presumably as a marker that it has yet to be calculated), copy it to the // dimension. However, if it matches what the automatic biome would be, don't // copy it, so that WorldPainter will automatically adjust the biome when the // user makes changes if ((biome != 255) && (biome != dimension.getAutoBiome(blockX, blockY))) { if ((biome < 0) || (biome > 255)) { // This has been seen in the wild; perhaps a modded map? if (! invalidBiomeIds.contains(biome)) { invalidBiomeIds.add(biome); reportBuilder.append(""Unsupported biome ID "" + biome + "" encountered at location "" + blockX + "","" + blockY + ""; ignoring biome and marking chunk(s) Read-Only"" + EOL); logger.error(""Unsupported biome ID {} encountered at location {},{}; ignoring biome and marking chunk(s) Read-Only"", biome, blockX, blockY); } markReadOnly = true; } else { dimension.setLayerValueAt(Biome.INSTANCE, blockX, blockY, biome); } } } } } newChunks.remove(new Point(chunkX << 4, chunkZ << 4)); } catch (NullPointerException e) { reportBuilder.append(""Null pointer exception while reading chunk "" + chunkX + "","" + chunkZ + ""; skipping chunk"" + EOL); logger.error(""Null pointer exception while reading chunk {},{}; skipping chunk"", chunkX, chunkZ, e); return true; } catch (ArrayIndexOutOfBoundsException e) { reportBuilder.append(""Array index out of bounds while reading chunk "" + chunkX + "","" + chunkZ + "" (message: \"""" + e.getMessage() + ""\""); skipping chunk"" + EOL); logger.error(""Array index out of bounds while reading chunk {},{}; skipping chunk"", chunkX, chunkZ, e); return true; } if (markReadOnly || ((readOnlyOption == MAN_MADE) && (manMadeStructuresBelowGround || manMadeStructuresAboveGround)) || ((readOnlyOption == MAN_MADE_ABOVE_GROUND) && manMadeStructuresAboveGround) || (readOnlyOption == ALL)) { dimension.setBitLayerValueAt(ReadOnly.INSTANCE, chunkX << 4, chunkZ << 4, true); } } catch (ProgressReceiver.OperationCancelled e) { return false; } return true; } @Override public boolean chunkError(MinecraftCoords coords, String message) { reportBuilder.append(""\"""" + message + ""\"" while reading chunk "" + coords.x + "","" + coords.z + ""; skipping chunk"" + EOL); return true; } })) { throw new ProgressReceiver.OperationCancelled(""Operation cancelled""); } if (! nonNativePlatformsEncountered.isEmpty()) { if (reportBuilder.length() > 0) { reportBuilder.insert(0, EOL + EOL); } reportBuilder.insert(0, ""This map contains chunks that belong to (an)other version(s) of Minecraft: "" + EOL + nonNativePlatformsEncountered.entrySet().stream() .map(e -> e.getKey().displayName + "" ("" + e.getValue().get() + "" chunk(s))"") .collect(joining("", "")) + EOL + ""It may therefore not be possible to Merge your changes back to this map."" + EOL + ""It is highly recommended to use the Optimize function of"" + EOL + platform + "" to bring the map fully up to date.""); } if (! customNamedBiomes.isEmpty()) { List customBiomes = new ArrayList<>(customNamedBiomes.size()); for (Map.Entry entry: customNamedBiomes.entrySet()) { customBiomes.add(new CustomBiome(entry.getKey(), entry.getValue(), 0xff00ff)); } dimension.setCustomBiomes(customBiomes); } // Process chunks that were only added to fill out a tile. This includes chunks that were skipped during // import due to an error final Map notPresentChunksCountPerTile = new HashMap<>(); for (Point newChunkCoords: newChunks) { dimension.setBitLayerValueAt(NotPresent.INSTANCE, newChunkCoords.x, newChunkCoords.y, true); final Point tileCoords = new Point(newChunkCoords.x >> 3, newChunkCoords.y >> 3); if (notPresentChunksCountPerTile.computeIfAbsent(tileCoords, k -> new AtomicInteger()).incrementAndGet() == 64) { // All the chunks in this tile are ""not present"" (this might happen if chunks were skipped due to // errors) dimension.removeTile(tileCoords); } } if (progressReceiver != null) { progressReceiver.setProgress(1.0f); } if (logger.isDebugEnabled()) { if (! manMadeBlockTypes.isEmpty()) { logger.debug(""Man-made block types encountered: {}"", String.join("", "", manMadeBlockTypes)); } if (! unknownBiomes.isEmpty()) { logger.debug(""Unknown biome IDs encountered: {}"", unknownBiomes.stream().map(Object::toString).collect(joining("", ""))); } if (! allBiomes.isEmpty()) { logger.debug(""All named biomes encountered: {}"", allBiomes); } } return reportBuilder.length() != 0 ? reportBuilder.toString() : null; } }",Mark chunk read-only instead of crashing on encountering invalid biome ID during import,https://github.com/Captain-Chaos/WorldPainter/commit/c84618d555d6d8e85e3f2dad07ff844b6e37226b,,,WorldPainter/WPCore/src/main/java/org/pepsoft/worldpainter/importing/JavaMapImporter.java,3,java,False,2022-08-02T14:27:20Z "@Inject(method = ""playerTouch(Lnet/minecraft/world/entity/player/Player;)V"", at = @At(value = ""HEAD""), cancellable = true) public void playerTouch(Player player, CallbackInfo ci) { if(!this.level.isClientSide) { // Fire the Forge event if(ClumpsCommon.pickupXPEvent.test(player, (ExperienceOrb) (Entity) this)) { return; } player.takeXpDelay = 0; player.take(this, 1); clumps$getClumpedMap().forEach((value, amount) -> { Either result = Services.EVENT.fireValueEvent(player, value); int actualValue = result.map(IValueEvent::getValue, UnaryOperator.identity()); for(int i = 0; i < amount; i++) { int leftOver = this.repairPlayerItems(player, actualValue); if(leftOver > 0) { player.giveExperiencePoints(leftOver); } } }); this.discard(); ci.cancel(); } }","@Inject(method = ""playerTouch(Lnet/minecraft/world/entity/player/Player;)V"", at = @At(value = ""HEAD""), cancellable = true) public void playerTouch(Player player, CallbackInfo ci) { if(!this.level.isClientSide) { // Fire the Forge event if(ClumpsCommon.pickupXPEvent.test(player, (ExperienceOrb) (Entity) this)) { return; } player.takeXpDelay = 0; player.take(this, 1); if(this.value != 0 || clumps$resolve()) { AtomicInteger toGive = new AtomicInteger(); clumps$getClumpedMap().forEach((value, amount) -> { Either result = Services.EVENT.fireValueEvent(player, value); int actualValue = result.map(IValueEvent::getValue, UnaryOperator.identity()); for(int i = 0; i < amount; i++) { int leftOver = this.repairPlayerItems(player, actualValue); if(leftOver > 0) { toGive.addAndGet(leftOver); } } }); if(toGive.get() > 0) { player.giveExperiencePoints(toGive.get()); } } this.discard(); ci.cancel(); } }",Fix stack overflow error. Close #107,https://github.com/jaredlll08/Clumps/commit/740511d4f3c4d51e4ca924910864fb6568097f59,,,Common/src/main/java/com/blamejared/clumps/mixin/MixinExperienceOrb.java,3,java,False,2022-08-02T22:52:35Z "private void updateTextState() { super.setText(allCaps ? originalText.toString().toUpperCase() : originalText, originalType); }","private void updateTextState() { if (originalText == null) { super.setText(null, originalType); return; } super.setText(allCaps ? originalText.toString().toUpperCase() : originalText, originalType); }","Fix crashing on TextView-based widgets when text is null and textAllCaps = true, add FrameLayout to LayoutInflater",https://github.com/zl-suu/ingrauladolfo/commit/65e0623432cb862f95a856c6240fbdea38a28ff4,,,library/src/org/holoeverywhere/widget/Button.java,3,java,False,2022-12-06T19:50:59Z "@Override public void handleInnerData(byte[] data) { TraceManager.TraceObject traceObject = TraceManager.serviceTrace(this, ""handle-auth-data""); try { this.setPacketId(data[3]); if (data.length == QuitPacket.QUIT.length && data[4] == MySQLPacket.COM_QUIT) { connection.close(""quit packet""); return; } else if (data.length == PingPacket.PING.length && data[4] == PingPacket.COM_PING) { pingResponse(); return; } if (needAuthSwitched) { handleSwitchResponse(data); } else { handleAuthPacket(data); } } finally { TraceManager.finishSpan(this, traceObject); } }","@Override public void handleInnerData(byte[] data) { TraceManager.TraceObject traceObject = TraceManager.serviceTrace(this, ""handle-auth-data""); try { this.setPacketId(data[3]); if (data.length == QuitPacket.QUIT.length && data[4] == MySQLPacket.COM_QUIT) { connection.close(""quit packet""); return; } else if (data.length == PingPacket.PING.length && data[4] == PingPacket.COM_PING) { pingResponse(); return; } if (needAuthSwitched) { handleSwitchResponse(data); } else { handleAuthPacket(data); } } catch (Exception e) { LOGGER.error(""illegal auth packet {}"", data, e); writeErrMessage(ErrorCode.ER_ACCESS_DENIED_ERROR, ""illegal auth packet, the detail error message is "" + e.getMessage()); connection.close(""illegal auth packet""); } finally { TraceManager.finishSpan(this, traceObject); } }","inner-1124:prevent illegal auth packet (#2673) Signed-off-by: dcy ",https://github.com/actiontech/dble/commit/3a4f861790722748c4195eed768c362d3db420d5,,,src/main/java/com/actiontech/dble/services/mysqlauthenticate/MySQLFrontAuthService.java,3,java,False,2021-05-24T05:20:16Z "private int hasNonVanillaEnchant(MethodNode method) { int curLine = -1; int foundLine = -1; for (AbstractInsnNode abstractInsnNode : method.instructions) { if (abstractInsnNode instanceof MethodInsnNode) { MethodInsnNode methodInsnNode = (MethodInsnNode) abstractInsnNode; if (methodInsnNode.owner.equals(""org/bukkit/inventory/meta/ItemMeta"") && methodInsnNode.name.equals(""addEnchant"") && methodInsnNode.desc.equals(""(Lorg/bukkit/enchantments/Enchantment;IZ)Z"")) { AbstractInsnNode enchantLevelNode = (AbstractInsnNode) methodInsnNode.getPrevious().getPrevious(); int enchantLevel = 1; if (enchantLevelNode instanceof IntInsnNode) { enchantLevel = ((IntInsnNode) enchantLevelNode).operand; } if (!(enchantLevelNode.getPrevious() instanceof FieldInsnNode)) { continue; } FieldInsnNode enchantNameNode = (FieldInsnNode) enchantLevelNode.getPrevious(); if (enchantLevel > ENCHANTMENT_MAX_LEVELS.get(enchantNameNode.name)) { foundLine = curLine; } } } else if (abstractInsnNode instanceof LineNumberNode) { curLine = ((LineNumberNode) abstractInsnNode).line; } } return foundLine; }","private int hasNonVanillaEnchant(MethodNode method) { int curLine = -1; int foundLine = -1; for (AbstractInsnNode abstractInsnNode : method.instructions) { if (abstractInsnNode instanceof MethodInsnNode) { MethodInsnNode methodInsnNode = (MethodInsnNode) abstractInsnNode; if (methodInsnNode.owner.equals(""org/bukkit/inventory/meta/ItemMeta"") && methodInsnNode.name.equals(""addEnchant"") && methodInsnNode.desc.equals(""(Lorg/bukkit/enchantments/Enchantment;IZ)Z"")) { AbstractInsnNode enchantLevelNode = (AbstractInsnNode) methodInsnNode.getPrevious().getPrevious(); int enchantLevel = 1; if (enchantLevelNode instanceof IntInsnNode) { enchantLevel = ((IntInsnNode) enchantLevelNode).operand; } if (!(enchantLevelNode.getPrevious() instanceof FieldInsnNode)) { continue; } FieldInsnNode enchantNameNode = (FieldInsnNode) enchantLevelNode.getPrevious(); if (ENCHANTMENT_MAX_LEVELS.containsKey(enchantNameNode.name)) { if (enchantLevel > ENCHANTMENT_MAX_LEVELS.get(enchantNameNode.name)) { foundLine = curLine; } } } } else if (abstractInsnNode instanceof LineNumberNode) { curLine = ((LineNumberNode) abstractInsnNode).line; } } return foundLine; }","Changes Fixed some issues in CrasherCheck Fixed some issues in DispatchCommandCheck Fixed an issue in NonVanillaEnchantCheck Fixed a security issue related to zips Now checks for JNIC usage",https://github.com/OpticFusion1/MCAntiMalware/commit/8b07511019fee60ea2c5bc29b26d68446eabf494,,,MCAntiMalware-Core/src/main/java/optic_fusion1/antimalware/check/impl/NonVanillaEnchantCheck.java,3,java,False,2021-08-18T09:50:22Z "function assignValue(val, key) { if (typeof result[key] === 'object' && typeof val === 'object') { result[key] = merge(result[key], val); } else { result[key] = val; } }","function assignValue(val, key) { if (typeof result[key] === 'object' && typeof val === 'object') { result[key] = deepMerge(result[key], val); } else if (typeof val === 'object') { result[key] = deepMerge({}, val); } else { result[key] = val; } }",Merge branch 'master' into master,https://github.com/axios/axios/commit/1791bed5fa029fdc8347a5e4960c4e2713d9a2a8,CVE-2019-10742,['CWE-755'],dist/axios.js,3,js,False,2019-03-10T18:06:40Z "public static MySQLSinkDTO getFromRequest(MySQLSinkRequest request) { return MySQLSinkDTO.builder() .jdbcUrl(request.getJdbcUrl()) .username(request.getUsername()) .password(request.getPassword()) .primaryKey(request.getPrimaryKey()) .tableName(request.getTableName()) .properties(request.getProperties()) .build(); }","public static MySQLSinkDTO getFromRequest(MySQLSinkRequest request) { String url = filterSensitive(request.getJdbcUrl()); return MySQLSinkDTO.builder() .jdbcUrl(url) .username(request.getUsername()) .password(request.getPassword()) .primaryKey(request.getPrimaryKey()) .tableName(request.getTableName()) .properties(request.getProperties()) .build(); }",[INLONG-5881][Manager] Fix the vulnerability to security attacks for the MySQL JDBC URL (#5884),https://github.com/apache/inlong/commit/41981d937f49db17ae9ccb71b0021a4dfc33cffd,,,inlong-manager/manager-pojo/src/main/java/org/apache/inlong/manager/pojo/sink/mysql/MySQLSinkDTO.java,3,java,False,2022-09-14T06:28:13Z "@Override public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { LOG.info(""Loading Discovery configuration.""); HttpSession sess = request.getSession(true); DiscoveryConfiguration config = (DiscoveryConfiguration) sess.getAttribute(ATTRIBUTE_DISCOVERY_CONFIGURATION); if (config == null) { config = getDiscoveryConfig(); sess.setAttribute(ATTRIBUTE_DISCOVERY_CONFIGURATION, config); } //Update general settings from the incoming request parameters config = GeneralSettingsLoader.load(request, config); String action = request.getParameter(""action""); LOG.debug(""action: {}"", action); //add a Specific if(action.equals(addSpecificAction)){ LOG.debug(""Adding Specific""); String ipAddr = request.getParameter(""specificipaddress""); String timeout = request.getParameter(""specifictimeout""); String retries = request.getParameter(""specificretries""); String foreignSource = request.getParameter(""specificforeignsource""); String location = request.getParameter(""specificlocation""); Specific newSpecific = new Specific(); newSpecific.setAddress(ipAddr); if(timeout!=null && !"""".equals(timeout.trim()) && !timeout.equals(String.valueOf(config.getTimeout().orElse(null)))){ newSpecific.setTimeout(WebSecurityUtils.safeParseLong(timeout)); } if(retries!=null && !"""".equals(retries.trim()) && !retries.equals(String.valueOf(config.getRetries().orElse(null)))){ newSpecific.setRetries(WebSecurityUtils.safeParseInt(retries)); } if(foreignSource!=null && !"""".equals(foreignSource.trim()) && !foreignSource.equals(config.getForeignSource().orElse(null))){ newSpecific.setForeignSource(foreignSource); } if (!LocationUtils.doesLocationsMatch(location, config.getLocation().orElse(LocationUtils.DEFAULT_LOCATION_NAME))) { newSpecific.setLocation(location); } config.addSpecific(newSpecific); } //remove 'Specific' from configuration if(action.equals(removeSpecificAction)){ LOG.debug(""Removing Specific""); String specificIndex = request.getParameter(""index""); int index = WebSecurityUtils.safeParseInt(specificIndex); final int index1 = index; Specific spec= config.getSpecifics().get(index1); boolean result = config.removeSpecific(spec); LOG.debug(""Removing Specific result = {}"", result); } //add an 'Include Range' if(action.equals(addIncludeRangeAction)){ LOG.debug(""Adding Include Range""); String ipAddrBase = request.getParameter(""irbase""); String ipAddrEnd = request.getParameter(""irend""); String timeout = request.getParameter(""irtimeout""); String retries = request.getParameter(""irretries""); String foreignSource = request.getParameter(""irforeignsource""); String location = request.getParameter(""irlocation""); IncludeRange newIR = new IncludeRange(); newIR.setBegin(ipAddrBase); newIR.setEnd(ipAddrEnd); if(timeout!=null && !"""".equals(timeout.trim()) && !timeout.equals(String.valueOf(config.getTimeout().orElse(null)))){ newIR.setTimeout(WebSecurityUtils.safeParseLong(timeout)); } if(retries!=null && !"""".equals(retries.trim()) && !retries.equals(String.valueOf(config.getRetries().orElse(null)))){ newIR.setRetries(WebSecurityUtils.safeParseInt(retries)); } if(foreignSource!=null && !"""".equals(foreignSource.trim()) && !foreignSource.equals(config.getForeignSource().orElse(null))){ newIR.setForeignSource(foreignSource); } if (!LocationUtils.doesLocationsMatch(location, config.getLocation().orElse(LocationUtils.DEFAULT_LOCATION_NAME))) { newIR.setLocation(location); } config.addIncludeRange(newIR); } //remove 'Include Range' from configuration if(action.equals(removeIncludeRangeAction)){ LOG.debug(""Removing Include Range""); String specificIndex = request.getParameter(""index""); int index = WebSecurityUtils.safeParseInt(specificIndex); final int index1 = index; IncludeRange ir= config.getIncludeRanges().get(index1); boolean result = config.removeIncludeRange(ir); LOG.debug(""Removing Include Range result = {}"", result); } //add an 'Include URL' if(action.equals(addIncludeUrlAction)){ LOG.debug(""Adding Include URL""); String url = request.getParameter(""iuurl""); String timeout = request.getParameter(""iutimeout""); String retries = request.getParameter(""iuretries""); String foreignSource = request.getParameter(""iuforeignsource""); String location = request.getParameter(""iulocation""); IncludeUrl iu = new IncludeUrl(); iu.setUrl(url); if(timeout!=null && !"""".equals(timeout.trim()) && !timeout.equals(String.valueOf(config.getTimeout().orElse(null)))){ iu.setTimeout(WebSecurityUtils.safeParseLong(timeout)); } if(retries!=null && !"""".equals(retries.trim()) && !retries.equals(String.valueOf(config.getRetries().orElse(null)))){ iu.setRetries(WebSecurityUtils.safeParseInt(retries)); } if(foreignSource!=null && !"""".equals(foreignSource.trim()) && !foreignSource.equals(config.getForeignSource().orElse(null))){ iu.setForeignSource(foreignSource); } if (!LocationUtils.doesLocationsMatch(location, config.getLocation().orElse(LocationUtils.DEFAULT_LOCATION_NAME))) { iu.setLocation(location); } config.addIncludeUrl(iu); } //remove 'Include URL' from configuration if(action.equals(removeIncludeUrlAction)){ LOG.debug(""Removing Include URL""); String specificIndex = request.getParameter(""index""); int index = WebSecurityUtils.safeParseInt(specificIndex); final int index1 = index; IncludeUrl iu = config.getIncludeUrls().get(index1); boolean result = config.removeIncludeUrl(iu); LOG.debug(""Removing Include URL result = {}"", result); } //add an 'Exclude URL' if(action.equals(addExcludeUrlAction)){ LOG.debug(""Adding Exclude URL""); String url = request.getParameter(""euurl""); String foreignSource = request.getParameter(""euforeignsource""); String location = request.getParameter(""eulocation""); ExcludeUrl eu = new ExcludeUrl(); eu.setUrl(url); if(foreignSource!=null && !"""".equals(foreignSource.trim()) && !foreignSource.equals(config.getForeignSource().orElse(null))){ eu.setForeignSource(foreignSource); } if (!LocationUtils.doesLocationsMatch(location, config.getLocation().orElse(LocationUtils.DEFAULT_LOCATION_NAME))) { eu.setLocation(location); } config.addExcludeUrl(eu); } //remove 'Exclude URL' from configuration if(action.equals(removeExcludeUrlAction)){ LOG.debug(""Removing Exclude URL""); String specificIndex = request.getParameter(""index""); int index = WebSecurityUtils.safeParseInt(specificIndex); final int index1 = index; ExcludeUrl eu = config.getExcludeUrls().get(index1); boolean result = config.removeExcludeUrl(eu); LOG.debug(""Removing Exclude URL result = {}"", result); } //add an 'Exclude Range' if(action.equals(addExcludeRangeAction)){ LOG.debug(""Adding Exclude Range""); String ipAddrBegin = request.getParameter(""erbegin""); String ipAddrEnd = request.getParameter(""erend""); String location = request.getParameter(""erlocation""); ExcludeRange newER = new ExcludeRange(); newER.setBegin(ipAddrBegin); newER.setEnd(ipAddrEnd); if (!LocationUtils.doesLocationsMatch(location, config.getLocation().orElse(LocationUtils.DEFAULT_LOCATION_NAME))) { newER.setLocation(location); } config.addExcludeRange(newER); } //remove 'Exclude Range' from configuration if(action.equals(removeExcludeRangeAction)){ LOG.debug(""Removing Exclude Range""); String specificIndex = request.getParameter(""index""); int index = WebSecurityUtils.safeParseInt(specificIndex); final int index1 = index; ExcludeRange er= config.getExcludeRanges().get(index1); boolean result = config.removeExcludeRange(er); LOG.debug(""Removing Exclude Range result = {}"", result); } //save configuration and restart discovery service if(action.equals(saveAndRestartAction)){ DiscoveryConfigFactory dcf=null; try{ StringWriter configString = new StringWriter(); JaxbUtils.marshal(config, configString); LOG.debug(configString.toString().trim()); dcf = DiscoveryConfigFactory.getInstance(); dcf.saveConfiguration(config); }catch(Throwable ex){ LOG.error(""Error while saving configuration. {}"", ex); throw new ServletException(ex); } EventProxy proxy = null; try { proxy = Util.createEventProxy(); } catch (Throwable me) { LOG.error(me.getMessage()); } EventBuilder bldr = new EventBuilder(EventConstants.DISCOVERYCONFIG_CHANGED_EVENT_UEI, ""ActionDiscoveryServlet""); bldr.setHost(""host""); try { proxy.send(bldr.getEvent()); } catch (Throwable me) { LOG.error(me.getMessage()); } LOG.info(""Restart Discovery requested!""); sess.removeAttribute(ATTRIBUTE_DISCOVERY_CONFIGURATION); response.sendRedirect(Util.calculateUrlBase( request, ""admin/discovery/config-done.jsp"" )); return; } sess.setAttribute(ATTRIBUTE_DISCOVERY_CONFIGURATION, config); RequestDispatcher dispatcher = this.getServletContext().getRequestDispatcher(""/admin/discovery/edit-config.jsp""); dispatcher.forward(request, response); }","@Override public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { LOG.info(""Loading Discovery configuration.""); HttpSession sess = request.getSession(true); DiscoveryConfiguration config = (DiscoveryConfiguration) sess.getAttribute(ATTRIBUTE_DISCOVERY_CONFIGURATION); if (config == null) { config = getDiscoveryConfig(); sess.setAttribute(ATTRIBUTE_DISCOVERY_CONFIGURATION, config); } //Update general settings from the incoming request parameters config = GeneralSettingsLoader.load(request, config); String action = request.getParameter(""action""); LOG.debug(""action: {}"", action); //add a Specific if(action.equals(addSpecificAction)){ LOG.debug(""Adding Specific""); String ipAddr = request.getParameter(""specificipaddress""); String timeout = request.getParameter(""specifictimeout""); String retries = request.getParameter(""specificretries""); String foreignSource = request.getParameter(""specificforeignsource""); String location = request.getParameter(""specificlocation""); Specific newSpecific = new Specific(); newSpecific.setAddress(ipAddr); if(timeout!=null && !"""".equals(timeout.trim()) && !timeout.equals(String.valueOf(config.getTimeout().orElse(null)))){ newSpecific.setTimeout(WebSecurityUtils.safeParseLong(timeout)); } if(retries!=null && !"""".equals(retries.trim()) && !retries.equals(String.valueOf(config.getRetries().orElse(null)))){ newSpecific.setRetries(WebSecurityUtils.safeParseInt(retries)); } if(foreignSource!=null && !"""".equals(foreignSource.trim()) && !foreignSource.equals(config.getForeignSource().orElse(null))){ newSpecific.setForeignSource(foreignSource); } if (!LocationUtils.doesLocationsMatch(location, config.getLocation().orElse(LocationUtils.DEFAULT_LOCATION_NAME))) { newSpecific.setLocation(location); } config.addSpecific(newSpecific); } //remove 'Specific' from configuration if(action.equals(removeSpecificAction)){ LOG.debug(""Removing Specific""); String specificIndex = request.getParameter(""index""); int index = WebSecurityUtils.safeParseInt(specificIndex); final int index1 = index; Specific spec= config.getSpecifics().get(index1); boolean result = config.removeSpecific(spec); LOG.debug(""Removing Specific result = {}"", result); } //add an 'Include Range' if(action.equals(addIncludeRangeAction)){ LOG.debug(""Adding Include Range""); String ipAddrBase = request.getParameter(""irbase""); String ipAddrEnd = request.getParameter(""irend""); String timeout = request.getParameter(""irtimeout""); String retries = request.getParameter(""irretries""); String foreignSource = request.getParameter(""irforeignsource""); String location = request.getParameter(""irlocation""); IncludeRange newIR = new IncludeRange(); newIR.setBegin(ipAddrBase); newIR.setEnd(ipAddrEnd); if(timeout!=null && !"""".equals(timeout.trim()) && !timeout.equals(String.valueOf(config.getTimeout().orElse(null)))){ newIR.setTimeout(WebSecurityUtils.safeParseLong(timeout)); } if(retries!=null && !"""".equals(retries.trim()) && !retries.equals(String.valueOf(config.getRetries().orElse(null)))){ newIR.setRetries(WebSecurityUtils.safeParseInt(retries)); } if(foreignSource!=null && !"""".equals(foreignSource.trim()) && !foreignSource.equals(config.getForeignSource().orElse(null))){ newIR.setForeignSource(foreignSource); } if (!LocationUtils.doesLocationsMatch(location, config.getLocation().orElse(LocationUtils.DEFAULT_LOCATION_NAME))) { newIR.setLocation(location); } config.addIncludeRange(newIR); } //remove 'Include Range' from configuration if(action.equals(removeIncludeRangeAction)){ LOG.debug(""Removing Include Range""); String specificIndex = request.getParameter(""index""); int index = WebSecurityUtils.safeParseInt(specificIndex); final int index1 = index; IncludeRange ir= config.getIncludeRanges().get(index1); boolean result = config.removeIncludeRange(ir); LOG.debug(""Removing Include Range result = {}"", result); } //add an 'Include URL' if(action.equals(addIncludeUrlAction)){ LOG.debug(""Adding Include URL""); String url = WebSecurityUtils.sanitizeString(request.getParameter(""iuurl"")); String timeout = request.getParameter(""iutimeout""); String retries = request.getParameter(""iuretries""); String foreignSource = request.getParameter(""iuforeignsource""); String location = request.getParameter(""iulocation""); IncludeUrl iu = new IncludeUrl(); iu.setUrl(url); if(timeout!=null && !"""".equals(timeout.trim()) && !timeout.equals(String.valueOf(config.getTimeout().orElse(null)))){ iu.setTimeout(WebSecurityUtils.safeParseLong(timeout)); } if(retries!=null && !"""".equals(retries.trim()) && !retries.equals(String.valueOf(config.getRetries().orElse(null)))){ iu.setRetries(WebSecurityUtils.safeParseInt(retries)); } if(foreignSource!=null && !"""".equals(foreignSource.trim()) && !foreignSource.equals(config.getForeignSource().orElse(null))){ iu.setForeignSource(foreignSource); } if (!LocationUtils.doesLocationsMatch(location, config.getLocation().orElse(LocationUtils.DEFAULT_LOCATION_NAME))) { iu.setLocation(location); } config.addIncludeUrl(iu); } //remove 'Include URL' from configuration if(action.equals(removeIncludeUrlAction)){ LOG.debug(""Removing Include URL""); String specificIndex = request.getParameter(""index""); int index = WebSecurityUtils.safeParseInt(specificIndex); final int index1 = index; IncludeUrl iu = config.getIncludeUrls().get(index1); boolean result = config.removeIncludeUrl(iu); LOG.debug(""Removing Include URL result = {}"", result); } //add an 'Exclude URL' if(action.equals(addExcludeUrlAction)){ LOG.debug(""Adding Exclude URL""); String url = WebSecurityUtils.sanitizeString(request.getParameter(""euurl"")); String foreignSource = request.getParameter(""euforeignsource""); String location = request.getParameter(""eulocation""); ExcludeUrl eu = new ExcludeUrl(); eu.setUrl(url); if(foreignSource!=null && !"""".equals(foreignSource.trim()) && !foreignSource.equals(config.getForeignSource().orElse(null))){ eu.setForeignSource(foreignSource); } if (!LocationUtils.doesLocationsMatch(location, config.getLocation().orElse(LocationUtils.DEFAULT_LOCATION_NAME))) { eu.setLocation(location); } config.addExcludeUrl(eu); } //remove 'Exclude URL' from configuration if(action.equals(removeExcludeUrlAction)){ LOG.debug(""Removing Exclude URL""); String specificIndex = request.getParameter(""index""); int index = WebSecurityUtils.safeParseInt(specificIndex); final int index1 = index; ExcludeUrl eu = config.getExcludeUrls().get(index1); boolean result = config.removeExcludeUrl(eu); LOG.debug(""Removing Exclude URL result = {}"", result); } //add an 'Exclude Range' if(action.equals(addExcludeRangeAction)){ LOG.debug(""Adding Exclude Range""); String ipAddrBegin = request.getParameter(""erbegin""); String ipAddrEnd = request.getParameter(""erend""); String location = request.getParameter(""erlocation""); ExcludeRange newER = new ExcludeRange(); newER.setBegin(ipAddrBegin); newER.setEnd(ipAddrEnd); if (!LocationUtils.doesLocationsMatch(location, config.getLocation().orElse(LocationUtils.DEFAULT_LOCATION_NAME))) { newER.setLocation(location); } config.addExcludeRange(newER); } //remove 'Exclude Range' from configuration if(action.equals(removeExcludeRangeAction)){ LOG.debug(""Removing Exclude Range""); String specificIndex = request.getParameter(""index""); int index = WebSecurityUtils.safeParseInt(specificIndex); final int index1 = index; ExcludeRange er= config.getExcludeRanges().get(index1); boolean result = config.removeExcludeRange(er); LOG.debug(""Removing Exclude Range result = {}"", result); } //save configuration and restart discovery service if(action.equals(saveAndRestartAction)){ DiscoveryConfigFactory dcf=null; try{ StringWriter configString = new StringWriter(); JaxbUtils.marshal(config, configString); LOG.debug(configString.toString().trim()); dcf = DiscoveryConfigFactory.getInstance(); dcf.saveConfiguration(config); }catch(Throwable ex){ LOG.error(""Error while saving configuration. {}"", ex); throw new ServletException(ex); } EventProxy proxy = null; try { proxy = Util.createEventProxy(); } catch (Throwable me) { LOG.error(me.getMessage()); } EventBuilder bldr = new EventBuilder(EventConstants.DISCOVERYCONFIG_CHANGED_EVENT_UEI, ""ActionDiscoveryServlet""); bldr.setHost(""host""); try { proxy.send(bldr.getEvent()); } catch (Throwable me) { LOG.error(me.getMessage()); } LOG.info(""Restart Discovery requested!""); sess.removeAttribute(ATTRIBUTE_DISCOVERY_CONFIGURATION); response.sendRedirect(Util.calculateUrlBase( request, ""admin/discovery/config-done.jsp"" )); return; } sess.setAttribute(ATTRIBUTE_DISCOVERY_CONFIGURATION, config); RequestDispatcher dispatcher = this.getServletContext().getRequestDispatcher(""/admin/discovery/edit-config.jsp""); dispatcher.forward(request, response); }",NMS-14591: Fix stored XSS issues,https://github.com/OpenNMS/opennms/commit/16cbb759360add1332572c8d992a5c3aed72063a,,,opennms-webapp/src/main/java/org/opennms/web/admin/discovery/ActionDiscoveryServlet.java,3,java,False,2022-08-12T13:46:32Z "@Override public String toString() { if (mParentSession != null && mIsStartedFromActiveSession) { // Log.startSession was called from within another active session. Use the parent's // Id instead of the child to reduce confusion. return mParentSession.toString(); } else { StringBuilder methodName = new StringBuilder(); methodName.append(getFullMethodPath(false /*truncatePath*/)); if (mOwnerInfo != null && !mOwnerInfo.isEmpty()) { methodName.append(""(""); methodName.append(mOwnerInfo); methodName.append("")""); } return methodName.toString() + ""@"" + getFullSessionId(); } }","@Override public String toString() { Session sessionToPrint = this; if (getParentSession() != null && isStartedFromActiveSession()) { // Log.startSession was called from within another active session. Use the parent's // Id instead of the child to reduce confusion. sessionToPrint = getRootSession(""toString""); } StringBuilder methodName = new StringBuilder(); methodName.append(sessionToPrint.getFullMethodPath(false /*truncatePath*/)); if (sessionToPrint.getOwnerInfo() != null && !sessionToPrint.getOwnerInfo().isEmpty()) { methodName.append(""(""); methodName.append(sessionToPrint.getOwnerInfo()); methodName.append("")""); } return methodName.toString() + ""@"" + sessionToPrint.getFullSessionId(); }","Bound Telecom logging recursion Put a bound on the recursion in Session#toString to ensure we do not accidently cause a Stack overflow Bug: 186694546 Test: atest TeleServiceTests Merged-In: I52f44dd02d0d860d0894e9b84fded8cf5ff5a18e Change-Id: I52f44dd02d0d860d0894e9b84fded8cf5ff5a18e",https://github.com/omnirom/android_frameworks_base/commit/9ee6f302730d426b33d5f80bd1fca761af566d88,,,telecomm/java/android/telecom/Logging/Session.java,3,java,False,2021-04-29T20:59:16Z "public static TriPhasePreProcessor getTriPhasePreProcessor(final SingleSign sSign) throws AOInvalidFormatException { if (sSign == null) { throw new IllegalArgumentException(""La firma no puede ser nula""); //$NON-NLS-1$ } switch(sSign.getSignFormat()) { case PADES: return new PAdESTriPhasePreProcessor(); case CADES: return new CAdESTriPhasePreProcessor(); case CADES_ASIC: return new CAdESASiCSTriPhasePreProcessor(); case XADES: return new XAdESTriPhasePreProcessor(); case XADES_ASIC: return new XAdESASiCSTriPhasePreProcessor(); case FACTURAE: return new FacturaETriPhasePreProcessor(); case PKCS1: return new Pkcs1TriPhasePreProcessor(); default: throw new AOInvalidFormatException(""Formato de firma no soportado: "" + sSign.getSignFormat()); //$NON-NLS-1$ } }","public static TriPhasePreProcessor getTriPhasePreProcessor(final SingleSign sSign) throws AOInvalidFormatException { if (sSign == null) { throw new IllegalArgumentException(""La firma no puede ser nula""); //$NON-NLS-1$ } switch(sSign.getSignFormat()) { case PADES: configurePdfShadowAttackParameters(sSign.getExtraParams()); return new PAdESTriPhasePreProcessor(); case CADES: return new CAdESTriPhasePreProcessor(); case CADES_ASIC: return new CAdESASiCSTriPhasePreProcessor(); case XADES: return new XAdESTriPhasePreProcessor(); case XADES_ASIC: return new XAdESASiCSTriPhasePreProcessor(); case FACTURAE: return new FacturaETriPhasePreProcessor(); case PKCS1: return new Pkcs1TriPhasePreProcessor(); default: throw new AOInvalidFormatException(""Formato de firma no soportado: "" + sSign.getSignFormat()); //$NON-NLS-1$ } }","Correcciones PDF Shadow Attack - Se corrige comportamiento en la operación invocada de firmar y guardar. - Mejora del proceso de confirmación al usuario. - Se incorpora el comportamiento por defecto para la comprobación de PSA en las operaciones de firma de lotes.",https://github.com/ctt-gob-es/clienteafirma/commit/3e96a60350fbe2197ed5d56f781fee715a931e38,,,afirma-server-triphase-signer/src/main/java/es/gob/afirma/signers/batch/TriPhaseHelper.java,3,java,False,2022-06-01T11:16:51Z "public static void spawnNonBeeMobsForChunkGeneration(ServerLevelAccessor serverLevelAccessor, Holder holder, ChunkPos chunkPos, RandomSource randomSource) { MobSpawnSettings mobSpawnSettings = holder.value().getMobSettings(); WeightedRandomList weightedRandomList = mobSpawnSettings.getMobs(MobCategory.CREATURE); weightedRandomList = WeightedRandomList.create(weightedRandomList.unwrap().stream().filter(e -> e.type != EntityType.BEE).toList()); if (weightedRandomList.isEmpty()) { return; } int i = chunkPos.getMinBlockX(); int j = chunkPos.getMinBlockZ(); int seaLevel = ((ServerChunkCache)serverLevelAccessor.getChunkSource()).getGenerator().getSeaLevel(); while (randomSource.nextFloat() < mobSpawnSettings.getCreatureProbability() * 0.5) { Optional optional = weightedRandomList.getRandom(randomSource); if (optional.isEmpty()) continue; MobSpawnSettings.SpawnerData spawnerData = optional.get(); int k = spawnerData.minCount + randomSource.nextInt(1 + spawnerData.maxCount - spawnerData.minCount); SpawnGroupData spawnGroupData = null; int x = i + randomSource.nextInt(16); int z = j + randomSource.nextInt(16); int n = x; int o = z; for (int p = 0; p < k; ++p) { BlockPos.MutableBlockPos mutableBlockPos = new BlockPos.MutableBlockPos(x, randomSource.nextInt(250 - seaLevel) + seaLevel, z); if (serverLevelAccessor.dimensionType().hasCeiling()) { do { mutableBlockPos.move(Direction.DOWN); } while (!serverLevelAccessor.getBlockState(mutableBlockPos).isAir()); do { mutableBlockPos.move(Direction.DOWN); } while (serverLevelAccessor.getBlockState(mutableBlockPos).isAir() && mutableBlockPos.getY() > serverLevelAccessor.getMinBuildHeight()); } if (spawnerData.type.canSummon()) { Entity entity; float f = spawnerData.type.getWidth(); double d = Mth.clamp(x, (double)i + (double)f, (double)i + 16.0 - (double)f); double e = Mth.clamp(z, (double)j + (double)f, (double)j + 16.0 - (double)f); try { entity = spawnerData.type.create(serverLevelAccessor.getLevel()); } catch (Exception exception) { Bumblezone.LOGGER.warn(""Failed to create mob"", exception); continue; } entity.moveTo(d, mutableBlockPos.getY(), e, randomSource.nextFloat() * 360.0f, 0.0f); if (entity instanceof Mob mob && mob.checkSpawnObstruction(serverLevelAccessor)) { spawnGroupData = mob.finalizeSpawn(serverLevelAccessor, serverLevelAccessor.getCurrentDifficultyAt(mob.blockPosition()), MobSpawnType.CHUNK_GENERATION, spawnGroupData, null); serverLevelAccessor.addFreshEntityWithPassengers(mob); } } x += randomSource.nextInt(5) - randomSource.nextInt(5); z += randomSource.nextInt(5) - randomSource.nextInt(5); while (x < i || x >= i + 16 || z < j || z >= j + 16) { x = n + randomSource.nextInt(5) - randomSource.nextInt(5); z = o + randomSource.nextInt(5) - randomSource.nextInt(5); } } } }","public static void spawnNonBeeMobsForChunkGeneration(ServerLevelAccessor serverLevelAccessor, Holder holder, ChunkPos chunkPos, RandomSource randomSource) { MobSpawnSettings mobSpawnSettings = holder.value().getMobSettings(); WeightedRandomList weightedRandomList = mobSpawnSettings.getMobs(MobCategory.CREATURE); weightedRandomList = WeightedRandomList.create(weightedRandomList.unwrap().stream().filter(e -> e.type != EntityType.BEE).toList()); if (weightedRandomList.isEmpty()) { return; } int i = chunkPos.getMinBlockX(); int j = chunkPos.getMinBlockZ(); int seaLevel = ((ServerChunkCache)serverLevelAccessor.getChunkSource()).getGenerator().getSeaLevel(); while (randomSource.nextFloat() < mobSpawnSettings.getCreatureProbability() * 0.5) { Optional optional = weightedRandomList.getRandom(randomSource); if (optional.isEmpty()) continue; MobSpawnSettings.SpawnerData spawnerData = optional.get(); int k = spawnerData.minCount + randomSource.nextInt(1 + spawnerData.maxCount - spawnerData.minCount); SpawnGroupData spawnGroupData = null; int x = i + randomSource.nextInt(16); int z = j + randomSource.nextInt(16); int n = x; int o = z; for (int p = 0; p < k; ++p) { BlockPos.MutableBlockPos mutableBlockPos = new BlockPos.MutableBlockPos(x, randomSource.nextInt(250 - seaLevel) + seaLevel, z); if (serverLevelAccessor.dimensionType().hasCeiling()) { do { mutableBlockPos.move(Direction.DOWN); } while (!serverLevelAccessor.getBlockState(mutableBlockPos).isAir()); do { mutableBlockPos.move(Direction.DOWN); } while (serverLevelAccessor.getBlockState(mutableBlockPos).isAir() && mutableBlockPos.getY() > serverLevelAccessor.getMinBuildHeight()); } if (spawnerData.type.canSummon()) { Entity entity; float f = spawnerData.type.getWidth(); double d = Mth.clamp(x, (double)i + (double)f, (double)i + 16.0 - (double)f); double e = Mth.clamp(z, (double)j + (double)f, (double)j + 16.0 - (double)f); if (!serverLevelAccessor.getWorldBorder().isWithinBounds(d, e)) { continue; } try { entity = spawnerData.type.create(serverLevelAccessor.getLevel()); } catch (Exception exception) { Bumblezone.LOGGER.warn(""Failed to create mob"", exception); continue; } entity.moveTo(d, mutableBlockPos.getY(), e, randomSource.nextFloat() * 360.0f, 0.0f); if (entity instanceof Mob mob && mob.checkSpawnObstruction(serverLevelAccessor)) { spawnGroupData = mob.finalizeSpawn(serverLevelAccessor, serverLevelAccessor.getCurrentDifficultyAt(mob.blockPosition()), MobSpawnType.CHUNK_GENERATION, spawnGroupData, null); serverLevelAccessor.addFreshEntityWithPassengers(mob); } } x += randomSource.nextInt(5) - randomSource.nextInt(5); z += randomSource.nextInt(5) - randomSource.nextInt(5); while (x < i || x >= i + 16 || z < j || z >= j + 16) { x = n + randomSource.nextInt(5) - randomSource.nextInt(5); z = o + randomSource.nextInt(5) - randomSource.nextInt(5); } } } }",fixed world border crash,https://github.com/TelepathicGrunt/Bumblezone/commit/14b7e582a769167f70a5bf3b5a5f33594333796c,,,src/main/java/com/telepathicgrunt/the_bumblezone/world/dimension/BzChunkGenerator.java,3,java,False,2022-07-20T00:28:19Z "@PostMapping(value = {""/api/package/addAttachment""}, produces = MediaType.APPLICATION_JSON_VALUE) public Result addAttachment(@CurrentSecurityContext SysUser requestor, @RequestParam(value = ""fileSetId"") String fileSetId, @RequestParam(value = ""fileType"") String fileType, @RequestParam(value = ""loadType"", required = false) String loadType, @RequestParam(value = ""loadDir"", required = false) String loadDir, @RequestParam(value = ""attachment"") MultipartFile attachment) { if (requestor == null) { return Result.error(HttpStatus.UNAUTHORIZED.value(), ""unauthorized""); } if (attachment.isEmpty()) { return Result.error(HttpStatus.BAD_REQUEST.value(), ""attachment file empty""); } TestFileSet testFileSet = testFileSetService.getFileSetInfo(fileSetId); if (testFileSet == null) { return Result.error(HttpStatus.BAD_REQUEST.value(), ""Error fileSetId""); } if (!sysUserService.checkUserAdmin(requestor) && !userTeamManagementService.checkRequestorTeamRelation(requestor, testFileSet.getTeamId())) { return Result.error(HttpStatus.UNAUTHORIZED.value(), ""Unauthorized, the TestFileSet doesn't belong to user's Teams""); } String[] limitFileTypes = null; switch (fileType) { case BlobFileInfo.FileType.WINDOWS_APP: limitFileTypes = new String[]{FILE_SUFFIX.APPX_FILE}; break; case BlobFileInfo.FileType.COMMON_FILE: Assert.notNull(loadType, ""loadType is required""); Assert.notNull(loadDir, ""loadDir is required""); Assert.isTrue(FileUtil.isLegalFolderPath(loadDir), ""illegal loadDir""); if (BlobFileInfo.LoadType.UNZIP.equals(loadType)) { limitFileTypes = new String[]{FILE_SUFFIX.ZIP_FILE}; } break; default: return Result.error(HttpStatus.BAD_REQUEST.value(), ""Error fileType""); } String newFileName = attachment.getOriginalFilename().replaceAll("" "", """"); String fileRelativePath = FileUtil.getPathForToday(); String parentDir = CENTER_FILE_BASE_DIR + fileRelativePath; try { File savedAttachment = attachmentService.verifyAndSaveFile(attachment, parentDir, false, newFileName, limitFileTypes); BlobFileInfo blobFileInfo = new BlobFileInfo(savedAttachment, fileRelativePath, fileType, loadType, loadDir); attachmentService.addAttachment(fileSetId, EntityFileRelation.EntityType.APP_FILE_SET, blobFileInfo, savedAttachment, logger); testFileSet.setAttachments(attachmentService.getAttachments(fileSetId, EntityFileRelation.EntityType.APP_FILE_SET)); testFileSetService.saveFileSetToMem(testFileSet); return Result.ok(testFileSet); } catch (HydraLabRuntimeException e) { e.printStackTrace(); return Result.error(e.getCode(), e.getMessage()); } catch (Exception e) { e.printStackTrace(); return Result.error(HttpStatus.INTERNAL_SERVER_ERROR.value(), e.getMessage()); } }","@PostMapping(value = {""/api/package/addAttachment""}, produces = MediaType.APPLICATION_JSON_VALUE) public Result addAttachment(@CurrentSecurityContext SysUser requestor, @RequestParam(value = ""fileSetId"") String fileSetId, @RequestParam(value = ""fileType"") String fileType, @RequestParam(value = ""loadType"", required = false) String loadType, @RequestParam(value = ""loadDir"", required = false) String loadDir, @RequestParam(value = ""attachment"") MultipartFile attachment) { if (requestor == null) { return Result.error(HttpStatus.UNAUTHORIZED.value(), ""unauthorized""); } if (attachment.isEmpty()) { return Result.error(HttpStatus.BAD_REQUEST.value(), ""attachment file empty""); } TestFileSet testFileSet = testFileSetService.getFileSetInfo(fileSetId); if (testFileSet == null) { return Result.error(HttpStatus.BAD_REQUEST.value(), ""Error fileSetId""); } if (!sysUserService.checkUserAdmin(requestor) && !userTeamManagementService.checkRequestorTeamRelation(requestor, testFileSet.getTeamId())) { return Result.error(HttpStatus.UNAUTHORIZED.value(), ""Unauthorized, the TestFileSet doesn't belong to user's Teams""); } String[] limitFileTypes = null; switch (fileType) { case BlobFileInfo.FileType.WINDOWS_APP: limitFileTypes = new String[]{FILE_SUFFIX.APPX_FILE}; break; case BlobFileInfo.FileType.COMMON_FILE: Assert.notNull(loadType, ""loadType is required""); Assert.notNull(loadDir, ""loadDir is required""); Assert.isTrue(FileUtil.isLegalFolderPath(loadDir), ""illegal loadDir""); if (BlobFileInfo.LoadType.UNZIP.equals(loadType)) { limitFileTypes = new String[]{FILE_SUFFIX.ZIP_FILE}; } break; default: return Result.error(HttpStatus.BAD_REQUEST.value(), ""Error fileType""); } try { String newFileName = FileUtil.getLegalFileName(attachment.getOriginalFilename()); String fileRelativePath = FileUtil.getPathForToday(); String parentDir = CENTER_FILE_BASE_DIR + fileRelativePath; File savedAttachment = attachmentService.verifyAndSaveFile(attachment, parentDir, false, newFileName, limitFileTypes); BlobFileInfo blobFileInfo = new BlobFileInfo(savedAttachment, fileRelativePath, fileType, loadType, loadDir); attachmentService.addAttachment(fileSetId, EntityFileRelation.EntityType.APP_FILE_SET, blobFileInfo, savedAttachment, logger); testFileSet.setAttachments(attachmentService.getAttachments(fileSetId, EntityFileRelation.EntityType.APP_FILE_SET)); testFileSetService.saveFileSetToMem(testFileSet); return Result.ok(testFileSet); } catch (HydraLabRuntimeException e) { e.printStackTrace(); return Result.error(e.getCode(), e.getMessage()); } catch (Exception e) { e.printStackTrace(); return Result.error(HttpStatus.INTERNAL_SERVER_ERROR.value(), e.getMessage()); } }","Fix security alert (#106) * format file name * fix: Inclusion of functionality from an untrusted source",https://github.com/microsoft/HydraLab/commit/b68eb716e30d75930e39c836ae3a888eb3536b3a,,,center/src/main/java/com/microsoft/hydralab/center/controller/PackageSetController.java,3,java,False,2022-11-02T07:35:05Z "@Override public Promise searchUsers(Collection usernames, int limit) { return delegate.searchUsers(usernames, limit) .then(matches -> { // override roles return new Users( matches.stream().map(user -> new User(user.getUserId(), ADMINPARTY_ROLES)).collect(Collectors.toList()), matches.getLimit(), matches.getTotal() ); }); }","@Override public Promise searchUsers(Collection usernames, int limit) { return delegate.searchUsers(usernames, limit) .then(matches -> { // override roles return new Users( matches.stream().map(user -> overrideUserRoles(user)).collect(Collectors.toList()), matches.getLimit(), matches.getTotal() ); }); }","fix(auth): ensure when authenticating through admin party wrapper... ...user gets admin privileges properly",https://github.com/b2ihealthcare/snow-owl/commit/64738e65057c8a06e7863c499229fcc15ea88f84,,,core/com.b2international.snowowl.core/src/com/b2international/snowowl/core/identity/AdminPartyIdentityProvider.java,3,java,False,2022-11-28T10:58:30Z "public void run() { try (BufferedReader br = new BufferedReader(new InputStreamReader(process.getInputStream()))) { String line; while (null != (line = br.readLine())) { Matcher matcher = pattern.matcher(line); if (matcher.find()) { String url = matcher.group(1); CustomTabsIntent.Builder builder = new CustomTabsIntent.Builder(); CustomTabsIntent customTabsIntent = builder.build(); customTabsIntent.launchUrl(context, Uri.parse(url)); // Do NOT break here, or the stream will be closed. // When rclone then tries to write to the stream, it will receive SIGPIPE // and rclone will exit confused why it can't just output its log messages. // Instead, wait for rclone to close the stream. } } } catch (IOException e) { FLog.e(TAG, ""doInBackground: could not read auth url"", e); process.destroy(); } }","public void run() { try (BufferedReader br = new BufferedReader(new InputStreamReader(process.getInputStream()))) { String line; while (null != (line = br.readLine())) { Matcher matcher = pattern.matcher(line); if (matcher.find()) { String url = matcher.group(1); if (url != null) { launchBrowser(context, url); } // Do NOT break here, or the stream will be closed. // When rclone then tries to write to the stream, it will receive SIGPIPE // and rclone will exit confused why it can't just output its log messages. // Instead, wait for rclone to close the stream. } } } catch (IOException e) { FLog.e(TAG, ""doInBackground: could not read auth url"", e); process.destroy(); } }","Fix: Crash when using OAuth on misconfigured devices Some devices will try to open the browser launch intent with a non-exported third party activity leading to a crash. We cannot fix the third party app, but this fix at least prevents the crash. Ref: SecurityException @ OauthHelper:72",https://github.com/x0b/rcx/commit/49a5bd3abf07424c4291f0f902946d602351f856,,,app/src/main/java/ca/pkay/rcloneexplorer/RemoteConfig/OauthHelper.java,3,java,False,2020-12-07T20:17:18Z "@Override public void invoke(SysUserImportVo userVo, AnalysisContext context) { SysUser user = this.userService.selectUserByUserName(userVo.getUserName()); try { // 验证是否存在这个用户 if (StringUtils.isNull(user)) { user = BeanUtil.toBean(userVo, SysUser.class); user.setPassword(password); user.setCreateBy(operName); userService.insertUser(user); successNum++; successMsg.append(""
"").append(successNum).append(""、账号 "").append(user.getUserName()).append("" 导入成功""); } else if (isUpdateSupport) { user.setUpdateBy(operName); userService.updateUser(user); successNum++; successMsg.append(""
"").append(successNum).append(""、账号 "").append(user.getUserName()).append("" 更新成功""); } else { failureNum++; failureMsg.append(""
"").append(failureNum).append(""、账号 "").append(user.getUserName()).append("" 已存在""); } } catch (Exception e) { failureNum++; String msg = ""
"" + failureNum + ""、账号 "" + user.getUserName() + "" 导入失败:""; failureMsg.append(msg).append(e.getMessage()); log.error(msg, e); } }","@Override public void invoke(SysUserImportVo userVo, AnalysisContext context) { SysUser user = this.userService.selectUserByUserName(userVo.getUserName()); try { // 验证是否存在这个用户 if (StringUtils.isNull(user)) { user = BeanUtil.toBean(userVo, SysUser.class); ValidatorUtils.validate(user); user.setPassword(password); user.setCreateBy(operName); userService.insertUser(user); successNum++; successMsg.append(""
"").append(successNum).append(""、账号 "").append(user.getUserName()).append("" 导入成功""); } else if (isUpdateSupport) { ValidatorUtils.validate(user); user.setUpdateBy(operName); userService.updateUser(user); successNum++; successMsg.append(""
"").append(successNum).append(""、账号 "").append(user.getUserName()).append("" 更新成功""); } else { failureNum++; failureMsg.append(""
"").append(failureNum).append(""、账号 "").append(user.getUserName()).append("" 已存在""); } } catch (Exception e) { failureNum++; String msg = ""
"" + failureNum + ""、账号 "" + user.getUserName() + "" 导入失败:""; failureMsg.append(msg).append(e.getMessage()); log.error(msg, e); } }",add 增加 自定义 Xss 校验注解 用户导入增加 Bean 校验,https://github.com/dromara/RuoYi-Vue-Plus/commit/2455d0b859708e39fa9fd5b710bebee45c32b085,,,ruoyi-system/src/main/java/com/ruoyi/system/listener/SysUserImportListener.java,3,java,False,2021-12-15T07:03:44Z "private void rightIndexing(ExecutionContext ec) { //get input and requested index range CacheableData in = ec.getCacheableData(input1); IndexRange ixrange = getIndexRange(ec); //prepare output federation map (copy-on-write) FederationMap fedMap = in.getFedMapping().filter(ixrange); //modify federated ranges in place String[] instStrings = new String[fedMap.getSize()]; //create new frame schema List schema = new ArrayList<>(); // replace old reshape values for each worker int i = 0; for(Pair e : fedMap.getMap()) { FederatedRange range = e.getKey(); long rs = range.getBeginDims()[0], re = range.getEndDims()[0], cs = range.getBeginDims()[1], ce = range.getEndDims()[1]; long rsn = (ixrange.rowStart >= rs) ? (ixrange.rowStart - rs) : 0; long ren = (ixrange.rowEnd >= rs && ixrange.rowEnd < re) ? (ixrange.rowEnd - rs) : (re - rs - 1); long csn = (ixrange.colStart >= cs) ? (ixrange.colStart - cs) : 0; long cen = (ixrange.colEnd >= cs && ixrange.colEnd < ce) ? (ixrange.colEnd - cs) : (ce - cs - 1); range.setBeginDim(0, Math.max(rs - ixrange.rowStart, 0)); range.setBeginDim(1, Math.max(cs - ixrange.colStart, 0)); range.setEndDim(0, (ixrange.rowEnd >= re ? re-ixrange.rowStart : ixrange.rowEnd-ixrange.rowStart + 1)); range.setEndDim(1, (ixrange.colEnd >= ce ? ce-ixrange.colStart : ixrange.colEnd-ixrange.colStart + 1)); long[] newIx = new long[]{rsn, ren, csn, cen}; // change 4 indices in instString instStrings[i] = modifyIndices(newIx, 3, 7); if(input1.isFrame()) { //modify frame schema if(in.isFederated(FType.ROW)) schema = Arrays.asList(((FrameObject) in).getSchema((int) csn, (int) cen)); else Collections.addAll(schema, ((FrameObject) in).getSchema((int) csn, (int) cen)); } i++; } long id = FederationUtils.getNextFedDataID(); FederatedRequest tmp = new FederatedRequest(FederatedRequest.RequestType.PUT_VAR, id, in.getMetaData().getDataCharacteristics(), in.getDataType()); Types.ExecType execType = InstructionUtils.getExecType(instString); if (execType == Types.ExecType.FED) execType = Types.ExecType.CP; FederatedRequest[] fr1 = FederationUtils.callInstruction(instStrings, output, id, new CPOperand[] {input1}, new long[] {fedMap.getID()}, execType); fedMap.execute(getTID(), true, tmp); fedMap.execute(getTID(), true, fr1, new FederatedRequest[0]); if(input1.isFrame()) { FrameObject out = ec.getFrameObject(output); out.setSchema(schema.toArray(new Types.ValueType[0])); out.getDataCharacteristics().setDimension(fedMap.getMaxIndexInRange(0), fedMap.getMaxIndexInRange(1)); out.setFedMapping(fedMap.copyWithNewID(fr1[0].getID())); } else { MatrixObject out = ec.getMatrixObject(output); out.getDataCharacteristics().set(fedMap.getMaxIndexInRange(0), fedMap.getMaxIndexInRange(1), (int) ((MatrixObject)in).getBlocksize()); out.setFedMapping(fedMap.copyWithNewID(fr1[0].getID())); } }","private void rightIndexing(ExecutionContext ec) { //get input and requested index range CacheableData in = ec.getCacheableData(input1); IndexRange ixrange = getIndexRange(ec); //prepare output federation map (copy-on-write) FederationMap fedMap = in.getFedMapping().filter(ixrange); //modify federated ranges in place String[] instStrings = new String[fedMap.getSize()]; //create new frame schema List schema = new ArrayList<>(); // replace old reshape values for each worker int i = 0; for(Pair e : fedMap.getMap()) { FederatedRange range = e.getKey(); long rs = range.getBeginDims()[0], re = range.getEndDims()[0], cs = range.getBeginDims()[1], ce = range.getEndDims()[1]; long rsn = (ixrange.rowStart >= rs) ? (ixrange.rowStart - rs) : 0; long ren = (ixrange.rowEnd >= rs && ixrange.rowEnd < re) ? (ixrange.rowEnd - rs) : (re - rs - 1); long csn = (ixrange.colStart >= cs) ? (ixrange.colStart - cs) : 0; long cen = (ixrange.colEnd >= cs && ixrange.colEnd < ce) ? (ixrange.colEnd - cs) : (ce - cs - 1); range.setBeginDim(0, Math.max(rs - ixrange.rowStart, 0)); range.setBeginDim(1, Math.max(cs - ixrange.colStart, 0)); range.setEndDim(0, (ixrange.rowEnd >= re ? re-ixrange.rowStart : ixrange.rowEnd-ixrange.rowStart + 1)); range.setEndDim(1, (ixrange.colEnd >= ce ? ce-ixrange.colStart : ixrange.colEnd-ixrange.colStart + 1)); long[] newIx = new long[]{rsn, ren, csn, cen}; // change 4 indices in instString instStrings[i] = modifyIndices(newIx, 3, 7); if(input1.isFrame()) { //modify frame schema if(in.isFederated(FType.ROW)) schema = Arrays.asList(((FrameObject) in).getSchema((int) csn, (int) cen)); else Collections.addAll(schema, ((FrameObject) in).getSchema((int) csn, (int) cen)); } i++; } long id = FederationUtils.getNextFedDataID(); FederatedRequest tmp = new FederatedRequest(FederatedRequest.RequestType.PUT_VAR, id, in.getMetaData().getDataCharacteristics(), in.getDataType()); Types.ExecType execType = InstructionUtils.getExecType(instString); if (execType == Types.ExecType.FED) execType = Types.ExecType.CP; FederatedRequest[] fr1 = FederationUtils.callInstruction(instStrings, output, id, new CPOperand[] {input1}, new long[] {fedMap.getID()}, execType); fedMap.execute(getTID(), true, tmp); Future[] ret = fedMap.execute(getTID(), true, fr1, new FederatedRequest[0]); //set output characteristics for frames and matrices CacheableData out = ec.getCacheableData(output); if(input1.isFrame()) ((FrameObject) out).setSchema(schema.toArray(new Types.ValueType[0])); out.getDataCharacteristics() .setDimension(fedMap.getMaxIndexInRange(0), fedMap.getMaxIndexInRange(1)) .setBlocksize(in.getBlocksize()) .setNonZeros(FederationUtils.sumNonZeros(ret)); out.setFedMapping(fedMap.copyWithNewID(fr1[0].getID())); }","[SYSTEMDS-3451] Fix missing NNZ propagation in federated instructions For many federated operations that output federated data, no information on the number of non-zeros was propagated back to the coordinator and hence, suboptional plan choices where made during dynamic recompilation. We now generally return the nnz of instruction outputs from all EXEC_INST and EXEC_UDF types, and provide utils to obtain this info from the federated responses. The exploitation of this info was already introduced into right indexing, append, and replace which are often executed on the main federated matrix. On a scenario of training MLogReg on 3 workers and a Critero subset with 1M rows and ~98M columns after one hot encoding, this patch reduced the end-to-end execution time by more than 4x but is generally applicable. a) STATS BEFORE PATCH: Total elapsed time: 402.882 sec. Total compilation time: 2.046 sec. Total execution time: 400.837 sec. Cache hits (Mem/Li/WB/FS/HDFS): 4452/0/0/0/0. Cache writes (Li/WB/FS/HDFS): 4/1576/0/0. Cache times (ACQr/m, RLS, EXP): 0.085/0.051/0.389/0.000 sec. HOP DAGs recompiled (PRED, SB): 0/248. HOP DAGs recompile time: 1.810 sec. Functions recompiled: 1. Functions recompile time: 0.253 sec. Federated I/O (Read, Put, Get): 3/409/134. Federated Execute (Inst, UDF): 436/6. Fed Put Count (Sc/Li/Ma/Fr/MC): 0/0/378/0/31. Fed Put Bytes (Mat/Frame): 1507638888/0 Bytes. Federated prefetch count: 0. Total JIT compile time: 29.476 sec. Total JVM GC count: 18. Total JVM GC time: 0.442 sec. Heavy hitter instructions: 1 m_multiLogReg 370.387 1 2 fed_r' 221.613 29 3 fed_mmchain 53.184 63 4 fed_ba+* 36.619 62 5 fed_transformencode 17.992 1 6 n+ 13.264 121 7 * 11.882 754 8 fed_fedinit 8.670 1 9 - 4.210 361 10 +* 3.892 127 b) STATS AFTER PATCH: Total elapsed time: 88.907 sec. Total compilation time: 2.065 sec. Total execution time: 86.842 sec. Cache hits (Mem/Li/WB/FS/HDFS): 4510/0/0/0/0. Cache writes (Li/WB/FS/HDFS): 4/1634/0/0. Cache times (ACQr/m, RLS, EXP): 0.049/0.034/0.311/0.000 sec. HOP DAGs recompiled (PRED, SB): 0/248. HOP DAGs recompile time: 0.506 sec. Functions recompiled: 1. Functions recompile time: 0.268 sec. Federated I/O (Read, Put, Get): 3/380/134. Federated Execute (Inst, UDF): 378/6. Fed Put Count (Sc/Li/Ma/Fr/MC): 0/0/378/0/2. Fed Put Bytes (Mat/Frame): 1507638888/0 Bytes. Federated prefetch count: 0. Total JIT compile time: 19.534 sec. Total JVM GC count: 17. Total JVM GC time: 0.436 sec. Heavy hitter instructions: 1 m_multiLogReg 56.603 1 2 fed_mmchain 21.669 63 3 fed_transformencode 18.811 1 4 fed_ba+* 12.250 62 5 fed_fedinit 9.061 1 6 n+ 5.271 121 7 * 3.699 754 8 fed_rightIndex 1.557 2 9 fed_uack+ 1.475 2 10 +* 1.330 127",https://github.com/apache/systemds/commit/03508eec80f3a144c9d311e8d4092f979abb5dee,,,src/main/java/org/apache/sysds/runtime/instructions/fed/IndexingFEDInstruction.java,3,java,False,2022-10-19T19:11:19Z "private SecureSocketConfig getSecureSocketConfig(ExpressionNode expressionNode) { MappingConstructorExpressionNode expressionNode1 = (MappingConstructorExpressionNode) expressionNode; SeparatedNodeList fields = expressionNode1.fields(); SecureSocketConfig secureSocketConfig = new SecureSocketConfig(); for (MappingFieldNode field : fields) { if (field.kind() != SyntaxKind.SPECIFIC_FIELD) { continue; } SpecificFieldNode specificFieldNode = (SpecificFieldNode) field; String nameOfIdentifier = getNameOfIdentifier(specificFieldNode.fieldName()); if ((""certFile"").equals(nameOfIdentifier)) { secureSocketConfig.setCertFile(extractString(specificFieldNode.valueExpr().get())); } else if (""keyFile"".equals(nameOfIdentifier)) { secureSocketConfig.setKeyFile(extractString(specificFieldNode.valueExpr().get())); } else if (""path"".equals(nameOfIdentifier)) { secureSocketConfig.setPath(extractString(specificFieldNode.valueExpr().get())); } } return secureSocketConfig; }","private Optional getSecureSocketConfig(ExpressionNode expressionNode) { MappingConstructorExpressionNode expressionNode1 = (MappingConstructorExpressionNode) expressionNode; SeparatedNodeList fields = expressionNode1.fields(); SecureSocketConfig secureSocketConfig = new SecureSocketConfig(); for (MappingFieldNode field : fields) { if (field.kind() != SyntaxKind.SPECIFIC_FIELD) { continue; } SpecificFieldNode specificFieldNode = (SpecificFieldNode) field; String nameOfIdentifier = getNameOfIdentifier(specificFieldNode.fieldName()); if ((""certFile"").equals(nameOfIdentifier)) { secureSocketConfig.setCertFile(extractString(specificFieldNode.valueExpr().get())); } else if (""keyFile"".equals(nameOfIdentifier)) { secureSocketConfig.setKeyFile(extractString(specificFieldNode.valueExpr().get())); } else if (""path"".equals(nameOfIdentifier)) { secureSocketConfig.setPath(extractString(specificFieldNode.valueExpr().get())); } } if (secureSocketConfig.getPath() == null && secureSocketConfig.getCertFile() == null && secureSocketConfig.getKeyFile() == null) { return Optional.empty(); } return Optional.of(secureSocketConfig); }",Fix secure socket variable retrival failure crashes,https://github.com/ballerina-platform/module-ballerina-c2c/commit/f4041cf95d63e255b9f4e0098fb42aecafc3cbed,,,c2c-util/src/main/java/io/ballerina/c2c/util/C2CVisitor.java,3,java,False,2022-03-30T10:14:49Z "def proxy(protocol, url): url = protocol + '://' + unquote(url) params = request.args try: result = requests.get(url, params, allow_redirects=False, verify=False, timeout=5, headers=headers) except Exception as e: return dict(status=False, error=repr(e)) else: if result.status_code == 200: try: version = result.json()['version'] return dict(status=True, version=version) except Exception: return dict(status=False, error='Error Occurred. Check your settings.') elif result.status_code == 401: return dict(status=False, error='Access Denied. Check API key.') elif result.status_code == 404: return dict(status=False, error='Cannot get version. Maybe unsupported legacy API call?') elif 300 <= result.status_code <= 399: return dict(status=False, error='Wrong URL Base.') else: return dict(status=False, error=result.raise_for_status())","def proxy(protocol, url): if protocol.lower not in ['http', 'https']: return dict(status=False, error='Unsupported protocol') url = protocol + '://' + unquote(url) params = request.args try: result = requests.get(url, params, allow_redirects=False, verify=False, timeout=5, headers=headers) except Exception as e: return dict(status=False, error=repr(e)) else: if result.status_code == 200: try: version = result.json()['version'] return dict(status=True, version=version) except Exception: return dict(status=False, error='Error Occurred. Check your settings.') elif result.status_code == 401: return dict(status=False, error='Access Denied. Check API key.') elif result.status_code == 404: return dict(status=False, error='Cannot get version. Maybe unsupported legacy API call?') elif 300 <= result.status_code <= 399: return dict(status=False, error='Wrong URL Base.') else: return dict(status=False, error=result.raise_for_status())",Fixed some code to prevent arbitrary file read and blind SSRF.,https://github.com/morpheus65535/bazarr/commit/17add7fbb3ae1919a40d505470d499d46df9ae6b,,,bazarr/app/ui.py,3,py,False,2023-09-18T15:59:45Z "@Override public boolean finishReceiverLocked(@NonNull ProcessRecord app, int resultCode, @Nullable String resultData, @Nullable Bundle resultExtras, boolean resultAbort, boolean waitForServices) { final BroadcastProcessQueue queue = getProcessQueue(app); final BroadcastRecord r = queue.getActive(); r.resultCode = resultCode; r.resultData = resultData; r.resultExtras = resultExtras; r.resultAbort = resultAbort; // When the caller aborted an ordered broadcast, we mark all remaining // receivers as skipped if (r.ordered && resultAbort) { for (int i = r.finishedCount + 1; i < r.receivers.size(); i++) { r.setDeliveryState(i, BroadcastRecord.DELIVERY_SKIPPED); } } return finishReceiverLocked(queue, BroadcastRecord.DELIVERY_DELIVERED); }","@Override public boolean finishReceiverLocked(@NonNull ProcessRecord app, int resultCode, @Nullable String resultData, @Nullable Bundle resultExtras, boolean resultAbort, boolean waitForServices) { final BroadcastProcessQueue queue = getProcessQueue(app); final BroadcastRecord r = queue.getActive(); r.resultCode = resultCode; r.resultData = resultData; r.resultExtras = resultExtras; if (!r.isNoAbort()) { r.resultAbort = resultAbort; } // When the caller aborted an ordered broadcast, we mark all remaining // receivers as skipped if (r.ordered && r.resultAbort) { for (int i = r.finishedCount + 1; i < r.receivers.size(); i++) { r.setDeliveryState(i, BroadcastRecord.DELIVERY_SKIPPED); } } return finishReceiverLocked(queue, BroadcastRecord.DELIVERY_DELIVERED); }","BroadcastQueue: misc bookkeeping events for OS. This change brings over the remaining bookkeeping events that other parts of the OS expects, such as allowing background activity starts, temporary allowlisting for power, more complete OOM adjustments, thawing apps before dispatch, and metrics events. Fixes bug so that apps aren't able to abort broadcasts marked with NO_ABORT flag. Tests to confirm all the above behaviors are identical between both broadcast stack implementations. Bug: 245771249 Test: atest FrameworksMockingServicesTests:BroadcastQueueTest Change-Id: If3532d335c94c8138a9ebcf8d11bf3674d1c42aa",https://github.com/LineageOS/android_frameworks_base/commit/6a6e2295915440e17104151160a4b4ce21796962,,,services/core/java/com/android/server/am/BroadcastQueueModernImpl.java,3,java,False,2022-09-22T22:04:12Z "private void manageUserUnchecked(ComponentName admin, ComponentName profileOwner, @UserIdInt int userId, @Nullable PersistableBundle adminExtras, boolean showDisclaimer) { synchronized (getLockObject()) { if (VERBOSE_LOG) { Slogf.v(LOG_TAG, ""manageUserUnchecked(): admin="" + admin + "", po="" + profileOwner + "", userId="" + userId + "", hasAdminExtras="" + (adminExtras != null) + "", showDisclaimer="" + showDisclaimer); } } final String adminPkg = admin.getPackageName(); try { // Install the profile owner if not present. if (!mIPackageManager.isPackageAvailable(adminPkg, userId)) { mIPackageManager.installExistingPackageAsUser(adminPkg, userId, PackageManager.INSTALL_ALL_WHITELIST_RESTRICTED_PERMISSIONS, PackageManager.INSTALL_REASON_POLICY, /* allowlistedRestrictedPermissions= */ null); } } catch (RemoteException e) { // Does not happen, same process Slogf.wtf(LOG_TAG, e, ""Failed to install admin package %s for user %d"", adminPkg, userId); } // Set admin. setActiveAdmin(profileOwner, /* refreshing= */ true, userId); final String ownerName = getProfileOwnerNameUnchecked( Process.myUserHandle().getIdentifier()); setProfileOwner(profileOwner, ownerName, userId); synchronized (getLockObject()) { DevicePolicyData policyData = getUserData(userId); policyData.mInitBundle = adminExtras; policyData.mAdminBroadcastPending = true; policyData.mNewUserDisclaimer = showDisclaimer ? DevicePolicyData.NEW_USER_DISCLAIMER_NEEDED : DevicePolicyData.NEW_USER_DISCLAIMER_NOT_NEEDED; saveSettingsLocked(userId); } }","private void manageUserUnchecked(ComponentName admin, ComponentName profileOwner, @UserIdInt int userId, @Nullable PersistableBundle adminExtras, boolean showDisclaimer) { synchronized (getLockObject()) { if (VERBOSE_LOG) { Slogf.v(LOG_TAG, ""manageUserUnchecked(): admin="" + admin + "", po="" + profileOwner + "", userId="" + userId + "", hasAdminExtras="" + (adminExtras != null) + "", showDisclaimer="" + showDisclaimer); } } final String adminPkg = admin.getPackageName(); mInjector.binderWithCleanCallingIdentity(() -> { try { // Install the profile owner if not present. if (!mIPackageManager.isPackageAvailable(adminPkg, userId)) { mIPackageManager.installExistingPackageAsUser(adminPkg, userId, PackageManager.INSTALL_ALL_WHITELIST_RESTRICTED_PERMISSIONS, PackageManager.INSTALL_REASON_POLICY, /* allowlistedRestrictedPermissions= */ null); } } catch (RemoteException e) { // Does not happen, same process Slogf.wtf(LOG_TAG, e, ""Failed to install admin package %s for user %d"", adminPkg, userId); } }); // Set admin. setActiveAdmin(profileOwner, /* refreshing= */ true, userId); final String ownerName = getProfileOwnerNameUnchecked( Process.myUserHandle().getIdentifier()); setProfileOwner(profileOwner, ownerName, userId); synchronized (getLockObject()) { DevicePolicyData policyData = getUserData(userId); policyData.mInitBundle = adminExtras; policyData.mAdminBroadcastPending = true; policyData.mNewUserDisclaimer = showDisclaimer ? DevicePolicyData.NEW_USER_DISCLAIMER_NEEDED : DevicePolicyData.NEW_USER_DISCLAIMER_NOT_NEEDED; saveSettingsLocked(userId); } }","Proper fix for setDeviceOwner() permission check. Previous fix was clearing the binding identity for the whole manageUserUnchecked() call, which would break setting it using adb - this change limits the scope just to the package manager calls. Test: atest com.android.bedstead.nene.devicepolicy.DevicePolicyTest#setDeviceOwner_deviceOwnerIsAlreadySet_throwsException Test: adb shell dpm set-device-owner --user 0 com.afwsamples.testdpc/.DeviceAdminReceiver Fixes: 200810234 BYPASS_INCLUSIVE_LANGUAGE_REASON=existing API Change-Id: I82e4ea2bef710420306ab17f58255ef7bc9cbb06",https://github.com/omnirom/android_frameworks_base/commit/ab0a45f0491d1b2266b041cf2676b47051d35ff6,,,services/devicepolicy/java/com/android/server/devicepolicy/DevicePolicyManagerService.java,3,java,False,2021-09-30T23:20:30Z "public void gadgetCall(MethodCandidate targetMethod, Object gadget, int argumentPosition) { int attackArgument = findNonPrimitiveArgument(targetMethod, argumentPosition); Logger.printGadgetCallIntro(""RMI""); printGadgetIntro(targetMethod, attackArgument); MethodArguments argumentArray = prepareArgumentArray(targetMethod, gadget, attackArgument); try { rmi.genericCall(null, -1, targetMethod.getHash(), argumentArray, false, getMethodName(targetMethod), remoteRef); Logger.eprintln(""Remote method invocation didn't cause any exception.""); Logger.eprintln(""This is unusual and the attack probably didn't work.""); } catch (java.rmi.ServerException e) { Throwable cause = ExceptionHandler.getCause(e); if( cause instanceof java.rmi.UnmarshalException ) { Logger.eprintlnMixedYellow(""Method"", targetMethod.getSignature(), ""does not exist on this remote object.""); ExceptionHandler.showStackTrace(e); } else if( cause instanceof java.lang.ClassNotFoundException ) { if( e.getMessage().contains(randomClassName) ) { ExceptionHandler.deserializeClassNotFoundRandom(e, ""deserialization"", ""attack"", randomClassName); } else { ExceptionHandler.deserializeClassNotFound(e); } } else if( cause instanceof java.security.AccessControlException ) { ExceptionHandler.accessControl(e, ""deserialization"", ""attack""); } else if( cause instanceof java.io.InvalidClassException ) { ExceptionHandler.invalidClass(e, ""RMI endpoint""); } else if( cause instanceof java.lang.UnsupportedOperationException ) { ExceptionHandler.unsupportedOperationException(e, ""method""); } else { ExceptionHandler.unexpectedException(e, ""deserialization"", ""attack"", false); } } catch( java.lang.ClassCastException e ) { ExceptionHandler.deserlializeClassCast(e, true); } catch( java.security.AccessControlException e ) { ExceptionHandler.accessControl(e, ""deserialization"", ""attack""); } catch( java.rmi.UnmarshalException e ) { Throwable t = ExceptionHandler.getCause(e); if( t instanceof java.lang.ClassNotFoundException ) { Logger.eprintlnMixedYellow(""Caught local"", ""ClassNotFoundException"", ""during deserialization attack.""); Logger.eprintlnMixedBlue(""This usually occurs when the"", ""gadget caused an exception"", ""on the server side.""); Logger.eprintlnMixedYellow(""You probably entered entered an"", ""invalid command"", ""for the gadget.""); ExceptionHandler.showStackTrace(e); } else { ExceptionHandler.unexpectedException(e, ""deserialization"", ""attack"", false); } } catch( Exception e ) { ExceptionHandler.unknownDeserializationException(e); } }","public void gadgetCall(MethodCandidate targetMethod, Object gadget, int argumentPosition) { int attackArgument = findNonPrimitiveArgument(targetMethod, argumentPosition); Logger.printGadgetCallIntro(""RMI""); printGadgetIntro(targetMethod, attackArgument); MethodArguments argumentArray = prepareArgumentArray(targetMethod, gadget, attackArgument); try { rmi.genericCall(null, -1, targetMethod.getHash(), argumentArray, false, getMethodName(targetMethod), remoteRef); Logger.eprintln(""Remote method invocation didn't cause any exception.""); Logger.eprintln(""This is unusual and the attack probably didn't work.""); } catch (Exception e) { Throwable cause = ExceptionHandler.getCause(e); if( cause instanceof java.rmi.UnmarshalException && cause.getMessage().contains(""unrecognized method hash"")) { Logger.eprintlnMixedYellow(""Method"", targetMethod.getSignature(), ""does not exist on this remote object.""); ExceptionHandler.showStackTrace(e); } else { ExceptionHandler.handleGadgetCallException(e, RMIComponent.CUSTOM, ""method"", randomClassName); } } }","Unifi exception handling remote-method-guesser allows Codebase and GadgetCall attacks on different RMI components. The attack structure stays basically the same for each different component and the possible exceptions are quite similar. So far, remote-method-guesser used explicit exception handling for each component. This was now replaced with a unified exception handling method that is called by each component.",https://github.com/qtc-de/remote-method-guesser/commit/8cc33c2518bd71562d223130fdff0ec3bb000e73,,,src/de/qtc/rmg/operations/RemoteObjectClient.java,3,java,False,2021-10-24T16:15:06Z "private void startUpRun(String start) { try (IOContext suin = new ScannerIOContext(new StringReader(start))) { run(suin); } catch (Exception ex) { errormsg(""jshell.err.startup.unexpected.exception"", ex); ex.printStackTrace(cmderr); } }","private void startUpRun(String start) { try (IOContext suin = new ScannerIOContext(new StringReader(start))) { while (run(suin)) { if (!live) { resetState(); } } } catch (Exception ex) { errormsg(""jshell.err.startup.unexpected.exception"", ex); ex.printStackTrace(cmderr); } }","8254196: jshell infinite loops when startup script contains System.exit call Reviewed-by: sundar",https://github.com/AdoptOpenJDK/openjdk-jdk/commit/6c0fbf70e89fe55f43d0f11ba5120e4de4521e90,,,src/jdk.jshell/share/classes/jdk/internal/jshell/tool/JShellTool.java,3,java,False,2021-03-24T10:34:31Z "def get(self): """"""Returns a list of roles --- description: >- Returns a list of roles. Depending on your permission, you get all the roles at the server or only the roles that belong to your organization.\n ### Permission Table\n |Rule name|Scope|Operation|Assigned to node|Assigned to container| Description|\n |--|--|--|--|--|--|\n |Role|Global|View|❌|❌|View all roles|\n |Role|Collaboration|View|❌|❌|View all roles in your collaborations|\n |Role|Organization|View|❌|❌|View roles that are part of your organization|\n Accesible to users. parameters: - in: query name: name schema: type: string description: >- Name to match with a LIKE operator. \n * The percent sign (%) represents zero, one, or multiple characters\n * underscore sign (_) represents one, single character - in: query name: description schema: type: string description: >- Description to match with a LIKE operator. \n * The percent sign (%) represents zero, one, or multiple characters\n * underscore sign (_) represents one, single character - in: query name: organization_id schema: type: array items: type: integer description: Organization id of which you want to get roles - in: query name: collaboration_id schema: type: integer description: Collaboration id - in: query name: rule_id schema: type: integer description: Rule that is part of a role - in: query name: user_id schema: type: integer description: get roles for this user id - in: query name: include_root schema: type: boolean description: Whether or not to include root role (default=False) - in: query name: page schema: type: integer description: Page number for pagination (default=1) - in: query name: per_page schema: type: integer description: Number of items per page (default=10) - in: query name: sort schema: type: string description: >- Sort by one or more fields, separated by a comma. Use a minus sign (-) in front of the field to sort in descending order. responses: 200: description: Ok 401: description: Unauthorized 400: description: Improper values for pagination or sorting parameters security: - bearerAuth: [] tags: [""Role""] """""" q = g.session.query(db.Role) auth_org_id = self.obtain_organization_id() args = request.args # filter by organization ids (include root role if desired) org_filters = args.getlist('organization_id') if org_filters: if 'include_root' in args and args['include_root']: q = q.filter(or_( db.Role.organization_id.in_(org_filters), db.Role.organization_id.is_(None) )) else: q = q.filter(db.Role.organization_id.in_(org_filters)) # filter by collaboration id if 'collaboration_id' in args: if not self.r.can_for_col(P.VIEW, args['collaboration_id'], self.obtain_auth_collaborations()): return { 'msg': 'You lack the permission view all roles from ' f'collaboration {args[""collaboration_id""]}!' }, HTTPStatus.UNAUTHORIZED org_ids = get_org_ids_from_collabs(g.user, args['collaboration_id']) if 'include_root' in args and args['include_root']: q = q.filter(or_( db.Role.organization_id.in_(org_ids), db.Role.organization_id.is_(None) )) else: q = q.filter(db.Role.organization_id.in_(org_ids)) # filter by one or more names or descriptions for param in ['name', 'description']: filters = args.getlist(param) if filters: q = q.filter(or_(*[ getattr(db.Role, param).like(f) for f in filters ])) # find roles containing a specific rule if 'rule_id' in args: q = q.join(db.role_rule_association).join(db.Rule)\ .filter(db.Rule.id == args['rule_id']) if 'user_id' in args: q = q.join(db.Permission).join(db.User)\ .filter(db.User.id == args['user_id']) if not self.r.v_glo.can(): own_role_ids = [role.id for role in g.user.roles] if self.r.v_org.can(): # allow user to view all roles of their organization and any # other roles they may have themselves, or default roles from # the root organization q = q.filter(or_( db.Role.organization_id == auth_org_id, db.Role.id.in_(own_role_ids), db.Role.organization_id.is_(None) )) else: # allow users without permission to view only their own roles q = q.filter(db.Role.id.in_(own_role_ids)) # paginate results try: page = Pagination.from_query(query=q, request=request) except ValueError as e: return {'msg': str(e)}, HTTPStatus.BAD_REQUEST return self.response(page, role_schema)","def get(self): """"""Returns a list of roles --- description: >- Returns a list of roles. Depending on your permission, you get all the roles at the server or only the roles that belong to your organization.\n ### Permission Table\n |Rule name|Scope|Operation|Assigned to node|Assigned to container| Description|\n |--|--|--|--|--|--|\n |Role|Global|View|❌|❌|View all roles|\n |Role|Collaboration|View|❌|❌|View all roles in your collaborations|\n |Role|Organization|View|❌|❌|View roles that are part of your organization|\n Accesible to users. parameters: - in: query name: name schema: type: string description: >- Name to match with a LIKE operator. \n * The percent sign (%) represents zero, one, or multiple characters\n * underscore sign (_) represents one, single character - in: query name: description schema: type: string description: >- Description to match with a LIKE operator. \n * The percent sign (%) represents zero, one, or multiple characters\n * underscore sign (_) represents one, single character - in: query name: organization_id schema: type: array items: type: integer description: Organization id of which you want to get roles - in: query name: collaboration_id schema: type: integer description: Collaboration id - in: query name: rule_id schema: type: integer description: Rule that is part of a role - in: query name: user_id schema: type: integer description: get roles for this user id - in: query name: include_root schema: type: boolean description: Whether or not to include root role (default=False) - in: query name: page schema: type: integer description: Page number for pagination (default=1) - in: query name: per_page schema: type: integer description: Number of items per page (default=10) - in: query name: sort schema: type: string description: >- Sort by one or more fields, separated by a comma. Use a minus sign (-) in front of the field to sort in descending order. responses: 200: description: Ok 401: description: Unauthorized 400: description: Improper values for pagination or sorting parameters security: - bearerAuth: [] tags: [""Role""] """""" q = g.session.query(db.Role) auth_org = self.obtain_auth_organization() args = request.args # filter by organization ids (include root role if desired) org_filters = args.getlist('organization_id') if org_filters: if 'include_root' in args and args['include_root']: q = q.filter(or_( db.Role.organization_id.in_(org_filters), db.Role.organization_id.is_(None) )) else: q = q.filter(db.Role.organization_id.in_(org_filters)) # filter by collaboration id if 'collaboration_id' in args: if not self.r.can_for_col(P.VIEW, args['collaboration_id'], self.obtain_auth_collaborations()): return { 'msg': 'You lack the permission view all roles from ' f'collaboration {args[""collaboration_id""]}!' }, HTTPStatus.UNAUTHORIZED org_ids = get_org_ids_from_collabs(g.user, args['collaboration_id']) if 'include_root' in args and args['include_root']: q = q.filter(or_( db.Role.organization_id.in_(org_ids), db.Role.organization_id.is_(None) )) else: q = q.filter(db.Role.organization_id.in_(org_ids)) # filter by one or more names or descriptions for param in ['name', 'description']: filters = args.getlist(param) if filters: q = q.filter(or_(*[ getattr(db.Role, param).like(f) for f in filters ])) # find roles containing a specific rule if 'rule_id' in args: rule = db.Rule.query.get(args['rule_id']) if not rule: return {'msg': f'Rule with id={args[""rule_id""]} does not ' 'exist!'}, HTTPStatus.BAD_REQUEST q = q.join(db.role_rule_association).join(db.Rule)\ .filter(db.Rule.id == args['rule_id']) if 'user_id' in args: user = db.User.query.get(args['user_id']) if not user: return {'msg': f'User with id={args[""user_id""]} does not ' 'exist!'}, HTTPStatus.BAD_REQUEST elif self.r.can_for_org(P.VIEW, user.organization_id, auth_org): return { 'msg': 'You lack the permission view roles from the ' f'organization that user id={user.id} belongs to!' }, HTTPStatus.UNAUTHORIZED q = q.join(db.Permission).join(db.User)\ .filter(db.User.id == args['user_id']) if not self.r.v_glo.can(): own_role_ids = [role.id for role in g.user.roles] if self.r.v_org.can(): # allow user to view all roles of their organization and any # other roles they may have themselves, or default roles from # the root organization q = q.filter(or_( db.Role.organization_id == auth_org.id, db.Role.id.in_(own_role_ids), db.Role.organization_id.is_(None) )) else: # allow users without permission to view only their own roles q = q.filter(db.Role.id.in_(own_role_ids)) # paginate results try: page = Pagination.from_query(query=q, request=request) except ValueError as e: return {'msg': str(e)}, HTTPStatus.BAD_REQUEST return self.response(page, role_schema)",Improved permission checks for GET endpoints that return multiple resources. We now check better if the user is allowed to see resources for the arguments they provide,https://github.com/vantage6/vantage6/commit/a2362568e989b8b042a3df5cc73f9bb7c98f2368,,,vantage6-server/vantage6/server/resource/role.py,3,py,False,2023-06-09T09:58:52Z "private boolean isFilenameTooLong() { int maxNameLen = tool.getProject().getProjectData().getMaxNameLength(); String fullPath = getName(); String currentPath = fullPath; while (!StringUtils.isBlank(currentPath)) { String filename = FilenameUtils.getName(currentPath); if (filename.isEmpty()) { return false; } if (filename.length() >= maxNameLen) { return true; } currentPath = FilenameUtils.getFullPathNoEndSeparator(currentPath); } return false; }","private boolean isFilenameTooLong() { int maxNameLen = tool.getProject().getProjectData().getMaxNameLength(); for (String pathPart : getName().split(""/"")) { if (pathPart.length() >= maxNameLen) { return true; } } return false; }","GP-1849 Fix infinite loop when importing file with leading tilde in name Fixes #4034.",https://github.com/NationalSecurityAgency/ghidra/commit/1504fcf6c629974bba11ba87e1ec44c6e3a18170,,,Ghidra/Features/Base/src/main/java/ghidra/plugin/importer/ImporterDialog.java,3,java,False,2022-03-22T17:49:47Z "@Override @Nullable public String onUnfetchedAttribute(FetchGroupTracker entity, String attributeName) { if (cannotAccessUnfetched(entity)) return ""Cannot get unfetched attribute ["" + attributeName + ""] from object "" + entity; return wrappedFetchGroup.onUnfetchedAttribute(entity, attributeName); }","@Override @Nullable public String onUnfetchedAttribute(FetchGroupTracker entity, String attributeName) { //Do not invoke entity.toString() when it causes unfetched exception inside and leads to stackoverflow. //It may happen for custom toString() implementations (not recommended) // or if strange things happens with composite id (see jmix-framework/jmix#1273). if (Boolean.TRUE.equals(unfetchedExceptionAlreadyOccurred.get())) return ""Cannot get unfetched attribute ["" + attributeName + ""] from "" + entity.getClass(); unfetchedExceptionAlreadyOccurred.set(true); try { if (cannotAccessUnfetched(entity)) return ""Cannot get unfetched attribute ["" + attributeName + ""] from object "" + entity; return wrappedFetchGroup.onUnfetchedAttribute(entity, attributeName); } finally { unfetchedExceptionAlreadyOccurred.set(false); } }",Processing 'unfetched' results in a stack overflow jmix-framework/jmix#1273,https://github.com/jmix-framework/jmix/commit/929c83994223dcb030674909a9a787169f273476,,,jmix-data/eclipselink/src/main/java/io/jmix/eclipselink/impl/JmixEntityFetchGroup.java,3,java,False,2022-12-19T07:13:53Z "@Inject( method = ""tick"", at = @At(""RETURN"") ) private void releaseAfterTick(CallbackInfo ci) { MemoryLeakFix.BUFFERS_TO_CLEAR.removeIf(this::canRelease); }","@Inject( method = ""tick"", at = @At(""RETURN"") ) private void releaseAfterTick(CallbackInfo ci) { MemoryLeakFix.BUFFERS_TO_CLEAR.removeIf(this::tryRelease); }","Fix #25 Fixes crash due to MemoryLeakFix attempting to release a ByteBuffer too early",https://github.com/FxMorin/MemoryLeakFix/commit/8333c6af808ad57d7531317cfc822cea1d83b89c,,,src/main/java/ca/fxco/memoryleakfix/mixin/customPayloadLeak/MinecraftClient_freeBufferMixin.java,3,java,False,2022-07-17T21:26:43Z "static int dissect_spoolss_keybuffer(tvbuff_t *tvb, int offset, packet_info *pinfo, proto_tree *tree, dcerpc_info *di, guint8 *drep) { guint32 size; int end_offset; if (di->conformant_run) return offset; /* Dissect size and data */ offset = dissect_ndr_uint32(tvb, offset, pinfo, tree, di, drep, hf_keybuffer_size, &size); end_offset = offset + (size*2); if (end_offset < offset) { /* * Overflow - make the end offset one past the end of * the packet data, so we throw an exception (as the * size is almost certainly too big). */ end_offset = tvb_reported_length_remaining(tvb, offset) + 1; } while (offset < end_offset) offset = dissect_spoolss_uint16uni( tvb, offset, pinfo, tree, drep, NULL, hf_keybuffer); return offset; }","static int dissect_spoolss_keybuffer(tvbuff_t *tvb, int offset, packet_info *pinfo, proto_tree *tree, dcerpc_info *di, guint8 *drep) { guint32 size; int end_offset; if (di->conformant_run) return offset; /* Dissect size and data */ offset = dissect_ndr_uint32(tvb, offset, pinfo, tree, di, drep, hf_keybuffer_size, &size); end_offset = offset + (size*2); if (end_offset < offset) { /* * Overflow - make the end offset one past the end of * the packet data, so we throw an exception (as the * size is almost certainly too big). */ end_offset = tvb_reported_length_remaining(tvb, offset) + 1; } while (offset > 0 && offset < end_offset) { offset = dissect_spoolss_uint16uni( tvb, offset, pinfo, tree, drep, NULL, hf_keybuffer); } return offset; }","SPOOLSS: Try to avoid an infinite loop. Use tvb_reported_length_remaining in dissect_spoolss_uint16uni. Make sure our offset always increments in dissect_spoolss_keybuffer. Change-Id: I7017c9685bb2fa27161d80a03b8fca4ef630e793 Reviewed-on: https://code.wireshark.org/review/14687 Reviewed-by: Gerald Combs Petri-Dish: Gerald Combs Tested-by: Petri Dish Buildbot Reviewed-by: Michael Mann ",https://github.com/wireshark/wireshark/commit/b4d16b4495b732888e12baf5b8a7e9bf2665e22b,,,epan/dissectors/packet-dcerpc-spoolss.c,3,c,False,2016-03-28T22:46:33Z "public Boolean allowTopicPolicyOperation(TopicName topicName, PolicyName policy, PolicyOperation operation, String originalRole, String role, AuthenticationDataSource authData) { try { return allowTopicPolicyOperationAsync( topicName, policy, operation, originalRole, role, authData).get(); } catch (InterruptedException e) { throw new RestException(e); } catch (ExecutionException e) { throw new RestException(e.getCause()); } }","public Boolean allowTopicPolicyOperation(TopicName topicName, PolicyName policy, PolicyOperation operation, String originalRole, String role, AuthenticationDataSource authData) throws Exception { try { return allowTopicPolicyOperationAsync( topicName, policy, operation, originalRole, role, authData).get( conf.getMetadataStoreOperationTimeoutSeconds(), SECONDS); } catch (InterruptedException e) { throw new RestException(e); } catch (ExecutionException e) { throw new RestException(e.getCause()); } }",[fix][security] Add timeout of sync methods and avoid call sync method for AuthoriationService (#15694),https://github.com/apache/pulsar/commit/6af365e36aed74e95ca6e088f453d9513094bb36,,,pulsar-broker-common/src/main/java/org/apache/pulsar/broker/authorization/AuthorizationService.java,3,java,False,2022-06-09T01:06:28Z "@Override protected void onStart() { super.onStart(); if (mDialog2 != null || mDialog != null || !hasWifiManager()) { return; } if (WizardManagerHelper.isAnySetupWizard(getIntent())) { createDialogWithSuwTheme(); } else { if (mIsWifiTrackerLib) { mDialog2 = WifiDialog2.createModal(this, this, mNetworkDetailsTracker.getWifiEntry(), WifiConfigUiBase2.MODE_CONNECT); } else { mDialog = WifiDialog.createModal( this, this, mAccessPoint, WifiConfigUiBase.MODE_CONNECT); } } if (mIsWifiTrackerLib) { if (mDialog2 != null) { mDialog2.show(); mDialog2.setOnDismissListener(this); } } else { if (mDialog != null) { mDialog.show(); mDialog.setOnDismissListener(this); } } }","@Override protected void onStart() { super.onStart(); if (mDialog2 != null || mDialog != null || !hasWifiManager()) { return; } if (WizardManagerHelper.isAnySetupWizard(getIntent())) { createDialogWithSuwTheme(); } else { if (mIsWifiTrackerLib) { mDialog2 = WifiDialog2.createModal(this, this, mNetworkDetailsTracker.getWifiEntry(), WifiConfigUiBase2.MODE_CONNECT); } else { mDialog = WifiDialog.createModal( this, this, mAccessPoint, WifiConfigUiBase.MODE_CONNECT); } } if (mIsWifiTrackerLib) { if (mDialog2 != null) { mDialog2.show(); mDialog2.setOnDismissListener(this); } } else { if (mDialog != null) { mDialog.show(); mDialog.setOnDismissListener(this); } } if (mDialog2 != null || mDialog != null) { mLockScreenMonitor = new LockScreenMonitor(this); } }","Prevent leaking Wi-Fi dialog on lock screen - The Wi-Fi dialog is designed to be displayed on the system UI - Dismiss Wi-Fi dialog to prevent leaking user data on lock screen Bug: 231583603 Test: manual test make RunSettingsRoboTests ROBOTEST_FILTER=WifiDialogActivityTest Change-Id: Ie67ff1138ffeddd3e358331d8cef61e0629173e2",https://github.com/LineageOS/android_packages_apps_Settings/commit/be23c28ff299dc1143f714dc3fa27507d44fbe72,,,src/com/android/settings/wifi/WifiDialogActivity.java,3,java,False,2022-07-07T21:37:07Z "def _run_git(self, git_path, args): output = err = exit_status = None if not git_path: git_path = self._find_working_git() if git_path: self._git_path = git_path else: # Warn user only if he has version check enabled if app.VERSION_NOTIFY: log.warning(u""No git specified, can't use git commands"") app.NEWEST_VERSION_STRING = ERROR_MESSAGE exit_status = 1 return output, err, exit_status # If we have a valid git remove the git warning # String will be updated as soon we check github app.NEWEST_VERSION_STRING = None cmd = git_path + ' ' + args try: log.debug(u'Executing {cmd} with your shell in {dir}', {'cmd': cmd, 'dir': app.PROG_DIR}) p = subprocess.Popen(cmd, stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=subprocess.STDOUT, shell=True, cwd=app.PROG_DIR) output, err = p.communicate() exit_status = p.returncode # Convert bytes to string in python3 if isinstance(output, (bytes, bytearray)): output = output.decode('utf-8') if output: output = output.strip() except OSError: log.info(u""Command {cmd} didn't work"", {'cmd': cmd}) exit_status = 1 if exit_status == 0: log.debug(u'{cmd} : returned successful', {'cmd': cmd}) elif exit_status == 1: if output: if 'stash' in output: log.warning(u""Enable 'git reset' in settings or stash your changes in local files"") else: log.warning(u'{cmd} returned : {output}', {'cmd': cmd, 'output': output}) else: log.warning(u'{cmd} returned no data', {'cmd': cmd}) elif exit_status == 128: log.warning('{cmd} returned ({status}) : {output}', {'cmd': cmd, 'status': exit_status, 'output': output}) elif exit_status == 129: if 'unknown option' in output and 'set-upstream-to' in output: log.info(""Can't set upstream to origin/{0} because you're running an old version of git."" '\nPlease upgrade your git installation to its latest version.', app.BRANCH) else: log.warning('{cmd} returned ({status}) : {output}', {'cmd': cmd, 'status': exit_status, 'output': output}) else: log.warning(u'{cmd} returned : {output}. Treat as error for now', {'cmd': cmd, 'output': output}) exit_status = 1 return output, err, exit_status","def _run_git(self, git_path, args): output = err = exit_status = None if not git_path: git_path = self._find_working_git() if git_path: self._git_path = git_path else: # Warn user only if he has version check enabled if app.VERSION_NOTIFY: log.warning(u""No git specified, can't use git commands"") app.NEWEST_VERSION_STRING = ERROR_MESSAGE exit_status = 1 return output, err, exit_status if git_path != 'git' and not os.path.isfile(git_path): log.warning(u""Invalid git specified, can't use git commands"") exit_status = 1 return output, err, exit_status # If we have a valid git remove the git warning # String will be updated as soon we check github app.NEWEST_VERSION_STRING = None cmd = git_path + ' ' + args try: log.debug(u'Executing {cmd} with your shell in {dir}', {'cmd': cmd, 'dir': app.PROG_DIR}) p = subprocess.Popen(cmd, stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=subprocess.STDOUT, shell=True, cwd=app.PROG_DIR) output, err = p.communicate() exit_status = p.returncode # Convert bytes to string in python3 if isinstance(output, (bytes, bytearray)): output = output.decode('utf-8') if output: output = output.strip() except OSError: log.info(u""Command {cmd} didn't work"", {'cmd': cmd}) exit_status = 1 if exit_status == 0: log.debug(u'{cmd} : returned successful', {'cmd': cmd}) elif exit_status == 1: if output: if 'stash' in output: log.warning(u""Enable 'git reset' in settings or stash your changes in local files"") else: log.warning(u'{cmd} returned : {output}', {'cmd': cmd, 'output': output}) else: log.warning(u'{cmd} returned no data', {'cmd': cmd}) elif exit_status == 128: log.warning('{cmd} returned ({status}) : {output}', {'cmd': cmd, 'status': exit_status, 'output': output}) elif exit_status == 129: if 'unknown option' in output and 'set-upstream-to' in output: log.info(""Can't set upstream to origin/{0} because you're running an old version of git."" '\nPlease upgrade your git installation to its latest version.', app.BRANCH) else: log.warning('{cmd} returned ({status}) : {output}', {'cmd': cmd, 'status': exit_status, 'output': output}) else: log.warning(u'{cmd} returned : {output}. Treat as error for now', {'cmd': cmd, 'output': output}) exit_status = 1 return output, err, exit_status","Ensure that git_path is a valid file (#11138) * Ensure that git_path is a valid file * Update github_updater.py",https://github.com/pymedusa/Medusa/commit/66d4be8f0872bd5ddcdc5c5a58cb014d22834a45,,,medusa/updater/github_updater.py,3,py,False,2023-02-22T10:23:45Z "public void UpdateSystemInfo(int id) { StarSystem current = galaxy().system(id); if(!systemInfoBuffer.containsKey(id)) { AISystemInfo buffy = new AISystemInfo(); if(!empire.tech().hyperspaceCommunications()) { for(StarSystem sys : galaxy().systemsInRange(current, empire.shipRange())) { if(!empire.sv.inShipRange(sys.id)) { if(empire.canColonize(sys.id) || empire.unexploredSystems().contains(sys)) { buffy.additionalSystemsInRangeWhenColonized++; } } } } for(ShipFleet incoming : current.incomingFleets()) { if(incoming.empire().aggressiveWith(empire.id)) { if(!empire.visibleShips().contains(incoming)) continue; if(incoming.arrivalTime() > galaxy().currentTime() + 1) continue; buffy.enemyBombardDamage += incoming.expectedBombardDamage(current); if(incoming.isArmed()) buffy.enemyBc += incoming.bcValue(); } if(incoming.empire() == empire) { buffy.myBombardDamage += incoming.expectedBombardDamage(current); if(incoming.isArmed() || incoming.hasColonyShip()) buffy.myBc += incoming.bcValue(); if(incoming.canColonizeSystem(current)) buffy.colonizersEnroute++; } } for(ShipFleet orbiting : current.orbitingFleets()) { if(orbiting.retreating()) continue; if(orbiting.empire().aggressiveWith(empire.id)) { if(!empire.visibleShips().contains(orbiting)) continue; buffy.enemyBombardDamage += orbiting.expectedBombardDamage(); if(orbiting.isArmed()) buffy.enemyBc += orbiting.bcValue(); } if(orbiting.empire() == empire) { buffy.myBombardDamage += orbiting.expectedBombardDamage(); if(orbiting.isArmed()) buffy.myBc += orbiting.bcValue(); if(orbiting.canColonizeSystem(current)) buffy.colonizersEnroute++; } } if(current.colony() != null) { buffy.enemyIncomingTransports += empire.unfriendlyTransportsInTransit(current) * empire.maxRobotControls(); buffy.myIncomingTransports += empire.transportsInTransit(current) * empire.maxRobotControls(); } systemInfoBuffer.put(id, buffy); } }","public void UpdateSystemInfo(int id) { StarSystem current = galaxy().system(id); if(!systemInfoBuffer.containsKey(id)) { AISystemInfo buffy = new AISystemInfo(); if(!empire.tech().hyperspaceCommunications()) { for(StarSystem sys : galaxy().systemsInRange(current, empire.shipRange())) { if(!empire.sv.inShipRange(sys.id)) { if(empire.canColonize(sys.id) || empire.unexploredSystems().contains(sys)) { buffy.additionalSystemsInRangeWhenColonized++; } } } } for(ShipFleet incoming : current.incomingFleets()) { if(incoming.empire().aggressiveWith(empire.id)) { if(!empire.visibleShips().contains(incoming)) continue; if(incoming.arrivalTime() > galaxy().currentTime() + 1) continue; buffy.enemyBombardDamage += incoming.expectedBombardDamage(current); if(incoming.isArmed()) buffy.enemyFightingBc += bcValue(incoming, false, true, false, false); } if(incoming.empire() == empire) { buffy.myBombardDamage += incoming.expectedBombardDamage(current); if(incoming.isArmed() || incoming.hasColonyShip()) buffy.myFightingBc += bcValue(incoming, false, true, false, false); if(incoming.canColonizeSystem(current)) buffy.colonizersEnroute++; } } for(ShipFleet orbiting : current.orbitingFleets()) { if(orbiting.retreating()) continue; if(orbiting.empire().aggressiveWith(empire.id)) { if(!empire.visibleShips().contains(orbiting)) continue; buffy.enemyBombardDamage += orbiting.expectedBombardDamage(); if(orbiting.isArmed()) buffy.enemyFightingBc += bcValue(orbiting, false, true, false, false); } if(orbiting.empire() == empire) { buffy.myBombardDamage += orbiting.expectedBombardDamage(); if(orbiting.isArmed()) buffy.myFightingBc += bcValue(orbiting, false, true, false, false); if(orbiting.canColonizeSystem(current)) buffy.colonizersEnroute++; } } if(current.colony() != null) { buffy.enemyIncomingTransports += empire.unfriendlyTransportsInTransit(current); buffy.myIncomingTransports += empire.transportsInTransit(current); } systemInfoBuffer.put(id, buffy); } }","New algorithm to determine whom to go to war with (#71) * Update AIScientist.java Adjusted values of a bunch of techs. * Update AIShipCaptain.java Fixed accidental removal of range-adjustment in new target-selection-formula and removed unused code. * Update NewShipTemplate.java Allowing missiles to be used again under certain circumstances, taking ECM into account and basing weapon-decision on actual shield-levels rather than best possible. * Update TechMissileWeapon.java Fixed that 2-rack-missiles didn't have +1 speed as they should have according to official strategy-guide. * Update AIScientist.java Tech-Slider-Allocations now depend on racial-bonuses, not leader-personality. * Immersive Xilmi-AI When set to AI: Selectable, the Xilmi AI now goes in immersive-mode, once again making numerous uses of leader-traits. * Update CombatStackColony.java Fixed a bug, that planets without missile-bases always absorbed damage as if they already had a shield-built, even if they had none and even if they were in a nebula. * Tactical combat improvements Can now detect when someone protects another stack with repulsor-beams and retreats, when it cannot counter it with long-range-weapons. Optimal range for firing missiles increased by repulsor-radius so missile-ships won't be affected by the can't counter repulsors-detection. Missiles will now be held back until getting closer to prevent target from dodging them easily. Unused specials like Repulsor will no longer prevent ships from kiting. * Update AIShipCaptain.java Only kite when there's either repulsor-beam or missile-weapons installed on the ship. * Update AIFleetCommander.java Defending is only half as desirable as attacking now. * Immersive Xilmi-AI Lot's of changes for the personality-mode of Xilmi-AI. * Update DiplomaticEmbassy.java Fix for one empire still holding a grudge against the other when signing a peace-treaty. * Update AIShipCaptain.java Somehow the Xilmi-AI must have had conquered a system with a missile-base on it against another type of AI and then crashed at this place, I didn't even think it would get to for a colony. * Update AISpyMaster.java No longer consider computer-advantage for how much to spend into counter-espionage. * Race-fitting-playstyles implemented and leader-specfic-self-restrictions removed. * Update AIGeneral.java Invader-AI back to normal victim-selection. * Update AIGovernor.java Turns out espionage didn't work like I thought it would. So Darlok just building ships and relying on stealing techs was a bad idea. (You can only steal techs below your highest level in any given tree!) * Update AIDiplomat.java Fixed issue where AI wouldn't allow the player to ask for tech-trades and where they would take deals that are horrible for themselves when trading with other AIs. Trades are now usually all done within a 66%-150% tech-cost-range. * Update AIGeneral.java Giving themselves a personality/objective-combination that fits their behavior. * Update AIDiplomat.java Tech exchange only will work within same tier now. * Update AIGeneral.java Removed setting of personalities as this causes issue with missing texts. * Update AIScientist.java Fixed issue for Silicoids trading for Eco-restoration-techs. * Update ColonyDefense.java * Update ColonyDefense.java Shield will now only be built automatically under the following circumstances: There's missile-bases existing There's missile-bases needing to be upgraded There's missile-bases to be built * Update AIDiplomat.java Avoid false positives in war-declaration for incoming fleets when the system in question was only recently colonized. * Update AIShipCaptain.java Fixed a rare but not impossible crash. * Update AIDiplomat.java No longer accept joint-war-proposals from empires we like less than who they propose as victim. * Update AIGovernor.java Now building missile-bases... under very specific and rare circumstances. * Update AIShipCaptain.java Fixed crash when handling missile-bases. Individual stacks that can't find a target to attack no longer automatically retreat and instead let their behavior be governed by whether the whole fleet would want to retreat. * Update ColonyDefense.java Reverted previous changes which also happened to prevent AI from building shields. * Update CombatStackShip.java Fixed issue where multi-shot-weapons weren't reported as used when they were used. * Update AIFleetCommander.java Fleets now are split depending on their warp-speed unless they are on the way to their final-attack-target. * Update AIDiplomat.java Knowing about uncolonized systems no longer prevents wars. * Update CombatStackShip.java Revert change to shipComponentIsUsed * Update AIShipCaptain.java Moved logic that detects if a weapon has been used to this file. * Update AIScientist.java Try to avoid researching techs we know our neighbors already have since we can trade for it or steal it. * Update AIFleetCommander.java Colony ships now only ignore distance if they are huge as otherwise ignoring distance was horrible in late-game with hyperspace-communications. Keeping scout-designs around for longer. * Fixed a very annoying issue that caused eco-spending to become... insufficient and thus people to die when adjusting espionage- or security-spending. * Reserve-management-improvements Rich and Ultra-Rich planets now put their production into reserve when they would otherwise conduct research. Reserve will now try to keep an emergency-reserve for dealing with events like Supernova. Exceeding twice the amount of that reserve will always be spent so the money doesn't just lie around unused, when there's no new colonies that still need industry. * Update AIShipCaptain.java Removed an unneccessary white line 8[ * Update AIFleetCommander.java Reversed keeping scouts for longer * Update AIGovernor.java no industry, when under siege * Update AIGovernor.java Small fixed to sieged colonies building industry when they shouldn't. * Update Rotp.java Versioning 0.93a * Update RacesUI.java Race-selector no longer jumps after selecting a race. Race-selector scroll-speed when dragging is no longer amplified like the scroll-bar but instead moves 1:1 the distance dragged. * Update AIFleetCommander.java Smart-Path will no longer path over systems further away than the target-system. Fleets will now always be split by speed if more than 2/3rd of the fleet have the fastest speed possible. * Update AIGovernor.java Build more fleet when fighting someone who has no or extremely little fleet. * Update AIShipCaptain.java Kiting no longer uses path-finding during auto-resolve. Ships with repulsor and long-range will no longer get closer than 2 tiles before firing against ships that don't have long range. Will only retreat to system with enemy fleets when there's no system without enemy fleets to retreat to. * Update CombatStackColony.java Added override for optimal firing-range for missile-bases. It is 9. * Update CombatStackShip.java Optimal firing-range for ship-stacks with missiles will now be at least two when they have repulsors. * Update NewShipTemplate.java The willingness of the AI to use repulsor-beam now scales with how many opponent ships have long range. It will be higher if there's only a few but drop down to 0 if all opponent ships use them. * Update AI.java Improved logic for shuttling around population within the empire. * Update ShipBattleUI.java Fixed a bug where remaining commands were transferred from one stack to another, which could also cause a crash when missile-bases were involved. * Update Colony.java currentProductionCapacity now correctly takes into consideration how many factories are actually operated. * Update NewShipTemplate.java Fixes and improvements to special-selection. Mainly bigger emphasis on using cloaking-device and stasis-field. * Update AIShipDesigner.java Consider getting an important special like cloaking, stasis or black-hole-generator as reason to immediately make a new design. * Update SystemView.java Systems with enemy-fleets will now flash the Alert. Especially usefull when under siege by cloaked enemy fleets. * Update AIShipCaptain.java Added check whether retreat was possible when retreating for the reason that nothing can be done. * Update AIGovernor.java Taking natural pop-growth and the cost of terraforming into account when deciding to build factories or population. This usually results to prefering factories almost always when they can be operated. * War- and Peace-making changes. Prevent war-declaration when there's barely any fleet to attack with. Smarter selection of preferred victim. In particular taking their diplomatic status with others into account. Toned down overall aggressiveness. Several personalities now are taken into account for determining behavior. * Update General.java Don't attack too early. * Update AIFleetCommander.java Colony ships will now always prefer undefended targets instead of waiting for help if they want to colonize a defended system. * Update Rotp.java Version 0.93b * Update NewShipTemplate.java Not needing ranged weapon, when we have cloaking-device. * Improved behavior when using missiles to act according to expectations of /u/bot39lvl * Showing pop-growth at clean-eco. * New Version with u/bot39lvl recommended changes to missile-boat-handling * Fixed issue that caused ships being scrapped after loading a game, no longer taking incoming enemy fleets into consideration that are more than one turn away from reaching their target. * Stacks that want to retreat will now also try and damage their target if it is more than one space away as long as they don't use up all movement-points. Planets with no missile-bases will not become a target unless all non-bomb-weapons were used. * Fixed an issue where a new design would override a similar existing one. * When defending or when having better movement-speed now shall always try to get the 1st strike. * Not keeping a defensive fleet on duty when the incoming opponent attack will overwhelm them anyways. * Using more unique ship-names * Avoid ship-information being cut off by drawing ship-button-overlay into the upper direction as soon as a stack is below the middle of the screen. * Fixed exploit that allowed player to ignore enemy repulsor-beams via auto-resolve. * Fixed issue that caused missile-ships to sometimes retreat when they shouldn't. * Calling beam/missileDefense() method instead of looking at the member since the function also takes stealth into account which we want to do for better decision-making. * Ships with limited shot-weapons no longer think they can land all hits at once. * Best tech of each type no longer gets it's research-value reduced. * Halfed inertial-value again as it otherwise may suppress vital range-tech. * Prevent overbuilding colony-ships in lategame by taking into consideration when systems can build more than one per turn. * Design-names now use name of a system that is actually owned and add a number to make sure they are unique. * Fixed some issues with no longer firing before retreating after rework and now ignoring stacks in stasis for whether to retreat or not. * Evenly distributing population across the empire led to an increase of almost 30% productivity at a reference turn in tests and thus turned out to be a much better population-distribution-strategy when compared to the ""bring new colonies to 25%""-rule-of-thumb as suggested in the official-strategy-guide. * Last defending stacks in stasis are now also made to autoretreat as otherwise this would result in 100 turns of ""you can't do anything but watch"". * Avoid having more than two designs with Stasis-Field as it doesn't stack. * Should fix an issue that caused usage of Hyper-Space-Communications to be inefficient. * Futher optimization on population-shuttling. * Fixed possible crash from trying to make peace while being involved in a final war. * Fixed infinite loop when trying to scrap the last existing design. * Making much better use of natural growth. * Some further slight adjustments to economy-handling that lead to an even better result in my test. * Fix for ""Hyperspace Communications: can't reroute back to the starting planet - bug"" by setting system to null, when leaving the orbit. In this vein no longer check for a stargate-connection when a fleet isn't at a system anymore. * Only the victor and the owner of the colony fought over get a scan on the system. Not all participants. Especially not someone who fled from the orion-guardian and wanted to exploit this bug to get free high-end-techs! * Prepare next version number since Ray hasn't commited anything yet since the beginning of June. :( * Presumably a better fix to the issue of carrying over button-presses to the next stack. But I don't have a good save to test it. * Fixed that for certain techs the inherited baseValue method either had no override or the override did not reference to the corresponding AI-method. * Reverted fix for redirecting ships with hyperspace-communications to their source-system because it could crash the game when trying to redirect ships using rally-points. * Using same ship-design-naming-pattern for all types of ships so player can't idintify colony-ships by looking at the name. * Added missing override for baseValue from AI. * Made separate method for upgradeCost so it can be used from outside, like AI for example. * Fixed an issue where ships wouldn't retreat when they couldn't path to their preferred target. * Changed how much the AI values certain technologies. Most notably will it like warp-speed-improvements more. * Introduced an algorithm that guesses how long it will take to kill another empire and how long it would take the other empire to kill ourselves. This is used in target-selection and also in order to decide on whether we should go all in with our military. If we think the other empire can kill us more quickly than what it takes to benefit from investments into economy, we go all-in with building military. * Fixed an issue that prevented ships being sent back to where they came from while in space via using hyperspace-communications. Note: The intention of that code is already handled by the ""CanSendTo""-check just above of it. At this place the differientiation between beeing in transit is made, so that code was redundant for it's intended use-case. * Production- and reseach-modifier now considered in decision to build ships non-stop or not. Fixed bug that caused AI-colonies to not build ships when they should. Consider incoming transports in decision whether to build population or not. * Big revamp of dimplomatic AI-behavior. AI should now make much more sophisticated decisions about when to go to war. * No longer bolstering population of low-pop-systems during war as this is pretty exploitable and detracts from producting military. * Version * Fixed a weird issue that prevented AIs from bombarding each other unless the player had knowledge about who the owner of the system to be bombarded is. * Less willing to go to war, when there's other ways to expand. * Fixed issue with colonizers and hyper-space-communications, that I thought I had fixed before. When there's other possible targets to attack, a fleet waiting for invasion-forces, that can glass the system it is orbiting will split up and continue its attack. * Only building excess colonizers, when someone we know (including ourselves) is at war and there's potential to colonize systems that are freed up by that war. * At 72% and higher population a system wanting to build a colonizer will go all-in on it. This mostly affects Sakkra and Meklar, so they expand quicker and make more use of fast pop-growth. * Fixed extremely rare crash. * 0.93g * Guessing travel-time and impact of nebulae instead of actually calculating the correct travel-times including nebulae to improve turn-times. * No longer using bestVictim in ship-Design-Code. * Lower limit from transport-size removed. * Yet another big revamp about when to go to war. It's much more simple now. * Transports sent towards someone who we don't want to have a war with now will be set to surrender on arrival. Travel-distance-calculation simplified in favor of turn-processing. Fixed dysfunctional defense-code that was recently broken. * Pop-growth now plays a role in invasion-decisionmaking. Invasions now can occur without a fleet in orbit. Code for estimating kill-time now takes invasions into account. Drastically simplified victim-selection. * Due to the changes in how the AI handles it's fleets during the wait time for invasions the amount of bombers built was increased. * Changed how it is determined whether to retreat against fleets with repulsors. Fixed issue with not firing missiles under certain circumstances. Stacks of smaller ships fighting against stacks of bigger ships are now more likely to retreat, when they can't kill at least one of the bigger ships per turn. * Moved accidental-stargate-building-prevention-workaround to where it actually is effective. * Fixed an issue where a combat would end prematurely when missiles were fired but still on their way to their target. * Removed commented-out code * Removed actual war-weariness from the reasons to make peace as there's now other and better reasons to make peace. * Bombers are now more specialized as in better at bombing and worse at actual combat. * Bomb-Percentage now considers all opponents, not just the current enemy. * The usage of designs is now recognized by their loadout and not by what role it was assigned to it during design. * No longer super-heavy commitment to ship-production in war. Support of hybrid-playstyle. * Fixed issue that sometimes prevented shooting missiles. * Lowered counter-espionage by no longer looking at average tech-level of opponents but instead at tech-level of highest opponent. * Support for hybrid ship-designs and many tweaks- and fixes in scrapping-logic. * Setting eco-slider with a popup that promts for a percentage now uses the percentage of the amount that isn't required to keep clean. * Fixed previously integrated potential dead-lock. * Indentation * Fix for becoming enemy of others before they are in range in the always-war-mode. * Version-number for next inofficial build. * No security-spending when no contact. But luckily that actually makes no difference between it only actually gets detracted from income when there's contacts. * Revert ""Setting eco-slider with a popup that promts for a percentage now uses the percentage of the amount that isn't required to keep clean."" This reverts commit a2fe5dce3c1be344b6c96b6bfa1b5d16b321fafa. * Taught AI to use divert-reserve to research-checkbox * I don't know how it can happen but I've seen rare cases of colonies with negative-population. This is a workaround that changes them back to 1 pop. * Skip AI turn when corresponing empire is dead. * Fixed possible endless-loop from scrapping last existing ship-design. * Fixed issue where AI would build colonizers as bombers after having scrapped their last existing bomber-design. * Removed useless code. * Removed useless code. * Xilmi AI now capable of deciding when to use bio-weapons. * Bioweapon-support * New voting behavior: Xilmi Ai now votes for whoever they are most scared of but aren't at war with. * Fixed for undecisive behavior of launching an assault but retreating until transports arrive because developmentPct is no longer maxxed after sending transports. (War would still get triggered by the invasion but the fleet sent to accompany the invasion would retreat) * No longer escorting colony-ships on their way to presumably undefended systems. Reason: This oftentimes used a good portion of the fleet for no good reason, when they could be better used for attacking/defending. * Requiring closer range to fire missiles. * Lower score for using bio-weapons depending on how many missile-bases are seen. * No longer altering tech-allocations based on war-state. * New, more diverse and supposedly more interesting diplomatic behavior for AI. * Pick weapon to counter best enemy shield in use rather than average to avoid situations where lasers or scatterpack-V are countered too hard. Also: Make sure that there is a design with the most current bomb before considering bio-weapons. * Weapons that allow heavy-mounts don't get their value decreased so AI doesn't end up without decent repulsor-counter. * Moved negative-population workaround to a place where it is actually called. * Smarter decision-making about when to bomb or not to bomb during on-going invasions. * Incoming invasions of oneself should be slightly better covered but without tying too much of the fleet to it. * Choose target by distance from fleet. * Giving more cover to incoming invasions. * Made rank-check-functions available outside of diplomat too. * Always abstain if not both candidates are known. Superpowers should avoid wars. * Fixed an issue where defenders wouldn't always stay back when they should. * Don't hold back full power when in war anymore. * Quality of ships now more important for scrapping than before. * Reversed prior change in retreat-logic for smaller ships: Yes, the enemy could retreat but control over the system is probably more important than preserving some ships. * Fixed issue where AI would retreat from repulsors when they had missiles. * Minimum speed-requirement for missiles now takes repulsor-beams and diagonals into account. * AI will prepare their wars a little better and also take having to prepare into account before invadion. * No longer voting until both candidates are met. AI now knows much better to capitalize on an advantage and actually win the game instead of throwing it in a risky way. * Moved a debug-output to another place. * 0.93l * Better preparations before going to war. Removed alliances again. * Pick war-target by population-center rather than potential population center. * Fixed a bunch of issued leading to bad colony-ship-management in the lategame. * The better an AI is doing, the more careful they are about how to pick their enemies. * Increased minimum ship-maintenance-threshold for the early-game. * New version * Forgot to remove a debug-message. * Fixed issue reported by u/Individual_Act289: Transports launched before final war disappear on arrival. * Fixed logical error in maxFiringRange-method which could cause unwanted retreats. * When at war, AI will not make so many colony-ships, fixed issue where invasions wouldn't happen against partially built missile-bases, build more bombers when there's a high military-superiority * Willingness to defend now scales with defense-ratio. * Holding back before going to war as long as techs can still be easily researched. * AI will get a bit more tech when it's opportune instead of going for war. * Smart path will avoid paths where the detour would be longer than 50%, fleets that would otherwise go to a staging-point while they are orbiting an enemy will instead stay in orbit of the enemy. * Yet unused methor determining the required count of fighters to shoo scouts away. * Techs that are more than 5 levels behind the average will now be researched even if they are low priority. * Handling for enemy missile-frigates. * No longer scrap ships while at war. * Shields are seen as more useful, new way of determining what size ships should be. * enemyTransportsInTransit now also returns transports of neutral/cold-war-opponents * Created separate method unfriendlyTransportsInTransit * Improved algorithm to determine ship-design-size, reduction in score for hybrids without bombs * Run from missile code should no longer try to outrun missiles that are too close already * New method for unfriendlyTransportsInTransit used * Taught AI to protect their systems against scouting * Taught AI to protect their systems against scouting * Fixed issue that prevented scouts from being sent to long-range-targets when they were part of a fleet with other ships. * Xilmi-AI now declaring war at any poploss, not just at 30+ * Sanity check for fleeing from missiles: Only do it when something could actually be lost. * Prepare better for potential attacks. * Some code cleanup * Fixed issue where other ships than destroyers could be built as scout-repellers. * Avoid downsizing of weapons in non-destroyer-ships. * Distances need to be recalculated immediately after obtaining new system as otherwise AI would act on outdated information. In this case it led to the AI offering peace due to losing range on an opponent whos colony it just conquered despite that act bringing lots of new systems into range. * Fixed an issue where AI would consider an opponents contacts instead of their own when determining the opponents relative standing. Also no longer looking at empires outside of ship-range for potential wars. * Priority for my purpose needs to be above 1000 and below 1400. Below 1000 it gets into conflict with scouts and above 1400 it will rush out the ships under all circumstances. * The widespread usage of scout-repellers makes adding a weapon to a colony-ship much more important. * Added missing override for maxFiringRange * Fixed that after capturing a colony the default for max-bases was not used from the settings of the new owner. * Default for bases on new systems and whether excess-spending goes to research can now be changed in Remnants.cfg * Fixed issue that allowed ship-designs without weapons to be considered the best design. * Fixed a rare crash I had never seen before and can't really explain. * Now taking into account if a weapon would cause a lot of overkill and reduce it's score if it is the case. Most likely will only affect Death-Ray and maybe Mauler-Device. * Fixed an issue with negative-fleets and error-messages. Fixed an issue where systems of empires without income wouldn't be attacked when they had stealth-ships or were out of sensor-range. * Improved detection on whether scout-repellers are needed. Also forbid scout-repellers when unlimited range is available. * Removed code that would consistently scrap unused designs, which sometimes had unintended side-effects when building bigger ships. Replaced what it was meant for by something vastly better: A design-rotation that happens based on how much the design contributes to the maintenance-cost. When there's 4 available slots for combat-designs and one design takes up more than 1/3rd of the maintenance, a new design is enforced, even if it is the same as before. * Fixed issue where ships wouldn't shoot at nearby targets when they couldn't reach their preferred target. Rewrote combat-outcome-expectation to much better guess the expected outcome, which now also consideres auto-repair. * New algorithm to determine who is the best target for a war. * New algorithm to determine the ratio of bombers vs. fighters respectively bombs vs. anti-ship-weapons on a hybrid. * Fixed issue where huge colonizers wouldn't be built when Orion was reachable. * The slots for scouts and scout-repellers are no longer used during wars. * Improved strategic target-selection to better take ship-roles into account. * Fixed issue in bcValue not recognizing scouts of non-AI-player * Fixed several issues with design-scoring. (possible zero-division and using size instead of space) * Much more dedicated and better adapted defending-techniques. * Improved estimate on how many troops need to stay back in order to shoot down transports.",https://github.com/rayfowler/rotp-public/commit/2ec066ab66098db56a37be9f35ccf980ce38866b,,,src/rotp/model/ai/xilmi/AIFleetCommander.java,3,java,False,2021-10-12T17:22:38Z "private boolean crumbleBlock(ItemStack stack, World world, LivingEntity living, BlockPos pos) { BlockState state = world.getBlockState(pos); Block block = state.getBlock(); if (block.isAir(state, world, pos)) return false; for (Pair, UnaryOperator> transform : crumbleTransforms) { if (transform.getLeft().test(state) && world.rand.nextInt(CHANCE_CRUMBLE) == 0) { world.setBlockState(pos, transform.getRight().apply(state), 3); world.playEvent(2001, pos, Block.getStateId(state)); postTrigger(living, stack, world, pos); return true; } } for (Predicate predicate : harvestedStates) { if (predicate.test(state) && world.rand.nextInt(CHANCE_HARVEST) == 0) { if (living instanceof PlayerEntity) { if (block.canHarvestBlock(state, world, pos, (PlayerEntity) living)) { world.removeBlock(pos, false); block.harvestBlock(world, (PlayerEntity) living, pos, state, world.getTileEntity(pos), ItemStack.EMPTY); world.playEvent(2001, pos, Block.getStateId(state)); postTrigger(living, stack, world, pos); return true; } } else if (ForgeEventFactory.getMobGriefingEvent(world, living)) { world.destroyBlock(pos, true); postTrigger(living, stack, world, pos); return true; } } } return false; }","private boolean crumbleBlock(ItemStack stack, World world, LivingEntity living, BlockPos pos) { BlockState state = world.getBlockState(pos); Block block = state.getBlock(); if (block.isAir(state, world, pos)) return false; if(living instanceof PlayerEntity) { if (MinecraftForge.EVENT_BUS.post(new BlockEvent.BreakEvent(world, pos, state, (PlayerEntity)living))) return false; } for (Pair, UnaryOperator> transform : crumbleTransforms) { if (transform.getLeft().test(state) && world.rand.nextInt(CHANCE_CRUMBLE) == 0) { world.setBlockState(pos, transform.getRight().apply(state), 3); world.playEvent(2001, pos, Block.getStateId(state)); postTrigger(living, stack, world, pos); return true; } } for (Predicate predicate : harvestedStates) { if (predicate.test(state) && world.rand.nextInt(CHANCE_HARVEST) == 0) { if (living instanceof PlayerEntity) { if (block.canHarvestBlock(state, world, pos, (PlayerEntity) living)) { world.removeBlock(pos, false); block.harvestBlock(world, (PlayerEntity) living, pos, state, world.getTileEntity(pos), ItemStack.EMPTY); world.playEvent(2001, pos, Block.getStateId(state)); postTrigger(living, stack, world, pos); return true; } } else if (ForgeEventFactory.getMobGriefingEvent(world, living)) { world.destroyBlock(pos, true); postTrigger(living, stack, world, pos); return true; } } } return false; }",fixed some items being able to claim bypass with FTB Chunks,https://github.com/TeamTwilight/twilightforest-fabric/commit/880625e08a27adfc3dbfe092e97d81f9ba2e6876,,,src/main/java/twilightforest/item/ItemTFCrumbleHorn.java,3,java,False,2021-06-14T05:35:46Z "@Override public void tick() { if (!world.isClient()) { if (Math.abs(getVelocity().x) < 0.01 && Math.abs(getVelocity().x) < 0.01 && Math.abs(getVelocity().y) < 0.01) { discard(); } } super.tick(); if (age % 1000 == 0) { setNoGravity(false); } getSpellSlot().get(true).filter(spell -> spell.tick(this, Situation.PROJECTILE)); if (getHydrophobic()) { if (world.getBlockState(getBlockPos()).getMaterial().isLiquid()) { Vec3d vel = getVelocity(); double velY = vel.y; velY *= -1; if (!hasNoGravity()) { velY += 0.16; } setVelocity(new Vec3d(vel.x, velY, vel.z)); } } }","@Override public void tick() { if (!world.isClient()) { if (Math.abs(getVelocity().x) < 0.01 && Math.abs(getVelocity().x) < 0.01 && Math.abs(getVelocity().y) < 0.01) { discard(); } } super.tick(); if (getOwner() == null) { return; } getSpellSlot().get(true).filter(spell -> spell.tick(this, Situation.PROJECTILE)); if (getHydrophobic()) { if (world.getBlockState(getBlockPos()).getMaterial().isLiquid()) { Vec3d vel = getVelocity(); double velY = vel.y; velY *= -1; if (!hasNoGravity()) { velY += 0.16; } setVelocity(new Vec3d(vel.x, velY, vel.z)); } } }",Fixed crash when ticking a projectile with no loaded owner,https://github.com/Sollace/Unicopia/commit/baa370074855279c0dad4c7371bd83662891561b,,,src/main/java/com/minelittlepony/unicopia/projectile/MagicProjectileEntity.java,3,java,False,2021-12-27T00:14:48Z "@Override public String toString() { return ""TaskFragmentInfo{"" + "" fragmentToken="" + mFragmentToken + "" token="" + mToken + "" runningActivityCount="" + mRunningActivityCount + "" isVisible="" + mIsVisible + "" activities="" + mActivities + "" positionInParent="" + mPositionInParent + "" isTaskClearedForReuse="" + mIsTaskClearedForReuse + "" isTaskFragmentClearedForPip"" + mIsTaskFragmentClearedForPip + "" minimumDimensions"" + mMinimumDimensions + ""}""; }","@Override public String toString() { return ""TaskFragmentInfo{"" + "" fragmentToken="" + mFragmentToken + "" token="" + mToken + "" runningActivityCount="" + mRunningActivityCount + "" isVisible="" + mIsVisible + "" activities="" + mActivities + "" positionInParent="" + mPositionInParent + "" isTaskClearedForReuse="" + mIsTaskClearedForReuse + "" isTaskFragmentClearedForPip="" + mIsTaskFragmentClearedForPip + "" mIsClearedForReorderActivityToFront="" + mIsClearedForReorderActivityToFront + "" minimumDimensions="" + mMinimumDimensions + ""}""; }","Fixes app crash when starts activity with FLAG_ACTIVITY_REORDER_TO_FRONT Application was crashed while starting an embedded Activity with FLAG_ACTIVITY_REORDER_TO_FRONT, because the embedded Activity was not the direct child of the Task. In this CL, the embedded activity is now moved to the top-most position of the Task and dismissed from being embedded in order to honer FLAG_ACTIVITY_REORDER_TO_FRONT. Bug: 255701223 Test: locally verified with app Test: atest TaskTests Change-Id: I491139e5e1d712993f1fef9aebbd75e9ccfc539e",https://github.com/aosp-mirror/platform_frameworks_base/commit/5dc3ec5115e2223fd2f951efe71ee4f0c61377c1,,,core/java/android/window/TaskFragmentInfo.java,3,java,False,2022-10-29T09:30:59Z "@Override public void onBindViewHolder(@NonNull ViewHolder viewHolder, int i) { if (mItems.isEmpty()) return; int idx = i; if (idx > mItems.size()) idx = 0; final UriData ud = mItems.get(idx); if (ud != null) { // Set item views based on the views and data model TextView name = viewHolder.name; TextView index = viewHolder.index; TextView size = viewHolder.size; if (mListener != null) { name.setOnClickListener((v) -> mListener.onClick(ud)); index.setOnClickListener((v) -> mListener.onClick(ud)); size.setOnClickListener((v) -> mListener.onClick(ud)); } index.setText(String.format(""%"" + String.valueOf(ud.maxLength).length() + ""s - "", ud.index)); name.setText(ud.value); size.setText(ud.size); } }","@Override public void onBindViewHolder(@NonNull ViewHolder viewHolder, int i) { if (mItems.isEmpty()) return; int idx = i; if (idx > mItems.size()) idx = 0; final UriData ud = mItems.get(idx); if (ud != null) { // Set item views based on the views and data model TextView name = viewHolder.name; TextView index = viewHolder.index; TextView size = viewHolder.size; if (mListener != null) { final View.OnClickListener l = (v) -> { if (!ud.error) mListener.onClick(ud); }; name.setOnClickListener(l); index.setOnClickListener(l); size.setOnClickListener(l); } index.setText(String.format(""%"" + String.valueOf(ud.maxLength).length() + ""s - "", ud.index)); name.setText(ud.value); size.setText(ud.size); size.setTextColor(ContextCompat.getColor(ud.ctx, ud.error ? R.color.colorResultError : R.color.textColor)); } }",#96 & #104: Fix a crash related to permissions via the recently opened files view and added information about the file.,https://github.com/Keidan/HexViewer/commit/929fe1d693608792d7560cdaaffc639e4c2bb766,,,app/src/main/java/fr/ralala/hexviewer/ui/adapters/RecentlyOpenRecyclerAdapter.java,3,java,False,2021-08-13T19:48:22Z "public void validateRequesterInProjectGroup(String requester, T projectItem) { if (this.sharedProjectItemDaoJpa.getSharedProjectItems(requester).stream() .anyMatch(item -> Objects.equals(item.getId(), projectItem.getId()) && Objects.equals(item.getContentType(), projectItem.getContentType()))) { return; } validateRequesterInProjectGroup(requester, projectItem.getProject()); }","public void validateRequesterInProjectGroup(String requester, T projectItem) { if (projectItem.isShared()) { return; } validateRequesterInProjectGroup(requester, projectItem.getProject()); }",Fix Authz for shared project item,https://github.com/singerdmx/BulletJournal/commit/e29ebf5db9b4e37baab1be73b0cfeb06c1f1080e,,,backend/src/main/java/com/bulletjournal/authz/AuthorizationService.java,3,java,False,2022-01-01T03:14:17Z "@Override public void handleChat(@NotNull Player p, @NotNull String msg) { handleChat(p, msg, false); }","@Override public void handleChat(@NotNull Player p, @NotNull String msg) { if (!plugin.getShopManager().getActions().containsKey(p.getUniqueId())) { return; } String message = net.md_5.bungee.api.ChatColor.stripColor(msg); message = ChatColor.stripColor(message); QSHandleChatEvent qsHandleChatEvent = new QSHandleChatEvent(p, message); qsHandleChatEvent.callEvent(); message = qsHandleChatEvent.getMessage(); // Use from the main thread, because Bukkit hates life String finalMessage = message; Util.mainThreadRun(() -> { Map actions = getActions(); // They wanted to do something. Info info = actions.remove(p.getUniqueId()); if (info == null) { return; // multithreaded means this can happen } if (info.getLocation().getWorld() != p.getLocation().getWorld() || info.getLocation().distanceSquared(p.getLocation()) > 25) { plugin.text().of(p, ""not-looking-at-shop"").send(); return; } if (info.getAction() == ShopAction.CREATE) { actionCreate(p, info, finalMessage); } if (info.getAction() == ShopAction.BUY) { actionTrade(p, info, finalMessage); } }); }",fix: /qs supercreate can't bypass the protection checks,https://github.com/Ghost-chu/QuickShop-Hikari/commit/922536d2b476fdd11d4e96c90ff3e78cd0e1a38a,,,src/main/java/org/maxgamer/quickshop/shop/SimpleShopManager.java,3,java,False,2021-10-29T11:02:39Z "@Override protected void channelRead0(ChannelHandlerContext ctx, String msg) throws Exception { try { stopWatch.reset().start(); JvmmRequest request = JvmmRequest.parseFrom(msg); if (request.getType() == null) { return; } if (GlobalType.JVMM_TYPE_PING.name().equals(request.getType())) { ctx.channel().writeAndFlush(JvmmResponse.create() .setType(GlobalType.JVMM_TYPE_PONG) .setStatus(GlobalStatus.JVMM_STATUS_OK) .serialize()); } else { handleRequest(ctx, request); } if (!request.isHeartbeat()) { logger().debug(String.format(""%s %dms"", request.getType(), stopWatch.stop().elapsed(TimeUnit.MILLISECONDS))); } } catch (JsonSyntaxException e) { ctx.channel().writeAndFlush(JvmmResponse.create() .setType(GlobalType.JVMM_TYPE_HANDLE_MSG) .setStatus(GlobalStatus.JVMM_STATUS_UNRECOGNIZED_CONTENT.name()) .setMessage(e.getMessage()) .serialize()); } }","@Override protected void channelRead0(ChannelHandlerContext ctx, String msg) throws Exception { try { stopWatch.reset().start(); JvmmRequest request = JvmmRequest.parseFrom(msg); if (request.getType() == null) { return; } if (GlobalType.JVMM_TYPE_PING.name().equals(request.getType())) { ctx.channel().writeAndFlush(JvmmResponse.create() .setType(GlobalType.JVMM_TYPE_PONG) .setStatus(GlobalStatus.JVMM_STATUS_OK) .serialize()); } else { handleRequest(ctx, request); } if (!request.isHeartbeat()) { logger().debug(String.format(""%s %dms"", request.getType(), stopWatch.stop().elapsed(TimeUnit.MILLISECONDS))); } } catch (AuthenticationFailedException e) { ctx.channel().writeAndFlush(JvmmResponse.create() .setType(GlobalType.JVMM_TYPE_AUTHENTICATION) .setStatus(GlobalStatus.JVMM_STATUS_AUTHENTICATION_FAILED.name()) .setMessage(""Authentication failed."") .serialize()); ctx.close(); logger().debug(""Channel closed by auth failed""); } catch (JsonSyntaxException e) { ctx.channel().writeAndFlush(JvmmResponse.create() .setType(GlobalType.JVMM_TYPE_HANDLE_MSG) .setStatus(GlobalStatus.JVMM_STATUS_UNRECOGNIZED_CONTENT.name()) .setMessage(e.getMessage()) .serialize()); } catch (Throwable e) { ctx.fireExceptionCaught(e); } }",fix security auth,https://github.com/tzfun/jvmm/commit/b4f42504c49ea4135a72dd749b271c362074ce28,,,convey/src/main/java/org/beifengtz/jvmm/convey/handler/JvmmChannelHandler.java,3,java,False,2021-12-14T15:52:06Z "public InputStream setBlob(@NotNull final PersistentStoreTransaction txn, @NotNull final PersistentEntity entity, @NotNull final String blobName, @NotNull final InputStream stream) throws IOException { InputStream bufferedStream; if (!(stream instanceof BufferedInputStream)) { bufferedStream = new BufferedInputStream(stream); } else { bufferedStream = stream; } int maxEmbeddedBlobSize = config.getMaxInPlaceBlobSize(); bufferedStream.mark(Math.max(maxEmbeddedBlobSize + 1, IOUtil.DEFAULT_BUFFER_SIZE)); final ByteArrayOutputStream memCopy = new LightByteArrayOutputStream(); IOUtil.copyStreams(bufferedStream, maxEmbeddedBlobSize + 1, memCopy, IOUtil.getBUFFER_ALLOCATOR()); final int size = memCopy.size(); if (size <= maxEmbeddedBlobSize) { bufferedStream.close(); bufferedStream = new ByteArraySizedInputStream(memCopy.toByteArray(), 0, size); } else { bufferedStream.reset(); } final long blobHandle = createBlobHandle(txn, entity, blobName, bufferedStream, size); if (!isEmptyOrInPlaceBlobHandle(blobHandle)) { txn.addBlob(blobHandle, bufferedStream); } return bufferedStream; }","public InputStream setBlob(@NotNull final PersistentStoreTransaction txn, @NotNull final PersistentEntity entity, @NotNull final String blobName, @NotNull final InputStream stream) throws IOException { if (stream instanceof TmpBlobVaultBufferedInputStream) { TmpBlobVaultBufferedInputStream tmpStream = (TmpBlobVaultBufferedInputStream) stream; final Path path = tmpStream.getPath(); long blobHandle = tmpStream.getBlobHandle(); PersistentStoreTransaction transaction = tmpStream.getTransaction(); if (transaction != null) { if (transaction != txn) { throw new ExodusException( ""Blob stream was initially added in one transaction and used in another transaction.""); } if (txn.containsBlobStream(blobHandle)) { return stream; } throw new ExodusException(""Blob stream was added in current transaction, "" + ""but is not stored inside transaction.""); } blobHandle = createBlobHandle(txn, entity, blobName, null, Integer.MAX_VALUE); tmpStream.close(); tmpStream = new TmpBlobVaultBufferedInputStream(Files.newInputStream(path), path, blobHandle, txn); txn.addBlobStream(blobHandle, tmpStream); final long size = Files.size(path); setBlobFileLength(txn, blobHandle, size); return tmpStream; } InputStream bufferedStream; if (!(stream instanceof BufferedInputStream)) { bufferedStream = new BufferedInputStream(stream); } else { bufferedStream = stream; } int maxEmbeddedBlobSize = config.getMaxInPlaceBlobSize(); bufferedStream.mark(Math.max(maxEmbeddedBlobSize + 1, IOUtil.DEFAULT_BUFFER_SIZE)); final ByteArrayOutputStream memCopy = new LightByteArrayOutputStream(); IOUtil.copyStreams(bufferedStream, maxEmbeddedBlobSize + 1, memCopy, IOUtil.getBUFFER_ALLOCATOR()); final int size = memCopy.size(); if (size <= maxEmbeddedBlobSize) { bufferedStream.close(); bufferedStream = new ByteArraySizedInputStream(memCopy.toByteArray(), 0, size); } else { bufferedStream.reset(); } final long blobHandle = createBlobHandle(txn, entity, blobName, bufferedStream, size); if (!isEmptyOrInPlaceBlobHandle(blobHandle)) { final TmpBlobVaultBufferedInputStream tmpStream = (TmpBlobVaultBufferedInputStream) ((DiskBasedBlobVault) blobVault).copyToTemporaryStore(blobHandle, bufferedStream, txn); txn.addBlobStream(blobHandle, tmpStream); setBlobFileLength(txn, blobHandle, Files.size(tmpStream.getPath())); return tmpStream; } return bufferedStream; }","Ability to use InputStreams after addition into Entity as blobs was implemented without risk of OOM (#64) * Performance of blobs handling was improved. Storing of the stream data was moved from commit to the call of Entity#setBlob method. * Fix of bug with incorrect reusing of stream created by #setBlob function. * Errors which could be caused by re-addition of InputStream already stored in transaction are fixed.",https://github.com/JetBrains/xodus/commit/163d551237a6ba910c41414a727b6cee12db0507,,,entity-store/src/main/java/jetbrains/exodus/entitystore/PersistentEntityStoreImpl.java,3,java,False,2023-02-13T16:41:24Z "@Override public void startProgramListUpdates(ProgramList.Filter filter) { mTunerCallback.startProgramListUpdates(filter); }","@Override public void startProgramListUpdates(ProgramList.Filter filter) { if (!RadioServiceUserController.isCurrentOrSystemUser()) { Slogf.w(TAG, ""Cannot start program list updates on HAL 1.x client from non-current user""); return; } mTunerCallback.startProgramListUpdates(filter); }","Add user control for broadcast radio HAL client For opening tuner and adding announcement listener methods in HAL clients, an illegal state exception is thrown if the user calling methods is not the current user or system user. Calls from non-current on other public methods in HAL clients which can modify HAL state are rejected silently, to avoid crash radio apps when the current user is switched. Meanwhile, public methods in radio modules are changed to non-public since there is no need to access them outside their package. HAL 2.0 client code is also refactored. Bug: 240344065 Test: atest com.android.server.broadcastradio.aidl Change-Id: I62147a5d68b1f6a0314941ab65d0faedb78bfa7d",https://github.com/aosp-mirror/platform_frameworks_base/commit/024ec1687e81ba8df7d9bb8800fc9d4e0fd67423,,,services/core/java/com/android/server/broadcastradio/hal1/Tuner.java,3,java,False,2022-10-27T21:45:22Z "@Override public Authentication authenticate(final Authentication auth) throws org.springframework.security.core.AuthenticationException { CustomWebAuthenticationDetails customWebAuthenticationDetails = ((CustomWebAuthenticationDetails) auth .getDetails()); String verificationCode = customWebAuthenticationDetails.getVerificationCode(); UserEntity user = userRepository.findByUsernameIgnoreCase(auth.getName()); if (user == null || !user.getActiveFlag()) { throw new UsernameNotFoundException(""User '"" + auth.getName() + ""' does not exist""); } try { Authentication result = super.authenticate(auth); if (user.getIs2FaEnabled()) { if (!user.getIs2FaConfigured() && !customWebAuthenticationDetails.isConfigure2Fa()) { throw new TwoFaKeyNotSetException(); } else { if (verificationCode == null || verificationCode.isEmpty()) { throw new OtpRequiredException(); } else if (!TwoFactorUtility.validateOtp(verificationCode, user.getTwoFaKey())) { throw new InvalidOtpException(""Invalid verfication code""); } } } return new UsernamePasswordAuthenticationToken(user, result.getCredentials(), result.getAuthorities()); } catch (BadCredentialsException e) { throw new BadCredentialsException(e.getMessage()); } }","@Override public Authentication authenticate(final Authentication auth) throws org.springframework.security.core.AuthenticationException { CustomWebAuthenticationDetails customWebAuthenticationDetails = ((CustomWebAuthenticationDetails) auth .getDetails()); String verificationCode = customWebAuthenticationDetails.getVerificationCode(); UserEntity user = userRepository.findByUsernameIgnoreCase(auth.getName()); if (user == null || !user.getActiveFlag()) { throw new BadCredentialsException(""Login failed; Invalid email or password.""); } String loginCount = null; String unlockTime = null; if (user.getUserId() != 1) { loginCount = applicationSettingService.getApplicationSetting(ApplicationSetting.INVALID_LOGIN_ATTEMPT); unlockTime = applicationSettingService.getApplicationSetting(ApplicationSetting .USER_ACCOUNT_UNLOCK_TIME); if (!user.getStatusEntity().getStatus().equalsIgnoreCase(""ACTIVE"")) { checkUserLoginAttempts(user, loginCount, unlockTime); } } try { final Authentication result = super.authenticate(auth); if (user.getIs2FaEnabled()) { if (!user.getIs2FaConfigured() && !customWebAuthenticationDetails.isConfigure2Fa()) { throw new TwoFaKeyNotSetException(); } else { if (verificationCode == null || verificationCode.isEmpty()) { throw new OtpRequiredException(); } else if (!TwoFactorUtility.validateOtp(verificationCode, user.getTwoFaKey())) { throw new InvalidOtpException(""Invalid verfication code""); } } } return new UsernamePasswordAuthenticationToken(user, result.getCredentials(), result.getAuthorities()); } catch (BadCredentialsException e) { if (user.getUserId() != 1) { updateInvalidLoginAttempts(user, loginCount, unlockTime); } throw new BadCredentialsException(e.getMessage()); } }","Improvement in login system to defend brute force attack Resolves:#3564",https://github.com/telstra/open-kilda/commit/80322ae7dd56fe2b78e85a73c7be479a48a8adaf,,,src-gui/src/main/java/org/openkilda/security/CustomAuthenticationProvider.java,3,java,False,2021-03-23T09:46:05Z "static int get_registers(rtl8150_t * dev, u16 indx, u16 size, void *data) { return usb_control_msg(dev->udev, usb_rcvctrlpipe(dev->udev, 0), RTL8150_REQ_GET_REGS, RTL8150_REQT_READ, indx, 0, data, size, 500); }","static int get_registers(rtl8150_t * dev, u16 indx, u16 size, void *data) { void *buf; int ret; buf = kmalloc(size, GFP_NOIO); if (!buf) return -ENOMEM; ret = usb_control_msg(dev->udev, usb_rcvctrlpipe(dev->udev, 0), RTL8150_REQ_GET_REGS, RTL8150_REQT_READ, indx, 0, buf, size, 500); if (ret > 0 && ret <= size) memcpy(data, buf, ret); kfree(buf); return ret; }","rtl8150: Use heap buffers for all register access Allocating USB buffers on the stack is not portable, and no longer works on x86_64 (with VMAP_STACK enabled as per default). Fixes: 1da177e4c3f4 (""Linux-2.6.12-rc2"") Signed-off-by: Ben Hutchings Signed-off-by: David S. Miller ",https://github.com/torvalds/linux/commit/7926aff5c57b577ab0f43364ff0c59d968f6a414,,,drivers/net/usb/rtl8150.c,3,c,False,2017-02-04T16:56:32Z "public static void removeGotos(ControlFlowGraph graph) { for (BasicBlock block : graph.getBlocks()) { Instruction instr = block.getLastInstruction(); if (instr != null && instr.opcode == CodeConstants.opc_goto) { block.getSeq().removeLast(); } } removeEmptyBlocks(graph); }","public static void removeGotos(ControlFlowGraph graph) { for (BasicBlock block : graph.getBlocks()) { Instruction instr = block.getLastInstruction(); if (instr != null && instr.opcode == CodeConstants.opc_goto) { // Destination points towards itself- infinite loop? if (graph.getSequence().getInstr(((JumpInstruction)instr).destination) == instr) { continue; } block.getSeq().removeLast(); } } removeEmptyBlocks(graph); }",Fix infinite loops,https://github.com/Earthcomputer/kotlin-decompiler/commit/eae9973afd90b648c5c6ff0834d9967793046d86,,,src/org/jetbrains/java/decompiler/modules/code/DeadCodeHelper.java,3,java,False,2021-07-03T04:15:05Z "@Override public void stopAllChannels() { mRunning = false; List toStop = new ArrayList<>(mChannelSources); for(TunerChannelSource tunerChannelSource: toStop) { try { tunerChannelSource.process(SourceEvent.tunerShutdown(tunerChannelSource)); } catch(SourceException se) { mLog.error(""Error stopping tuner channel source for tuner shutdown""); } } }","@Override public void stopAllChannels() { mRunning = false; List toStop = new ArrayList<>(mChannelSources); for(TunerChannelSource tunerChannelSource: toStop) { MyEventBus.getGlobalEventBus().post(new ChannelStopProcessingRequest(tunerChannelSource)); } }","#1243 Updates USB tuner error handling to prevent stack overflow when tuner error occurs while streaming. (#1247) Co-authored-by: Dennis Sheirer ",https://github.com/DSheirer/sdrtrunk/commit/8bfb1d54702ce89f44094a76346e98f4b9f7e255,,,src/main/java/io/github/dsheirer/source/tuner/manager/HeterodyneChannelSourceManager.java,3,java,False,2022-05-09T11:16:35Z "public Date getDate(int col) throws SQLException { DB db = getDatabase(); switch (db.column_type(stmt.pointer, markCol(col))) { case SQLITE_NULL: return null; case SQLITE_TEXT: try { return new Date( getConnectionConfig() .getDateFormat() .parse(db.column_text(stmt.pointer, markCol(col))) .getTime()); } catch (Exception e) { SQLException error = new SQLException(""Error parsing date""); error.initCause(e); throw error; } case SQLITE_FLOAT: return new Date( julianDateToCalendar(db.column_double(stmt.pointer, markCol(col))) .getTimeInMillis()); default: // SQLITE_INTEGER: return new Date( db.column_long(stmt.pointer, markCol(col)) * getConnectionConfig().getDateMultiplier()); } }","public Date getDate(int col) throws SQLException { DB db = getDatabase(); switch (safeGetColumnType(markCol(col))) { case SQLITE_NULL: return null; case SQLITE_TEXT: try { return new Date( getConnectionConfig() .getDateFormat() .parse(safeGetColumnText(col)) .getTime()); } catch (Exception e) { SQLException error = new SQLException(""Error parsing date""); error.initCause(e); throw error; } case SQLITE_FLOAT: return new Date(julianDateToCalendar(safeGetDoubleCol(col)).getTimeInMillis()); default: // SQLITE_INTEGER: return new Date(safeGetLongCol(col) * getConnectionConfig().getDateMultiplier()); } }",Wrap Statement Pointers to prevent use after free race,https://github.com/xerial/sqlite-jdbc/commit/e1d282cb2887ef427c7ad93d4fe7dd05a6c11473,,,src/main/java/org/sqlite/jdbc3/JDBC3ResultSet.java,3,java,False,2022-07-29T03:54:01Z "def create_network(self, instance_name, instance, network_info): """"""Create the LXD container network on the host :param instance_name: nova instance name :param instance: nova instance object :param network_info: instance network configuration object :return:network configuration dictionary """""" LOG.debug('create_network called for instance', instance=instance) try: network_devices = {} if not network_info: return for vifaddr in network_info: cfg = self.vif_driver.get_config(instance, vifaddr) network_devices[str(cfg['bridge'])] = \ {'nictype': 'bridged', 'hwaddr': str(cfg['mac_address']), 'parent': str(cfg['bridge']), 'type': 'nic'} return network_devices except Exception as ex: with excutils.save_and_reraise_exception(): LOG.error( _LE('Fail to configure network for %(instance)s: %(ex)s'), {'instance': instance_name, 'ex': ex}, instance=instance)","def create_network(self, instance_name, instance, network_info): """"""Create the LXD container network on the host :param instance_name: nova instance name :param instance: nova instance object :param network_info: instance network configuration object :return:network configuration dictionary """""" LOG.debug('create_network called for instance', instance=instance) try: network_devices = {} if not network_info: return for vifaddr in network_info: cfg = self.vif_driver.get_config(instance, vifaddr) key = str(cfg['bridge']) network_devices[key] = \ {'nictype': 'bridged', 'hwaddr': str(cfg['mac_address']), 'parent': key, 'type': 'nic'} host_device = self.vif_driver.get_vif_devname(vifaddr) if host_device: network_devices[key]['host_name'] = host_device return network_devices except Exception as ex: with excutils.save_and_reraise_exception(): LOG.error( _LE('Fail to configure network for %(instance)s: %(ex)s'), {'instance': instance_name, 'ex': ex}, instance=instance)","Ensure LXD veth host device is named correctly LXD uses a veth pair to plumb the LXD instance into the bridge providing access to neutron networking. In later nova-lxd versions, the host_name parameter is set based on the neutron configured name for the host part of the pair, ensuring that neutron iptables firewall rules are correctly applied to instances. Update the mitaka version of the driver to populate the LXD network device configuration to ensure that any firewall rules are correctly applied. (also dropped version from setup.cfg, as pbr will automatically generate the version based on git tags, so its really surplus to requirements). Change-Id: Ic5b9ad6944a1ac45cd1983d038431252ff738985 Closes-Bug: 1656847",https://github.com/openstack/nova-lxd/commit/1b76cefb92081efa1e88cd8f330253f857028bd2,,,nova_lxd/nova/virt/lxd/config.py,3,py,False,2017-01-31T11:23:06Z "@Override public void onPacketReceiving(PacketEvent event) { if ((checkTemporaryPlayers && event.isPlayerTemporary()) || event.isCancelled()) { return; } PacketContainer packet = event.getPacket(); if (packet.getType() == PacketType.Play.Client.USE_ENTITY) { int id = packet.getIntegers().read(0); Entity entity = null; try { entity = packet.getEntityModifier(event).readSafely(0); } catch (RuntimeException ignored) { } if (entity == null && event.getPlayer() != null) { entity = MyPetApi.getPlatformHelper().getEntity(id, event.getPlayer().getWorld()); } if (entity instanceof MyPetBukkitPart) { entity = ((MyPetBukkitPart) entity).getPetOwner(); packet.getIntegers().write(0, entity.getEntityId()); } } }","@Override public void onPacketReceiving(PacketEvent event) { if ((checkTemporaryPlayers && event.isPlayerTemporary()) || event.isCancelled()) { return; } //Prevent click-spamming causing Network-Issues for entire server. Basically cheap rate-limiting if (tempBlockedPlayers.contains(event.getPlayer())) { return; } else { tempBlockedPlayers.add(event.getPlayer()); //Register Rate-Limit-Clear-Task Bukkit.getScheduler().runTaskLaterAsynchronously(MyPetApi.getPlugin(), () -> { tempBlockedPlayers.remove(event.getPlayer()); }, 2L); } PacketContainer packet = event.getPacket(); if (packet.getType() == PacketType.Play.Client.USE_ENTITY) { try { Entity ent = ensureMainThread(() -> { int id = packet.getIntegers().read(0); Entity entity = null; try { entity = packet.getEntityModifier(event).readSafely(0); } catch (RuntimeException ignored) { } if (entity == null && event.getPlayer() != null) { entity = MyPetApi.getPlatformHelper().getEntity(id, event.getPlayer().getWorld()); } if (entity instanceof MyPetBukkitPart) { entity = ((MyPetBukkitPart) entity).getPetOwner(); } return entity; }); if(ent != null) { packet.getIntegers().write(0, ent.getEntityId()); } } catch (Exception e) { e.printStackTrace(); } } }","Introduce cheap ratelimiting to packet handling Introduce cheap ratelimiting to mitigate click-spam exploit in 1.17+ versions",https://github.com/MyPetORG/MyPet/commit/0cdc28888e1f9e8bea9ace86dc28ed4fdf553523,,,modules/Plugin/src/main/java/de/Keyle/MyPet/util/hooks/ProtocolLibHook.java,3,java,False,2022-11-16T23:19:49Z "@Override public String getHeader(String name) { String value = super.getHeader(name); if (value == null) { return null; } return HtmlUtils.htmlEscape(value); }","@Override public String getHeader(String name) { String value = super.getHeader(name); if (value == null) { return null; } return HtmlUtils.cleanUnSafe(value); }",:zap: 使用 Jackson2ObjectMapperBuilder 构造 ObjectMapper,保留使用配置文件配置 jackson 属性的能力,以及方便用户增加自定义配置,https://github.com/ballcat-projects/ballcat/commit/d4d5d4c4aa4402bec83db4eab7007f0cf70e8e01,,,ballcat-common/ballcat-common-core/src/main/java/com/hccake/ballcat/common/core/request/wrapper/XSSRequestWrapper.java,3,java,False,2021-03-08T14:05:28Z "@Override public ClientBuilder loadConf(Map config) { conf = ConfigurationDataUtils.loadData(config, conf, ClientConfigurationData.class); return this; }","@Override public ClientBuilder loadConf(Map config) { conf = ConfigurationDataUtils.loadData(config, conf, ClientConfigurationData.class); setAuthenticationFromPropsIfAvailable(conf); return this; }",[fix][client] Set authentication when using loadConf in client and admin client (#18358),https://github.com/apache/pulsar/commit/0f72a822dd8aa21fa3d86bb6f62ea4482fc3b907,,,pulsar-client/src/main/java/org/apache/pulsar/client/impl/ClientBuilderImpl.java,3,java,False,2023-02-04T20:03:23Z "@SuppressLint(""WrongConstant"") private static void createNotification(Context context) { setNotiCount(); cancelNotification(context); NotificationManager notificationManager = (NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE); if (notificationManager.getNotificationChannel(CHANNEL_ID) == null) { notificationManager.createNotificationChannel(new NotificationChannel(CHANNEL_ID, CHANNEL_NAME, NotificationManager.IMPORTANCE_LOW)); } Intent intent = new Intent(); intent.setAction(""android.settings.FACE_SETTINGS""); intent.addFlags(268435456); notificationManager.notify(1, new Notification.Builder(context, CHANNEL_ID) .setSmallIcon(R.drawable.ic_face_auth) .setContentTitle(context.getString(R.string.facelock_setup_notification_title)) .setContentText(context.getString(R.string.facelock_setup_notification_text)) .setAutoCancel(true) .setChannelId(CHANNEL_ID) .setContentIntent(PendingIntent.getActivity(context, 0, intent, 268435456)).build()); }","@SuppressLint(""WrongConstant"") private static void createNotification(Context context) { setNotiCount(); cancelNotification(context); NotificationManager notificationManager = (NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE); if (notificationManager.getNotificationChannel(CHANNEL_ID) == null) { notificationManager.createNotificationChannel(new NotificationChannel(CHANNEL_ID, CHANNEL_NAME, NotificationManager.IMPORTANCE_LOW)); } Intent intent = new Intent(); intent.setAction(""android.settings.FACE_SETTINGS""); intent.addFlags(268435456); notificationManager.notify(1, new Notification.Builder(context, CHANNEL_ID) .setSmallIcon(R.drawable.ic_face_auth) .setContentTitle(context.getString(R.string.facelock_setup_notification_title)) .setContentText(context.getString(R.string.facelock_setup_notification_text)) .setAutoCancel(true) .setChannelId(CHANNEL_ID) .setContentIntent(PendingIntent.getActivity(context, 0, intent, PendingIntent.FLAG_CANCEL_CURRENT | PendingIntent.FLAG_IMMUTABLE)).build()); }",Fix PendingIntent mutability crash on Android 12+,https://github.com/null-dev/UniversalAuth/commit/c052cfa8bcf341705b61a8cda28085dc8879fb9e,,,faceunlock/src/main/java/ax/nd/faceunlock/util/NotificationUtils.java,3,java,False,2022-03-21T09:26:04Z "public static boolean hasCraftingTable(Player player) { var uuid = player.getUUID(); if (!CACHED_HAS_CRAFTING_TABLE.contains(uuid) || player.getLevel().getGameTime() % CHECK_TICKS_FAST == 0) { var hasCraftingTable = CharmApi.getProviders(IChecksInventoryTag.class).stream() .flatMap(s -> s.getInventoryTagChecks().stream()) .anyMatch(check -> check.test(player, CRAFTING_TABLES)); if (hasCraftingTable) { CACHED_HAS_CRAFTING_TABLE.add(uuid); } else { CACHED_HAS_CRAFTING_TABLE.remove(uuid); } } return CACHED_HAS_CRAFTING_TABLE.contains(uuid); }","public static boolean hasCraftingTable(Player player) { var uuid = player.getUUID(); if (!CACHED_HAS_CRAFTING_TABLE.contains(uuid) || player.getLevel().getGameTime() % CHECK_TICKS_FAST == 0) { var hasCraftingTable = CharmApi.getProviders(IChecksInventoryTag.class).stream() .flatMap(s -> s.getInventoryTagChecks().stream()) .anyMatch(check -> check.test(player, CRAFTING_TABLES)); if (hasCraftingTable && !CACHED_HAS_CRAFTING_TABLE.contains(uuid)) { CACHED_HAS_CRAFTING_TABLE.add(uuid); } else { CACHED_HAS_CRAFTING_TABLE.remove(uuid); } } return CACHED_HAS_CRAFTING_TABLE.contains(uuid); }",Fix crafting table cache stack overflow,https://github.com/svenhjol/Charm/commit/e330c322e81062510e35c9cacfdd15cb472dd21f,,,common/src/main/java/svenhjol/charm/feature/portable_crafting/PortableCrafting.java,3,java,False,2023-02-11T16:00:20Z "@Nullable private static IRecipeTransferError transferRecipe( RecipeTransferManager recipeTransferManager, C container, IRecipeLayoutInternal recipeLayout, Player player, boolean maxTransfer, boolean doTransfer ) { if (Internal.getRuntime().isEmpty()) { return RecipeTransferErrorInternal.INSTANCE; } IRecipeCategory recipeCategory = recipeLayout.getRecipeCategory(); final IRecipeTransferHandler transferHandler = recipeTransferManager.getRecipeTransferHandler(container, recipeCategory); if (transferHandler == null) { if (doTransfer) { LOGGER.error(""No Recipe Transfer handler for container {}"", container.getClass()); } return RecipeTransferErrorInternal.INSTANCE; } RecipeSlots recipeSlots = recipeLayout.getRecipeSlots(); IRecipeSlotsView recipeSlotsView = recipeSlots.getView(); return transferHandler.transferRecipe(container, recipeLayout.getRecipe(), recipeSlotsView, player, maxTransfer, doTransfer); }","@Nullable private static IRecipeTransferError transferRecipe( RecipeTransferManager recipeTransferManager, C container, IRecipeLayoutInternal recipeLayout, Player player, boolean maxTransfer, boolean doTransfer ) { if (Internal.getRuntime().isEmpty()) { return RecipeTransferErrorInternal.INSTANCE; } IRecipeCategory recipeCategory = recipeLayout.getRecipeCategory(); final IRecipeTransferHandler transferHandler = recipeTransferManager.getRecipeTransferHandler(container, recipeCategory); if (transferHandler == null) { if (doTransfer) { LOGGER.error(""No Recipe Transfer handler for container {}"", container.getClass()); } return RecipeTransferErrorInternal.INSTANCE; } RecipeSlots recipeSlots = recipeLayout.getRecipeSlots(); IRecipeSlotsView recipeSlotsView = recipeSlots.getView(); try { return transferHandler.transferRecipe(container, recipeLayout.getRecipe(), recipeSlotsView, player, maxTransfer, doTransfer); } catch (RuntimeException e) { LOGGER.error( ""Recipe transfer handler '{}' for container '{}' and recipe type '{}' threw an error: "", transferHandler.getClass(), transferHandler.getContainerClass(), recipeCategory.getRecipeType().getUid(), e ); return RecipeTransferErrorInternal.INSTANCE; } }",Fix #2890 Protect against broken recipe transfer handlers crashing,https://github.com/mezz/JustEnoughItems/commit/4f991ab7b552256c01009993454f4f9c76a46865,,,Common/src/main/java/mezz/jei/common/transfer/RecipeTransferUtil.java,3,java,False,2022-07-14T00:42:01Z "public boolean checkIfPathNumberIsOverLimit(List resultColumns) throws PathNumOverLimitException { int maxQueryDeduplicatedPathNum = IoTDBDescriptor.getInstance().getConfig().getMaxQueryDeduplicatedPathNum(); if (currentLimit == 0) { if (maxQueryDeduplicatedPathNum < resultColumns.size()) { throw new PathNumOverLimitException(maxQueryDeduplicatedPathNum); } return true; } return false; }","public boolean checkIfPathNumberIsOverLimit(List resultColumns) throws PathNumOverLimitException { if (resultColumns.size() > IoTDBDescriptor.getInstance().getConfig().getMaxQueryDeduplicatedPathNum()) { throw new PathNumOverLimitException(); } return currentLimit == 0; }",[IOTDB-1975] OOM caused by that MaxQueryDeduplicatedPathNum doesn't take effect (#4345),https://github.com/apache/iotdb/commit/7e718f0ba703f7bca0cb0be2b717cdd6cc48d888,,,server/src/main/java/org/apache/iotdb/db/qp/utils/WildcardsRemover.java,3,java,False,2021-11-10T05:46:29Z "protected final View prepareDecorView(View v) { v = FontLoader.apply(v); if (!getConfig().isDisableContextMenu()) { v = new ContextMenuDecorView(v, this); } return v; }","protected final View prepareDecorView(View v) { v = FontLoader.apply(v); if (!getConfig().isDisableContextMenu() && v != null) { v = new ContextMenuDecorView(this, v, this); } return v; }",Fix crashing when content view in activity or fragment cause npe into ContextMenuDecorView,https://github.com/zl-suu/ingrauladolfo/commit/1d5aa50dfda2aedfdb678648dae567df7d068841,,,library/src/com/WazaBe/HoloEverywhere/app/Activity.java,3,java,False,2022-07-31T08:13:46Z "@Override public Element[] supStreamFeatures(final XMPPResourceConnection session) { // If session does not exist, just return null, we don't provide features // for non-existen stream, the second condition means that the TLS // has not been yet completed for the user connection. if ((session != null) && (session.getSessionData(ID) == null)) { VHostItem vhost = session.getDomain(); if ((vhost != null) && session.isTlsRequired()) { return F_REQUIRED; } else { return F_NOT_REQUIRED; } } else { return null; } // end of if (session.isAuthorized()) else }","@Override public Element[] supStreamFeatures(final XMPPResourceConnection session) { // If session does not exist, just return null, we don't provide features // for non-existen stream, the second condition means that the TLS // has not been yet completed for the user connection. if ((session != null) && (session.getSessionData(ID) == null)) { if (session.isEncrypted()) { // connection is already SSL/TLS protected return null; } VHostItem vhost = session.getDomain(); if ((vhost != null) && session.isTlsRequired()) { return F_REQUIRED; } else { return F_NOT_REQUIRED; } } else { return null; } // end of if (session.isAuthorized()) else }",Fixed advertisement stream features for unauthorized stream #server-1334,https://github.com/tigase/tigase-server/commit/b9bc6f1db3891f1b4c80d28281cf7678f284892f,,,src/main/java/tigase/xmpp/impl/StartTLS.java,3,java,False,2022-10-07T14:16:48Z "public CompletableFuture ping(@Nullable EventLoop loop, ProtocolVersion version) { if (server == null) { throw new IllegalStateException(""No Velocity proxy instance available""); } CompletableFuture pingFuture = new CompletableFuture<>(); server.createBootstrap(loop) .handler(new ChannelInitializer() { @Override protected void initChannel(Channel ch) throws Exception { ch.pipeline() .addLast(READ_TIMEOUT, new ReadTimeoutHandler(server.getConfiguration().getReadTimeout(), TimeUnit.MILLISECONDS)) .addLast(FRAME_DECODER, new MinecraftVarintFrameDecoder()) .addLast(FRAME_ENCODER, MinecraftVarintLengthEncoder.INSTANCE) .addLast(MINECRAFT_DECODER, new MinecraftDecoder(ProtocolUtils.Direction.CLIENTBOUND)) .addLast(MINECRAFT_ENCODER, new MinecraftEncoder(ProtocolUtils.Direction.SERVERBOUND)); ch.pipeline().addLast(HANDLER, new MinecraftConnection(ch, server)); } }) .connect(serverInfo.getAddress()) .addListener((ChannelFutureListener) future -> { if (future.isSuccess()) { MinecraftConnection conn = future.channel().pipeline().get(MinecraftConnection.class); conn.setSessionHandler(new PingSessionHandler( pingFuture, VelocityRegisteredServer.this, conn, version)); } else { pingFuture.completeExceptionally(future.cause()); } }); return pingFuture; }","public CompletableFuture ping(@Nullable EventLoop loop, ProtocolVersion version) { if (server == null) { throw new IllegalStateException(""No Velocity proxy instance available""); } CompletableFuture pingFuture = new CompletableFuture<>(); server.createBootstrap(loop) .handler(new ChannelInitializer() { @Override protected void initChannel(Channel ch) throws Exception { ch.pipeline() .addLast(FRAME_DECODER, new MinecraftVarintFrameDecoder()) .addLast(READ_TIMEOUT, new ReadTimeoutHandler(server.getConfiguration().getReadTimeout(), TimeUnit.MILLISECONDS)) .addLast(FRAME_ENCODER, MinecraftVarintLengthEncoder.INSTANCE) .addLast(MINECRAFT_DECODER, new MinecraftDecoder(ProtocolUtils.Direction.CLIENTBOUND)) .addLast(MINECRAFT_ENCODER, new MinecraftEncoder(ProtocolUtils.Direction.SERVERBOUND)); ch.pipeline().addLast(HANDLER, new MinecraftConnection(ch, server)); } }) .connect(serverInfo.getAddress()) .addListener((ChannelFutureListener) future -> { if (future.isSuccess()) { MinecraftConnection conn = future.channel().pipeline().get(MinecraftConnection.class); conn.setSessionHandler(new PingSessionHandler( pingFuture, VelocityRegisteredServer.this, conn, version)); } else { pingFuture.completeExceptionally(future.cause()); } }); return pingFuture; }","Move timeout handler to after frame decoder Mitigates attacks like the one described in SpigotMC/BungeeCord#3066. This cannot be considered a full protection, only a mitigation that expects full packets. The attack described is essentially the infamous Slowloris attack.",https://github.com/PaperMC/Velocity/commit/f1cb3eb1a28bc5003d8dd844b5cdf990970ab89d,,,proxy/src/main/java/com/velocitypowered/proxy/server/VelocityRegisteredServer.java,3,java,False,2021-04-16T02:56:37Z "@Override public void initEntityValues() { if (!getEntity().isPresent()) { return; } final AbstractEntityCitizen citizen = getEntity().get(); citizen.setCitizenId(getId()); citizen.getCitizenColonyHandler().setColonyId(getColony().getID()); citizen.setIsChild(isChild()); citizen.setCustomName(new TextComponent(getName())); citizen.getAttribute(Attributes.MAX_HEALTH).setBaseValue(BASE_MAX_HEALTH); citizen.setFemale(isFemale()); citizen.setTextureId(getTextureId()); citizen.getEntityData().set(DATA_COLONY_ID, colony.getID()); citizen.getEntityData().set(DATA_CITIZEN_ID, citizen.getCivilianID()); citizen.getEntityData().set(DATA_IS_FEMALE, citizen.isFemale() ? 1 : 0); citizen.getEntityData().set(DATA_TEXTURE, citizen.getTextureId()); citizen.getEntityData().set(DATA_TEXTURE_SUFFIX, getTextureSuffix()); citizen.getEntityData().set(DATA_IS_ASLEEP, isAsleep()); citizen.getEntityData().set(DATA_IS_CHILD, isChild()); citizen.getEntityData().set(DATA_BED_POS, getBedPos()); citizen.getEntityData().set(DATA_JOB, getJob() == null ? """" : getJob().getJobRegistryEntry().getRegistryName().toString()); citizen.getEntityData().set(DATA_STYLE, colony.getTextureStyleId()); citizen.getCitizenExperienceHandler().updateLevel(); setLastPosition(citizen.blockPosition()); citizen.getCitizenJobHandler().onJobChanged(citizen.getCitizenJobHandler().getColonyJob()); applyResearchEffects(); applyItemModifiers(citizen); markDirty(); }","@Override public void initEntityValues() { if (!getEntity().isPresent()) { return; } final AbstractEntityCitizen citizen = getEntity().get(); citizen.setCitizenId(getId()); citizen.getCitizenColonyHandler().setColonyId(getColony().getID()); citizen.setIsChild(isChild()); citizen.setCustomName(new TextComponent(getName())); citizen.getAttribute(Attributes.MAX_HEALTH).setBaseValue(BASE_MAX_HEALTH); citizen.setFemale(isFemale()); citizen.setTextureId(getTextureId()); citizen.getEntityData().set(DATA_COLONY_ID, colony.getID()); citizen.getEntityData().set(DATA_CITIZEN_ID, citizen.getCivilianID()); citizen.getEntityData().set(DATA_IS_FEMALE, citizen.isFemale() ? 1 : 0); citizen.getEntityData().set(DATA_TEXTURE, citizen.getTextureId()); citizen.getEntityData().set(DATA_TEXTURE_SUFFIX, getTextureSuffix()); citizen.getEntityData().set(DATA_IS_ASLEEP, isAsleep()); citizen.getEntityData().set(DATA_IS_CHILD, isChild()); citizen.getEntityData().set(DATA_BED_POS, getBedPos()); citizen.getEntityData().set(DATA_JOB, getJob() == null ? """" : getJob().getJobRegistryEntry().getRegistryName().toString()); citizen.getEntityData().set(DATA_STYLE, colony.getTextureStyleId()); // Safety check that ensure the citizen its job matches the work building job if (getJob() != null && workBuilding != null) { boolean hasCorrectJob = false; for (WorkerBuildingModule module : workBuilding.getModules(WorkerBuildingModule.class)) { if (module.getJobEntry().equals(getJob().getJobRegistryEntry())) { hasCorrectJob = true; break; } } if (!hasCorrectJob) { MessageUtils.format(DEBUG_WARNING_CITIZEN_LOAD_FAILURE, citizen.getName()).sendTo(colony).forAllPlayers(); Log.getLogger().log(Level.ERROR, String.format(""Worker %s has been unassigned from his job, a problem was found during load. Worker job: %s; Building: %s"", citizen.getName().getString(), getJob().getJobRegistryEntry().getKey().toString(), workBuilding.getBuildingType().getRegistryName().toString())); // Remove the citizen from the building to prevent failures in the future. for (WorkerBuildingModule module : workBuilding.getModules(WorkerBuildingModule.class)) { module.removeCitizen(this); } } } citizen.getCitizenExperienceHandler().updateLevel(); setLastPosition(citizen.blockPosition()); citizen.getCitizenJobHandler().onJobChanged(citizen.getCitizenJobHandler().getColonyJob()); applyResearchEffects(); applyItemModifiers(citizen); markDirty(); }","Fix NBT assignment corruption (#8905) In some cases it's possible that NBT data gets corrupted and causes citizens their jobs to no longer match the expected job in the building they are assigned to. This fix will prevent any loading issues by unassigning the worker when an improper link between the citizen it's job and building is found, to prevent any crashes.",https://github.com/ldtteam/minecolonies/commit/aa6a3774f4fb0cc7af88cd20abda1c090bf6c7f2,,,src/main/java/com/minecolonies/coremod/colony/CitizenData.java,3,java,False,2023-01-22T12:58:44Z "@Override protected void addServices(Injector injector, List services, List closeableResources, MasterEnvironment masterEnv, MasterEnvironmentContext masterEnvContext, EnvironmentOptions options) { closeableResources.add(injector.getInstance(AccessControllerInstantiator.class)); services.add(injector.getInstance(OperationalStatsService.class)); services.add(injector.getInstance(SecureStoreService.class)); services.add(injector.getInstance(DatasetOpExecutorService.class)); services.add(injector.getInstance(ServiceStore.class)); Binding zkBinding = injector.getExistingBinding(Key.get(ZKClientService.class)); if (zkBinding != null) { services.add(zkBinding.getProvider().get()); } // Start both the remote TwillRunnerService and regular TwillRunnerService TwillRunnerService remoteTwillRunner = injector.getInstance(Key.get(TwillRunnerService.class, Constants.AppFabric.RemoteExecution.class)); services.add(new TwillRunnerServiceWrapper(remoteTwillRunner)); services.add(new TwillRunnerServiceWrapper(injector.getInstance(TwillRunnerService.class))); services.add(new RetryOnStartFailureService(() -> injector.getInstance(DatasetService.class), RetryStrategies.exponentialDelay(200, 5000, TimeUnit.MILLISECONDS))); services.add(injector.getInstance(AppFabricServer.class)); CConfiguration cConf = injector.getInstance(CConfiguration.class); if (cConf.getBoolean(Constants.TaskWorker.POOL_ENABLE)) { services.add(injector.getInstance(TaskWorkerServiceLauncher.class)); } if (SecurityUtil.isInternalAuthEnabled(cConf)) { services.add(injector.getInstance(TokenManager.class)); } // Optionally adds the master environment task masterEnv.getTask().ifPresent(task -> services.add(new MasterTaskExecutorService(task, masterEnvContext))); }","@Override protected void addServices(Injector injector, List services, List closeableResources, MasterEnvironment masterEnv, MasterEnvironmentContext masterEnvContext, EnvironmentOptions options) { CConfiguration cConf = injector.getInstance(CConfiguration.class); if (SecurityUtil.isInternalAuthEnabled(cConf)) { services.add(injector.getInstance(TokenManager.class)); } closeableResources.add(injector.getInstance(AccessControllerInstantiator.class)); services.add(injector.getInstance(OperationalStatsService.class)); services.add(injector.getInstance(SecureStoreService.class)); services.add(injector.getInstance(DatasetOpExecutorService.class)); services.add(injector.getInstance(ServiceStore.class)); Binding zkBinding = injector.getExistingBinding(Key.get(ZKClientService.class)); if (zkBinding != null) { services.add(zkBinding.getProvider().get()); } // Start both the remote TwillRunnerService and regular TwillRunnerService TwillRunnerService remoteTwillRunner = injector.getInstance(Key.get(TwillRunnerService.class, Constants.AppFabric.RemoteExecution.class)); services.add(new TwillRunnerServiceWrapper(remoteTwillRunner)); services.add(new TwillRunnerServiceWrapper(injector.getInstance(TwillRunnerService.class))); services.add(new RetryOnStartFailureService(() -> injector.getInstance(DatasetService.class), RetryStrategies.exponentialDelay(200, 5000, TimeUnit.MILLISECONDS))); services.add(injector.getInstance(AppFabricServer.class)); if (cConf.getBoolean(Constants.TaskWorker.POOL_ENABLE)) { services.add(injector.getInstance(TaskWorkerServiceLauncher.class)); } // Optionally adds the master environment task masterEnv.getTask().ifPresent(task -> services.add(new MasterTaskExecutorService(task, masterEnvContext))); }","[CDAP-18322] Fix 2 issues with internal auth: start tokenmanager sooner and auth context for program 1. Start TokenManager serivce first in the AppFab startup, since other services may depend on it during their startup process when internal auth is enabled. 2. Use WorkerAuthenticationContext for program containers",https://github.com/cdapio/cdap/commit/c4a19f34a3b11f79d220ba2c2d4b8b8bdbdc86eb,,,cdap-master/src/main/java/io/cdap/cdap/master/environment/k8s/AppFabricServiceMain.java,3,java,False,2022-01-31T17:40:48Z "private static void unzipIgnoreFirstFolder(String zipFilePath, String destDir) { File dir = new File(destDir); // create output directory if it doesn't exist if (!dir.exists()) dir.mkdirs(); FileInputStream fis; //buffer for read and write data to file byte[] buffer = new byte[1024]; try { fis = new FileInputStream(zipFilePath); ZipInputStream zis = new ZipInputStream(fis); ZipEntry ze = zis.getNextEntry(); while (ze != null) { if (!ze.isDirectory()) { String fileName = ze.getName(); fileName = fileName.substring(fileName.split(""/"")[0].length() + 1); File newFile = new File(destDir + File.separator + fileName); //create directories for sub directories in zip new File(newFile.getParent()).mkdirs(); FileOutputStream fos = new FileOutputStream(newFile); int len; while ((len = zis.read(buffer)) > 0) { fos.write(buffer, 0, len); } fos.close(); } //close this ZipEntry zis.closeEntry(); ze = zis.getNextEntry(); } //close last ZipEntry zis.closeEntry(); zis.close(); fis.close(); } catch (IOException e) { e.printStackTrace(); } }","private static void unzipIgnoreFirstFolder(String zipFilePath, String destDir) { File dir = new File(destDir); // create output directory if it doesn't exist if (!dir.exists()) dir.mkdirs(); FileInputStream fis; //buffer for read and write data to file byte[] buffer = new byte[1024]; try { fis = new FileInputStream(zipFilePath); ZipInputStream zis = new ZipInputStream(fis); ZipEntry ze = zis.getNextEntry(); while (ze != null) { if (!ze.isDirectory()) { String fileName = ze.getName(); fileName = fileName.substring(fileName.split(""/"")[0].length() + 1); File newFile = new File(destDir + File.separator + fileName); //create directories for sub directories in zip new File(newFile.getParent()).mkdirs(); if (!isInTree(dir, newFile)) { throw new RuntimeException(""Not Enough Updates detected an invalid zip file. This is a potential security risk, please report this in the Moulberry discord.""); } FileOutputStream fos = new FileOutputStream(newFile); int len; while ((len = zis.read(buffer)) > 0) { fos.write(buffer, 0, len); } fos.close(); } //close this ZipEntry zis.closeEntry(); ze = zis.getNextEntry(); } //close last ZipEntry zis.closeEntry(); zis.close(); fis.close(); } catch (IOException e) { e.printStackTrace(); } }","Recipe Reloading should no longer duplicate recipes (#65) * Remove potential RCE only exploitable by Moulberry himself, i still want my cape tho * no more recipe dupes",https://github.com/Moulberry/NotEnoughUpdates/commit/6107995ad7892807bf6ba098548754fea439cee4,,,src/main/java/io/github/moulberry/notenoughupdates/NEUManager.java,3,java,False,2022-01-17T15:15:53Z "@EventHandler(priority = EventPriority.HIGH) public void onBlockExploding(TownyExplodingBlocksEvent event) { if(SiegeWarSettings.isCannonsIntegrationEnabled() && SiegeWar.getCannonsPluginDetected()) { List vanillaExplodeList = event.getVanillaBlockList(); //original list of exploding blocks List townyFilteredExplodeList = event.getTownyFilteredBlockList(); //the list of exploding blocks Towny has allowed List finalExplodeList = new ArrayList<>(); if(townyFilteredExplodeList != null) finalExplodeList.addAll(townyFilteredExplodeList); //Override Towny's protections if there is a cannon session in progress Town town; for (Block block : vanillaExplodeList) { if(!finalExplodeList.contains(block)) { town = TownyAPI.getInstance().getTown(block.getLocation()); if (town != null && SiegeController.hasActiveSiege(town) && SiegeController.getSiege(town).getCannonSessionRemainingShortTicks() > 0) { finalExplodeList.add(block); } } } event.setBlockList(finalExplodeList); } }","@EventHandler(priority = EventPriority.HIGH) public void onBlockExploding(TownyExplodingBlocksEvent event) { List finalExplodeList = new ArrayList<>(); //Do not add to final explode list: Blocks near banner or protected by trap mitigation List townyExplodeList = event.getTownyFilteredBlockList(); if(townyExplodeList != null) { for(Block block: townyExplodeList) { if ((SiegeWarSettings.isTrapWarfareMitigationEnabled() && SiegeWarDistanceUtil.isLocationInActiveTimedPointZoneAndBelowSiegeBannerAltitude(block.getLocation())) || SiegeWarBlockUtil.isBlockNearAnActiveSiegeBanner(block)) { //Do not add block to final explode list } else { //Add to final explode list finalExplodeList.add(block); } } } //Add to final explode list: town blocks if there is a cannon session in progress if(SiegeWarSettings.isCannonsIntegrationEnabled() && SiegeWar.getCannonsPluginDetected()) { List vanillaExplodeList = event.getVanillaBlockList(); //original list of exploding blocks Town town; for (Block block : vanillaExplodeList) { if(!finalExplodeList.contains(block)) { town = TownyAPI.getInstance().getTown(block.getLocation()); if (town != null && SiegeController.hasActiveSiege(town) && SiegeController.getSiege(town).getCannonSessionRemainingShortTicks() > 0) { finalExplodeList.add(block); } } } event.setBlockList(finalExplodeList); } }",Fixed bug with explosions bypassing trap mitigation,https://github.com/TownyAdvanced/SiegeWar/commit/b1971d00aebe44cc62d524b906de89370b7dc232,,,src/main/java/com/gmail/goosius/siegewar/listeners/SiegeWarTownyEventListener.java,3,java,False,2021-03-05T16:25:26Z "private void populateRemoveAndProtectedHeaders(RequestContext requestContext) { Map securitySchemeDefinitions = requestContext.getMatchedAPI().getSecuritySchemeDefinitions(); // API key headers are considered to be protected headers, such that the header would not be sent // to backend and traffic manager. // This would prevent leaking credentials, even if user is invoking unsecured resource with some // credentials. for (Map.Entry entry : securitySchemeDefinitions.entrySet()) { SecuritySchemaConfig schema = entry.getValue(); if (APIConstants.SWAGGER_API_KEY_AUTH_TYPE_NAME.equalsIgnoreCase(schema.getType())) { if (APIConstants.SWAGGER_API_KEY_IN_HEADER.equals(schema.getIn())) { requestContext.getProtectedHeaders().add(schema.getName()); requestContext.getRemoveHeaders().add(schema.getName()); continue; } if (APIConstants.SWAGGER_API_KEY_IN_QUERY.equals(schema.getIn())) { requestContext.getQueryParamsToRemove().add(schema.getName()); } } } // Internal-Key credential is considered to be protected headers, such that the header would not be sent // to backend and traffic manager. String internalKeyHeader = ConfigHolder.getInstance().getConfig().getAuthHeader() .getTestConsoleHeaderName().toLowerCase(); requestContext.getRemoveHeaders().add(internalKeyHeader); // Avoid internal key being published to the Traffic Manager requestContext.getProtectedHeaders().add(internalKeyHeader); // Remove Authorization Header AuthHeaderDto authHeader = ConfigHolder.getInstance().getConfig().getAuthHeader(); String authHeaderName = FilterUtils.getAuthHeaderName(requestContext); if (!authHeader.isEnableOutboundAuthHeader()) { requestContext.getRemoveHeaders().add(authHeaderName); } // Authorization Header should not be included in the throttle publishing event. requestContext.getProtectedHeaders().add(authHeaderName); // not allow clients to set cluster header manually requestContext.getRemoveHeaders().add(AdapterConstants.CLUSTER_HEADER); // Remove mTLS certificate header MutualSSLDto mtlsInfo = ConfigHolder.getInstance().getConfig().getMtlsInfo(); String certificateHeaderName = FilterUtils.getCertificateHeaderName(); if (!mtlsInfo.isEnableOutboundCertificateHeader()) { requestContext.getRemoveHeaders().add(certificateHeaderName); } // mTLS Certificate Header should not be included in the throttle publishing event. requestContext.getProtectedHeaders().add(certificateHeaderName); }","private void populateRemoveAndProtectedHeaders(RequestContext requestContext) { Map securitySchemeDefinitions = requestContext.getMatchedAPI().getSecuritySchemeDefinitions(); // API key headers are considered to be protected headers, such that the header would not be sent // to backend and traffic manager. // This would prevent leaking credentials, even if user is invoking unsecured resource with some // credentials. for (Map.Entry entry : securitySchemeDefinitions.entrySet()) { SecuritySchemaConfig schema = entry.getValue(); if (APIConstants.SWAGGER_API_KEY_AUTH_TYPE_NAME.equalsIgnoreCase(schema.getType())) { if (APIConstants.SWAGGER_API_KEY_IN_HEADER.equals(schema.getIn())) { String header = StringUtils.lowerCase(schema.getName()); requestContext.getProtectedHeaders().add(header); requestContext.getRemoveHeaders().add(header); continue; } if (APIConstants.SWAGGER_API_KEY_IN_QUERY.equals(schema.getIn())) { requestContext.getQueryParamsToRemove().add(schema.getName()); } } } Utils.removeCommonAuthHeaders(requestContext); // Remove mTLS certificate header MutualSSLDto mtlsInfo = ConfigHolder.getInstance().getConfig().getMtlsInfo(); String certificateHeaderName = FilterUtils.getCertificateHeaderName(); if (!mtlsInfo.isEnableOutboundCertificateHeader()) { requestContext.getRemoveHeaders().add(certificateHeaderName); } // mTLS Certificate Header should not be included in the throttle publishing event. requestContext.getProtectedHeaders().add(certificateHeaderName); }",Fix apikey failure when header key is in uppercase and prevent common auth headers reaching websocket backends,https://github.com/wso2/product-microgateway/commit/b0754afcf624ef88eb29daa10889b20887b26e50,,,enforcer-parent/enforcer/src/main/java/org/wso2/choreo/connect/enforcer/api/RestAPI.java,3,java,False,2022-10-03T07:32:33Z "public void markMessagesReadAfter(long timestamp) { this.cleanUpReadMap(timestamp); for (Map.Entry entry : unreadMessagesSentAt.entrySet()) { if (entry.getValue() < timestamp) { messagesReadAt.put(entry.getKey(), entry.getValue()); unreadMessagesSentAt.remove(entry.getKey()); } } }","public void markMessagesReadAfter(long timestamp) { cleanUpReadMap(timestamp); final Iterator> iterator = unreadMessagesSentAt.entrySet().iterator(); while (iterator.hasNext()) { final Map.Entry entry = iterator.next(); if (entry.getValue() < timestamp) { messagesReadAt.put(entry.getKey(), entry.getValue()); iterator.remove(); } } }",[#3835] Fix unread counter crash (#3836),https://github.com/airyhq/airy/commit/4aaf0398819b355c1518b8d39eaec24463eb6a28,,,backend/components/unread-counter/src/main/java/co/airy/core/unread_counter/dto/UnreadCountState.java,3,java,False,2022-10-17T16:15:16Z "void onAssociationPreRemove(Association association) { String deviceProfile = association.getDeviceProfile(); if (deviceProfile != null) { Association otherAssociationWithDeviceProfile = find( getAllAssociations(association.getUserId()), a -> !a.equals(association) && deviceProfile.equals(a.getDeviceProfile())); if (otherAssociationWithDeviceProfile != null) { Slog.i(LOG_TAG, ""Not revoking "" + deviceProfile + "" for "" + association + "" - profile still present in "" + otherAssociationWithDeviceProfile); } else { long identity = Binder.clearCallingIdentity(); try { mRoleManager.removeRoleHolderAsUser( association.getDeviceProfile(), association.getPackageName(), RoleManager.MANAGE_HOLDERS_FLAG_DONT_KILL_APP, UserHandle.of(association.getUserId()), getContext().getMainExecutor(), success -> { if (!success) { Slog.e(LOG_TAG, ""Failed to revoke device profile role "" + association.getDeviceProfile() + "" to "" + association.getPackageName() + "" for user "" + association.getUserId()); } }); } finally { Binder.restoreCallingIdentity(identity); } } } if (association.isNotifyOnDeviceNearby()) { ServiceConnector serviceConnector = mDeviceListenerServiceConnectors.forUser(association.getUserId()) .get(association.getPackageName()); if (serviceConnector != null) { serviceConnector.unbind(); restartBleScan(); } } }","void onAssociationPreRemove(Association association) { if (association.isNotifyOnDeviceNearby()) { ServiceConnector serviceConnector = mDeviceListenerServiceConnectors.forUser(association.getUserId()) .get(association.getPackageName()); if (serviceConnector != null) { serviceConnector.unbind(); } } String deviceProfile = association.getDeviceProfile(); if (deviceProfile != null) { Association otherAssociationWithDeviceProfile = find( getAllAssociations(association.getUserId()), a -> !a.equals(association) && deviceProfile.equals(a.getDeviceProfile())); if (otherAssociationWithDeviceProfile != null) { Slog.i(LOG_TAG, ""Not revoking "" + deviceProfile + "" for "" + association + "" - profile still present in "" + otherAssociationWithDeviceProfile); } else { long identity = Binder.clearCallingIdentity(); try { mRoleManager.removeRoleHolderAsUser( association.getDeviceProfile(), association.getPackageName(), RoleManager.MANAGE_HOLDERS_FLAG_DONT_KILL_APP, UserHandle.of(association.getUserId()), getContext().getMainExecutor(), success -> { if (!success) { Slog.e(LOG_TAG, ""Failed to revoke device profile role "" + association.getDeviceProfile() + "" to "" + association.getPackageName() + "" for user "" + association.getUserId()); } }); } finally { Binder.restoreCallingIdentity(identity); } } } }","Fix system crash when unpair app No need to restartBleScan after each unbind serviceSelector restart ble scan after update the associations Also, move unbind serviceSelector before the permission revoke since permission revoking caused app crashed. Fix: 190506983 Test: Manual test Change-Id: Icc2a19f56295be4000155a4ccd6650a30e7c9b66",https://github.com/PixelExperience/frameworks_base/commit/5f9987a5c0b0e04daeb5cb590655308c0b0b31e1,,,services/companion/java/com/android/server/companion/CompanionDeviceManagerService.java,3,java,False,2021-06-08T17:17:19Z "public void serializeViewNetworkData(@NotNull final FriendlyByteBuf buf, @NotNull final Rank viewerRank) { buf.writeVarInt(ranks.size()); for (Rank rank : ranks.values()) { buf.writeVarInt(rank.getId()); buf.writeUtf(rank.getName()); buf.writeBoolean(rank.isSubscriber()); buf.writeBoolean(rank.isInitial()); buf.writeBoolean(rank.isColonyManager()); buf.writeBoolean(rank.isHostile()); } buf.writeVarInt(viewerRank.getId()); // Owners buf.writeVarInt(players.size()); for (@NotNull final Map.Entry player : players.entrySet()) { PacketUtils.writeUUID(buf, player.getKey()); buf.writeUtf(player.getValue().getName()); buf.writeVarInt(player.getValue().getRank().getId()); } // Permissions buf.writeVarInt(permissionMap.size()); for (@NotNull final Map.Entry entry : permissionMap.entrySet()) { buf.writeVarLong(entry.getKey().getId()); buf.writeVarLong(entry.getValue()); } }","public void serializeViewNetworkData(@NotNull final FriendlyByteBuf buf, @NotNull final Rank viewerRank) { buf.writeVarInt(ranks.size()); for (Rank rank : ranks.values()) { buf.writeVarInt(rank.getId()); buf.writeLong(rank.getPermissions()); buf.writeUtf(rank.getName()); buf.writeBoolean(rank.isSubscriber()); buf.writeBoolean(rank.isInitial()); buf.writeBoolean(rank.isColonyManager()); buf.writeBoolean(rank.isHostile()); } buf.writeVarInt(viewerRank.getId()); // Owners buf.writeVarInt(players.size()); for (@NotNull final Map.Entry player : players.entrySet()) { PacketUtils.writeUUID(buf, player.getKey()); buf.writeUtf(player.getValue().getName()); buf.writeVarInt(player.getValue().getRank().getId()); } }","Fix permission issues (#7972) Ranks are no longer a static map, which was used as a per-colony map thus causing crashes and desyncs. If the last colony loaded had a custom rank, all other colonies would crash out due to not matching permissions for that rank. Permission/Rank seperation is removed, permission flag is now part of the rank instead of an externally synced map, which also auto-corrects bad stored data to default permissions. UI now has non-changeable permission buttons disabled.",https://github.com/ldtteam/minecolonies/commit/b1b86dffe64dd4c0f9d3060769fc418fd5d2869a,,,src/main/java/com/minecolonies/coremod/colony/permissions/Permissions.java,3,java,False,2022-01-23T12:23:45Z "static MagickBooleanType load_tile(Image *image,Image *tile_image, XCFDocInfo *inDocInfo,XCFLayerInfo *inLayerInfo,size_t data_length, ExceptionInfo *exception) { ssize_t y; register ssize_t x; register Quantum *q; ssize_t count; unsigned char *graydata; XCFPixelInfo *xcfdata, *xcfodata; xcfdata=(XCFPixelInfo *) AcquireQuantumMemory(data_length,sizeof(*xcfdata)); if (xcfdata == (XCFPixelInfo *) NULL) ThrowBinaryException(ResourceLimitError,""MemoryAllocationFailed"", image->filename); xcfodata=xcfdata; graydata=(unsigned char *) xcfdata; /* used by gray and indexed */ count=ReadBlob(image,data_length,(unsigned char *) xcfdata); if (count != (ssize_t) data_length) ThrowBinaryException(CorruptImageError,""NotEnoughPixelData"", image->filename); for (y=0; y < (ssize_t) tile_image->rows; y++) { q=GetAuthenticPixels(tile_image,0,y,tile_image->columns,1,exception); if (q == (Quantum *) NULL) break; if (inDocInfo->image_type == GIMP_GRAY) { for (x=0; x < (ssize_t) tile_image->columns; x++) { SetPixelGray(tile_image,ScaleCharToQuantum(*graydata),q); SetPixelAlpha(tile_image,ScaleCharToQuantum((unsigned char) inLayerInfo->alpha),q); graydata++; q+=GetPixelChannels(tile_image); } } else if (inDocInfo->image_type == GIMP_RGB) { for (x=0; x < (ssize_t) tile_image->columns; x++) { SetPixelRed(tile_image,ScaleCharToQuantum(xcfdata->red),q); SetPixelGreen(tile_image,ScaleCharToQuantum(xcfdata->green),q); SetPixelBlue(tile_image,ScaleCharToQuantum(xcfdata->blue),q); SetPixelAlpha(tile_image,xcfdata->alpha == 255U ? TransparentAlpha : ScaleCharToQuantum((unsigned char) inLayerInfo->alpha),q); xcfdata++; q+=GetPixelChannels(tile_image); } } if (SyncAuthenticPixels(tile_image,exception) == MagickFalse) break; } xcfodata=(XCFPixelInfo *) RelinquishMagickMemory(xcfodata); return MagickTrue; }","static MagickBooleanType load_tile(Image *image,Image *tile_image, XCFDocInfo *inDocInfo,XCFLayerInfo *inLayerInfo,size_t data_length, ExceptionInfo *exception) { ssize_t y; register ssize_t x; register Quantum *q; ssize_t count; unsigned char *graydata; XCFPixelInfo *xcfdata, *xcfodata; xcfdata=(XCFPixelInfo *) AcquireQuantumMemory(MagickMax(data_length, tile_image->columns*tile_image->rows),sizeof(*xcfdata)); if (xcfdata == (XCFPixelInfo *) NULL) ThrowBinaryException(ResourceLimitError,""MemoryAllocationFailed"", image->filename); xcfodata=xcfdata; graydata=(unsigned char *) xcfdata; /* used by gray and indexed */ count=ReadBlob(image,data_length,(unsigned char *) xcfdata); if (count != (ssize_t) data_length) ThrowBinaryException(CorruptImageError,""NotEnoughPixelData"", image->filename); for (y=0; y < (ssize_t) tile_image->rows; y++) { q=GetAuthenticPixels(tile_image,0,y,tile_image->columns,1,exception); if (q == (Quantum *) NULL) break; if (inDocInfo->image_type == GIMP_GRAY) { for (x=0; x < (ssize_t) tile_image->columns; x++) { SetPixelGray(tile_image,ScaleCharToQuantum(*graydata),q); SetPixelAlpha(tile_image,ScaleCharToQuantum((unsigned char) inLayerInfo->alpha),q); graydata++; q+=GetPixelChannels(tile_image); } } else if (inDocInfo->image_type == GIMP_RGB) { for (x=0; x < (ssize_t) tile_image->columns; x++) { SetPixelRed(tile_image,ScaleCharToQuantum(xcfdata->red),q); SetPixelGreen(tile_image,ScaleCharToQuantum(xcfdata->green),q); SetPixelBlue(tile_image,ScaleCharToQuantum(xcfdata->blue),q); SetPixelAlpha(tile_image,xcfdata->alpha == 255U ? TransparentAlpha : ScaleCharToQuantum((unsigned char) inLayerInfo->alpha),q); xcfdata++; q+=GetPixelChannels(tile_image); } } if (SyncAuthenticPixels(tile_image,exception) == MagickFalse) break; } xcfodata=(XCFPixelInfo *) RelinquishMagickMemory(xcfodata); return MagickTrue; }",https://github.com/ImageMagick/ImageMagick/issues/104,https://github.com/ImageMagick/ImageMagick/commit/a2e1064f288a353bc5fef7f79ccb7683759e775c,,,coders/xcf.c,3,c,False,2016-01-30T14:51:24Z "public void gadgetCall(Object payloadObject) { Logger.printGadgetCallIntro(""Activation""); try { activateCall(prepareCallArguments(payloadObject), false); } catch( java.rmi.ServerException e ) { Throwable cause = ExceptionHandler.getCause(e); if( cause instanceof java.io.InvalidClassException ) { ExceptionHandler.invalidClass(e, ""Activator""); } else if( cause instanceof java.lang.UnsupportedOperationException ) { ExceptionHandler.unsupportedOperationException(e, ""activate""); } else if( cause instanceof java.lang.ClassNotFoundException) { ExceptionHandler.deserializeClassNotFound(e); } else if( cause instanceof java.lang.ClassCastException) { ExceptionHandler.deserlializeClassCast(e, false); } else { ExceptionHandler.unknownDeserializationException(e); } } catch( java.lang.ClassCastException e ) { ExceptionHandler.deserlializeClassCast(e, false); } catch( java.lang.IllegalArgumentException e ) { ExceptionHandler.illegalArgument(e); } catch( java.rmi.NoSuchObjectException e ) { ExceptionHandler.noSuchObjectException(e, ""activator"", false); } catch( Exception e ) { ExceptionHandler.unexpectedException(e, ""activate"", ""call"", false); } }","public void gadgetCall(Object payloadObject) { Logger.printGadgetCallIntro(""Activation""); try { activateCall(prepareCallArguments(payloadObject), false); } catch( Exception e ) { ExceptionHandler.handleGadgetCallException(e, RMIComponent.ACTIVATOR, ""activate""); } }","Unifi exception handling remote-method-guesser allows Codebase and GadgetCall attacks on different RMI components. The attack structure stays basically the same for each different component and the possible exceptions are quite similar. So far, remote-method-guesser used explicit exception handling for each component. This was now replaced with a unified exception handling method that is called by each component.",https://github.com/qtc-de/remote-method-guesser/commit/8cc33c2518bd71562d223130fdff0ec3bb000e73,,,src/de/qtc/rmg/operations/ActivationClient.java,3,java,False,2021-10-24T16:15:06Z "protected Optional> getCommand(GHEventPayload.IssueComment issueCommentPayload) { String body = issueCommentPayload.getComment().getBody(); if (body == null || body.isBlank()) { return Optional.empty(); } Optional firstLineOptional = body.trim().lines().findFirst(); if (firstLineOptional.isEmpty() || firstLineOptional.get().isBlank()) { return Optional.empty(); } String firstLine = firstLineOptional.get().trim(); List commandLine = Commandline.translateCommandline(firstLine); String cliName = commandLine.remove(0); if (!matches(cliName)) { return Optional.empty(); } ParseResult parseResult = cli.parseWithResult(commandLine); if (parseResult.wasSuccessful()) { String commandClassName = parseResult.getState().getCommand().getType().getName(); CommandConfig commandConfig = commandConfigs.getOrDefault(commandClassName, cliConfig.getDefaultCommandConfig()); if (!commandConfig.getScope().isInScope(issueCommentPayload.getIssue().isPullRequest())) { return Optional.empty(); } CommandPermissionConfig commandPermissionConfig = commandPermissionConfigs.getOrDefault(commandClassName, cliConfig.getDefaultCommandPermissionConfig()); CommandTeamConfig commandTeamConfig = commandTeamConfigs.getOrDefault(commandClassName, cliConfig.getDefaultCommandTeamConfig()); if (!hasPermission(commandPermissionConfig, commandTeamConfig, issueCommentPayload.getRepository(), issueCommentPayload.getSender())) { if (commandConfig.getReactionStrategy().reactionOnError()) { Reactions.createReaction(issueCommentPayload, ReactionContent.MINUS_ONE); } return Optional.empty(); } GHReaction ackReaction; if (commandConfig.getReactionStrategy().reactionOnProgress()) { ackReaction = Reactions.createReaction(issueCommentPayload, ReactionContent.ROCKET); } else { ackReaction = null; } return Optional.of(new CommandExecutionContext<>(firstLine, parseResult.getCommand(), commandConfig, ackReaction)); } CommandConfig bestCommandConfig = getBestCommandConfigInErrorState(parseResult); if (bestCommandConfig.getReactionStrategy().reactionOnError()) { Reactions.createReaction(issueCommentPayload, ReactionContent.CONFUSED); } handleParseError(issueCommentPayload, firstLine, commandLine, parseResult); return Optional.empty(); }","protected Optional> getCommand(GHEventPayload.IssueComment issueCommentPayload) { String body = issueCommentPayload.getComment().getBody(); if (body == null || body.isBlank()) { return Optional.empty(); } Optional firstLineOptional = body.trim().lines().findFirst(); if (firstLineOptional.isEmpty() || firstLineOptional.get().isBlank()) { return Optional.empty(); } String firstLine = firstLineOptional.get().trim(); String cliName = firstLine.split("" "", 2)[0]; if (!matches(cliName)) { return Optional.empty(); } List commandLine; try { commandLine = Commandline.translateCommandline(firstLine); commandLine.remove(0); } catch (IllegalArgumentException e) { handleParseError(issueCommentPayload, firstLine, null, e.getMessage()); if (cliConfig.getDefaultCommandConfig().getReactionStrategy().reactionOnError()) { Reactions.createReaction(issueCommentPayload, ReactionContent.CONFUSED); } return Optional.empty(); } ParseResult parseResult = cli.parseWithResult(commandLine); if (parseResult.wasSuccessful()) { String commandClassName = parseResult.getState().getCommand().getType().getName(); CommandConfig commandConfig = commandConfigs.getOrDefault(commandClassName, cliConfig.getDefaultCommandConfig()); if (!commandConfig.getScope().isInScope(issueCommentPayload.getIssue().isPullRequest())) { return Optional.empty(); } CommandPermissionConfig commandPermissionConfig = commandPermissionConfigs.getOrDefault(commandClassName, cliConfig.getDefaultCommandPermissionConfig()); CommandTeamConfig commandTeamConfig = commandTeamConfigs.getOrDefault(commandClassName, cliConfig.getDefaultCommandTeamConfig()); if (!hasPermission(commandPermissionConfig, commandTeamConfig, issueCommentPayload.getRepository(), issueCommentPayload.getSender())) { if (commandConfig.getReactionStrategy().reactionOnError()) { Reactions.createReaction(issueCommentPayload, ReactionContent.MINUS_ONE); } return Optional.empty(); } GHReaction ackReaction; if (commandConfig.getReactionStrategy().reactionOnProgress()) { ackReaction = Reactions.createReaction(issueCommentPayload, ReactionContent.ROCKET); } else { ackReaction = null; } return Optional.of(new CommandExecutionContext<>(firstLine, parseResult.getCommand(), commandConfig, ackReaction)); } CommandConfig bestCommandConfig = getBestCommandConfigInErrorState(parseResult); if (bestCommandConfig.getReactionStrategy().reactionOnError()) { Reactions.createReaction(issueCommentPayload, ReactionContent.CONFUSED); } handleParseError(issueCommentPayload, firstLine, parseResult, null); return Optional.empty(); }","Catch errors from Commandline.translateCommandline() Also prevent an infinite loop and include errors by default.",https://github.com/quarkiverse/quarkus-github-app/commit/249fa8e274f2fe1fca5659ac535da870e70ef7f6,,,command-airline/runtime/src/main/java/io/quarkiverse/githubapp/command/airline/runtime/AbstractCommandDispatcher.java,3,java,False,2022-09-12T15:26:05Z "private void pcapFileResult(final ActivityResult result) { if (result.getResultCode() == RESULT_OK && result.getData() != null) { startWithPcapFile(result.getData().getData()); } else { mPcapUri = null; } }","private void pcapFileResult(final ActivityResult result) { if (result.getResultCode() == RESULT_OK && result.getData() != null) { startWithPcapFile(result.getData().getData(), (result.getData().getFlags() & Intent.FLAG_GRANT_PERSISTABLE_URI_PERMISSION) != 0); } else { mPcapUri = null; } }","Fix SecurityException with PCAP file dump on Android TV When no file manager was available, takePersistableUriPermission was called without an Intent (and the corresponding FLAG_GRANT_PERSISTABLE_URI_PERMISSION flag), causing a SecurityException. Fixes #176",https://github.com/emanuele-f/PCAPdroid/commit/3364a4946ef4a852213271a2a57fdbd8aa57ae1d,,,app/src/main/java/com/emanuelef/remote_capture/activities/MainActivity.java,3,java,False,2022-01-20T23:17:14Z "@Path(""/{group-id}/schemas/{schema-id}"") @DELETE void deleteSchema(@PathParam(""group-id"") String groupId, @PathParam(""schema-id"") String schemaId);","@Path(""/{group-id}/schemas/{schema-id}"") @DELETE @Authorized void deleteSchema(@PathParam(""group-id"") String groupId, @PathParam(""schema-id"") String schemaId);","Implement owner-only authorization support (optional, enabled via appication.properties) (#1407) * trying to implement simple authorization using CDI interceptors * added @Authorized to appropriate methods * updated the auth test * Removed some debugging statements * Improved and applied authn/z to other APIs (v1, cncf, etc) * Fixed some issues with GroupOnly authorization * Disable the IBM API by default due to authorization issues * fix the IBM api test",https://github.com/Apicurio/apicurio-registry/commit/90a856197b104c99032163fa26c04d01465bf487,,,app/src/main/java/io/apicurio/registry/cncf/schemaregistry/SchemagroupsResource.java,3,java,False,2021-04-13T09:08:58Z "@Override public Authentication attemptAuthentication(HttpServletRequest request, HttpServletResponse response) throws AuthenticationException { if (this.postOnly && !request.getMethod().equals(""POST"")) { throw new AuthenticationServiceException( ""Authentication method not supported: "" + request.getMethod()); } if (this.token == null) { return null; } String code = request.getParameter(this.codeParameter); code = (code != null) ? code : """"; code = code.trim(); ExtendedAuthenticationToken authRequest = new ExtendedAuthenticationToken(this.token); authRequest.setCode(code); return this.authenticationManager.authenticate(authRequest); }","@Override public Authentication attemptAuthentication(HttpServletRequest request, HttpServletResponse response) throws AuthenticationException { if (this.postOnly && !request.getMethod().equals(""POST"")) { throw new AuthenticationServiceException( ""Authentication method not supported: "" + request.getMethod()); } Authentication auth = SecurityContextHolder.getContext().getAuthentication(); if (auth == null || !(auth instanceof ExtendedAuthenticationToken)) { throw new AuthenticationServiceException(""Bad authentication""); } String code = request.getParameter(this.codeParameter); code = (code != null) ? code : """"; code = code.trim(); ExtendedAuthenticationToken authRequest = (ExtendedAuthenticationToken) auth; authRequest.setCode(code); return this.getAuthenticationManager().authenticate(authRequest); }","Fixing TOTP verification process Incorrect setting of failure handlers and handling of errors in general meant incorrect TOTPs would cause a crash. Incorrect codes now redirect back to the /verify endpoint in the same way as a failed credential check would redirect back to the /login endpoint",https://github.com/indigo-iam/iam/commit/dc01d78eec671b039faa79f9614d087cfa09b96a,,,iam-login-service/src/main/java/it/infn/mw/iam/authn/multi_factor_authentication/MultiFactorVerificationFilter.java,3,java,False,2022-02-25T18:02:03Z "@Override protected boolean parseCommand(@NotNull String[] args) { // Validating state of sender if (dataHolder == null || permissionHandler == null) { if (!setDefaultWorldHandler(sender)) return true; } // Validating arguments if (args.length != 1) { sender.sendMessage(ChatColor.RED + Messages.getString(""ERROR_REVIEW_ARGUMENTS"") + Messages.getString(""MANGLISTP_SYNTAX"")); //$NON-NLS-1$ //$NON-NLS-2$ return true; } auxGroup = dataHolder.getGroup(args[0]); if (auxGroup == null) { sender.sendMessage(ChatColor.RED + String.format(Messages.getString(""ERROR_GROUP_DOES_NOT_EXIST""), args[0])); //$NON-NLS-1$ return true; } // Validating permission // Seems OK auxString = """"; //$NON-NLS-1$ for (String perm : auxGroup.getPermissionList()) { auxString += perm + "", ""; //$NON-NLS-1$ } if (auxString.lastIndexOf("","") > 0) { //$NON-NLS-1$ auxString = auxString.substring(0, auxString.lastIndexOf("","")); //$NON-NLS-1$ sender.sendMessage(ChatColor.YELLOW + String.format(Messages.getString(""GROUP_HAS_PERMISSIONS""), auxGroup.getName(), ChatColor.WHITE + auxString)); //$NON-NLS-1$ auxString = """"; //$NON-NLS-1$ for (String grp : auxGroup.getInherits()) { auxString += grp + "", ""; //$NON-NLS-1$ } if (auxString.lastIndexOf("","") > 0) { //$NON-NLS-1$ auxString = auxString.substring(0, auxString.lastIndexOf("","")); //$NON-NLS-1$ sender.sendMessage(ChatColor.YELLOW + String.format(Messages.getString(""AND_ALL_PERMISSIONS_GROUPS""), auxString)); //$NON-NLS-1$ } } else { sender.sendMessage(ChatColor.YELLOW + String.format(Messages.getString(""GROUP_NO_SPECIFIC_PERMISSIONS""), auxGroup.getName())); //$NON-NLS-1$ auxString = """"; //$NON-NLS-1$ for (String grp : auxGroup.getInherits()) { auxString += grp + "", ""; //$NON-NLS-1$ } if (auxString.lastIndexOf("","") > 0) { //$NON-NLS-1$ auxString = auxString.substring(0, auxString.lastIndexOf("","")); //$NON-NLS-1$ sender.sendMessage(ChatColor.YELLOW + String.format(Messages.getString(""AND_ALL_PERMISSIONS_GROUPS""), auxString)); //$NON-NLS-1$ } } return true; }","@Override protected boolean parseCommand(@NotNull String[] args) { // Validating state of sender if (dataHolder == null || permissionHandler == null) { if (!setDefaultWorldHandler(sender)) return true; } // Validating arguments if (args.length != 1) { sender.sendMessage(ChatColor.RED + Messages.getString(""ERROR_REVIEW_ARGUMENTS"") + Messages.getString(""MANGLISTP_SYNTAX"")); //$NON-NLS-1$ //$NON-NLS-2$ return true; } auxGroup = dataHolder.getGroup(args[0]); if (auxGroup == null) { sender.sendMessage(ChatColor.RED + String.format(Messages.getString(""ERROR_GROUP_DOES_NOT_EXIST""), args[0])); //$NON-NLS-1$ return true; } // Validating permission // Seems OK auxString = """"; //$NON-NLS-1$ for (String perm : auxGroup.getPermissionList()) { // Prevent over sized strings crashing the parser in BungeeCord if (auxString.length() > 1024) { auxString = auxString.substring(0, auxString.lastIndexOf("","")); //$NON-NLS-1$ sender.sendMessage(ChatColor.YELLOW + String.format(Messages.getString(""GROUP_HAS_PERMISSIONS""), auxGroup.getName(), ChatColor.WHITE + auxString)); //$NON-NLS-1$ auxString = """"; //$NON-NLS-1$ } auxString += perm + "", ""; //$NON-NLS-1$ } if (auxString.lastIndexOf("","") > 0) { //$NON-NLS-1$ auxString = auxString.substring(0, auxString.lastIndexOf("","")); //$NON-NLS-1$ sender.sendMessage(ChatColor.YELLOW + String.format(Messages.getString(""GROUP_HAS_PERMISSIONS""), auxGroup.getName(), ChatColor.WHITE + auxString)); //$NON-NLS-1$ auxString = """"; //$NON-NLS-1$ for (String grp : auxGroup.getInherits()) { auxString += grp + "", ""; //$NON-NLS-1$ } if (auxString.lastIndexOf("","") > 0) { //$NON-NLS-1$ auxString = auxString.substring(0, auxString.lastIndexOf("","")); //$NON-NLS-1$ sender.sendMessage(ChatColor.YELLOW + String.format(Messages.getString(""AND_ALL_PERMISSIONS_GROUPS""), auxString)); //$NON-NLS-1$ } } else { sender.sendMessage(ChatColor.YELLOW + String.format(Messages.getString(""GROUP_NO_SPECIFIC_PERMISSIONS""), auxGroup.getName())); //$NON-NLS-1$ auxString = """"; //$NON-NLS-1$ for (String grp : auxGroup.getInherits()) { auxString += grp + "", ""; //$NON-NLS-1$ } if (auxString.lastIndexOf("","") > 0) { //$NON-NLS-1$ auxString = auxString.substring(0, auxString.lastIndexOf("","")); //$NON-NLS-1$ sender.sendMessage(ChatColor.YELLOW + String.format(Messages.getString(""AND_ALL_PERMISSIONS_GROUPS""), auxString)); //$NON-NLS-1$ } } return true; }",Prevent over-sized strings crashing the parser in BungeeCord.,https://github.com/ElgarL/GroupManager/commit/496a9edd1aa302787ae544c3c0bc9b33a69a9fd7,,,src/org/anjocaido/groupmanager/commands/ManGListP.java,3,java,False,2021-03-09T23:43:52Z "private static void addPathsForEntity(OADoc document, int level, Map paths, String base, EntityType entityType, GeneratorContext options) { if (options.isAddEntityProperties()) { addPathsForEntityProperties(entityType, paths, base, options); } for (NavigationProperty navProp : entityType.getNavigationSets()) { if (level < options.getRecurse()) { addPathsForSet(document, level + 1, paths, base, navProp.getEntityType(), options); } } for (NavigationProperty navProp : entityType.getNavigationEntities()) { if (level < options.getRecurse()) { EntityType type = navProp.getEntityType(); String baseName = base + ""/"" + type.entityName; OAPath paPath = createPathForEntity(options, baseName, type); paths.put(baseName, paPath); addPathsForEntity(document, level, paths, baseName, type, options); } } }","private static void addPathsForEntity(OADoc document, int level, Map paths, String base, EntityType entityType, GeneratorContext options) { if (options.isAddEntityProperties()) { addPathsForEntityProperties(entityType, paths, base, options); } for (NavigationProperty navProp : entityType.getNavigationSets()) { if (level < options.getRecurse()) { addPathsForSet(document, level + 1, paths, base, navProp.getEntityType(), options); } } for (NavigationProperty navProp : entityType.getNavigationEntities()) { if (level < options.getRecurse()) { EntityType type = navProp.getEntityType(); String baseName = base + ""/"" + type.entityName; OAPath paPath = createPathForEntity(options, baseName, type); paths.put(baseName, paPath); addPathsForEntity(document, level + 1, paths, baseName, type, options); } } }",Fixed StackOverflow in OpenAPI generator on 1-1 relations,https://github.com/FraunhoferIOSB/FROST-Server/commit/aad771c50a83d587e658a19fe9dc0b88389753c4,,,Plugins/OpenApi/src/main/java/de/fraunhofer/iosb/ilt/frostserver/plugin/openapi/spec/OpenApiGenerator.java,3,java,False,2022-06-13T13:18:19Z "private boolean warWeary(EmpireView v) { if (v.embassy().finalWar()) return false; //ail: when we have incoming transports, we don't want them to perish for(Transport trans:empire.transports()) { if(trans.destination().empire() == v.empire()) return false; } if(!empire.inShipRange(v.empId())) { //System.out.println(galaxy().currentTurn()+"" ""+empire.name()+"" is war-weary because ""+v.empire().name()+"" is not in range.""); return true; } //ail: no war-weariness in always-war-mode if(galaxy().options().baseAIRelationsAdj() <= -30) return false; //ail: If we are not fighting our preferred target, we don't really want a war if(v.empire() != empire.generalAI().bestVictim()) return true; //ail: only colonies and factories relevant for war-weariness. Population and Military are merely tools to achieve our goals TreatyWar treaty = (TreatyWar) v.embassy().treaty(); //ail: If I have more than one war, I'd like to get rid of the older wars. if(empire.warEnemies().size() > 1) { float newestWarDate = 0; for(Empire warEnemy : empire.warEnemies()) { EmpireView warView = empire.viewForEmpire(warEnemy); //ail need to differentiate with final war as that one cannot be cast if(warView.embassy().treaty().isWar()) { TreatyWar war = (TreatyWar)warView.embassy().treaty(); if(war.date() > newestWarDate) newestWarDate = war.date(); } } if(treaty.date() < newestWarDate) return true; } return false; }","private boolean warWeary(EmpireView v) { if (v.embassy().finalWar()) return false; //ail: when we have incoming transports, we don't want them to perish for(Transport trans:empire.transports()) { if(trans.destination().empire() == v.empire()) return false; } if(!empire.inShipRange(v.empId())) { //System.out.println(galaxy().currentTurn()+"" ""+empire.name()+"" is war-weary because ""+v.empire().name()+"" is not in range.""); return true; } //ail: no war-weariness in always-war-mode if(galaxy().options().baseAIRelationsAdj() <= -30) return false; //ail: If we are not fighting our preferred target, we don't really want a war if(v.empire() != empire.generalAI().bestVictim()) return true; //ail: only colonies and factories relevant for war-weariness. Population and Military are merely tools to achieve our goals TreatyWar treaty = (TreatyWar) v.embassy().treaty(); //ail: If I have more than one war, I'd like to get rid of the older wars. if(empire.warEnemies().size() > 1) { float newestWarDate = 0; for(Empire warEnemy : empire.warEnemies()) { EmpireView warView = empire.viewForEmpire(warEnemy); //ail need to differentiate with final war as that one cannot be cast if(warView.embassy().treaty().isWar()) { TreatyWar war = (TreatyWar)warView.embassy().treaty(); if(war.date() > newestWarDate) newestWarDate = war.date(); } } if(treaty.date() < newestWarDate) return true; } boolean everythingUnderSiege = true; for(StarSystem sys : empire.allColonizedSystems()) { if(sys.colony() == null) continue; if(!sys.enemyShipsInOrbit(empire) && sys.colony().currentProductionCapacity() > 0.5) { everythingUnderSiege = false; break; } } if(everythingUnderSiege) return true; return false; }","New algorithm to determine whom to go to war with (#71) * Update AIScientist.java Adjusted values of a bunch of techs. * Update AIShipCaptain.java Fixed accidental removal of range-adjustment in new target-selection-formula and removed unused code. * Update NewShipTemplate.java Allowing missiles to be used again under certain circumstances, taking ECM into account and basing weapon-decision on actual shield-levels rather than best possible. * Update TechMissileWeapon.java Fixed that 2-rack-missiles didn't have +1 speed as they should have according to official strategy-guide. * Update AIScientist.java Tech-Slider-Allocations now depend on racial-bonuses, not leader-personality. * Immersive Xilmi-AI When set to AI: Selectable, the Xilmi AI now goes in immersive-mode, once again making numerous uses of leader-traits. * Update CombatStackColony.java Fixed a bug, that planets without missile-bases always absorbed damage as if they already had a shield-built, even if they had none and even if they were in a nebula. * Tactical combat improvements Can now detect when someone protects another stack with repulsor-beams and retreats, when it cannot counter it with long-range-weapons. Optimal range for firing missiles increased by repulsor-radius so missile-ships won't be affected by the can't counter repulsors-detection. Missiles will now be held back until getting closer to prevent target from dodging them easily. Unused specials like Repulsor will no longer prevent ships from kiting. * Update AIShipCaptain.java Only kite when there's either repulsor-beam or missile-weapons installed on the ship. * Update AIFleetCommander.java Defending is only half as desirable as attacking now. * Immersive Xilmi-AI Lot's of changes for the personality-mode of Xilmi-AI. * Update DiplomaticEmbassy.java Fix for one empire still holding a grudge against the other when signing a peace-treaty. * Update AIShipCaptain.java Somehow the Xilmi-AI must have had conquered a system with a missile-base on it against another type of AI and then crashed at this place, I didn't even think it would get to for a colony. * Update AISpyMaster.java No longer consider computer-advantage for how much to spend into counter-espionage. * Race-fitting-playstyles implemented and leader-specfic-self-restrictions removed. * Update AIGeneral.java Invader-AI back to normal victim-selection. * Update AIGovernor.java Turns out espionage didn't work like I thought it would. So Darlok just building ships and relying on stealing techs was a bad idea. (You can only steal techs below your highest level in any given tree!) * Update AIDiplomat.java Fixed issue where AI wouldn't allow the player to ask for tech-trades and where they would take deals that are horrible for themselves when trading with other AIs. Trades are now usually all done within a 66%-150% tech-cost-range. * Update AIGeneral.java Giving themselves a personality/objective-combination that fits their behavior. * Update AIDiplomat.java Tech exchange only will work within same tier now. * Update AIGeneral.java Removed setting of personalities as this causes issue with missing texts. * Update AIScientist.java Fixed issue for Silicoids trading for Eco-restoration-techs. * Update ColonyDefense.java * Update ColonyDefense.java Shield will now only be built automatically under the following circumstances: There's missile-bases existing There's missile-bases needing to be upgraded There's missile-bases to be built * Update AIDiplomat.java Avoid false positives in war-declaration for incoming fleets when the system in question was only recently colonized. * Update AIShipCaptain.java Fixed a rare but not impossible crash. * Update AIDiplomat.java No longer accept joint-war-proposals from empires we like less than who they propose as victim. * Update AIGovernor.java Now building missile-bases... under very specific and rare circumstances. * Update AIShipCaptain.java Fixed crash when handling missile-bases. Individual stacks that can't find a target to attack no longer automatically retreat and instead let their behavior be governed by whether the whole fleet would want to retreat. * Update ColonyDefense.java Reverted previous changes which also happened to prevent AI from building shields. * Update CombatStackShip.java Fixed issue where multi-shot-weapons weren't reported as used when they were used. * Update AIFleetCommander.java Fleets now are split depending on their warp-speed unless they are on the way to their final-attack-target. * Update AIDiplomat.java Knowing about uncolonized systems no longer prevents wars. * Update CombatStackShip.java Revert change to shipComponentIsUsed * Update AIShipCaptain.java Moved logic that detects if a weapon has been used to this file. * Update AIScientist.java Try to avoid researching techs we know our neighbors already have since we can trade for it or steal it. * Update AIFleetCommander.java Colony ships now only ignore distance if they are huge as otherwise ignoring distance was horrible in late-game with hyperspace-communications. Keeping scout-designs around for longer. * Fixed a very annoying issue that caused eco-spending to become... insufficient and thus people to die when adjusting espionage- or security-spending. * Reserve-management-improvements Rich and Ultra-Rich planets now put their production into reserve when they would otherwise conduct research. Reserve will now try to keep an emergency-reserve for dealing with events like Supernova. Exceeding twice the amount of that reserve will always be spent so the money doesn't just lie around unused, when there's no new colonies that still need industry. * Update AIShipCaptain.java Removed an unneccessary white line 8[ * Update AIFleetCommander.java Reversed keeping scouts for longer * Update AIGovernor.java no industry, when under siege * Update AIGovernor.java Small fixed to sieged colonies building industry when they shouldn't. * Update Rotp.java Versioning 0.93a * Update RacesUI.java Race-selector no longer jumps after selecting a race. Race-selector scroll-speed when dragging is no longer amplified like the scroll-bar but instead moves 1:1 the distance dragged. * Update AIFleetCommander.java Smart-Path will no longer path over systems further away than the target-system. Fleets will now always be split by speed if more than 2/3rd of the fleet have the fastest speed possible. * Update AIGovernor.java Build more fleet when fighting someone who has no or extremely little fleet. * Update AIShipCaptain.java Kiting no longer uses path-finding during auto-resolve. Ships with repulsor and long-range will no longer get closer than 2 tiles before firing against ships that don't have long range. Will only retreat to system with enemy fleets when there's no system without enemy fleets to retreat to. * Update CombatStackColony.java Added override for optimal firing-range for missile-bases. It is 9. * Update CombatStackShip.java Optimal firing-range for ship-stacks with missiles will now be at least two when they have repulsors. * Update NewShipTemplate.java The willingness of the AI to use repulsor-beam now scales with how many opponent ships have long range. It will be higher if there's only a few but drop down to 0 if all opponent ships use them. * Update AI.java Improved logic for shuttling around population within the empire. * Update ShipBattleUI.java Fixed a bug where remaining commands were transferred from one stack to another, which could also cause a crash when missile-bases were involved. * Update Colony.java currentProductionCapacity now correctly takes into consideration how many factories are actually operated. * Update NewShipTemplate.java Fixes and improvements to special-selection. Mainly bigger emphasis on using cloaking-device and stasis-field. * Update AIShipDesigner.java Consider getting an important special like cloaking, stasis or black-hole-generator as reason to immediately make a new design. * Update SystemView.java Systems with enemy-fleets will now flash the Alert. Especially usefull when under siege by cloaked enemy fleets. * Update AIShipCaptain.java Added check whether retreat was possible when retreating for the reason that nothing can be done. * Update AIGovernor.java Taking natural pop-growth and the cost of terraforming into account when deciding to build factories or population. This usually results to prefering factories almost always when they can be operated. * War- and Peace-making changes. Prevent war-declaration when there's barely any fleet to attack with. Smarter selection of preferred victim. In particular taking their diplomatic status with others into account. Toned down overall aggressiveness. Several personalities now are taken into account for determining behavior. * Update General.java Don't attack too early. * Update AIFleetCommander.java Colony ships will now always prefer undefended targets instead of waiting for help if they want to colonize a defended system. * Update Rotp.java Version 0.93b * Update NewShipTemplate.java Not needing ranged weapon, when we have cloaking-device. * Improved behavior when using missiles to act according to expectations of /u/bot39lvl * Showing pop-growth at clean-eco. * New Version with u/bot39lvl recommended changes to missile-boat-handling * Fixed issue that caused ships being scrapped after loading a game, no longer taking incoming enemy fleets into consideration that are more than one turn away from reaching their target. * Stacks that want to retreat will now also try and damage their target if it is more than one space away as long as they don't use up all movement-points. Planets with no missile-bases will not become a target unless all non-bomb-weapons were used. * Fixed an issue where a new design would override a similar existing one. * When defending or when having better movement-speed now shall always try to get the 1st strike. * Not keeping a defensive fleet on duty when the incoming opponent attack will overwhelm them anyways. * Using more unique ship-names * Avoid ship-information being cut off by drawing ship-button-overlay into the upper direction as soon as a stack is below the middle of the screen. * Fixed exploit that allowed player to ignore enemy repulsor-beams via auto-resolve. * Fixed issue that caused missile-ships to sometimes retreat when they shouldn't. * Calling beam/missileDefense() method instead of looking at the member since the function also takes stealth into account which we want to do for better decision-making. * Ships with limited shot-weapons no longer think they can land all hits at once. * Best tech of each type no longer gets it's research-value reduced. * Halfed inertial-value again as it otherwise may suppress vital range-tech. * Prevent overbuilding colony-ships in lategame by taking into consideration when systems can build more than one per turn. * Design-names now use name of a system that is actually owned and add a number to make sure they are unique. * Fixed some issues with no longer firing before retreating after rework and now ignoring stacks in stasis for whether to retreat or not. * Evenly distributing population across the empire led to an increase of almost 30% productivity at a reference turn in tests and thus turned out to be a much better population-distribution-strategy when compared to the ""bring new colonies to 25%""-rule-of-thumb as suggested in the official-strategy-guide. * Last defending stacks in stasis are now also made to autoretreat as otherwise this would result in 100 turns of ""you can't do anything but watch"". * Avoid having more than two designs with Stasis-Field as it doesn't stack. * Should fix an issue that caused usage of Hyper-Space-Communications to be inefficient. * Futher optimization on population-shuttling. * Fixed possible crash from trying to make peace while being involved in a final war. * Fixed infinite loop when trying to scrap the last existing design. * Making much better use of natural growth. * Some further slight adjustments to economy-handling that lead to an even better result in my test. * Fix for ""Hyperspace Communications: can't reroute back to the starting planet - bug"" by setting system to null, when leaving the orbit. In this vein no longer check for a stargate-connection when a fleet isn't at a system anymore. * Only the victor and the owner of the colony fought over get a scan on the system. Not all participants. Especially not someone who fled from the orion-guardian and wanted to exploit this bug to get free high-end-techs! * Prepare next version number since Ray hasn't commited anything yet since the beginning of June. :( * Presumably a better fix to the issue of carrying over button-presses to the next stack. But I don't have a good save to test it. * Fixed that for certain techs the inherited baseValue method either had no override or the override did not reference to the corresponding AI-method. * Reverted fix for redirecting ships with hyperspace-communications to their source-system because it could crash the game when trying to redirect ships using rally-points. * Using same ship-design-naming-pattern for all types of ships so player can't idintify colony-ships by looking at the name. * Added missing override for baseValue from AI. * Made separate method for upgradeCost so it can be used from outside, like AI for example. * Fixed an issue where ships wouldn't retreat when they couldn't path to their preferred target. * Changed how much the AI values certain technologies. Most notably will it like warp-speed-improvements more. * Introduced an algorithm that guesses how long it will take to kill another empire and how long it would take the other empire to kill ourselves. This is used in target-selection and also in order to decide on whether we should go all in with our military. If we think the other empire can kill us more quickly than what it takes to benefit from investments into economy, we go all-in with building military. * Fixed an issue that prevented ships being sent back to where they came from while in space via using hyperspace-communications. Note: The intention of that code is already handled by the ""CanSendTo""-check just above of it. At this place the differientiation between beeing in transit is made, so that code was redundant for it's intended use-case. * Production- and reseach-modifier now considered in decision to build ships non-stop or not. Fixed bug that caused AI-colonies to not build ships when they should. Consider incoming transports in decision whether to build population or not. * Big revamp of dimplomatic AI-behavior. AI should now make much more sophisticated decisions about when to go to war. * No longer bolstering population of low-pop-systems during war as this is pretty exploitable and detracts from producting military. * Version * Fixed a weird issue that prevented AIs from bombarding each other unless the player had knowledge about who the owner of the system to be bombarded is. * Less willing to go to war, when there's other ways to expand. * Fixed issue with colonizers and hyper-space-communications, that I thought I had fixed before. When there's other possible targets to attack, a fleet waiting for invasion-forces, that can glass the system it is orbiting will split up and continue its attack. * Only building excess colonizers, when someone we know (including ourselves) is at war and there's potential to colonize systems that are freed up by that war. * At 72% and higher population a system wanting to build a colonizer will go all-in on it. This mostly affects Sakkra and Meklar, so they expand quicker and make more use of fast pop-growth. * Fixed extremely rare crash. * 0.93g * Guessing travel-time and impact of nebulae instead of actually calculating the correct travel-times including nebulae to improve turn-times. * No longer using bestVictim in ship-Design-Code. * Lower limit from transport-size removed. * Yet another big revamp about when to go to war. It's much more simple now. * Transports sent towards someone who we don't want to have a war with now will be set to surrender on arrival. Travel-distance-calculation simplified in favor of turn-processing. Fixed dysfunctional defense-code that was recently broken. * Pop-growth now plays a role in invasion-decisionmaking. Invasions now can occur without a fleet in orbit. Code for estimating kill-time now takes invasions into account. Drastically simplified victim-selection. * Due to the changes in how the AI handles it's fleets during the wait time for invasions the amount of bombers built was increased. * Changed how it is determined whether to retreat against fleets with repulsors. Fixed issue with not firing missiles under certain circumstances. Stacks of smaller ships fighting against stacks of bigger ships are now more likely to retreat, when they can't kill at least one of the bigger ships per turn. * Moved accidental-stargate-building-prevention-workaround to where it actually is effective. * Fixed an issue where a combat would end prematurely when missiles were fired but still on their way to their target. * Removed commented-out code * Removed actual war-weariness from the reasons to make peace as there's now other and better reasons to make peace. * Bombers are now more specialized as in better at bombing and worse at actual combat. * Bomb-Percentage now considers all opponents, not just the current enemy. * The usage of designs is now recognized by their loadout and not by what role it was assigned to it during design. * No longer super-heavy commitment to ship-production in war. Support of hybrid-playstyle. * Fixed issue that sometimes prevented shooting missiles. * Lowered counter-espionage by no longer looking at average tech-level of opponents but instead at tech-level of highest opponent. * Support for hybrid ship-designs and many tweaks- and fixes in scrapping-logic. * Setting eco-slider with a popup that promts for a percentage now uses the percentage of the amount that isn't required to keep clean. * Fixed previously integrated potential dead-lock. * Indentation * Fix for becoming enemy of others before they are in range in the always-war-mode. * Version-number for next inofficial build. * No security-spending when no contact. But luckily that actually makes no difference between it only actually gets detracted from income when there's contacts. * Revert ""Setting eco-slider with a popup that promts for a percentage now uses the percentage of the amount that isn't required to keep clean."" This reverts commit a2fe5dce3c1be344b6c96b6bfa1b5d16b321fafa. * Taught AI to use divert-reserve to research-checkbox * I don't know how it can happen but I've seen rare cases of colonies with negative-population. This is a workaround that changes them back to 1 pop. * Skip AI turn when corresponing empire is dead. * Fixed possible endless-loop from scrapping last existing ship-design. * Fixed issue where AI would build colonizers as bombers after having scrapped their last existing bomber-design. * Removed useless code. * Removed useless code. * Xilmi AI now capable of deciding when to use bio-weapons. * Bioweapon-support * New voting behavior: Xilmi Ai now votes for whoever they are most scared of but aren't at war with. * Fixed for undecisive behavior of launching an assault but retreating until transports arrive because developmentPct is no longer maxxed after sending transports. (War would still get triggered by the invasion but the fleet sent to accompany the invasion would retreat) * No longer escorting colony-ships on their way to presumably undefended systems. Reason: This oftentimes used a good portion of the fleet for no good reason, when they could be better used for attacking/defending. * Requiring closer range to fire missiles. * Lower score for using bio-weapons depending on how many missile-bases are seen. * No longer altering tech-allocations based on war-state. * New, more diverse and supposedly more interesting diplomatic behavior for AI. * Pick weapon to counter best enemy shield in use rather than average to avoid situations where lasers or scatterpack-V are countered too hard. Also: Make sure that there is a design with the most current bomb before considering bio-weapons. * Weapons that allow heavy-mounts don't get their value decreased so AI doesn't end up without decent repulsor-counter. * Moved negative-population workaround to a place where it is actually called. * Smarter decision-making about when to bomb or not to bomb during on-going invasions. * Incoming invasions of oneself should be slightly better covered but without tying too much of the fleet to it. * Choose target by distance from fleet. * Giving more cover to incoming invasions. * Made rank-check-functions available outside of diplomat too. * Always abstain if not both candidates are known. Superpowers should avoid wars. * Fixed an issue where defenders wouldn't always stay back when they should. * Don't hold back full power when in war anymore. * Quality of ships now more important for scrapping than before. * Reversed prior change in retreat-logic for smaller ships: Yes, the enemy could retreat but control over the system is probably more important than preserving some ships. * Fixed issue where AI would retreat from repulsors when they had missiles. * Minimum speed-requirement for missiles now takes repulsor-beams and diagonals into account. * AI will prepare their wars a little better and also take having to prepare into account before invadion. * No longer voting until both candidates are met. AI now knows much better to capitalize on an advantage and actually win the game instead of throwing it in a risky way. * Moved a debug-output to another place. * 0.93l * Better preparations before going to war. Removed alliances again. * Pick war-target by population-center rather than potential population center. * Fixed a bunch of issued leading to bad colony-ship-management in the lategame. * The better an AI is doing, the more careful they are about how to pick their enemies. * Increased minimum ship-maintenance-threshold for the early-game. * New version * Forgot to remove a debug-message. * Fixed issue reported by u/Individual_Act289: Transports launched before final war disappear on arrival. * Fixed logical error in maxFiringRange-method which could cause unwanted retreats. * When at war, AI will not make so many colony-ships, fixed issue where invasions wouldn't happen against partially built missile-bases, build more bombers when there's a high military-superiority * Willingness to defend now scales with defense-ratio. * Holding back before going to war as long as techs can still be easily researched. * AI will get a bit more tech when it's opportune instead of going for war. * Smart path will avoid paths where the detour would be longer than 50%, fleets that would otherwise go to a staging-point while they are orbiting an enemy will instead stay in orbit of the enemy. * Yet unused methor determining the required count of fighters to shoo scouts away. * Techs that are more than 5 levels behind the average will now be researched even if they are low priority. * Handling for enemy missile-frigates. * No longer scrap ships while at war. * Shields are seen as more useful, new way of determining what size ships should be. * enemyTransportsInTransit now also returns transports of neutral/cold-war-opponents * Created separate method unfriendlyTransportsInTransit * Improved algorithm to determine ship-design-size, reduction in score for hybrids without bombs * Run from missile code should no longer try to outrun missiles that are too close already * New method for unfriendlyTransportsInTransit used * Taught AI to protect their systems against scouting * Taught AI to protect their systems against scouting * Fixed issue that prevented scouts from being sent to long-range-targets when they were part of a fleet with other ships. * Xilmi-AI now declaring war at any poploss, not just at 30+ * Sanity check for fleeing from missiles: Only do it when something could actually be lost. * Prepare better for potential attacks. * Some code cleanup * Fixed issue where other ships than destroyers could be built as scout-repellers. * Avoid downsizing of weapons in non-destroyer-ships. * Distances need to be recalculated immediately after obtaining new system as otherwise AI would act on outdated information. In this case it led to the AI offering peace due to losing range on an opponent whos colony it just conquered despite that act bringing lots of new systems into range. * Fixed an issue where AI would consider an opponents contacts instead of their own when determining the opponents relative standing. Also no longer looking at empires outside of ship-range for potential wars. * Priority for my purpose needs to be above 1000 and below 1400. Below 1000 it gets into conflict with scouts and above 1400 it will rush out the ships under all circumstances. * The widespread usage of scout-repellers makes adding a weapon to a colony-ship much more important. * Added missing override for maxFiringRange * Fixed that after capturing a colony the default for max-bases was not used from the settings of the new owner. * Default for bases on new systems and whether excess-spending goes to research can now be changed in Remnants.cfg * Fixed issue that allowed ship-designs without weapons to be considered the best design. * Fixed a rare crash I had never seen before and can't really explain. * Now taking into account if a weapon would cause a lot of overkill and reduce it's score if it is the case. Most likely will only affect Death-Ray and maybe Mauler-Device. * Fixed an issue with negative-fleets and error-messages. Fixed an issue where systems of empires without income wouldn't be attacked when they had stealth-ships or were out of sensor-range. * Improved detection on whether scout-repellers are needed. Also forbid scout-repellers when unlimited range is available. * Removed code that would consistently scrap unused designs, which sometimes had unintended side-effects when building bigger ships. Replaced what it was meant for by something vastly better: A design-rotation that happens based on how much the design contributes to the maintenance-cost. When there's 4 available slots for combat-designs and one design takes up more than 1/3rd of the maintenance, a new design is enforced, even if it is the same as before. * Fixed issue where ships wouldn't shoot at nearby targets when they couldn't reach their preferred target. Rewrote combat-outcome-expectation to much better guess the expected outcome, which now also consideres auto-repair. * New algorithm to determine who is the best target for a war. * New algorithm to determine the ratio of bombers vs. fighters respectively bombs vs. anti-ship-weapons on a hybrid. * Fixed issue where huge colonizers wouldn't be built when Orion was reachable. * The slots for scouts and scout-repellers are no longer used during wars. * Improved strategic target-selection to better take ship-roles into account. * Fixed issue in bcValue not recognizing scouts of non-AI-player * Fixed several issues with design-scoring. (possible zero-division and using size instead of space) * Much more dedicated and better adapted defending-techniques. * Improved estimate on how many troops need to stay back in order to shoot down transports.",https://github.com/rayfowler/rotp-public/commit/2ec066ab66098db56a37be9f35ccf980ce38866b,,,src/rotp/model/ai/xilmi/AIDiplomat.java,3,java,False,2021-10-12T17:22:38Z "public static boolean hasPermission(Context context, String permission) { return context.checkCallingOrSelfPermission(permission) == PERMISSION_GRANTED; }","public static boolean hasPermission(Context context, String permission) { return hasPermission(context, permission, 0); }","in order to address the issue with crashing permission check I introduced another hasPermission api that can repeat the call in case an exception has been thrown while checking the permission (#749) Co-authored-by: Sergii Kozyrev ",https://github.com/segmentio/analytics-android/commit/86086cf3d34f5fd4570a1a2da63187ee818b4c34,,,analytics/src/main/java/com/segment/analytics/internal/Utils.java,3,java,False,2021-03-12T22:02:45Z "function prepareMessagePayload(modules, messagePayload) { var crypto = modules.crypto, config = modules.config; var stringifiedPayload = JSON.stringify(messagePayload); if (config.cipherKey) { stringifiedPayload = crypto.encrypt(stringifiedPayload); stringifiedPayload = JSON.stringify(stringifiedPayload); } return stringifiedPayload; }","function prepareMessagePayload(modules, messagePayload) { var stringifiedPayload = JSON.stringify(messagePayload); if (modules.cryptoModule) { var encrypted = modules.cryptoModule.encrypt(stringifiedPayload); stringifiedPayload = typeof encrypted === 'string' ? encrypted : (0, base64_codec_1.encode)(encrypted); stringifiedPayload = JSON.stringify(stringifiedPayload); } return stringifiedPayload || ''; }","feat/CryptoModule (#339) * ref: decoupling cryptor module * cryptoModule * lint * rever cryptors in config * lint fixes * CryptoModule for web and node * step definitions for contract tests * lib files * fix:es-lint * let vs const * and some more ts not wanting me to specific about trivials * access modfiers * refactor-1 * lint, cleanup test * refactor - 2 * code cleanup in stream encryption with new cryptor * fix: lint issue. * refactor: eliminate ts-ignores by defining file reated types * * integration of crypto module * refactoring cryptoModule * lib and dist * support for setCipherKey * fix: setCipherKey() * lib and dist files * fix: staticIV support * lib and dist * refactor: cryptoModule, * added support for PubNub.CryptoModule factory * fix: types * dist and libs * fix: test- customEncrypt function * fix: legacy crypto init, tests * refactor: typecheck on incoming data for aescbc cryptor * code cleanup, * fix: broken file cryptography operations on web * lib and dist directories * refactor: crypto initialiser apis default value initialisation * LICENSE * reverted last commit 11351ec * update LICENSE * PubNub SDK v7.4.0 release. --------- Co-authored-by: PubNub Release Bot <120067856+pubnub-release-bot@users.noreply.github.com>",https://github.com/pubnub/javascript/commit/fb6cd0417cbb4ba87ea2d5d86a9c94774447e119,CVE-2023-26154,['CWE-331'],lib/core/endpoints/publish.js,3,js,False,2023-10-16T11:14:10Z "@Override public void onHelp(@Modality int modality, String help) { mBiometricView.onHelp(modality, help); }","@Override public void onHelp(@Modality int modality, String help) { if (mBiometricView != null) { mBiometricView.onHelp(modality, help); } else { Log.e(TAG, ""onHelp(): mBiometricView is null""); } }","Fix NPEs in AuthContainerView Bug: 243493226 Test: N/A Change-Id: Ia3a677302ec3a270d421f44e746c12a701eb41a6",https://github.com/LineageOS/android_frameworks_base/commit/852108800780fac2edfcaaa1285c17a99c79eea1,,,packages/SystemUI/src/com/android/systemui/biometrics/AuthContainerView.java,3,java,False,2022-08-30T19:55:38Z "@Override public void complete(ScanRequest request, ScanResults results) throws MachinaException { try { ObjectMapper mapper = new ObjectMapper(); mapper.setSerializationInclusion(JsonInclude.Include.NON_NULL); if(request != null && results != null) { mapper.writeValue(new File(request.getFilename()), results); String resultUrl = request.getAdditionalMetadata(""result_url""); String filename = request.getFilename(); if(ScanUtils.anyEmpty(resultUrl, filename)){ log.error(""result_url | temporary file was massing from the ScanRequest metadata""); throw new MachinaException(); } File resultFile = new File(filename); log.info(""Saving file {} to signed web url"", filename); HttpHeaders headers = new HttpHeaders(); headers.setContentType(MediaType.APPLICATION_JSON); HttpEntity entity = new HttpEntity<>(Files.readAllBytes(Paths.get(resultFile.getCanonicalPath())), headers); URI uri = new URI(resultUrl); restTemplate.put(uri, entity); log.info(""Save successful""); } else { log.error(""No request or results provided""); throw new MachinaException(); } } catch (IOException e) { log.error(""Issue occurred while writing file {}"", request.getFilename(), e); throw new MachinaException(); }catch (URISyntaxException e){ log.error(""Error occurred: {}"", ExceptionUtils.getMessage(e), e); throw new MachinaException(); }catch (HttpClientErrorException e){ log.error(""HttpClientErrorException occurred: {}"", ExceptionUtils.getMessage(e), e); throw new MachinaException(); } }","@Override public void complete(ScanRequest request, ScanResults results) throws MachinaException { try { ObjectMapper mapper = new ObjectMapper(); mapper.setSerializationInclusion(JsonInclude.Include.NON_NULL); if (request != null && results != null) { mapper.writeValue(new File(request.getFilename()).getCanonicalFile(), results); String resultUrl = request.getAdditionalMetadata(""result_url""); String filename = request.getFilename(); if (ScanUtils.anyEmpty(resultUrl, filename)) { log.error(""result_url | temporary file was massing from the ScanRequest metadata""); throw new MachinaException(); } File resultFile = new File(filename); log.info(""Saving file {} to signed web url"", filename); HttpHeaders headers = new HttpHeaders(); headers.setContentType(MediaType.APPLICATION_JSON); HttpEntity entity = new HttpEntity<>(Files.readAllBytes(Paths.get(resultFile.getCanonicalPath())), headers); URI uri = new URI(resultUrl); restTemplate.put(uri, entity); log.info(""Save successful""); } else { log.error(""No request or results provided""); throw new MachinaException(); } } catch (IOException e) { log.error(""Issue occurred while writing file {}"", request.getFilename(), e); throw new MachinaException(); } catch (URISyntaxException e) { log.error(""Error occurred: {}"", ExceptionUtils.getMessage(e), e); throw new MachinaException(); } catch (HttpClientErrorException e) { log.error(""HttpClientErrorException occurred: {}"", ExceptionUtils.getMessage(e), e); throw new MachinaException(); } }","Saras fix vulnerabilities (#738) fix input path not canonicalize vulnerabilities",https://github.com/checkmarx-ltd/cx-flow/commit/60920be1b2764f71fad8dfa5a4940090e2a32c63,,,src/main/java/com/checkmarx/flow/custom/WebPostIssueTracker.java,3,java,False,2021-05-19T06:57:34Z "private void saveFile(ViewEditForm form, byte[] bytes, File dir, String fileName) { Stream.of(SUPPORTED_EXTENSIONS) .filter(fileName::endsWith) .findFirst() .ifPresent(ext -> { // Valid image! Add it to uploads int imageId = getNextImageId(dir); // Get an image id. String filename = imageId + ext; // Create the image file name. File image = new File(dir, filename); if(writeFile(bytes, image)) { // Save the file. form.getView().setBackgroundFilename(uploadDirectory + filename); LOG.info(""Image file has been successfully uploaded: "" + image.getName()); } else { LOG.warn(""Failed to save image file: "" + image.getName()); } }); }","private void saveFile(ViewEditForm form, byte[] bytes, File dir, String fileName) { int imageId = getNextImageId(dir); // Get an image id. String filename = createFileName(imageId, fileName); // Create the image file name. File image = new File(dir, filename); if (writeFile(bytes, image)) { // Save the file. form.getView().setBackgroundFilename(uploadDirectory + filename); LOG.info(""Image file has been successfully uploaded: "" + image.getName()); } else { LOG.warn(""Failed to save image file: "" + image.getName()); } }","#2173 Fixed import project CVE-2021-26828 - added filtering, for graghics only bitmap or info.txt, for uploads bitmap and svg: ZIPProjectManager, ViewEditController; corrected: ViewGraphicLoader; added: UploadFileUtils",https://github.com/SCADA-LTS/Scada-LTS/commit/9dadab1638562102d71ef1e43367c4303124c812,,,src/org/scada_lts/web/mvc/controller/ViewEditController.java,3,java,False,2022-04-13T08:18:24Z "public boolean shouldListenForFace() { if (mFaceManager == null) { // Device does not have face auth return false; } final boolean statusBarShadeLocked = mStatusBarState == StatusBarState.SHADE_LOCKED; final boolean awakeKeyguard = mKeyguardIsVisible && mDeviceInteractive && !mGoingToSleep && !statusBarShadeLocked; final int user = getCurrentUser(); final int strongAuth = mStrongAuthTracker.getStrongAuthForUser(user); final boolean isLockDown = containsFlag(strongAuth, STRONG_AUTH_REQUIRED_AFTER_DPM_LOCK_NOW) || containsFlag(strongAuth, STRONG_AUTH_REQUIRED_AFTER_USER_LOCKDOWN); final boolean isEncryptedOrTimedOut = containsFlag(strongAuth, STRONG_AUTH_REQUIRED_AFTER_BOOT) || containsFlag(strongAuth, STRONG_AUTH_REQUIRED_AFTER_TIMEOUT); boolean canBypass = mKeyguardBypassController != null && mKeyguardBypassController.canBypass(); // There's no reason to ask the HAL for authentication when the user can dismiss the // bouncer, unless we're bypassing and need to auto-dismiss the lock screen even when // TrustAgents or biometrics are keeping the device unlocked. boolean becauseCannotSkipBouncer = !getUserCanSkipBouncer(user) || canBypass; // Scan even when encrypted or timeout to show a preemptive bouncer when bypassing. // Lock-down mode shouldn't scan, since it is more explicit. boolean strongAuthAllowsScanning = (!isEncryptedOrTimedOut || canBypass && !mBouncer); // If the device supports face detection (without authentication), allow it to happen // if the device is in lockdown mode. Otherwise, prevent scanning. boolean supportsDetectOnly = !mFaceSensorProperties.isEmpty() && mFaceSensorProperties.get(0).supportsFaceDetection; if (isLockDown && !supportsDetectOnly) { strongAuthAllowsScanning = false; } // Only listen if this KeyguardUpdateMonitor belongs to the primary user. There is an // instance of KeyguardUpdateMonitor for each user but KeyguardUpdateMonitor is user-aware. final boolean shouldListen = (mBouncer || mAuthInterruptActive || mOccludingAppRequestingFace || awakeKeyguard || shouldListenForFaceAssistant()) && !mSwitchingUser && !isFaceDisabled(user) && becauseCannotSkipBouncer && !mKeyguardGoingAway && mBiometricEnabledForUser.get(user) && !mLockIconPressed && strongAuthAllowsScanning && mIsPrimaryUser && (!mSecureCameraLaunched || mOccludingAppRequestingFace); // Aggregate relevant fields for debug logging. if (DEBUG_FACE || DEBUG_SPEW) { final KeyguardFaceListenModel model = new KeyguardFaceListenModel( System.currentTimeMillis(), user, shouldListen, mBouncer, mAuthInterruptActive, mOccludingAppRequestingFace, awakeKeyguard, shouldListenForFaceAssistant(), mSwitchingUser, isFaceDisabled(user), becauseCannotSkipBouncer, mKeyguardGoingAway, mBiometricEnabledForUser.get(user), mLockIconPressed, strongAuthAllowsScanning, mIsPrimaryUser, mSecureCameraLaunched); maybeLogFaceListenerModelData(model); } return shouldListen; }","public boolean shouldListenForFace() { if (mFaceManager == null) { // Device does not have face auth return false; } final boolean statusBarShadeLocked = mStatusBarState == StatusBarState.SHADE_LOCKED; final boolean awakeKeyguard = mKeyguardIsVisible && mDeviceInteractive && !mGoingToSleep && !statusBarShadeLocked; final int user = getCurrentUser(); final int strongAuth = mStrongAuthTracker.getStrongAuthForUser(user); final boolean isLockDown = containsFlag(strongAuth, STRONG_AUTH_REQUIRED_AFTER_DPM_LOCK_NOW) || containsFlag(strongAuth, STRONG_AUTH_REQUIRED_AFTER_USER_LOCKDOWN); final boolean isEncryptedOrTimedOut = containsFlag(strongAuth, STRONG_AUTH_REQUIRED_AFTER_BOOT) || containsFlag(strongAuth, STRONG_AUTH_REQUIRED_AFTER_TIMEOUT); boolean canBypass = mKeyguardBypassController != null && mKeyguardBypassController.canBypass(); // There's no reason to ask the HAL for authentication when the user can dismiss the // bouncer, unless we're bypassing and need to auto-dismiss the lock screen even when // TrustAgents or biometrics are keeping the device unlocked. boolean becauseCannotSkipBouncer = !getUserCanSkipBouncer(user) || canBypass; // Scan even when encrypted or timeout to show a preemptive bouncer when bypassing. // Lock-down mode shouldn't scan, since it is more explicit. boolean strongAuthAllowsScanning = (!isEncryptedOrTimedOut || canBypass && !mBouncer); // If the device supports face detection (without authentication), allow it to happen // if the device is in lockdown mode. Otherwise, prevent scanning. boolean supportsDetectOnly = !mFaceSensorProperties.isEmpty() && mFaceSensorProperties.get(0).supportsFaceDetection; if (isLockDown && !supportsDetectOnly) { strongAuthAllowsScanning = false; } // If the face has recently been authenticated do not attempt to authenticate again. boolean faceAuthenticated = getIsFaceAuthenticated(); // Only listen if this KeyguardUpdateMonitor belongs to the primary user. There is an // instance of KeyguardUpdateMonitor for each user but KeyguardUpdateMonitor is user-aware. final boolean shouldListen = (mBouncer || mAuthInterruptActive || mOccludingAppRequestingFace || awakeKeyguard || shouldListenForFaceAssistant()) && !mSwitchingUser && !isFaceDisabled(user) && becauseCannotSkipBouncer && !mKeyguardGoingAway && mBiometricEnabledForUser.get(user) && !mLockIconPressed && strongAuthAllowsScanning && mIsPrimaryUser && (!mSecureCameraLaunched || mOccludingAppRequestingFace) && !faceAuthenticated; // Aggregate relevant fields for debug logging. if (DEBUG_FACE || DEBUG_SPEW) { final KeyguardFaceListenModel model = new KeyguardFaceListenModel( System.currentTimeMillis(), user, shouldListen, mBouncer, mAuthInterruptActive, mOccludingAppRequestingFace, awakeKeyguard, shouldListenForFaceAssistant(), mSwitchingUser, isFaceDisabled(user), becauseCannotSkipBouncer, mKeyguardGoingAway, mBiometricEnabledForUser.get(user), mLockIconPressed, strongAuthAllowsScanning, mIsPrimaryUser, mSecureCameraLaunched, faceAuthenticated); maybeLogFaceListenerModelData(model); } return shouldListen; }","Fixed double face auth on swipe Previously, if a face was rejected, and PIN/Pattern/Pass was presented, and the user swiped on to unlock simultaneously, 2x face authentications would be observed. Test: Verified 10/10 times that device no longer performs 2x face authentications in the scenario described above. Fixes: 188598635 Change-Id: I24f964981484cfa19f7e1709f95da485204ff7a9",https://github.com/PixelExperience/frameworks_base/commit/5afa7487dfe14e2272a7cf0f201c4f326dfe435f,,,packages/SystemUI/src/com/android/keyguard/KeyguardUpdateMonitor.java,3,java,False,2021-07-15T18:43:26Z "@Override public void validateReaderContext(ReaderContext readerContext, TransportRequest request) { if (readerContext.scrollContext() != null) { final Authentication originalAuth = readerContext.getFromContext(AuthenticationField.AUTHENTICATION_KEY); final Authentication current = securityContext.getAuthentication(); final ThreadContext threadContext = securityContext.getThreadContext(); final String action = threadContext.getTransient(ORIGINATING_ACTION_KEY); ensureAuthenticatedUserIsSame( originalAuth, current, auditTrailService, readerContext.id(), action, request, AuditUtil.extractRequestId(threadContext), threadContext.getTransient(AUTHORIZATION_INFO_KEY) ); // piggyback on context validation to assert the DLS/FLS permissions on the thread context of the scroll search handler if (null == securityContext.getThreadContext().getTransient(AuthorizationServiceField.INDICES_PERMISSIONS_KEY)) { // fill in the DLS and FLS permissions for the scroll search action from the scroll context IndicesAccessControl scrollIndicesAccessControl = readerContext.getFromContext( AuthorizationServiceField.INDICES_PERMISSIONS_KEY ); assert scrollIndicesAccessControl != null : ""scroll does not contain index access control""; securityContext.getThreadContext() .putTransient(AuthorizationServiceField.INDICES_PERMISSIONS_KEY, scrollIndicesAccessControl); } } }","@Override public void validateReaderContext(ReaderContext readerContext, TransportRequest request) { if (readerContext.scrollContext() != null) { final Authentication originalAuth = readerContext.getFromContext(AuthenticationField.AUTHENTICATION_KEY); if (false == securityContext.canIAccessResourcesCreatedBy(originalAuth)) { auditAccessDenied(request); throw new SearchContextMissingException(readerContext.id()); } // piggyback on context validation to assert the DLS/FLS permissions on the thread context of the scroll search handler if (null == securityContext.getThreadContext().getTransient(AuthorizationServiceField.INDICES_PERMISSIONS_KEY)) { // fill in the DLS and FLS permissions for the scroll search action from the scroll context IndicesAccessControl scrollIndicesAccessControl = readerContext.getFromContext( AuthorizationServiceField.INDICES_PERMISSIONS_KEY ); assert scrollIndicesAccessControl != null : ""scroll does not contain index access control""; securityContext.getThreadContext() .putTransient(AuthorizationServiceField.INDICES_PERMISSIONS_KEY, scrollIndicesAccessControl); } } }","Fix can access resource checks for API Keys with run as (#84277) This fixes two things for the ""can access"" authz check: * API Keys running as, have access to the resources created by the effective run as user * tokens created by API Keys (with the client credentials) have access to the API Key's resources In addition, this PR moves some of the authz plumbing code from the Async and Scroll services classes under the Security Context class (as a minor refactoring).",https://github.com/elastic/elasticsearch/commit/2f0733d1b5dc9458ec901efe2f7141742d9dfed8,,,x-pack/plugin/security/src/main/java/org/elasticsearch/xpack/security/authz/SecuritySearchOperationListener.java,3,java,False,2022-02-28T14:00:54Z "private static void addPrincipalsForPrivateCredentials(Set principals, Set privateCredentials) { for (Object credential : privateCredentials) { if (credential instanceof PasswordCredential) { String username = ((PasswordCredential)credential).getUsername(); Principal loginName = new LoginNamePrincipal(username); principals.add(loginName); } else if (credential instanceof BearerTokenCredential) { String token = ((BearerTokenCredential)credential).getToken(); byte[] hashBytes = Hashing.goodFastHash(128).hashBytes(token.getBytes(US_ASCII)).asBytes(); String hash = Base64.getEncoder().encodeToString(hashBytes); Principal p = new SimplePrincipal(hash); principals.add(p); } } }","private static void addPrincipalsForPrivateCredentials(Set principals, Set privateCredentials) { for (Object credential : privateCredentials) { if (credential instanceof PasswordCredential) { String username = ((PasswordCredential)credential).getUsername(); Principal loginName = new LoginNamePrincipal(username); principals.add(loginName); } else if (credential instanceof BearerTokenCredential) { String description = ((BearerTokenCredential)credential).describeToken(); principals.add(new SimplePrincipal(description)); } } }","gplazma: update fail login storage to use BearerToken#describeToken Motivation: gPlazma remembers which requests it has already seen. However, simply storing the Subject is a potential security vulnerability, as this would store sensitive (""private"") credentials in memory, such as username + passwords and bearer tokens. To avoid this, a sanitised principal is used instead of a private credential. With the ability for a BearerToken to provide a safe description of itself, the code to generate the safe representation is now redundant. Modification: Update principal generation to use the BearerTokenCredential's builtin representation. Result: No user or admin observable changes. Code is simpler to understand and maintain. Target: master Requires-notes: no Requires-book: no Patch: https://rb.dcache.org/r/12868/ Acked-by: Tigran Mkrtchyan Acked-by: Lea Morschel",https://github.com/dCache/dcache/commit/3ecedb41449a8a6d581e03ebf799ead2277395fe,,,modules/gplazma2/src/main/java/org/dcache/gplazma/GPlazma.java,3,java,False,2021-02-26T13:10:10Z "@Override public int decompress(byte[] input, int inputOffset, int inputLength, byte[] output, int outputOffset, int maxOutputLength) throws MalformedInputException { long inputAddress = ARRAY_BYTE_BASE_OFFSET + inputOffset; long inputLimit = inputAddress + inputLength; long outputAddress = ARRAY_BYTE_BASE_OFFSET + outputOffset; long outputLimit = outputAddress + maxOutputLength; return SnappyRawDecompressor.decompress(input, inputAddress, inputLimit, output, outputAddress, outputLimit); }","@Override public int decompress(byte[] input, int inputOffset, int inputLength, byte[] output, int outputOffset, int maxOutputLength) throws MalformedInputException { verifyRange(input, inputOffset, inputLength); verifyRange(output, outputOffset, maxOutputLength); long inputAddress = ARRAY_BYTE_BASE_OFFSET + inputOffset; long inputLimit = inputAddress + inputLength; long outputAddress = ARRAY_BYTE_BASE_OFFSET + outputOffset; long outputLimit = outputAddress + maxOutputLength; return SnappyRawDecompressor.decompress(input, inputAddress, inputLimit, output, outputAddress, outputLimit); }",Prevent JVM crash when buffer too small,https://github.com/airlift/aircompressor/commit/127b7f3c6330e6cc595f10648b68a197974b50bf,,,src/main/java/io/airlift/compress/snappy/SnappyDecompressor.java,3,java,False,2022-04-12T10:20:50Z "@Override protected final void onMenuClick(Player player, int slot, InventoryAction action, ClickType click, ItemStack cursor, ItemStack clicked, boolean cancelled) { if (this.mode == EditMode.CHANCE && this.canEditItem(slot) && slot < this.getSize() - 9) { Valid.checkNotNull(clicked, ""Should have not called onMenuClick for null clicked item at slot "" + slot); final double chance = this.editedDropChances.getOrDefault(slot, this.getDropChance(slot)); final double next = this.getNextQuantityDouble(click); final double newChance = MathUtil.range(chance + next, 0.D, 1.D); // Save drop chance this.editedDropChances.override(slot, newChance); // Update item this.setItem(slot, this.getItemAt(slot)); } }","@Override protected final void onMenuClick(Player player, int slot, InventoryAction action, ClickType click, ItemStack cursor, ItemStack clicked, boolean cancelled) { if (this.mode == EditMode.CHANCE && this.canEditItem(slot) && slot < this.getSize() - 9) { // Prevent exploiting chances menu holding an item if (clicked == null) return; final double chance = this.editedDropChances.getOrDefault(slot, this.getDropChance(slot)); final double next = this.getNextQuantityDouble(click); final double newChance = MathUtil.range(chance + next, 0.D, 1.D); // Save drop chance this.editedDropChances.override(slot, newChance); // Update item this.setItem(slot, this.getItemAt(slot)); } }",Prevent exploiting chances menu holding an item,https://github.com/kangarko/Foundation/commit/43e75e79a6f8b5da04fbb5a26da3b1fb0dec3e3e,,,src/main/java/org/mineacademy/fo/menu/MenuContainerChances.java,3,java,False,2021-10-18T14:56:36Z "public void clearScreens() { for (NUIScreenLayer uiScreen : uiScreens) { uiScreen.onRemoved(); } uiScreens.clear(); }","public void clearScreens() { Iterator screenIterator = uiScreens.descendingIterator(); while (screenIterator.hasNext()) { NUIScreenLayer uiScreen = screenIterator.next(); screenIterator.remove(); uiScreen.onRemoved(); } }","fix(NUIManager): call NUIScreenLayer#onRemoved after screen removal This makes more sense, since onRemoved implies that the screen has already been removed. It also prevents screens from creating stack overflows when trying to add themselves back again during an onRemoved call. BREAKING CHANGE: NUIScreenLayer#onRemoved is now called at a different part of the screen lifecycle.",https://github.com/MovingBlocks/DestinationSol/commit/f009c9ac7d1653d310c8b44907b09b629d7228b1,,,engine/src/main/java/org/destinationsol/ui/nui/NUIManager.java,3,java,False,2022-09-04T22:05:23Z "@Override public int pushWater(int max, boolean execute) { if(this.isMultiBlockOrigin()) { return super.pushWater(max, execute); } else { return this.getMultiBlockOrigin().pushWater(max, execute); } }","@Override public int pushWater(int max, boolean execute) { if(this.isMultiBlockOrigin()) { return super.pushWater(max, execute); } else { TileEntityIrrigationTank origin = this.getMultiBlockOrigin(); if(origin != null) { // origin can be null if the origin chunk is not loaded return origin.pushWater(max, execute); } return 0; } }",Fix Irrigation tank crash (#1392),https://github.com/AgriCraft/AgriCraft/commit/32944e66e27d2b8acc4602a22eedc100ce3535b6,,,src/main/java/com/infinityraider/agricraft/content/irrigation/TileEntityIrrigationTank.java,3,java,False,2021-08-25T17:10:03Z "public CompletableFuture authorize(AuthenticationDataSource authenticationData, Function> authorizeFunc) { List roles = getRoles(authenticationData); if (roles.isEmpty()) { return CompletableFuture.completedFuture(false); } List> futures = new ArrayList<>(roles.size()); roles.forEach(r -> futures.add(authorizeFunc.apply(r))); return FutureUtil.waitForAny(futures, ret -> (boolean) ret).thenApply(v -> v.isPresent()); }","public CompletableFuture authorize(AuthenticationDataSource authenticationData, Function> authorizeFunc) { Set roles = getRoles(authenticationData); if (roles.isEmpty()) { return CompletableFuture.completedFuture(false); } List> futures = new ArrayList<>(roles.size()); roles.forEach(r -> futures.add(authorizeFunc.apply(r))); return FutureUtil.waitForAny(futures, ret -> (boolean) ret).thenApply(v -> v.isPresent()); }",[fix][authorization] Fix multiple roles authorization (#16645),https://github.com/apache/pulsar/commit/d8483d48cb21e8e99fd56c786e5198f7fe7135f6,,,pulsar-broker-common/src/main/java/org/apache/pulsar/broker/authorization/MultiRolesTokenAuthorizationProvider.java,3,java,False,2022-07-25T09:57:19Z "@Nullable static Node rewrite(@NotNull Node root, @NotNull List rules) throws RewriteException, RepositoryException { String rootPath = root.getPath(); logger.debug(""Rewriting content tree rooted at: {}"", rootPath); long tick = System.currentTimeMillis(); Node startNode = root; boolean matched; Set finalPaths = new LinkedHashSet<>(); do { matched = false; TreeTraverser traverser = new TreeTraverser(startNode); Iterator iterator = traverser.iterator(); logger.debug(""Starting new pre-order tree traversal at root: {}"", startNode.getPath()); while (iterator.hasNext()) { Node node = iterator.next(); // If parent is ordered, move to the end to preserve order. Rules may delete/create new nodes on parent. if (node.getParent().getPrimaryNodeType().hasOrderableChildNodes()) { node.getParent().orderBefore(node.getName(), null); } // If we already matched, skip back to the root for next traversal if (matched) { continue; } // If any rule indicated that the path is final if (finalPaths.contains(node.getPath())) { continue; } // Apply the rules for (RewriteRule rule : rules) { if (rule.matches(node)) { logger.debug(""Rule [{}] matched subtree at [{}]"", rule.getId(), node.getPath()); Node result = rule.applyTo(node, finalPaths); // set the start node in case it was rewritten if (node.equals(startNode)) { startNode = result; } matched = true; // Only one rule is allowed to match, start back at top of tree due to deletes and rewrites. break; } } } } while (matched && startNode != null); long tock = System.currentTimeMillis(); logger.debug(""Rewrote content tree rooted at [{}] in {}ms"", root.getPath(), tock - tick); return startNode; }","@Nullable static Node rewrite(@NotNull Node root, @NotNull List rules) throws RewriteException, RepositoryException { String rootPath = root.getPath(); logger.debug(""Rewriting content tree rooted at: {}"", rootPath); long tick = System.currentTimeMillis(); Node startNode = root; boolean matched; Map> processed = new HashMap<>(); Set finalPaths = new LinkedHashSet<>(); do { matched = false; TreeTraverser traverser = new TreeTraverser(startNode); Iterator iterator = traverser.iterator(); logger.debug(""Starting new pre-order tree traversal at root: {}"", startNode.getPath()); while (iterator.hasNext()) { Node node = iterator.next(); // If parent is ordered, move to the end to preserve order. Rules may delete/create new nodes on parent. if (node.getParent().getPrimaryNodeType().hasOrderableChildNodes()) { node.getParent().orderBefore(node.getName(), null); } // If we already matched, skip back to the root for next traversal if (matched) { continue; } // If any rule indicated that the path is final if (finalPaths.contains(node.getPath())) { continue; } // Apply the rules for (RewriteRule rule : rules) { if (!processed.containsKey(rule.getId())) { processed.put(rule.getId(), new HashSet<>()); } // Some rules may process a node without changing its state enough to no longer match. Set ruleProcessedPaths = processed.get(rule.getId()); if (!ruleProcessedPaths.contains(node.getPath()) && rule.matches(node)) { String path = node.getPath(); logger.debug(""Rule [{}] matched subtree at [{}]"", rule.getId(), path); Node result = rule.applyTo(node, finalPaths); ruleProcessedPaths.add(path); // set the start node in case it was rewritten if (node.equals(startNode)) { startNode = result; } matched = true; // Only one rule is allowed to match, start back at top of tree due to deletes and rewrites. break; } } } } while (matched && startNode != null); long tock = System.currentTimeMillis(); logger.debug(""Rewrote content tree rooted at [{}] in {}ms"", root.getPath(), tock - tick); return startNode; }",Protect against infinite loops. (#100),https://github.com/adobe/aem-modernize-tools/commit/e22021c0709963b8d6034228145b936173b54d87,,,core/src/main/java/com/adobe/aem/modernize/component/impl/ComponentTreeRewriter.java,3,java,False,2022-01-07T20:05:47Z "protected void initialize( String filePath, String folderName, boolean resetRepository ) { if ( simpleBackendDb != null ) { simpleBackendDb.close(); } synchronized ( this ) { File folder = PolyphenyHomeDirManager.getInstance().registerNewFolder( folderName ); if ( Catalog.resetCatalog ) { StatusService.printInfo( ""Resetting monitoring repository on startup."" ); if ( new File( folder, filePath ).exists() ) { new File( folder, filePath ).delete(); } } simpleBackendDb = DBMaker .fileDB( new File( folder, filePath ) ) .closeOnJvmShutdown() .transactionEnable() .fileMmapEnableIfSupported() .fileMmapPreclearDisable() .make(); simpleBackendDb.getStore().fileLoad(); } }","protected void initialize( String filePath, String folderName, boolean resetRepository ) { if ( simpleBackendDb != null ) { simpleBackendDb.close(); } synchronized ( this ) { File folder = PolyphenyHomeDirManager.getInstance().registerNewFolder( folderName ); if ( Catalog.resetCatalog ) { StatusService.printInfo( ""Resetting monitoring repository on startup."" ); if ( new File( folder, filePath ).exists() ) { new File( folder, filePath ).delete(); } } // Assume that file is locked boolean fileLocked = true; long secondsToWait = 30; long timeThreshold = secondsToWait * 1000; long start = System.currentTimeMillis(); long finish = System.currentTimeMillis(); while ( fileLocked && ((finish - start) < timeThreshold) ) { try { simpleBackendDb = DBMaker .fileDB( new File( folder, filePath ) ) .closeOnJvmShutdown() .transactionEnable() .fileMmapEnableIfSupported() .fileMmapPreclearDisable() .make(); fileLocked = false; } catch ( DBException e ) { log.warn( ""Monitoring Repository is currently locked by another process. Waiting..."" ); } finish = System.currentTimeMillis(); } // Exceeded threshold if ( (finish - start) >= timeThreshold ) { throw new RuntimeException( ""Initializing Monitoring Repository took too long..."" ); } simpleBackendDb.getStore().fileLoad(); log.warn( ""Monitoring repository has been initialized"" ); } }",Fixed a bug when crashed monitoring repo stops DB from starting again,https://github.com/polypheny/Polypheny-DB/commit/a49801e5a8d1f085fce5e918302660d73c0eb9fd,,,monitoring/src/main/java/org/polypheny/db/monitoring/persistence/MapDbRepository.java,3,java,False,2022-01-22T14:53:49Z "def __init__(self, *, win_id, mode_manager, private, parent=None): self.private = private self.win_id = win_id self.tab_id = next(tab_id_gen) super().__init__(parent) self.registry = objreg.ObjectRegistry() tab_registry = objreg.get('tab-registry', scope='window', window=win_id) tab_registry[self.tab_id] = self objreg.register('tab', self, registry=self.registry) self.data = TabData() self._layout = miscwidgets.WrapperLayout(self) self._widget = None self._progress = 0 self._has_ssl_errors = False self._mode_manager = mode_manager self._load_status = usertypes.LoadStatus.none self._mouse_event_filter = mouse.MouseEventFilter( self, parent=self) self.backend = None # FIXME:qtwebengine Should this be public api via self.hints? # Also, should we get it out of objreg? hintmanager = hints.HintManager(win_id, self.tab_id, parent=self) objreg.register('hintmanager', hintmanager, scope='tab', window=self.win_id, tab=self.tab_id) self.predicted_navigation.connect(self._on_predicted_navigation)","def __init__(self, tab): self._widget = None self._tab = tab","Security: Remember hosts with ignored cert errors for load status Without this change, we only set a flag when a certificate error occurred. However, when the same certificate error then happens a second time (e.g. because of a reload or opening the same URL again), we then colored the URL as success_https (i.e. green) again. See #5403 (cherry picked from commit 021ab572a319ca3db5907a33a59774f502b3b975)",https://github.com/qutebrowser/qutebrowser/commit/4020210b193f77cf1785b21717f6ef7c5de5f0f8,,,qutebrowser/browser/browsertab.py,3,py,False,2020-05-02T16:54:05Z "@Override public boolean hasPermission(final Rank rank, @NotNull final Action action) { return Utils.testFlag(permissionMap.get(rank), action.getFlag()) || (fullyAbandoned && Utils.testFlag(fullyAbandonedPermissionsFlag, action.getFlag())); }","@Override public boolean hasPermission(final Rank rank, @NotNull final Action action) { return Utils.testFlag(rank.getPermissions(), action.getFlag()) || (fullyAbandoned && Utils.testFlag(fullyAbandonedPermissionsFlag, action.getFlag())); }","Fix permission issues (#7972) Ranks are no longer a static map, which was used as a per-colony map thus causing crashes and desyncs. If the last colony loaded had a custom rank, all other colonies would crash out due to not matching permissions for that rank. Permission/Rank seperation is removed, permission flag is now part of the rank instead of an externally synced map, which also auto-corrects bad stored data to default permissions. UI now has non-changeable permission buttons disabled.",https://github.com/ldtteam/minecolonies/commit/b1b86dffe64dd4c0f9d3060769fc418fd5d2869a,,,src/main/java/com/minecolonies/coremod/colony/permissions/Permissions.java,3,java,False,2022-01-23T12:23:45Z "protected String schema(int deepness, Schema schema, DiffContext context) { StringBuilder sb = new StringBuilder(); sb.append(listItem(deepness, ""Enum"", schema.getEnum())); sb.append(properties(deepness, ""Property"", schema.getProperties(), true, context)); if (schema instanceof ComposedSchema) { sb.append(schema(deepness, (ComposedSchema) schema, context)); } else if (schema instanceof ArraySchema) { sb.append(items(deepness, resolve(((ArraySchema) schema).getItems()), context)); } return sb.toString(); }","protected String schema(int deepness, Schema schema, DiffContext context) { if (handledSchemas.contains(schema)) return """"; handledSchemas.add(schema); StringBuilder sb = new StringBuilder(); sb.append(listItem(deepness, ""Enum"", schema.getEnum())); sb.append(properties(deepness, ""Property"", schema.getProperties(), true, context)); if (schema instanceof ComposedSchema) { sb.append(schema(deepness, (ComposedSchema) schema, context)); } else if (schema instanceof ArraySchema) { sb.append(items(deepness, resolve(((ArraySchema) schema).getItems()), context)); } return sb.toString(); }","Fix stack overflow in recursive definitions (#331) Co-authored-by: Mikkel Arentoft ",https://github.com/OpenAPITools/openapi-diff/commit/72517cc8de89fa442344591e39891604f36526b4,,,core/src/main/java/org/openapitools/openapidiff/core/output/MarkdownRender.java,3,java,False,2022-03-03T10:28:55Z "private String signature(@Nullable Type type) { if (type == null || type instanceof Type.UnknownType || type instanceof NullType) { return ""{undefined}""; } else if (type instanceof Type.ClassType) { try { return type.isParameterized() ? parameterizedSignature(type) : classSignature(type); } catch (Symbol.CompletionFailure ignored) { return classSignature(type); } } else if (type instanceof Type.TypeVar) { return genericSignature(type); } else if (type instanceof Type.JCPrimitiveType) { return primitiveSignature(type); } else if (type instanceof Type.JCVoidType) { return ""void""; } else if (type instanceof Type.ArrayType) { return arraySignature(type); } else if (type instanceof Type.WildcardType) { Type.WildcardType wildcard = (Type.WildcardType) type; StringBuilder s = new StringBuilder(""Generic{"" + wildcard.kind.toString()); if (!type.isUnbound()) { s.append(signature(wildcard.type)); } return s.append(""}"").toString(); } else if (type instanceof Type.JCNoType) { return ""{none}""; } throw new IllegalStateException(""Unexpected type "" + type.getClass().getName()); }","private String signature(@Nullable Type type) { if (type == null || type instanceof Type.UnknownType || type instanceof NullType) { return ""{undefined}""; } else if (type instanceof Type.ClassType) { try { return type.isParameterized() ? parameterizedSignature(type) : classSignature(type); } catch (Symbol.CompletionFailure ignored) { return classSignature(type); } } else if (type instanceof Type.CapturedType) { // CapturedType must be evaluated before TypeVar return signature(((Type.CapturedType) type).wildcard); } else if (type instanceof Type.TypeVar) { return genericSignature(type); } else if (type instanceof Type.JCPrimitiveType) { return primitiveSignature(type); } else if (type instanceof Type.JCVoidType) { return ""void""; } else if (type instanceof Type.ArrayType) { return arraySignature(type); } else if (type instanceof Type.WildcardType) { Type.WildcardType wildcard = (Type.WildcardType) type; StringBuilder s = new StringBuilder(""Generic{"" + wildcard.kind.toString()); if (!type.isUnbound()) { s.append(signature(wildcard.type)); } return s.append(""}"").toString(); } else if (type instanceof Type.JCNoType) { return ""{none}""; } throw new IllegalStateException(""Unexpected type "" + type.getClass().getName()); }",Prevent StackOverflow on parameterized `Type.CapturedType` symbols.,https://github.com/openrewrite/rewrite/commit/18ae87fac5ed6d879ac27e4244e7856fcc8fe398,,,rewrite-java-11/src/main/java/org/openrewrite/java/Java11TypeSignatureBuilder.java,3,java,False,2021-12-31T17:43:25Z "private boolean supportsSoftButtonImages() { SoftButtonCapabilities softButtonCapabilities = currentWindowCapability.getSoftButtonCapabilities().get(0); return softButtonCapabilities.getImageSupported().booleanValue(); }","private boolean supportsSoftButtonImages() { if (currentWindowCapability == null || currentWindowCapability.getSoftButtonCapabilities() == null || currentWindowCapability.getSoftButtonCapabilities().size() == 0 || currentWindowCapability.getSoftButtonCapabilities().get(0) == null ) { return true; } SoftButtonCapabilities softButtonCapabilities = currentWindowCapability.getSoftButtonCapabilities().get(0); return softButtonCapabilities.getImageSupported().booleanValue(); }","Add multiple checks to supportsSoftButtonImages() (#1801) This commit adds null checks and a List.size() check to PresentAlertOperation.supportsSoftButtonImages() These checks prevent crashes and returns true when soft button capabilities are unavailable This new behavior improves alignment with the other SDL libraries",https://github.com/smartdevicelink/sdl_java_suite/commit/01fa481fb39e292c9b07327c561eda99cdca0b20,,,base/src/main/java/com/smartdevicelink/managers/screen/PresentAlertOperation.java,3,java,False,2022-04-08T14:07:21Z "@Override public void sendIntent(String action, @Nullable ReadableArray extras, Promise promise) { if (action == null || action.isEmpty()) { promise.reject(new JSApplicationIllegalArgumentException(""Invalid Action: "" + action + ""."")); return; } Intent intent = new Intent(action); PackageManager packageManager = getReactApplicationContext().getPackageManager(); if (intent.resolveActivity(packageManager) == null) { promise.reject( new JSApplicationIllegalArgumentException( ""Could not launch Intent with action "" + action + ""."")); return; } if (extras != null) { for (int i = 0; i < extras.size(); i++) { ReadableMap map = extras.getMap(i); String name = map.keySetIterator().nextKey(); ReadableType type = map.getType(name); switch (type) { case String: { intent.putExtra(name, map.getString(name)); break; } case Number: { // We cannot know from JS if is an Integer or Double // See: https://github.com/facebook/react-native/issues/4141 // We might need to find a workaround if this is really an issue Double number = map.getDouble(name); intent.putExtra(name, number); break; } case Boolean: { intent.putExtra(name, map.getBoolean(name)); break; } default: { promise.reject( new JSApplicationIllegalArgumentException( ""Extra type for "" + name + "" not supported."")); return; } } } } getReactApplicationContext().startActivity(intent); }","@Override public void sendIntent(String action, @Nullable ReadableArray extras, Promise promise) { if (action == null || action.isEmpty()) { promise.reject(new JSApplicationIllegalArgumentException(""Invalid Action: "" + action + ""."")); return; } Intent intent = new Intent(action); PackageManager packageManager = getReactApplicationContext().getPackageManager(); if (intent.resolveActivity(packageManager) == null) { promise.reject( new JSApplicationIllegalArgumentException( ""Could not launch Intent with action "" + action + ""."")); return; } if (extras != null) { for (int i = 0; i < extras.size(); i++) { ReadableMap map = extras.getMap(i); String name = map.keySetIterator().nextKey(); ReadableType type = map.getType(name); switch (type) { case String: { intent.putExtra(name, map.getString(name)); break; } case Number: { // We cannot know from JS if is an Integer or Double // See: https://github.com/facebook/react-native/issues/4141 // We might need to find a workaround if this is really an issue Double number = map.getDouble(name); intent.putExtra(name, number); break; } case Boolean: { intent.putExtra(name, map.getBoolean(name)); break; } default: { promise.reject( new JSApplicationIllegalArgumentException( ""Extra type for "" + name + "" not supported."")); return; } } } } sendOSIntent(intent, true); }","Fix: Set ""new task flag"" for intent method (#29000) Summary: Addresses https://github.com/facebook/react-native/issues/28934 ## Changelog [Android] [Fixed] - When sending OS intents, always set ""FLAG_ACTIVITY_NEW_TASK"" flag (required by OS). Pull Request resolved: https://github.com/facebook/react-native/pull/29000 Test Plan: 1. Open RNTester on Android 2. Go to Linking section 3. Try opening ""POWER_USAGE_SUMMARY"" intent 4. App should open settings, instead of crashing Reviewed By: cortinico Differential Revision: D30876645 Pulled By: lunaleaps fbshipit-source-id: e427bfeadf9fb1ae38bf05bfeafd88e6776d71de",https://github.com/react-native-tvos/react-native-tvos/commit/04fe3ed80d9c201a483a2b477aeebd3d4169fd6d,,,ReactAndroid/src/main/java/com/facebook/react/modules/intent/IntentModule.java,3,java,False,2021-09-13T19:54:58Z "private CompletableFuture isNamespaceOperationAllowed(NamespaceName namespaceName, NamespaceOperation operation) { if (!service.isAuthorizationEnabled()) { return CompletableFuture.completedFuture(true); } CompletableFuture isProxyAuthorizedFuture; if (originalPrincipal != null) { isProxyAuthorizedFuture = service.getAuthorizationService().allowNamespaceOperationAsync( namespaceName, operation, originalPrincipal, getAuthenticationData()); } else { isProxyAuthorizedFuture = CompletableFuture.completedFuture(true); } CompletableFuture isAuthorizedFuture = service.getAuthorizationService().allowNamespaceOperationAsync( namespaceName, operation, authRole, authenticationData); return isProxyAuthorizedFuture.thenCombine(isAuthorizedFuture, (isProxyAuthorized, isAuthorized) -> { if (!isProxyAuthorized) { log.warn(""OriginalRole {} is not authorized to perform operation {} on namespace {}"", originalPrincipal, operation, namespaceName); } if (!isAuthorized) { log.warn(""Role {} is not authorized to perform operation {} on namespace {}"", authRole, operation, namespaceName); } return isProxyAuthorized && isAuthorized; }); }","private CompletableFuture isNamespaceOperationAllowed(NamespaceName namespaceName, NamespaceOperation operation) { if (!service.isAuthorizationEnabled()) { return CompletableFuture.completedFuture(true); } CompletableFuture isProxyAuthorizedFuture; if (originalPrincipal != null) { isProxyAuthorizedFuture = service.getAuthorizationService().allowNamespaceOperationAsync( namespaceName, operation, originalPrincipal, originalAuthData); } else { isProxyAuthorizedFuture = CompletableFuture.completedFuture(true); } CompletableFuture isAuthorizedFuture = service.getAuthorizationService().allowNamespaceOperationAsync( namespaceName, operation, authRole, authenticationData); return isProxyAuthorizedFuture.thenCombine(isAuthorizedFuture, (isProxyAuthorized, isAuthorized) -> { if (!isProxyAuthorized) { log.warn(""OriginalRole {} is not authorized to perform operation {} on namespace {}"", originalPrincipal, operation, namespaceName); } if (!isAuthorized) { log.warn(""Role {} is not authorized to perform operation {} on namespace {}"", authRole, operation, namespaceName); } return isProxyAuthorized && isAuthorized; }); }","[fix][broker] Fix passing incorrect authentication data (#16201) ### Motivation #16065 fixes the race condition issue, but introduces a new issue. This issue is triggered when the Proxy and Broker work together, when we use the proxy to request the broker to do lookup/subscribe/produce operation, the broker always uses the original authentication data for authorization, not proxy authentication data, which causes this issue. ### Modification - Fix passing authentication data, differentiate between original auth data and connected auth data by avoid to use the `getAuthenticationData()`, this method name is easy to cause confusion and can not correctly get the authentication data",https://github.com/apache/pulsar/commit/936bbbcc6a4e8cf61547aeedf92e84fb3a089502,,,pulsar-broker/src/main/java/org/apache/pulsar/broker/service/ServerCnx.java,3,java,False,2022-06-28T23:39:10Z "@Override public void onAvailableSubInfoChanged(List subInfoEntityList) { }","@Override public void onAvailableSubInfoChanged(List subInfoEntityList) { if (DataServiceUtils.shouldUpdateEntityList(mSubInfoEntityList, subInfoEntityList)) { // Check the current subId is existed or not, if so, finish it. if (!mSubscriptionInfoMap.isEmpty()) { // Check each subInfo and remove it in the map based on the new list. for (SubscriptionInfoEntity entity : subInfoEntityList) { mSubscriptionInfoMap.remove(Integer.parseInt(entity.subId)); } Iterator iterator = mSubscriptionInfoMap.keySet().iterator(); while (iterator.hasNext()) { if (iterator.next() == mSubId) { finishFragment(); return; } } } mSubInfoEntityList = subInfoEntityList; mSubInfoEntityList.forEach(entity -> { int subId = Integer.parseInt(entity.subId); mSubscriptionInfoMap.put(subId, entity); if (subId == mSubId) { mSubscriptionInfoEntity = entity; onSubscriptionDetailChanged(); } }); } }","[Settings] Fix crash and UI error when turn ON/OFF SIM 1. Should update the UI when turn off SIM 2. Fix ConcurrentModificationException Bug: 259487637 Test: manual Change-Id: If30a6b6323ac0237c92dc210bf3953ce86a199ae",https://github.com/LineageOS/android_packages_apps_Settings/commit/9ca3255c2d0c30b8c56f734f221b30bd2cacecc0,,,src/com/android/settings/network/telephony/MobileNetworkSettings.java,3,java,False,2022-12-08T22:01:13Z "public long getLong(int col) throws SQLException { DB db = getDatabase(); return db.column_long(stmt.pointer, markCol(col)); }","public long getLong(int col) throws SQLException { return safeGetLongCol(col); }",Wrap Statement Pointers to prevent use after free race,https://github.com/xerial/sqlite-jdbc/commit/e1d282cb2887ef427c7ad93d4fe7dd05a6c11473,,,src/main/java/org/sqlite/jdbc3/JDBC3ResultSet.java,3,java,False,2022-07-29T03:54:01Z "@Nonnull @Override @SuppressWarnings(""deprecation"") public IBlockState getStateFromMeta(int meta) { Material material = variantProperty.getAllowedValues().get(meta); return getDefaultState().withProperty(variantProperty, material); }","@Nonnull @Override @SuppressWarnings(""deprecation"") public IBlockState getStateFromMeta(int meta) { if (meta >= variantProperty.getAllowedValues().size()) { meta = 0; } return getDefaultState().withProperty(variantProperty, variantProperty.getAllowedValues().get(meta)); }","Grab default meta when meta exceeds allowed values for meta blocks (#621) - Prevents world corrupting crash",https://github.com/GregTechCEu/GregTech/commit/e7f9f0875c446ee7a4628859b4324e1a7ec35652,,,src/main/java/gregtech/common/blocks/BlockCompressed.java,3,java,False,2022-02-21T18:37:06Z "private int calculateOctreeOrigin(Collection chunksToLoad, boolean centerOctree) { int xmin = Integer.MAX_VALUE; int xmax = Integer.MIN_VALUE; int zmin = Integer.MAX_VALUE; int zmax = Integer.MIN_VALUE; for (ChunkPosition cp : chunksToLoad) { if (cp.x < xmin) { xmin = cp.x; } if (cp.x > xmax) { xmax = cp.x; } if (cp.z < zmin) { zmin = cp.z; } if (cp.z > zmax) { zmax = cp.z; } } xmax += 1; zmax += 1; xmin *= 16; xmax *= 16; zmin *= 16; zmax *= 16; int maxDimension = Math.max(yMax - yMin, Math.max(xmax - xmin, zmax - zmin)); int requiredDepth = QuickMath.log2(QuickMath.nextPow2(maxDimension)); if(centerOctree) { int xroom = (1 << requiredDepth) - (xmax - xmin); int yroom = (1 << requiredDepth) - (yMax - yMin); int zroom = (1 << requiredDepth) - (zmax - zmin); origin.set(xmin - xroom / 2, -yroom / 2, zmin - zroom / 2); } else { origin.set(xmin, 0, zmin); } return requiredDepth; }","private int calculateOctreeOrigin(Collection chunksToLoad, boolean centerOctree) { int xmin = Integer.MAX_VALUE; int xmax = Integer.MIN_VALUE; int zmin = Integer.MAX_VALUE; int zmax = Integer.MIN_VALUE; for (ChunkPosition cp : chunksToLoad) { if (cp.x < xmin) { xmin = cp.x; } if (cp.x > xmax) { xmax = cp.x; } if (cp.z < zmin) { zmin = cp.z; } if (cp.z > zmax) { zmax = cp.z; } } xmax += 1; zmax += 1; xmin *= 16; xmax *= 16; zmin *= 16; zmax *= 16; int maxDimension = Math.max(yMax - yMin, Math.max(xmax - xmin, zmax - zmin)); int requiredDepth = QuickMath.log2(QuickMath.nextPow2(maxDimension)); if(centerOctree) { int xroom = (1 << requiredDepth) - (xmax - xmin); int yroom = (1 << requiredDepth) - (yMax - yMin); int zroom = (1 << requiredDepth) - (zmax - zmin); origin.set(xmin - xroom / 2, -yroom / 2, zmin - zroom / 2); } else { // Note: Math.floorDiv rather than integer division for round toward -infinity origin.set(xmin, Math.floorDiv(yMin, 16) * 16, zmin); } return requiredDepth; }","Fix various octree bugs (#933) * Fix an of by one error where, if yMax was a multiple of 16, an additional iteration was done, inserting an additional empty cube in the octree. If the octree was small enough that this additional cube was out of bounds, it wrapped around and overwrote a valid cube, leading to the bottoms layers being replaced with air * Change the bound check against yClipMax to be exclusive when loading entities to be more consistent with the bound check against yMax when loading blocks. Change the bound check from yClip(Min|Max) to y(Min|Max) when loading block entity so the test is the same as when loading blocks because those entities are related to blocks. For the other entities, still using yClip(Min|Max) is desirable to be able to load entities that are below 0/higher than 256 * Only try to merge node starting at the depth of the inserted cube (because deeper than that, inside the cube, the parents have not been set and it would be useless anyway due to how the cube insertion is done). This was the cause of the StackOverflow in finalizeNode, due to a cycle in treeData, due to bad merges * Use yMin as the y coordinate of the origin so the coordinate inside the octree always start at 0 even for negative of greater than 0 y values. As for x and z, the y coordinate is forced to be a multiple of 16 to correctly work with the way the chunks are loaded in the octree. I think there is no need for additional changes to make entities (and emitter position) align with the loading chunks. I think that this change is technically not backward compatible because the way the origin is computed is different, but it only breaks compatibility with snapshot scene because scene created in stable release are already treated differently * Change the nodeEquals method to not return true when comparing two branch nodes. It lead to wrongful merge when a node had 8 children because every node compared equals even though they were different.",https://github.com/chunky-dev/chunky/commit/62877c6e39c57b07ca6a363e6a9ce16af266d4f9,,,chunky/src/java/se/llbit/chunky/renderer/scene/Scene.java,3,java,False,2021-05-12T20:46:01Z "@GET @Path ( ""/session-variable"" ) @Facet ( name = ""Unsupported"" ) @Produces( TEXT_PLAIN ) public Response getSessionVariable( @QueryParam ( ""key"" ) String key ) { if ( getSessionVarWhiteList.contains( key ) ) { Object value = UserConsoleService.getPentahoSession().getAttribute( key ); if ( value != null ) { return Response.ok( value ).build(); } else { return Response.noContent().build(); } } return Response.status( FORBIDDEN ).build(); }","@GET @Path ( ""/session-variable"" ) @Facet ( name = ""Unsupported"" ) @Produces( {TEXT_PLAIN, APPLICATION_JSON, APPLICATION_XML} ) public Response getSessionVariable( @QueryParam ( ""key"" ) String key ) { if ( getSessionVarWhiteList.contains( key ) ) { Object value = UserConsoleService.getPentahoSession().getAttribute( key ); if ( value != null ) { return Response.ok( value ).build(); } else { return Response.noContent().build(); } } return Response.status( FORBIDDEN ).build(); }",[PPP-4767] - Reflected Cross-Site Scripting (XSS) on parameter value of session-variable,https://github.com/pentaho/pentaho-platform/commit/8ebd8489ed08fb881e65ca82240e5d146fd29902,,,extensions/src/main/java/org/pentaho/platform/web/http/api/resources/UserConsoleResource.java,3,java,False,2022-11-08T10:11:03Z "@Override public void init(Context context, WindowManagerFuncs windowManagerFuncs) { mContext = context; mWindowManagerFuncs = windowManagerFuncs; mWindowManagerInternal = LocalServices.getService(WindowManagerInternal.class); mActivityManagerInternal = LocalServices.getService(ActivityManagerInternal.class); mActivityTaskManagerInternal = LocalServices.getService(ActivityTaskManagerInternal.class); mInputManagerInternal = LocalServices.getService(InputManagerInternal.class); mDreamManagerInternal = LocalServices.getService(DreamManagerInternal.class); mPowerManagerInternal = LocalServices.getService(PowerManagerInternal.class); mAppOpsManager = mContext.getSystemService(AppOpsManager.class); mDisplayManager = mContext.getSystemService(DisplayManager.class); mDisplayManagerInternal = LocalServices.getService(DisplayManagerInternal.class); mPackageManager = mContext.getPackageManager(); mHasFeatureWatch = mPackageManager.hasSystemFeature(FEATURE_WATCH); mHasFeatureLeanback = mPackageManager.hasSystemFeature(FEATURE_LEANBACK); mHasFeatureAuto = mPackageManager.hasSystemFeature(FEATURE_AUTOMOTIVE); mHasFeatureHdmiCec = mPackageManager.hasSystemFeature(FEATURE_HDMI_CEC); mAccessibilityShortcutController = new AccessibilityShortcutController(mContext, new Handler(), mCurrentUserId); mLogger = new MetricsLogger(); mScreenOffSleepTokenAcquirer = mActivityTaskManagerInternal .createSleepTokenAcquirer(""ScreenOff""); Resources res = mContext.getResources(); mWakeOnDpadKeyPress = res.getBoolean(com.android.internal.R.bool.config_wakeOnDpadKeyPress); mWakeOnAssistKeyPress = res.getBoolean(com.android.internal.R.bool.config_wakeOnAssistKeyPress); mWakeOnBackKeyPress = res.getBoolean(com.android.internal.R.bool.config_wakeOnBackKeyPress); // Init alert slider mHasAlertSlider = mContext.getResources().getBoolean(R.bool.config_hasAlertSlider) && !TextUtils.isEmpty(mContext.getResources().getString(R.string.alert_slider_state_path)) && !TextUtils.isEmpty(mContext.getResources().getString(R.string.alert_slider_uevent_match_path)); // Init display burn-in protection boolean burnInProtectionEnabled = context.getResources().getBoolean( com.android.internal.R.bool.config_enableBurnInProtection); // Allow a system property to override this. Used by developer settings. boolean burnInProtectionDevMode = SystemProperties.getBoolean(""persist.debug.force_burn_in"", false); if (burnInProtectionEnabled || burnInProtectionDevMode) { final int minHorizontal; final int maxHorizontal; final int minVertical; final int maxVertical; final int maxRadius; if (burnInProtectionDevMode) { minHorizontal = -8; maxHorizontal = 8; minVertical = -8; maxVertical = -4; maxRadius = (isRoundWindow()) ? 6 : -1; } else { Resources resources = context.getResources(); minHorizontal = resources.getInteger( com.android.internal.R.integer.config_burnInProtectionMinHorizontalOffset); maxHorizontal = resources.getInteger( com.android.internal.R.integer.config_burnInProtectionMaxHorizontalOffset); minVertical = resources.getInteger( com.android.internal.R.integer.config_burnInProtectionMinVerticalOffset); maxVertical = resources.getInteger( com.android.internal.R.integer.config_burnInProtectionMaxVerticalOffset); maxRadius = resources.getInteger( com.android.internal.R.integer.config_burnInProtectionMaxRadius); } mBurnInProtectionHelper = new BurnInProtectionHelper( context, minHorizontal, maxHorizontal, minVertical, maxVertical, maxRadius); } mHandler = new PolicyHandler(); mWakeGestureListener = new MyWakeGestureListener(mContext, mHandler); mSettingsObserver = new SettingsObserver(mHandler); mSettingsObserver.observe(); mModifierShortcutManager = new ModifierShortcutManager(context); mUiMode = context.getResources().getInteger( com.android.internal.R.integer.config_defaultUiModeType); mHomeIntent = new Intent(Intent.ACTION_MAIN, null); mHomeIntent.addCategory(Intent.CATEGORY_HOME); mHomeIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_RESET_TASK_IF_NEEDED); mEnableCarDockHomeCapture = context.getResources().getBoolean( com.android.internal.R.bool.config_enableCarDockHomeLaunch); mCarDockIntent = new Intent(Intent.ACTION_MAIN, null); mCarDockIntent.addCategory(Intent.CATEGORY_CAR_DOCK); mCarDockIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_RESET_TASK_IF_NEEDED); mDeskDockIntent = new Intent(Intent.ACTION_MAIN, null); mDeskDockIntent.addCategory(Intent.CATEGORY_DESK_DOCK); mDeskDockIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_RESET_TASK_IF_NEEDED); mVrHeadsetHomeIntent = new Intent(Intent.ACTION_MAIN, null); mVrHeadsetHomeIntent.addCategory(Intent.CATEGORY_VR_HOME); mVrHeadsetHomeIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_RESET_TASK_IF_NEEDED); mPowerManager = (PowerManager)context.getSystemService(Context.POWER_SERVICE); mBroadcastWakeLock = mPowerManager.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, ""PhoneWindowManager.mBroadcastWakeLock""); mPowerKeyWakeLock = mPowerManager.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, ""PhoneWindowManager.mPowerKeyWakeLock""); mEnableShiftMenuBugReports = ""1"".equals(SystemProperties.get(""ro.debuggable"")); mLidKeyboardAccessibility = mContext.getResources().getInteger( com.android.internal.R.integer.config_lidKeyboardAccessibility); mLidNavigationAccessibility = mContext.getResources().getInteger( com.android.internal.R.integer.config_lidNavigationAccessibility); mAllowTheaterModeWakeFromKey = mContext.getResources().getBoolean( com.android.internal.R.bool.config_allowTheaterModeWakeFromKey); mAllowTheaterModeWakeFromPowerKey = mAllowTheaterModeWakeFromKey || mContext.getResources().getBoolean( com.android.internal.R.bool.config_allowTheaterModeWakeFromPowerKey); mAllowTheaterModeWakeFromMotion = mContext.getResources().getBoolean( com.android.internal.R.bool.config_allowTheaterModeWakeFromMotion); mAllowTheaterModeWakeFromMotionWhenNotDreaming = mContext.getResources().getBoolean( com.android.internal.R.bool.config_allowTheaterModeWakeFromMotionWhenNotDreaming); mAllowTheaterModeWakeFromCameraLens = mContext.getResources().getBoolean( com.android.internal.R.bool.config_allowTheaterModeWakeFromCameraLens); mAllowTheaterModeWakeFromLidSwitch = mContext.getResources().getBoolean( com.android.internal.R.bool.config_allowTheaterModeWakeFromLidSwitch); mAllowTheaterModeWakeFromWakeGesture = mContext.getResources().getBoolean( com.android.internal.R.bool.config_allowTheaterModeWakeFromGesture); mGoToSleepOnButtonPressTheaterMode = mContext.getResources().getBoolean( com.android.internal.R.bool.config_goToSleepOnButtonPressTheaterMode); mSupportLongPressPowerWhenNonInteractive = mContext.getResources().getBoolean( com.android.internal.R.bool.config_supportLongPressPowerWhenNonInteractive); mLongPressOnBackBehavior = mContext.getResources().getInteger( com.android.internal.R.integer.config_longPressOnBackBehavior); mShortPressOnPowerBehavior = mContext.getResources().getInteger( com.android.internal.R.integer.config_shortPressOnPowerBehavior); mLongPressOnPowerBehavior = mContext.getResources().getInteger( com.android.internal.R.integer.config_longPressOnPowerBehavior); mLongPressOnPowerAssistantTimeoutMs = mContext.getResources().getInteger( com.android.internal.R.integer.config_longPressOnPowerDurationMs); mVeryLongPressOnPowerBehavior = mContext.getResources().getInteger( com.android.internal.R.integer.config_veryLongPressOnPowerBehavior); mDoublePressOnPowerBehavior = mContext.getResources().getInteger( com.android.internal.R.integer.config_doublePressOnPowerBehavior); mPowerDoublePressTargetActivity = ComponentName.unflattenFromString( mContext.getResources().getString( com.android.internal.R.string.config_doublePressOnPowerTargetActivity)); mTriplePressOnPowerBehavior = mContext.getResources().getInteger( com.android.internal.R.integer.config_triplePressOnPowerBehavior); mShortPressOnSleepBehavior = mContext.getResources().getInteger( com.android.internal.R.integer.config_shortPressOnSleepBehavior); mAllowStartActivityForLongPressOnPowerDuringSetup = mContext.getResources().getBoolean( com.android.internal.R.bool.config_allowStartActivityForLongPressOnPowerInSetup); mHapticTextHandleEnabled = mContext.getResources().getBoolean( com.android.internal.R.bool.config_enableHapticTextHandle); mUseTvRouting = AudioSystem.getPlatformType(mContext) == AudioSystem.PLATFORM_TELEVISION; mHandleVolumeKeysInWM = mContext.getResources().getBoolean( com.android.internal.R.bool.config_handleVolumeKeysInWindowManager); mPerDisplayFocusEnabled = mContext.getResources().getBoolean( com.android.internal.R.bool.config_perDisplayFocusEnabled); mWakeUpToLastStateTimeout = mContext.getResources().getInteger( com.android.internal.R.integer.config_wakeUpToLastStateTimeoutMillis); readConfigurationDependentBehaviors(); mDisplayFoldController = DisplayFoldController.create(context, DEFAULT_DISPLAY); mAccessibilityManager = (AccessibilityManager) context.getSystemService( Context.ACCESSIBILITY_SERVICE); // register for dock events IntentFilter filter = new IntentFilter(); filter.addAction(UiModeManager.ACTION_ENTER_CAR_MODE); filter.addAction(UiModeManager.ACTION_EXIT_CAR_MODE); filter.addAction(UiModeManager.ACTION_ENTER_DESK_MODE); filter.addAction(UiModeManager.ACTION_EXIT_DESK_MODE); filter.addAction(Intent.ACTION_DOCK_EVENT); Intent intent = context.registerReceiver(mDockReceiver, filter); if (intent != null) { // Retrieve current sticky dock event broadcast. mDefaultDisplayPolicy.setDockMode(intent.getIntExtra(Intent.EXTRA_DOCK_STATE, Intent.EXTRA_DOCK_STATE_UNDOCKED)); } // register for dream-related broadcasts filter = new IntentFilter(); filter.addAction(Intent.ACTION_DREAMING_STARTED); filter.addAction(Intent.ACTION_DREAMING_STOPPED); context.registerReceiver(mDreamReceiver, filter); // register for multiuser-relevant broadcasts filter = new IntentFilter(Intent.ACTION_USER_SWITCHED); context.registerReceiver(mMultiuserReceiver, filter); mVibrator = (Vibrator)context.getSystemService(Context.VIBRATOR_SERVICE); mSafeModeEnabledVibePattern = getLongIntArray(mContext.getResources(), com.android.internal.R.array.config_safeModeEnabledVibePattern); mGlobalKeyManager = new GlobalKeyManager(mContext); // Controls rotation and the like. initializeHdmiState(); // Match current screen state. if (!mPowerManager.isInteractive()) { startedGoingToSleep(PowerManager.GO_TO_SLEEP_REASON_TIMEOUT); finishedGoingToSleep(PowerManager.GO_TO_SLEEP_REASON_TIMEOUT); } mWindowManagerInternal.registerAppTransitionListener(new AppTransitionListener() { @Override public int onAppTransitionStartingLocked(boolean keyguardGoingAway, boolean keyguardOccluding, long duration, long statusBarAnimationStartTime, long statusBarAnimationDuration) { // When remote animation is enabled for KEYGUARD_GOING_AWAY transition, SysUI // receives IRemoteAnimationRunner#onAnimationStart to start animation, so we don't // need to call IKeyguardService#keyguardGoingAway here. return handleStartTransitionForKeyguardLw(keyguardGoingAway && !WindowManagerService.sEnableRemoteKeyguardGoingAwayAnimation, keyguardOccluding, duration); } @Override public void onAppTransitionCancelledLocked(boolean keyguardGoingAway) { handleStartTransitionForKeyguardLw( keyguardGoingAway, false /* keyguardOccludingStarted */, 0 /* duration */); } }); mKeyguardDelegate = new KeyguardServiceDelegate(mContext, new StateCallback() { @Override public void onTrustedChanged() { mWindowManagerFuncs.notifyKeyguardTrustedChanged(); } @Override public void onShowingChanged() { mWindowManagerFuncs.onKeyguardShowingAndNotOccludedChanged(); } }); initKeyCombinationRules(); initSingleKeyGestureRules(); mSideFpsEventHandler = new SideFpsEventHandler(mContext, mHandler, mPowerManager); }","@Override public void init(Context context, WindowManagerFuncs windowManagerFuncs) { mContext = context; mWindowManagerFuncs = windowManagerFuncs; mWindowManagerInternal = LocalServices.getService(WindowManagerInternal.class); mActivityManagerInternal = LocalServices.getService(ActivityManagerInternal.class); mActivityTaskManagerInternal = LocalServices.getService(ActivityTaskManagerInternal.class); mInputManagerInternal = LocalServices.getService(InputManagerInternal.class); mDreamManagerInternal = LocalServices.getService(DreamManagerInternal.class); mPowerManagerInternal = LocalServices.getService(PowerManagerInternal.class); mAppOpsManager = mContext.getSystemService(AppOpsManager.class); mDisplayManager = mContext.getSystemService(DisplayManager.class); mDisplayManagerInternal = LocalServices.getService(DisplayManagerInternal.class); mPackageManager = mContext.getPackageManager(); mHasFeatureWatch = mPackageManager.hasSystemFeature(FEATURE_WATCH); mHasFeatureLeanback = mPackageManager.hasSystemFeature(FEATURE_LEANBACK); mHasFeatureAuto = mPackageManager.hasSystemFeature(FEATURE_AUTOMOTIVE); mHasFeatureHdmiCec = mPackageManager.hasSystemFeature(FEATURE_HDMI_CEC); mAccessibilityShortcutController = new AccessibilityShortcutController(mContext, new Handler(), mCurrentUserId); mLogger = new MetricsLogger(); mScreenOffSleepTokenAcquirer = mActivityTaskManagerInternal .createSleepTokenAcquirer(""ScreenOff""); Resources res = mContext.getResources(); mWakeOnDpadKeyPress = res.getBoolean(com.android.internal.R.bool.config_wakeOnDpadKeyPress); mWakeOnAssistKeyPress = res.getBoolean(com.android.internal.R.bool.config_wakeOnAssistKeyPress); mWakeOnBackKeyPress = res.getBoolean(com.android.internal.R.bool.config_wakeOnBackKeyPress); // Init alert slider mHasAlertSlider = mContext.getResources().getBoolean(R.bool.config_hasAlertSlider) && !TextUtils.isEmpty(mContext.getResources().getString(R.string.alert_slider_state_path)) && !TextUtils.isEmpty(mContext.getResources().getString(R.string.alert_slider_uevent_match_path)); // Init display burn-in protection boolean burnInProtectionEnabled = context.getResources().getBoolean( com.android.internal.R.bool.config_enableBurnInProtection); // Allow a system property to override this. Used by developer settings. boolean burnInProtectionDevMode = SystemProperties.getBoolean(""persist.debug.force_burn_in"", false); if (burnInProtectionEnabled || burnInProtectionDevMode) { final int minHorizontal; final int maxHorizontal; final int minVertical; final int maxVertical; final int maxRadius; if (burnInProtectionDevMode) { minHorizontal = -8; maxHorizontal = 8; minVertical = -8; maxVertical = -4; maxRadius = (isRoundWindow()) ? 6 : -1; } else { Resources resources = context.getResources(); minHorizontal = resources.getInteger( com.android.internal.R.integer.config_burnInProtectionMinHorizontalOffset); maxHorizontal = resources.getInteger( com.android.internal.R.integer.config_burnInProtectionMaxHorizontalOffset); minVertical = resources.getInteger( com.android.internal.R.integer.config_burnInProtectionMinVerticalOffset); maxVertical = resources.getInteger( com.android.internal.R.integer.config_burnInProtectionMaxVerticalOffset); maxRadius = resources.getInteger( com.android.internal.R.integer.config_burnInProtectionMaxRadius); } mBurnInProtectionHelper = new BurnInProtectionHelper( context, minHorizontal, maxHorizontal, minVertical, maxVertical, maxRadius); } mHandler = new PolicyHandler(); mWakeGestureListener = new MyWakeGestureListener(mContext, mHandler); mSettingsObserver = new SettingsObserver(mHandler); mSettingsObserver.observe(); mModifierShortcutManager = new ModifierShortcutManager(context); mUiMode = context.getResources().getInteger( com.android.internal.R.integer.config_defaultUiModeType); mHomeIntent = new Intent(Intent.ACTION_MAIN, null); mHomeIntent.addCategory(Intent.CATEGORY_HOME); mHomeIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_RESET_TASK_IF_NEEDED); mEnableCarDockHomeCapture = context.getResources().getBoolean( com.android.internal.R.bool.config_enableCarDockHomeLaunch); mCarDockIntent = new Intent(Intent.ACTION_MAIN, null); mCarDockIntent.addCategory(Intent.CATEGORY_CAR_DOCK); mCarDockIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_RESET_TASK_IF_NEEDED); mDeskDockIntent = new Intent(Intent.ACTION_MAIN, null); mDeskDockIntent.addCategory(Intent.CATEGORY_DESK_DOCK); mDeskDockIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_RESET_TASK_IF_NEEDED); mVrHeadsetHomeIntent = new Intent(Intent.ACTION_MAIN, null); mVrHeadsetHomeIntent.addCategory(Intent.CATEGORY_VR_HOME); mVrHeadsetHomeIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_RESET_TASK_IF_NEEDED); mPowerManager = (PowerManager)context.getSystemService(Context.POWER_SERVICE); mBroadcastWakeLock = mPowerManager.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, ""PhoneWindowManager.mBroadcastWakeLock""); mPowerKeyWakeLock = mPowerManager.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, ""PhoneWindowManager.mPowerKeyWakeLock""); mEnableShiftMenuBugReports = ""1"".equals(SystemProperties.get(""ro.debuggable"")); mLidKeyboardAccessibility = mContext.getResources().getInteger( com.android.internal.R.integer.config_lidKeyboardAccessibility); mLidNavigationAccessibility = mContext.getResources().getInteger( com.android.internal.R.integer.config_lidNavigationAccessibility); mAllowTheaterModeWakeFromKey = mContext.getResources().getBoolean( com.android.internal.R.bool.config_allowTheaterModeWakeFromKey); mAllowTheaterModeWakeFromPowerKey = mAllowTheaterModeWakeFromKey || mContext.getResources().getBoolean( com.android.internal.R.bool.config_allowTheaterModeWakeFromPowerKey); mAllowTheaterModeWakeFromMotion = mContext.getResources().getBoolean( com.android.internal.R.bool.config_allowTheaterModeWakeFromMotion); mAllowTheaterModeWakeFromMotionWhenNotDreaming = mContext.getResources().getBoolean( com.android.internal.R.bool.config_allowTheaterModeWakeFromMotionWhenNotDreaming); mAllowTheaterModeWakeFromCameraLens = mContext.getResources().getBoolean( com.android.internal.R.bool.config_allowTheaterModeWakeFromCameraLens); mAllowTheaterModeWakeFromLidSwitch = mContext.getResources().getBoolean( com.android.internal.R.bool.config_allowTheaterModeWakeFromLidSwitch); mAllowTheaterModeWakeFromWakeGesture = mContext.getResources().getBoolean( com.android.internal.R.bool.config_allowTheaterModeWakeFromGesture); mGoToSleepOnButtonPressTheaterMode = mContext.getResources().getBoolean( com.android.internal.R.bool.config_goToSleepOnButtonPressTheaterMode); mSupportLongPressPowerWhenNonInteractive = mContext.getResources().getBoolean( com.android.internal.R.bool.config_supportLongPressPowerWhenNonInteractive); mLongPressOnBackBehavior = mContext.getResources().getInteger( com.android.internal.R.integer.config_longPressOnBackBehavior); mShortPressOnPowerBehavior = mContext.getResources().getInteger( com.android.internal.R.integer.config_shortPressOnPowerBehavior); mLongPressOnPowerBehavior = mContext.getResources().getInteger( com.android.internal.R.integer.config_longPressOnPowerBehavior); mLongPressOnPowerAssistantTimeoutMs = mContext.getResources().getInteger( com.android.internal.R.integer.config_longPressOnPowerDurationMs); mVeryLongPressOnPowerBehavior = mContext.getResources().getInteger( com.android.internal.R.integer.config_veryLongPressOnPowerBehavior); mDoublePressOnPowerBehavior = mContext.getResources().getInteger( com.android.internal.R.integer.config_doublePressOnPowerBehavior); mPowerDoublePressTargetActivity = ComponentName.unflattenFromString( mContext.getResources().getString( com.android.internal.R.string.config_doublePressOnPowerTargetActivity)); mTriplePressOnPowerBehavior = mContext.getResources().getInteger( com.android.internal.R.integer.config_triplePressOnPowerBehavior); mShortPressOnSleepBehavior = mContext.getResources().getInteger( com.android.internal.R.integer.config_shortPressOnSleepBehavior); mAllowStartActivityForLongPressOnPowerDuringSetup = mContext.getResources().getBoolean( com.android.internal.R.bool.config_allowStartActivityForLongPressOnPowerInSetup); mHapticTextHandleEnabled = mContext.getResources().getBoolean( com.android.internal.R.bool.config_enableHapticTextHandle); mUseTvRouting = AudioSystem.getPlatformType(mContext) == AudioSystem.PLATFORM_TELEVISION; mHandleVolumeKeysInWM = mContext.getResources().getBoolean( com.android.internal.R.bool.config_handleVolumeKeysInWindowManager); mPerDisplayFocusEnabled = mContext.getResources().getBoolean( com.android.internal.R.bool.config_perDisplayFocusEnabled); mWakeUpToLastStateTimeout = mContext.getResources().getInteger( com.android.internal.R.integer.config_wakeUpToLastStateTimeoutMillis); readConfigurationDependentBehaviors(); mDisplayFoldController = DisplayFoldController.create(context, DEFAULT_DISPLAY); mAccessibilityManager = (AccessibilityManager) context.getSystemService( Context.ACCESSIBILITY_SERVICE); // register for dock events IntentFilter filter = new IntentFilter(); filter.addAction(UiModeManager.ACTION_ENTER_CAR_MODE); filter.addAction(UiModeManager.ACTION_EXIT_CAR_MODE); filter.addAction(UiModeManager.ACTION_ENTER_DESK_MODE); filter.addAction(UiModeManager.ACTION_EXIT_DESK_MODE); filter.addAction(Intent.ACTION_DOCK_EVENT); Intent intent = context.registerReceiver(mDockReceiver, filter); if (intent != null) { // Retrieve current sticky dock event broadcast. mDefaultDisplayPolicy.setDockMode(intent.getIntExtra(Intent.EXTRA_DOCK_STATE, Intent.EXTRA_DOCK_STATE_UNDOCKED)); } // register for dream-related broadcasts filter = new IntentFilter(); filter.addAction(Intent.ACTION_DREAMING_STARTED); filter.addAction(Intent.ACTION_DREAMING_STOPPED); context.registerReceiver(mDreamReceiver, filter); // register for multiuser-relevant broadcasts filter = new IntentFilter(Intent.ACTION_USER_SWITCHED); context.registerReceiver(mMultiuserReceiver, filter); mVibrator = (Vibrator)context.getSystemService(Context.VIBRATOR_SERVICE); mSafeModeEnabledVibePattern = getLongIntArray(mContext.getResources(), com.android.internal.R.array.config_safeModeEnabledVibePattern); mGlobalKeyManager = new GlobalKeyManager(mContext); // Controls rotation and the like. initializeHdmiState(); // Match current screen state. if (!mPowerManager.isInteractive()) { startedGoingToSleep(PowerManager.GO_TO_SLEEP_REASON_TIMEOUT); finishedGoingToSleep(PowerManager.GO_TO_SLEEP_REASON_TIMEOUT); } mWindowManagerInternal.registerAppTransitionListener(new AppTransitionListener() { @Override public int onAppTransitionStartingLocked(boolean keyguardGoingAway, boolean keyguardOccluding, long duration, long statusBarAnimationStartTime, long statusBarAnimationDuration) { // When remote animation is enabled for KEYGUARD_GOING_AWAY transition, SysUI // receives IRemoteAnimationRunner#onAnimationStart to start animation, so we don't // need to call IKeyguardService#keyguardGoingAway here. return handleStartTransitionForKeyguardLw(keyguardGoingAway && !WindowManagerService.sEnableRemoteKeyguardGoingAwayAnimation, keyguardOccluding, duration); } @Override public void onAppTransitionCancelledLocked(boolean keyguardGoingAway) { handleStartTransitionForKeyguardLw( keyguardGoingAway, false /* keyguardOccludingStarted */, 0 /* duration */); } }); mKeyguardDelegate = new KeyguardServiceDelegate(mContext, new StateCallback() { @Override public void onTrustedChanged() { mWindowManagerFuncs.notifyKeyguardTrustedChanged(); } @Override public void onShowingChanged() { mWindowManagerFuncs.onKeyguardShowingAndNotOccludedChanged(); } }); final String[] deviceKeyHandlerLibs = res.getStringArray( com.android.internal.R.array.config_deviceKeyHandlerLibs); final String[] deviceKeyHandlerClasses = res.getStringArray( com.android.internal.R.array.config_deviceKeyHandlerClasses); for (int i = 0; i < deviceKeyHandlerLibs.length && i < deviceKeyHandlerClasses.length; i++) { try { PathClassLoader loader = new PathClassLoader( deviceKeyHandlerLibs[i], getClass().getClassLoader()); Class klass = loader.loadClass(deviceKeyHandlerClasses[i]); Constructor constructor = klass.getConstructor(Context.class); mDeviceKeyHandlers.add((DeviceKeyHandler) constructor.newInstance(mContext)); } catch (Exception e) { Slog.w(TAG, ""Could not instantiate device key handler "" + deviceKeyHandlerLibs[i] + "" from class "" + deviceKeyHandlerClasses[i], e); } } if (DEBUG_INPUT) { Slog.d(TAG, """" + mDeviceKeyHandlers.size() + "" device key handlers loaded""); } initKeyCombinationRules(); initSingleKeyGestureRules(); mSideFpsEventHandler = new SideFpsEventHandler(mContext, mHandler, mPowerManager); }","Support for device specific key handlers This is a squash commit of the following changes, only modified for the new SDK. Carbon Edits: get away from SDK Author: Alexander Hofbauer Date: Thu Apr 12 01:24:24 2012 +0200 Dispatch keys to a device specific key handler Injects a device key handler into the input path to handle additional keys (as found on some docks with a hardware keyboard). Configurable via overlay settings config_deviceKeyHandlerLib and config_deviceKeyHandlerClass. Change-Id: I6678c89c7530fdb1d4d516ba4f1d2c9e30ce79a4 Author: Jorge Ruesga Date: Thu Jan 24 02:34:49 2013 +0100 DeviceKeyHandle: The device should consume only known keys When the device receive the key, only should consume it if the device know about the key. Otherwise, the key must be handle by the active app. Also make mDeviceKeyHandler private (is not useful outside this class) Change-Id: I4b9ea57b802e8c8c88c8b93a63d510f5952b0700 Signed-off-by: Jorge Ruesga Author: Danesh Mondegarian Date: Sun Oct 20 00:34:48 2013 -0700 DeviceKeyHandler : Allow handling keyevents while screen off Some devices require the keyevents to be processed while the screen is off, this patchset addresses that by moving the filter up in the call hierarchy. Change-Id: If71beecc81aa5e453dcd08aba72b7bea5c210590 Author: Steve Kondik Date: Sun Sep 11 00:49:41 2016 -0700 policy: Use PathClassLoader for loading the keyhandler * Fix crash on start due to getCacheDir throwing an exception. * We can't do this anymore due to the new storage/crypto in N. Change-Id: I28426a5df824460ebc74aa19068192adb00d4f7c Author: Zhao Wei Liew Date: Sun Nov 20 08:20:15 2016 +0800 PhoneWindowManager: Support multiple key handlers Convert the string overlay to a string-array overlay to allow devices to specify an array of key handlers. Note that the keyhandlers towards the start of the array take precedence when loading. Change-Id: Iaaab737f1501a97d7016d8d519ccf127ca059218 Author: Paul Keith Date: Thu Nov 23 21:47:51 2017 +0100 fw/b: Return a KeyEvent instead of a boolean in KeyHandler * Allows handlers to modify the event before sending it off to another KeyHandler class, to handle things like rotation Change-Id: I481107e050f6323c5897260a5d241e64b4e031ac Change-Id: Ibac1c348717c83fdf9a2894a5d91dc035f9f3a18",https://github.com/AOSPA/android_frameworks_base/commit/4b0cc12ac886bcb55e99aef97f8a0787d88c5874,,,services/core/java/com/android/server/policy/PhoneWindowManager.java,3,java,False,2017-10-11T20:11:49Z "public static void evaluateSiegeWarPlaceBlockRequest(Player player, Block block, TownyBuildEvent event) { final Translator translator = Translator.locale(Translation.getLocale(player)); try { //Ensure siege is enabled in this world if (!TownyAPI.getInstance().getTownyWorld(block.getWorld()).isWarAllowed()) return; //If the event is in a town and was cancelled by towny, SW might un-cancel the event via wall breaching if(event.isCancelled() && SiegeWarSettings.isWallBreachingEnabled() && !TownyAPI.getInstance().isWilderness(block)) { Town town = TownyAPI.getInstance().getTown(block.getLocation()); if(!SiegeController.hasActiveSiege(town)) return; //SW doesn't un-cancel events in unsieged towns //Ensure player has permission if (!TownyUniverse.getInstance().getPermissionSource().testPermission(event.getPlayer(), SiegeWarPermissionNodes.SIEGEWAR_NATION_SIEGE_USE_BREACH_POINTS.getNode())) { event.setMessage(translator.of(""msg_err_action_disable"")); return; } //No wall breaching outside battle sessions if(!BattleSession.getBattleSession().isActive()) { event.setMessage(translator.of(""msg_err_cannot_breach_without_battle_session"")); return; } //Ensure player is on the town-hostile siege side Resident resident = TownyAPI.getInstance().getResident(event.getPlayer()); if(resident == null) return; Siege siege = SiegeController.getSiege(town); if(!SiegeWarAllegianceUtil.isPlayerOnTownHostileSide(event.getPlayer(), resident, siege)) return; //Ensure there are enough breach points if(siege.getWallBreachPoints() < SiegeWarSettings.getWallBreachingBlockPlacementCost()) { event.setMessage(translator.of(""msg_err_not_enough_breach_points_for_action"", SiegeWarSettings.getWallBreachingBlockPlacementCost(), siege.getFormattedBreachPoints())); return; } //Ensure height is ok if(!SiegeWarWallBreachUtil.validateBreachHeight(block, town, siege)) { event.setMessage(translator.of(""msg_err_cannot_breach_at_this_height"", SiegeWarSettings.getWallBreachingHomeblockBreachHeightLimitMin(), SiegeWarSettings.getWallBreachingHomeblockBreachHeightLimitMax())); return; } //Ensure the material is ok to place if(!SiegeWarSettings.getWallBreachingPlaceBlocksWhitelist() .contains(block.getType())) { event.setMessage(translator.of(""msg_err_breaching_cannot_place_this_material"")); return; } //IF we get here, it is a wall breach!! //Reduce breach points siege.setWallBreachPoints(siege.getWallBreachPoints() - SiegeWarSettings.getWallBreachingBlockPlacementCost()); //Un-cancel the event event.setCancelled(false); //Send message to player event.getPlayer().spigot().sendMessage(ChatMessageType.ACTION_BAR, new TextComponent(ChatColor.RED + translator.of(""msg_wall_breach_successful""))); return; } //Enforce Anti-Trap warfare build block if below siege banner altitude. if (SiegeWarSettings.isTrapWarfareMitigationEnabled() && SiegeWarDistanceUtil.isLocationInActiveTimedPointZoneAndBelowSiegeBannerAltitude(event.getBlock().getLocation())) { event.getPlayer().spigot().sendMessage(ChatMessageType.ACTION_BAR, new TextComponent(ChatColor.DARK_RED + translator.of(""msg_err_cannot_alter_blocks_below_banner_in_timed_point_zone""))); event.setCancelled(true); return; } Material mat = block.getType(); //Standing Banner placement if (Tag.BANNERS.isTagged(mat) && !mat.toString().contains(""_W"")) { try { if (evaluatePlaceStandingBanner(player, block)) event.setCancelled(false); } catch (TownyException e1) { Messaging.sendErrorMsg(player, e1.getMessage()); } return; } //Chest placement if (mat == Material.CHEST || mat == Material.TRAPPED_CHEST) { try { evaluatePlaceChest(player, block); } catch (TownyException e) { Messaging.sendErrorMsg(player, e.getMessage()); } return; } //Check for forbidden siegezone block placement if(SiegeWarSettings.getSiegeZoneWildernessForbiddenBlockMaterials().contains(mat) && TownyAPI.getInstance().isWilderness(block) && SiegeWarDistanceUtil.isLocationInActiveSiegeZone(block.getLocation())) { throw new TownyException(translator.of(""msg_war_siege_zone_block_placement_forbidden"")); } } catch (TownyException e) { event.setCancelled(true); event.setMessage(e.getMessage()); } }","public static void evaluateSiegeWarPlaceBlockRequest(Player player, Block block, TownyBuildEvent event) { final Translator translator = Translator.locale(Translation.getLocale(player)); try { //Ensure siege is enabled in this world if (!TownyAPI.getInstance().getTownyWorld(block.getWorld()).isWarAllowed()) return; if(event.isCancelled()) { //If the event is in a town and was cancelled by towny, SW might un-cancel the event via wall breaching if(SiegeWarSettings.isWallBreachingEnabled() && evaluateWallBreach(translator, block, event)) return; //If block glitching prevention is enabled, SW will ensure the player cannot block glitch. if(SiegeWarSettings.isBlockGlitchingPreventionEnabled()) { SiegeWarBlockUtil.applyBlockGlitchingPrevention(player); } return; } //Enforce Anti-Trap warfare build block if below siege banner altitude. if (SiegeWarSettings.isTrapWarfareMitigationEnabled() && SiegeWarDistanceUtil.isLocationInActiveTimedPointZoneAndBelowSiegeBannerAltitude(event.getBlock().getLocation())) { event.getPlayer().spigot().sendMessage(ChatMessageType.ACTION_BAR, new TextComponent(ChatColor.DARK_RED + translator.of(""msg_err_cannot_alter_blocks_below_banner_in_timed_point_zone""))); event.setCancelled(true); return; } Material mat = block.getType(); //Standing Banner placement if (Tag.BANNERS.isTagged(mat) && !mat.toString().contains(""_W"")) { try { if (evaluatePlaceStandingBanner(player, block)) event.setCancelled(false); } catch (TownyException e1) { Messaging.sendErrorMsg(player, e1.getMessage()); } return; } //Chest placement if (mat == Material.CHEST || mat == Material.TRAPPED_CHEST) { try { evaluatePlaceChest(player, block); } catch (TownyException e) { Messaging.sendErrorMsg(player, e.getMessage()); } return; } //Check for forbidden siegezone block placement if(SiegeWarSettings.getSiegeZoneWildernessForbiddenBlockMaterials().contains(mat) && TownyAPI.getInstance().isWilderness(block) && SiegeWarDistanceUtil.isLocationInActiveSiegeZone(block.getLocation())) { throw new TownyException(translator.of(""msg_war_siege_zone_block_placement_forbidden"")); } } catch (TownyException e) { event.setCancelled(true); event.setMessage(e.getMessage()); } }","Anti-Block-Glitching (#508) * Added prevention for 2 block glitching types: Fast-break bypassing of walls/doors, and pillaring * pom update 0.7.12 authored-by: goosius1 <=>",https://github.com/TownyAdvanced/SiegeWar/commit/a235afcddcd9d8bf4d7b9adc084969ccc6748719,,,src/main/java/com/gmail/goosius/siegewar/playeractions/PlaceBlock.java,3,java,False,2022-03-25T16:31:57Z "@SafeVarargs public static void tellBungee(String channel, BungeeAction action, T... datas) { Valid.checkBoolean(datas.length == action.getContent().length, ""Data count != valid values count in "" + action + ""! Given data: "" + datas.length + "" vs needed: "" + action.getContent().length); Valid.checkBoolean(Remain.isServerNameChanged(), ""Please configure your 'server-name' in server.properties according to mineacademy.org/server-properties first before using BungeeCord features""); Debugger.put(""bungee"", ""Server '"" + Remain.getServerName() + ""' sent bungee message ["" + channel + "", "" + action + ""]: ""); final Player recipient = getThroughWhomSendMessage(); // This server is empty, do not send if (recipient == null) { Debugger.put(""bungee"", ""Cannot send "" + action + "" bungee channel '"" + channel + ""' message because this server has no players""); return; } final ByteArrayDataOutput out = ByteStreams.newDataOutput(); out.writeUTF(recipient.getUniqueId().toString()); out.writeUTF(Remain.getServerName()); out.writeUTF(action.toString()); int actionHead = 0; for (Object data : datas) { try { Valid.checkNotNull(data, ""Bungee object in array is null! Array: "" + Common.join(datas, "", "", (Stringer) t -> t == null ? ""null"" : t.toString() + "" ("" + t.getClass().getSimpleName() + "")"")); if (data instanceof CommandSender) data = ((CommandSender) data).getName(); if (data instanceof Integer) { Debugger.put(""bungee"", data.toString() + "", ""); moveHead(actionHead, action, Integer.class, datas); out.writeInt((Integer) data); } else if (data instanceof Double) { Debugger.put(""bungee"", data.toString() + "", ""); moveHead(actionHead, action, Double.class, datas); out.writeDouble((Double) data); } else if (data instanceof Long) { Debugger.put(""bungee"", data.toString() + "", ""); moveHead(actionHead, action, Long.class, datas); out.writeLong((Long) data); } else if (data instanceof Boolean) { Debugger.put(""bungee"", data.toString() + "", ""); moveHead(actionHead, action, Boolean.class, datas); out.writeBoolean((Boolean) data); } else if (data instanceof String) { Debugger.put(""bungee"", data.toString() + "", ""); moveHead(actionHead, action, String.class, datas); out.writeUTF((String) data); } else if (data instanceof SerializedMap) { Debugger.put(""bungee"", data.toString() + "", ""); moveHead(actionHead, action, String.class, datas); out.writeUTF(((SerializedMap) data).toJson()); } else if (data instanceof UUID) { Debugger.put(""bungee"", data.toString() + "", ""); moveHead(actionHead, action, UUID.class, datas); out.writeUTF(((UUID) data).toString()); } else if (data instanceof Enum) { Debugger.put(""bungee"", data.toString() + "", ""); moveHead(actionHead, action, Enum.class, datas); out.writeUTF(((Enum) data).toString()); } else if (data instanceof byte[]) { Debugger.put(""bungee"", data.toString() + "", ""); moveHead(actionHead, action, String.class, datas); out.write((byte[]) data); } else throw new FoException(""Unknown type of data: "" + data + "" ("" + data.getClass().getSimpleName() + "")""); actionHead++; } catch (final Throwable t) { t.printStackTrace(); return; } } Debugger.push(""bungee""); recipient.sendPluginMessage(SimplePlugin.getInstance(), channel, out.toByteArray()); actionHead = 0; }","@SafeVarargs public static void tellBungee(String channel, BungeeAction action, T... datas) { Valid.checkBoolean(datas.length == action.getContent().length, ""Data count != valid values count in "" + action + ""! Given data: "" + datas.length + "" vs needed: "" + action.getContent().length); Valid.checkBoolean(Remain.isServerNameChanged(), ""Please configure your 'server-name' in server.properties according to mineacademy.org/server-properties first before using BungeeCord features""); Debugger.put(""bungee"", ""Server '"" + Remain.getServerName() + ""' sent bungee message ["" + channel + "", "" + action + ""]: ""); final Player recipient = getThroughWhomSendMessage(); // This server is empty, do not send if (recipient == null) { Debugger.put(""bungee"", ""Cannot send "" + action + "" bungee channel '"" + channel + ""' message because this server has no players""); return; } final ByteArrayDataOutput out = ByteStreams.newDataOutput(); out.writeUTF(recipient.getUniqueId().toString()); out.writeUTF(Remain.getServerName()); out.writeUTF(action.toString()); int actionHead = 0; for (Object data : datas) { try { Valid.checkNotNull(data, ""Bungee object in array is null! Array: "" + Common.join(datas, "", "", (Stringer) t -> t == null ? ""null"" : t.toString() + "" ("" + t.getClass().getSimpleName() + "")"")); if (data instanceof CommandSender) data = ((CommandSender) data).getName(); if (data instanceof Integer) { Debugger.put(""bungee"", data.toString() + "", ""); moveHead(actionHead, action, Integer.class, datas); out.writeInt((Integer) data); } else if (data instanceof Double) { Debugger.put(""bungee"", data.toString() + "", ""); moveHead(actionHead, action, Double.class, datas); out.writeDouble((Double) data); } else if (data instanceof Long) { Debugger.put(""bungee"", data.toString() + "", ""); moveHead(actionHead, action, Long.class, datas); out.writeLong((Long) data); } else if (data instanceof Boolean) { Debugger.put(""bungee"", data.toString() + "", ""); moveHead(actionHead, action, Boolean.class, datas); out.writeBoolean((Boolean) data); } else if (data instanceof String) { Debugger.put(""bungee"", data.toString() + "", ""); moveHead(actionHead, action, String.class, datas); out.writeUTF((String) data); } else if (data instanceof SerializedMap) { Debugger.put(""bungee"", data.toString() + "", ""); moveHead(actionHead, action, String.class, datas); out.writeUTF(((SerializedMap) data).toJson()); } else if (data instanceof UUID) { Debugger.put(""bungee"", data.toString() + "", ""); moveHead(actionHead, action, UUID.class, datas); out.writeUTF(((UUID) data).toString()); } else if (data instanceof Enum) { Debugger.put(""bungee"", data.toString() + "", ""); moveHead(actionHead, action, Enum.class, datas); out.writeUTF(((Enum) data).toString()); } else if (data instanceof byte[]) { Debugger.put(""bungee"", data.toString() + "", ""); moveHead(actionHead, action, String.class, datas); out.write((byte[]) data); } else throw new FoException(""Unknown type of data: "" + data + "" ("" + data.getClass().getSimpleName() + "")""); actionHead++; } catch (final Throwable t) { t.printStackTrace(); return; } } Debugger.push(""bungee""); byte[] byteArray = out.toByteArray(); try { recipient.sendPluginMessage(SimplePlugin.getInstance(), channel, byteArray); } catch (MessageTooLargeException ex) { Common.log(""Outgoing bungee message '"" + action + ""' was oversized, not sending. Max length: 32766 bytes, got "" + byteArray.length + "" bytes.""); } actionHead = 0; }",Prevent oversized bungee packets from crashing,https://github.com/kangarko/Foundation/commit/32edd990276dd4d30a3b26fb5ce467a47b833fc1,,,src/main/java/org/mineacademy/fo/BungeeUtil.java,3,java,False,2021-04-30T15:24:45Z "@GetMapping(""list"") public R> pagination( @RequestParam(value = ""sortField"", defaultValue = ""id"") String sortField, @RequestParam(value = ""sortBy"", defaultValue = ""desc"") String sortBy, @RequestParam(""environmentId"") Long environmentId, @RequestParam(value = ""pageNo"", defaultValue = ""1"") Integer pageNo, @RequestParam(value = ""pageSize"", defaultValue = ""20"") Integer pageSize, @LoginUser User user ) { if (user == null) { return R.error(NON_LOGIN_STATUS, NON_LOGIN_MSG); } if (null == environmentId || environmentId <= 0) { return R.error(VERSION_ID_NOT_EXISTS_STATUS, VERSION_ID_NOT_EXISTS_MSG); } Environment environment = environmentService.selectByPrimaryKey(environmentId); if (environment == null || Deleted.DELETE.getValue().equals(environment.getDeleted())) { return R.error(ENVIRONMENT_NOT_EXISTS_STATUS, ENVIRONMENT_NOT_EXISTS_MSG); } int offset = (pageNo - 1) * pageSize; Pagination pagination = versionService.pagination(VersionExample.newBuilder() .orderByClause(MetaVersion.getSafeColumnNameByField(sortField) + "" "" + sortBy, isNotBlank(sortField)) .start(offset) .limit(pageSize) .build() .createCriteria() .andEnvironmentIdEqualTo(environmentId) .andDeletedEqualTo(Deleted.OK.getValue()) .toExample(), item -> { VersionVo versionVo = new VersionVo(); versionVo.setId(item.getId()); versionVo.setName(item.getName()); versionVo.setMemo(item.getMemo()); versionVo.setEnvironmentId(item.getEnvironmentId()); return versionVo; } ); // 权限 Map ext = new HashMap<>(); boolean canManage = projectUserService.checkAuth(environment.getProductId(), environment.getProjectId(), user); ext.put(""canManage"", canManage); return R.ok(pagination, ext); }","@GetMapping(""list"") public R> pagination( @RequestParam(value = ""sortField"", defaultValue = ""id"") String sortField, @RequestParam(value = ""sortBy"", defaultValue = ""desc"") String sortBy, @RequestParam(""environmentId"") Long environmentId, @RequestParam(value = ""pageNo"", defaultValue = ""1"") Integer pageNo, @RequestParam(value = ""pageSize"", defaultValue = ""20"") Integer pageSize, @LoginUser User user ) { if (user == null) { return R.error(NON_LOGIN_STATUS, NON_LOGIN_MSG); } if (null == environmentId || environmentId <= 0) { return R.error(VERSION_ID_NOT_EXISTS_STATUS, VERSION_ID_NOT_EXISTS_MSG); } Environment environment = environmentService.selectByPrimaryKey(environmentId); if (environment == null || Deleted.DELETE.getValue().equals(environment.getDeleted())) { return R.error(ENVIRONMENT_NOT_EXISTS_STATUS, ENVIRONMENT_NOT_EXISTS_MSG); } int offset = (pageNo - 1) * pageSize; Pagination pagination = versionService.pagination(VersionExample.newBuilder() .orderByClause(MetaVersion.getSafeColumnNameByField(sortField) + "" "" + sortBy, isNotBlank(sortField)) .start(offset) .limit(pageSize) .build() .createCriteria() .andEnvironmentIdEqualTo(environmentId) .andDeletedEqualTo(Deleted.OK.getValue()) .toExample(), item -> { VersionVo versionVo = new VersionVo(); versionVo.setId(item.getId()); versionVo.setName(item.getName()); versionVo.setMemo(item.getMemo()); versionVo.setEnvironmentId(item.getEnvironmentId()); return versionVo; } ); // 权限 Map ext = new HashMap<>(); boolean canManage = environmentUserService .checkAuth(environment.getProductId(), environment.getProjectId(), environmentId, user); ext.put(""canManage"", canManage); return R.ok(pagination, ext); }",fix auth bug,https://github.com/baidu/brcc/commit/cfc885fb0211ebb170a434b89c9dc931f608932f,,,brcc-console/src/main/java/com/baidu/brcc/controller/VersionController.java,3,java,False,2021-05-17T07:44:22Z "@Packet public void onFlying(WrappedInFlyingPacket packet, long now) { long delta = now - lastFlying; long before = totalTimer; totalTimer+= 50; totalTimer-= lastFlying == 0 ? 50 : delta; long increase = totalTimer - before; averageIncrease.add(increase); double avgIncrease = averageIncrease.getAverage(); if(totalTimer > 100) { vl++; flag(""t=%s aInc=%.1f"", totalTimer, avgIncrease); totalTimer = 0; } debug(""delta=%sms total=%s inc=%s avgInc=%.1f"", delta, totalTimer, increase, avgIncrease); lastFlying = now; }","@Packet public void onFlying(WrappedInFlyingPacket packet, long now) { long delta = now - lastFlying; long before = totalTimer; totalTimer+= 50; totalTimer-= lastFlying == 0 ? 50 : delta; long increase = totalTimer - before; averageIncrease.add(increase); double avgIncrease = averageIncrease.getAverage(); totalTimer = Math.max(totalTimer, -1000); if(totalTimer > 150) { vl++; flag(""t=%s aInc=%.1f"", totalTimer, avgIncrease); totalTimer = 0; } debug(""delta=%sms total=%s inc=%s avgInc=%.1f"", delta, totalTimer, increase, avgIncrease); lastFlying = now; }",Update AimE.java,https://github.com/funkemunky/Kauri/commit/5b1d3be4df6cc73cf956432ba680ab92ecec73af,,,Regular/src/main/java/dev/brighten/anticheat/check/impl/packets/TimerB.java,3,java,False,2021-05-31T16:00:45Z "public static IPetsPlugin getPlugin() { return PLUGIN; }","public static IPetsPlugin getPlugin() { // Uhhh ohhh... someone shaded it in if ((PLUGIN == null) // If this is true then it means an error occurred or it is shaded || (!SimplePets.class.getPackage().getName().startsWith(""simplepets.brainsynder.api.plugin""))) { // Someone relocated the api in their shaded jar PluginDescriptionFile pdf = getCause(); String baseMessage = ""The SimplePets API was shaded into another plugin when it shouldn't be ""; // Pardon the mess... I threw this together and didn't feel like cleaning it up // since it will only be used for when another plugin shades the API if (pdf != null) { baseMessage += ""(plugin: ""+pdf.getName(); StringBuilder builder = new StringBuilder(); pdf.getAuthors().forEach(author -> builder.append(author).append("", "")); if (builder.length() != 0) { baseMessage += "" - by: "" + AdvString.replaceLast("", "", """", builder.toString()) + "")""; }else{ baseMessage += "")""; } } else { baseMessage += ""(Unable to pinpoint what plugin)""; } throw new SecurityException (baseMessage); } return PLUGIN; }",Fix end portal crash for Paper,https://github.com/brainsynder-Dev/SimplePets/commit/1916f9f6509d926801e5b4405ab934dad067c516,,,API/src/main/java/simplepets/brainsynder/api/plugin/SimplePets.java,3,java,False,2021-09-24T21:44:12Z "@Override protected AbstractFtpDoorV1 createInterpreter() { SSLEngine engine = sslContext.newEngine(ByteBufAllocator.DEFAULT); engine.setNeedClientAuth(false); /* REVISIT: with FTPS, it is possible for a client to send an X.509 * credential as part of the TLS handshake. Seemingly most FTPS clients * do not support this option (but curl is an example of a client that * does). Therefore, the code currently does not support X.509 based * authentication. */ engine.setWantClientAuth(false); return new TlsFtpDoor(engine, allowUsernamePassword, anonUser, anonymousRoot, requireAnonEmailPassword); }","@Override protected AbstractFtpDoorV1 createInterpreter() { SSLEngine engine = sslContext.createSSLEngine(); engine.setNeedClientAuth(false); /* REVISIT: with FTPS, it is possible for a client to send an X.509 * credential as part of the TLS handshake. Seemingly most FTPS clients * do not support this option (but curl is an example of a client that * does). Therefore, the code currently does not support X.509 based * authentication. */ engine.setWantClientAuth(false); return new TlsFtpDoor(engine, allowUsernamePassword, anonUser, anonymousRoot, requireAnonEmailPassword); }","common-security: revert GSI/FTP to Java SSL Motivation: https://github.com/dCache/dcache/issues/6195 ddd6c88 = https://rb.dcache.org/r/13044 introduced (7.2 only) the option of switching between the Java and OpenSSL SSL contexts/engines where possible. The changes affected LocationManager, GFTP, HTTPS and Xroot. While it was not possible to apply the changes everywhere, the switch was made for GFTP, HTTPS and Xroot doors. Now, for the latter two, a Netty pipeline is used, and the SSLHandler is added to it. The GFTP door uses a ""Line based"" Netty-based interpreter, and it is not immediately obvious how to wrap the engine in a handler and add it to the pipeline there. Unfortunately, I did not realize that simply contructing the engine without wrapping it in the SSLHandler and adding it to the pipeline meant that the necessary RELEASE would never be called, leaking native memory. It is this mistake which I believe indeed is wreaking havoc with our GFTP doors. Modification: The two classes ``` modules/dcache-ftp/src/main/java/org/dcache/ftp/door/TlsFtpInterpreterFactory.java modules/common-security/src/main/java/org/dcache/dss/ServerGsiEngineDssContextFactory.java ``` where this mistake was made have been reverted to used the Java SSLContext. This is the most immediate solution until we figure out (if that is even warranted) how to convert GFTP to OpenSSL. Result: Hopefully the memory leak causing OOM and other issues will thereby be resolved. Target: master Request: 7.2 Requires-notes: yes Requires-book: no Patch: https://rb.dcache.org/r/13247/ Acked-by: Paul Closes: #6195",https://github.com/dCache/dcache/commit/57c277aebda2b20bc1f27cc8a37ece0741f32dda,,,modules/dcache-ftp/src/main/java/org/dcache/ftp/door/TlsFtpInterpreterFactory.java,3,java,False,2021-11-04T14:42:10Z "private KeysetHandle.Entry entryByIndex(int i) { Keyset.Key protoKey = keyset.getKey(i); int id = protoKey.getKeyId(); ProtoKeySerialization protoKeySerialization = toProtoKeySerialization(protoKey); Key key = MutableSerializationRegistry.globalInstance() .parseKeyWithLegacyFallback(protoKeySerialization, InsecureSecretKeyAccess.get()); try { return new KeysetHandle.Entry( key, parseStatus(protoKey.getStatus()), id, id == keyset.getPrimaryKeyId()); } catch (GeneralSecurityException e) { // This may happen if a keyset without status makes it here; we should reject // such keysets earlier instead. throw new IllegalStateException(""Creating an entry failed"", e); } }","private KeysetHandle.Entry entryByIndex(int i) { Keyset.Key protoKey = keyset.getKey(i); int id = protoKey.getKeyId(); ProtoKeySerialization protoKeySerialization = toProtoKeySerialization(protoKey); try { Key key = MutableSerializationRegistry.globalInstance() .parseKeyWithLegacyFallback(protoKeySerialization, InsecureSecretKeyAccess.get()); return new KeysetHandle.Entry( key, parseStatus(protoKey.getStatus()), id, id == keyset.getPrimaryKeyId()); } catch (GeneralSecurityException e) { // This may happen if a keyset without status makes it here; or if a key has a parser // registered but parsing fails. We should reject such keysets earlier instead. throw new IllegalStateException(""Creating an entry failed"", e); } }","Let parseKeyWithLegacyFallback only fall back to LegacyProtoKey when no parser exists. When a parser exists and parsing fails, the function should raise a GeneralSecurityException. KeysetHandle currently contains unparsed keys that can be invalid and parses them when the user tries to access them using getAt(). Before this change, that function would return a LegacyProtoKey that contains the unparsed, invalid key. This behaviour is unexpected and should be changed. The only reasonable behavior is to raise an exception. But raising a checked exception is not possible, because it would break the API. So we have to convert the exception into an unchecked exception. Note that eventually we want this error to be raised earlier when the keyset handle is constructed, in which case we can raise this as a checked exception. This change may break users that currently have unparsable keys in their keyset and use getAt. But such keysets are unusable anyways, producing a primitive will always throw an exception. And Tink doesn't allow the user to generate such keysets. So I don't think there is a big risk in breaking anybody. PiperOrigin-RevId: 484271577",https://github.com/tink-crypto/tink/commit/cd76db8b7d2ae02ba59205f8367258aec7114c5a,,,java_src/src/main/java/com/google/crypto/tink/KeysetHandle.java,3,java,False,2022-10-27T16:19:28Z "@Override public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) { if (cause instanceof AuthenticationFailedException) { ctx.channel().writeAndFlush(JvmmResponse.create() .setStatus(GlobalStatus.JVMM_STATUS_AUTHENTICATION_FAILED.name()) .setMessage(""Authentication failed."") .serialize()); ctx.close(); logger().debug(""Channel closed by auth failed""); } else if (cause instanceof InvalidMsgException) { logger().error(""Invalid message verify, seed: {}, ip: {}"", ((InvalidMsgException) cause).getSeed(), JvmmConnector.getIpByCtx(ctx)); ctx.close(); logger().debug(""Channel closed by message verify""); } else if (cause instanceof IOException) { logger().debug(cause.toString()); } else if (cause instanceof TooLongFrameException) { logger().warn(""{} | {}"", cause.getMessage(), JvmmConnector.getIpByCtx(ctx)); ctx.close(); } else { logger().error(cause.toString(), cause); } }","@Override public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) { if (cause instanceof InvalidMsgException) { logger().error(""Invalid message verify, seed: {}, ip: {}"", ((InvalidMsgException) cause).getSeed(), JvmmConnector.getIpByCtx(ctx)); ctx.close(); logger().debug(""Channel closed by message verify""); } else if (cause instanceof IOException) { logger().debug(cause.toString()); } else if (cause instanceof TooLongFrameException) { logger().warn(""{} | {}"", cause.getMessage(), JvmmConnector.getIpByCtx(ctx)); ctx.close(); } else { logger().error(cause.toString(), cause); } }",fix security auth,https://github.com/tzfun/jvmm/commit/b4f42504c49ea4135a72dd749b271c362074ce28,,,convey/src/main/java/org/beifengtz/jvmm/convey/handler/JvmmChannelHandler.java,3,java,False,2021-12-14T15:52:06Z "protected byte[] perform(byte[] input) throws Exception { DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance(); dbf.setNamespaceAware(true); dbf.setExpandEntityReferences(false); Document doc = dbf.newDocumentBuilder().parse(new ByteArrayInputStream(input)); this.createSignature(doc); DOMSource source = new DOMSource(doc); ByteArrayOutputStream bos = new ByteArrayOutputStream(); StreamResult result = new StreamResult(bos); TransformerFactory transformerFactory = TransformerFactory.newInstance(); Transformer transformer = transformerFactory.newTransformer(); transformer.transform(source, result); return bos.toByteArray(); }","protected byte[] perform(byte[] input) throws Exception { DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance(); dbf.setNamespaceAware(true); dbf.setXIncludeAware(false); dbf.setExpandEntityReferences(false); Document doc = dbf.newDocumentBuilder().parse(new ByteArrayInputStream(input)); this.createSignature(doc); DOMSource source = new DOMSource(doc); ByteArrayOutputStream bos = new ByteArrayOutputStream(); StreamResult result = new StreamResult(bos); TransformerFactory transformerFactory = TransformerFactory.newInstance(); Transformer transformer = transformerFactory.newTransformer(); transformer.transform(source, result); return bos.toByteArray(); }",Disable External Entity Parsing also in XMLMultiSignature,https://github.com/usdAG/cstc/commit/ef98ebdb9a255c93db49ee45ecfd397a938de313,,,src/main/java/de/usd/cstchef/operations/signature/XmlFullSignature.java,3,java,False,2023-02-14T14:42:55Z "@SuppressLint(""SetJavaScriptEnabled"") @Override public View onCreateView( final LayoutInflater inflater, final ViewGroup container, final Bundle savedInstanceState) { mActivity = (BaseActivity)getActivity(); CookieSyncManager.createInstance(mActivity); outer = (FrameLayout)inflater.inflate(R.layout.web_view_fragment, null); final RedditPost srcPost = getArguments().getParcelable(""post""); final RedditPreparedPost post; if(srcPost != null) { final RedditParsedPost parsedPost = new RedditParsedPost( mActivity, srcPost, false); post = new RedditPreparedPost( mActivity, CacheManager.getInstance(mActivity), 0, parsedPost, -1, false, false, false, false); } else { post = null; } webView = outer.findViewById(R.id.web_view_fragment_webviewfixed); final FrameLayout loadingViewFrame = outer.findViewById(R.id.web_view_fragment_loadingview_frame); progressView = new ProgressBar( mActivity, null, android.R.attr.progressBarStyleHorizontal); loadingViewFrame.addView(progressView); loadingViewFrame.setPadding( General.dpToPixels(mActivity, 10), 0, General.dpToPixels(mActivity, 10), 0); final FrameLayout fullscreenViewFrame = outer.findViewById(R.id.web_view_fragment_fullscreen_frame); final VideoEnabledWebChromeClient chromeClient = new VideoEnabledWebChromeClient( loadingViewFrame, fullscreenViewFrame) { @Override public void onProgressChanged(final WebView view, final int newProgress) { super.onProgressChanged(view, newProgress); AndroidCommon.UI_THREAD_HANDLER.post(() -> { progressView.setProgress(newProgress); progressView.setVisibility(newProgress == 100 ? View.GONE : View.VISIBLE); }); } }; chromeClient.setOnToggledFullscreen(fullscreen -> { // Your code to handle the full-screen change, for example showing // and hiding the title bar. Example: if(fullscreen) { final WindowManager.LayoutParams attrs = mActivity.getWindow() .getAttributes(); attrs.flags |= WindowManager.LayoutParams.FLAG_FULLSCREEN; attrs.flags |= WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON; mActivity.getWindow().setAttributes(attrs); mActivity.getSupportActionBar().hide(); if(Build.VERSION.SDK_INT >= 14) { //noinspection all mActivity.getWindow() .getDecorView() .setSystemUiVisibility(View.SYSTEM_UI_FLAG_LOW_PROFILE); } } else { final WindowManager.LayoutParams attrs = mActivity.getWindow() .getAttributes(); //only re-enable status bar if there is no contradicting preference set if(PrefsUtility.pref_appearance_android_status() == PrefsUtility.AppearanceStatusBarMode.NEVER_HIDE) { attrs.flags &= ~WindowManager.LayoutParams.FLAG_FULLSCREEN; } attrs.flags &= ~WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON; mActivity.getWindow().setAttributes(attrs); mActivity.getSupportActionBar().show(); if(Build.VERSION.SDK_INT >= 14) { //noinspection all mActivity.getWindow() .getDecorView() .setSystemUiVisibility(View.SYSTEM_UI_FLAG_VISIBLE); } } }); /*handle download links show an alert box to load this outside the internal browser*/ webView.setDownloadListener((url, userAgent, contentDisposition, mimetype, contentLength) -> new AlertDialog.Builder(mActivity) .setTitle(R.string.download_link_title) .setMessage(R.string.download_link_message) .setPositiveButton( android.R.string.yes, (dialog, which) -> { final Intent i = new Intent(Intent.ACTION_VIEW); i.setData(Uri.parse(url)); try { getContext().startActivity(i); mActivity.onBackPressed(); //get back from internal browser } catch(final ActivityNotFoundException e) { General.quickToast( getContext(), R.string.action_not_handled_by_installed_app_toast); } }) .setNegativeButton( android.R.string.no, (dialog, which) -> { mActivity.onBackPressed(); //get back from internal browser }) .setIcon(android.R.drawable.ic_dialog_alert) .show()); /*handle download links end*/ final WebSettings settings = webView.getSettings(); settings.setBuiltInZoomControls(true); settings.setJavaScriptEnabled(true); settings.setJavaScriptCanOpenWindowsAutomatically(false); settings.setUseWideViewPort(true); settings.setLoadWithOverviewMode(true); settings.setDomStorageEnabled(true); settings.setDisplayZoomControls(false); // TODO handle long clicks webView.setWebChromeClient(chromeClient); if(mUrl != null) { webView.loadUrl(mUrl); } else { webView.loadHtmlUTF8WithBaseURL(""https://reddit.com/"", html); } webView.setWebViewClient(new WebViewClient() { @Override public boolean shouldOverrideUrlLoading( final WebView view, final String url) { if(url == null) { return false; } if(url.startsWith(""data:"")) { // Prevent imgur bug where we're directed to some random data URI return true; } // Go back if loading same page to prevent redirect loops. if(goingBack && currentUrl != null && url.equals(currentUrl)) { General.quickToast(mActivity, String.format( Locale.US, ""Handling redirect loop (level %d)"", -lastBackDepthAttempt), Toast.LENGTH_SHORT); lastBackDepthAttempt--; if(webView.canGoBackOrForward(lastBackDepthAttempt)) { webView.goBackOrForward(lastBackDepthAttempt); } else { mActivity.finish(); } } else { if(RedditURLParser.parse(Uri.parse(url)) != null) { LinkHandler.onLinkClicked(mActivity, url, false); } else { if (!url.startsWith(""http:"") && !url.startsWith(""https:"")) { final Intent nativeAppIntent = new Intent(Intent.ACTION_VIEW, Uri.parse(url)); try { startActivity(nativeAppIntent); return true; } catch (ActivityNotFoundException err) { // fall through and open the URL as though it's a regular HTTP URL } } if(!PrefsUtility.pref_behaviour_useinternalbrowser()) { LinkHandler.openWebBrowser( mActivity, Uri.parse(url), true); } else if(PrefsUtility.pref_behaviour_usecustomtabs() && Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN_MR2) { LinkHandler.openCustomTab( mActivity, Uri.parse(url), null); } else { webView.loadUrl(url); currentUrl = url; } } } return true; } @Override public void onPageStarted(final WebView view, final String url, final Bitmap favicon) { super.onPageStarted(view, url, favicon); if(mUrl != null && url != null) { final AppCompatActivity activity = mActivity; if(activity != null) { activity.setTitle(url); } } } @Override public void onPageFinished(final WebView view, final String url) { super.onPageFinished(view, url); new Timer().schedule(new TimerTask() { @Override public void run() { AndroidCommon.UI_THREAD_HANDLER.post(() -> { if(currentUrl == null || url == null) { return; } if(!url.equals(view.getUrl())) { return; } if(goingBack && url.equals(currentUrl)) { General.quickToast( mActivity, String.format( Locale.US, ""Handling redirect loop (level %d)"", -lastBackDepthAttempt)); lastBackDepthAttempt--; if(webView.canGoBackOrForward(lastBackDepthAttempt)) { webView.goBackOrForward(lastBackDepthAttempt); } else { mActivity.finish(); } } else { goingBack = false; } }); } }, 1000); } @Override public void doUpdateVisitedHistory( final WebView view, final String url, final boolean isReload) { super.doUpdateVisitedHistory(view, url, isReload); } }); final FrameLayout outerFrame = new FrameLayout(mActivity); outerFrame.addView(outer); if(post != null) { final SideToolbarOverlay toolbarOverlay = new SideToolbarOverlay(mActivity); final BezelSwipeOverlay bezelOverlay = new BezelSwipeOverlay( mActivity, new BezelSwipeOverlay.BezelSwipeListener() { @Override public boolean onSwipe(@BezelSwipeOverlay.SwipeEdge final int edge) { toolbarOverlay.setContents(post.generateToolbar( mActivity, false, toolbarOverlay)); toolbarOverlay.show(edge == BezelSwipeOverlay.LEFT ? SideToolbarOverlay.SideToolbarPosition.LEFT : SideToolbarOverlay.SideToolbarPosition.RIGHT); return true; } @Override public boolean onTap() { if(toolbarOverlay.isShown()) { toolbarOverlay.hide(); return true; } return false; } }); outerFrame.addView(bezelOverlay); outerFrame.addView(toolbarOverlay); General.setLayoutMatchParent(bezelOverlay); General.setLayoutMatchParent(toolbarOverlay); } return outerFrame; }","@SuppressLint(""SetJavaScriptEnabled"") @Override public View onCreateView( final LayoutInflater inflater, final ViewGroup container, final Bundle savedInstanceState) { mActivity = (BaseActivity)getActivity(); CookieSyncManager.createInstance(mActivity); outer = (FrameLayout)inflater.inflate(R.layout.web_view_fragment, null); final RedditPost srcPost = getArguments().getParcelable(""post""); final RedditPreparedPost post; if(srcPost != null) { final RedditParsedPost parsedPost = new RedditParsedPost( mActivity, srcPost, false); post = new RedditPreparedPost( mActivity, CacheManager.getInstance(mActivity), 0, parsedPost, -1, false, false, false, false); } else { post = null; } webView = outer.findViewById(R.id.web_view_fragment_webviewfixed); final FrameLayout loadingViewFrame = outer.findViewById(R.id.web_view_fragment_loadingview_frame); progressView = new ProgressBar( mActivity, null, android.R.attr.progressBarStyleHorizontal); loadingViewFrame.addView(progressView); loadingViewFrame.setPadding( General.dpToPixels(mActivity, 10), 0, General.dpToPixels(mActivity, 10), 0); final FrameLayout fullscreenViewFrame = outer.findViewById(R.id.web_view_fragment_fullscreen_frame); final VideoEnabledWebChromeClient chromeClient = new VideoEnabledWebChromeClient( loadingViewFrame, fullscreenViewFrame) { @Override public void onProgressChanged(final WebView view, final int newProgress) { super.onProgressChanged(view, newProgress); AndroidCommon.UI_THREAD_HANDLER.post(() -> { progressView.setProgress(newProgress); progressView.setVisibility(newProgress == 100 ? View.GONE : View.VISIBLE); }); } }; chromeClient.setOnToggledFullscreen(fullscreen -> { // Your code to handle the full-screen change, for example showing // and hiding the title bar. Example: if(fullscreen) { final WindowManager.LayoutParams attrs = mActivity.getWindow() .getAttributes(); attrs.flags |= WindowManager.LayoutParams.FLAG_FULLSCREEN; attrs.flags |= WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON; mActivity.getWindow().setAttributes(attrs); mActivity.getSupportActionBar().hide(); if(Build.VERSION.SDK_INT >= 14) { //noinspection all mActivity.getWindow() .getDecorView() .setSystemUiVisibility(View.SYSTEM_UI_FLAG_LOW_PROFILE); } } else { final WindowManager.LayoutParams attrs = mActivity.getWindow() .getAttributes(); //only re-enable status bar if there is no contradicting preference set if(PrefsUtility.pref_appearance_android_status() == PrefsUtility.AppearanceStatusBarMode.NEVER_HIDE) { attrs.flags &= ~WindowManager.LayoutParams.FLAG_FULLSCREEN; } attrs.flags &= ~WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON; mActivity.getWindow().setAttributes(attrs); mActivity.getSupportActionBar().show(); if(Build.VERSION.SDK_INT >= 14) { //noinspection all mActivity.getWindow() .getDecorView() .setSystemUiVisibility(View.SYSTEM_UI_FLAG_VISIBLE); } } }); /*handle download links show an alert box to load this outside the internal browser*/ webView.setDownloadListener((url, userAgent, contentDisposition, mimetype, contentLength) -> new AlertDialog.Builder(mActivity) .setTitle(R.string.download_link_title) .setMessage(R.string.download_link_message) .setPositiveButton( android.R.string.yes, (dialog, which) -> { final Intent i = new Intent(Intent.ACTION_VIEW); i.setData(Uri.parse(url)); try { getContext().startActivity(i); mActivity.onBackPressed(); //get back from internal browser } catch(final ActivityNotFoundException e) { General.quickToast( getContext(), R.string.action_not_handled_by_installed_app_toast); } }) .setNegativeButton( android.R.string.no, (dialog, which) -> { mActivity.onBackPressed(); //get back from internal browser }) .setIcon(android.R.drawable.ic_dialog_alert) .show()); /*handle download links end*/ final WebSettings settings = webView.getSettings(); settings.setBuiltInZoomControls(true); settings.setJavaScriptEnabled(true); settings.setJavaScriptCanOpenWindowsAutomatically(false); settings.setUseWideViewPort(true); settings.setLoadWithOverviewMode(true); settings.setDomStorageEnabled(true); settings.setDisplayZoomControls(false); // TODO handle long clicks webView.setWebChromeClient(chromeClient); if(mUrl != null) { webView.loadUrl(mUrl); } else { webView.loadHtmlUTF8WithBaseURL(""https://reddit.com/"", html); } webView.setWebViewClient(new WebViewClient() { @Override public boolean shouldOverrideUrlLoading( final WebView view, final String url) { if(url == null) { return false; } if(url.startsWith(""data:"")) { // Prevent imgur bug where we're directed to some random data URI return true; } // Go back if loading same page to prevent redirect loops. if(goingBack && currentUrl != null && url.equals(currentUrl)) { General.quickToast(mActivity, String.format( Locale.US, ""Handling redirect loop (level %d)"", -lastBackDepthAttempt), Toast.LENGTH_SHORT); lastBackDepthAttempt--; if(webView.canGoBackOrForward(lastBackDepthAttempt)) { webView.goBackOrForward(lastBackDepthAttempt); } else { mActivity.finish(); } } else { if(RedditURLParser.parse(Uri.parse(url)) != null) { LinkHandler.onLinkClicked(mActivity, url, false); } else { // When websites recognize the user agent is on Android, they sometimes // redirect or offer deep links into native apps. These come in two flavors: // // 1. `intent://` URLs for arbitrary native apps. Launching these may be a // security vulnerability, because it's not clear what app is being // loaded with RedReader's permissions. Luckily, these URLs often have // fallback HTTP URLs, which can be loaded instead. // // 2. Custom scheme URLs, like `twitter://` or `market://` URLs. While these // can also launch arbitrary apps, the assumption is custom schemes are // only used for widely known apps (though even those can be replaced by // alternative apps). Often, these URLs don't have fallbacks, so take the // risk of loading these in their native apps. // // All this logic is in the `else` block because processing these URLs can // fail, in which case the logic falls through and treats these URLs as // HTTP URLs. if (url.startsWith(""intent:"")) { if (onEncounteredIntentUrl(url)) { return true; } } else if (!url.startsWith(""http:"") && !url.startsWith(""https:"")) { if (onEncounteredCustomSchemeUrl(url)) { return true; } } if(!PrefsUtility.pref_behaviour_useinternalbrowser()) { LinkHandler.openWebBrowser( mActivity, Uri.parse(url), true); } else if(PrefsUtility.pref_behaviour_usecustomtabs() && Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN_MR2) { LinkHandler.openCustomTab( mActivity, Uri.parse(url), null); } else { webView.loadUrl(url); currentUrl = url; } } } return true; } /** * Assumes the {@code url} starts with `intent://` */ private boolean onEncounteredIntentUrl(final String url) { final Intent nativeAppIntent; try { nativeAppIntent = Intent.parseUri(url, Intent.URI_INTENT_SCHEME); } catch (URISyntaxException e) { return false; } if (nativeAppIntent == null) { return false; } final String fallbackUrl = nativeAppIntent.getStringExtra(""browser_fallback_url""); if (fallbackUrl == null) { return false; } webView.loadUrl(fallbackUrl); currentUrl = fallbackUrl; return true; } /** * Assumes the {@code url} starts with something other than `intent://`, `http://` or * `https://` */ private boolean onEncounteredCustomSchemeUrl(final String url) { final Intent nativeAppIntent = new Intent(Intent.ACTION_VIEW, Uri.parse(url)); try { startActivity(nativeAppIntent); return true; } catch (ActivityNotFoundException err) { return false; } } @Override public void onPageStarted(final WebView view, final String url, final Bitmap favicon) { super.onPageStarted(view, url, favicon); if(mUrl != null && url != null) { final AppCompatActivity activity = mActivity; if(activity != null) { activity.setTitle(url); } } } @Override public void onPageFinished(final WebView view, final String url) { super.onPageFinished(view, url); new Timer().schedule(new TimerTask() { @Override public void run() { AndroidCommon.UI_THREAD_HANDLER.post(() -> { if(currentUrl == null || url == null) { return; } if(!url.equals(view.getUrl())) { return; } if(goingBack && url.equals(currentUrl)) { General.quickToast( mActivity, String.format( Locale.US, ""Handling redirect loop (level %d)"", -lastBackDepthAttempt)); lastBackDepthAttempt--; if(webView.canGoBackOrForward(lastBackDepthAttempt)) { webView.goBackOrForward(lastBackDepthAttempt); } else { mActivity.finish(); } } else { goingBack = false; } }); } }, 1000); } @Override public void doUpdateVisitedHistory( final WebView view, final String url, final boolean isReload) { super.doUpdateVisitedHistory(view, url, isReload); } }); final FrameLayout outerFrame = new FrameLayout(mActivity); outerFrame.addView(outer); if(post != null) { final SideToolbarOverlay toolbarOverlay = new SideToolbarOverlay(mActivity); final BezelSwipeOverlay bezelOverlay = new BezelSwipeOverlay( mActivity, new BezelSwipeOverlay.BezelSwipeListener() { @Override public boolean onSwipe(@BezelSwipeOverlay.SwipeEdge final int edge) { toolbarOverlay.setContents(post.generateToolbar( mActivity, false, toolbarOverlay)); toolbarOverlay.show(edge == BezelSwipeOverlay.LEFT ? SideToolbarOverlay.SideToolbarPosition.LEFT : SideToolbarOverlay.SideToolbarPosition.RIGHT); return true; } @Override public boolean onTap() { if(toolbarOverlay.isShown()) { toolbarOverlay.hide(); return true; } return false; } }); outerFrame.addView(bezelOverlay); outerFrame.addView(toolbarOverlay); General.setLayoutMatchParent(bezelOverlay); General.setLayoutMatchParent(toolbarOverlay); } return outerFrame; }","Don't launch native apps for `intent://` URLs The assumption is that custom scheme URLs (like `twitter://`, `market://`, etc.) are typically handled by known apps, so the risk of a security vulnerability is present but low. In contrast, `intent://` URLs may be any app, so don't launch the corresponding app to avoid higher risk security vulnerabilities.",https://github.com/QuantumBadger/RedReader/commit/e4505bd1d0facd32a8b7f9ec42f411c72ce3d38d,,,src/main/java/org/quantumbadger/redreader/fragments/WebViewFragment.java,3,java,False,2021-09-09T03:55:33Z "public Dimension multiply(Dimension that) { return that instanceof UnitDimension ? this.multiply((UnitDimension) that) : this.multiply(that); }","public Dimension multiply(Dimension that) { return that instanceof UnitDimension ? this.multiply((UnitDimension) that) : that.multiply(this); }","339: Potential stackoverflow in UnitDimension#multiply(Dimension) and #divide(Dimension) Task-Url: https://github.com/unitsofmeasurement/indriya/issues/339",https://github.com/unitsofmeasurement/indriya/commit/e2b74cd58b5a181d5b83b3296cbd824c4f7418c9,,,src/main/jdk9/tech/units/indriya/unit/UnitDimension.java,3,java,False,2021-03-12T22:56:22Z "public CommandSender getBukkitSender(CommandSource wrapper) { return new ServerCommandSender() { private final boolean isOp = wrapper.hasPermissionLevel(wrapper.getServer().getOpPermissionLevel()); @Override public boolean isOp() { return isOp; } @Override public void setOp(boolean value) { } @Override public void sendMessage(@NotNull String message) { } @Override public void sendMessage(@NotNull String[] messages) { } @NotNull @Override public String getName() { return ""DUMMY""; } }; }","public CommandSender getBukkitSender(CommandSource wrapper) { return new ServerCommandSender() { private final boolean isOp = ((CommandSourceBridge)wrapper).bridge$getPermissionLevel()>=wrapper.getServer().getOpPermissionLevel(); @Override public boolean isOp() { return isOp; } @Override public void setOp(boolean value) { } @Override public void sendMessage(@NotNull String message) { } @Override public void sendMessage(@NotNull String[] messages) { } @NotNull @Override public String getName() { return ""DUMMY""; } }; }","Fix StackOverflow when using DUMMY command source (#898) * [1.16] Fix StackOverflow when using DUMMY command source Turn isOp field as lazy init for prevent dead loop in hasPermissionLevel (introduced by arclight-common/src/main/java/io/izzel/arclight/common/mixin/core/command/CommandSourceMixin.java#hasPermission) * Fix StackOverFlowError again Add bridge method to check permissionLevel directly",https://github.com/IzzelAliz/Arclight/commit/2d5aef04a886854aa936d60b41fcd98d94aff2d2,,,arclight-common/src/main/java/io/izzel/arclight/common/mixin/core/command/ICommandSource1Mixin.java,3,java,False,2023-01-29T10:24:16Z "public static String getBlocks(String name) { switch (name) { case ""Import"": case ""initializeLogic"": case ""onSwipeRefreshLayout"": case "" onLongClick"": case ""onPreExecute"": return """"; case ""onActivityResult"": return ""%d.requestCode %d.resultCode %m.intent""; case ""onTabLayoutNewTabAdded"": case ""onProgressUpdate"": return ""%d""; case ""doInBackground"": case ""onPostExecute"": return ""%s""; default: for (int i = 0, cachedCustomEventsSize = cachedCustomEvents.size(); i < cachedCustomEventsSize; i++) { HashMap customEvent = cachedCustomEvents.get(i); Object eventName = customEvent.get(""name""); if (eventName instanceof String) { if (name.equals(eventName)) { Object parameters = customEvent.get(""parameters""); if (parameters instanceof String) { return (String) parameters; } else { SketchwareUtil.toastError(""Found invalid parameters data type in Custom Event #"" + (i + 1)); } } } else { SketchwareUtil.toastError(""Found invalid name data type in Custom Event #"" + (i + 1)); } } return """"; } }","public static String getBlocks(String name) { switch (name) { case ""Import"": case ""initializeLogic"": case ""onSwipeRefreshLayout"": case "" onLongClick"": case ""onPreExecute"": return """"; case ""onActivityResult"": return ""%d.requestCode %d.resultCode %m.intent""; case ""onTabLayoutNewTabAdded"": case ""onProgressUpdate"": return ""%d""; case ""doInBackground"": case ""onPostExecute"": return ""%s""; default: for (int i = 0, cachedCustomEventsSize = cachedCustomEvents.size(); i < cachedCustomEventsSize; i++) { HashMap customEvent = cachedCustomEvents.get(i); if (customEvent != null) { Object eventName = customEvent.get(""name""); if (eventName instanceof String) { if (name.equals(eventName)) { Object parameters = customEvent.get(""parameters""); if (parameters instanceof String) { return (String) parameters; } else { SketchwareUtil.toastError(""Found invalid parameters data type in Custom Event #"" + (i + 1)); } } } else { SketchwareUtil.toastError(""Found invalid name data type in Custom Event #"" + (i + 1)); } } else { SketchwareUtil.toastError(""Found invalid (null) Custom Event at position "" + i); } } return """"; } }","fix: Handle null Custom Events and don't crash on an NPE No idea how that can happen, but looks like it can: https://discord.com/channels/790686719753846785/790696157550477342/1023241665433047132",https://github.com/Sketchware-Pro/Sketchware-Pro/commit/2db1b76b7ac5631b52e6ce15e801aa1a4063d856,,,app/src/main/java/mod/hilal/saif/events/EventsHandler.java,3,java,False,2022-09-24T15:18:36Z "@Override public int fill(FluidStack resource, FluidAction action) { if(!allowFill) return 0; FluidStack remaining = resource.copy(); for(IFluidTank tank : internal) { int filledHere = tank.fill(remaining, action); remaining.shrink(filledHere); if(remaining.isEmpty()) break; } if(resource.getAmount()!=remaining.getAmount()) afterTransfer.run(); return resource.getAmount()-remaining.getAmount(); }","@Override public int fill(FluidStack resource, FluidAction action) { if(!allowFill||resource.isEmpty()) return 0; FluidStack remaining = resource.copy(); for(IFluidTank tank : internal) { int filledHere = tank.fill(remaining, action); remaining.shrink(filledHere); if(remaining.isEmpty()) break; } if(resource.getAmount()!=remaining.getAmount()) afterTransfer.run(); return resource.getAmount()-remaining.getAmount(); }","Fix crash when inserting an empty fluid stack into an ArrayFluidHandler, closes #5220",https://github.com/BluSunrize/ImmersiveEngineering/commit/08d90bb4783bf79a6ddb43aa321c28bdd13790a5,,,src/main/java/blusunrize/immersiveengineering/common/fluids/ArrayFluidHandler.java,3,java,False,2022-02-12T07:36:47Z "@EventHandler public void onInventoryClick(InventoryClickEvent event) { if (event.getInventory().equals(inventory) && (event.getRawSlot() < 3 || event.getAction().equals(InventoryAction.MOVE_TO_OTHER_INVENTORY))) { final int slot = event.getRawSlot(); event.setCancelled(!interactableSlots.contains(slot)); final Player clicker = (Player) event.getWhoClicked(); if (event.getRawSlot() == Slot.OUTPUT) { final ItemStack clicked = inventory.getItem(Slot.OUTPUT); if (clicked == null || clicked.getType() == Material.AIR) return; final Response response = completeFunction.apply(new Completion( notNull(inventory.getItem(Slot.INPUT_LEFT)), notNull(inventory.getItem(Slot.INPUT_RIGHT)), notNull(inventory.getItem(Slot.OUTPUT)), player, clicked.hasItemMeta() ? clicked.getItemMeta().getDisplayName() : """")); if (response.getText() != null) { final ItemMeta meta = clicked.getItemMeta(); meta.setDisplayName(response.getText()); clicked.setItemMeta(meta); inventory.setItem(Slot.INPUT_LEFT, clicked); } else if (response.getInventoryToOpen() != null) { clicker.openInventory(response.getInventoryToOpen()); } else { closeInventory(); } } else if (event.getRawSlot() == Slot.INPUT_LEFT) { if (inputLeftClickListener != null) { inputLeftClickListener.accept(player); } } else if (event.getRawSlot() == Slot.INPUT_RIGHT) { if (inputRightClickListener != null) { inputRightClickListener.accept(player); } } } }","@EventHandler public void onInventoryClick(InventoryClickEvent event) { if (event.getInventory().equals(inventory) && event.getClickedInventory().equals(player.getInventory()) && event.getClick().equals(ClickType.DOUBLE_CLICK)) { event.setCancelled(true); } if (event.getInventory().equals(inventory) && (event.getRawSlot() < 3 || event.getAction().equals(InventoryAction.MOVE_TO_OTHER_INVENTORY))) { final int slot = event.getRawSlot(); event.setCancelled(!interactableSlots.contains(slot)); final Player clicker = (Player) event.getWhoClicked(); if (event.getRawSlot() == Slot.OUTPUT) { final ItemStack clicked = inventory.getItem(Slot.OUTPUT); if (clicked == null || clicked.getType() == Material.AIR) return; final Response response = completeFunction.apply(new Completion( notNull(inventory.getItem(Slot.INPUT_LEFT)), notNull(inventory.getItem(Slot.INPUT_RIGHT)), notNull(inventory.getItem(Slot.OUTPUT)), player, clicked.hasItemMeta() ? clicked.getItemMeta().getDisplayName() : """")); if (response.getText() != null) { final ItemMeta meta = clicked.getItemMeta(); meta.setDisplayName(response.getText()); clicked.setItemMeta(meta); inventory.setItem(Slot.INPUT_LEFT, clicked); } else if (response.getInventoryToOpen() != null) { clicker.openInventory(response.getInventoryToOpen()); } else { closeInventory(); } } else if (event.getRawSlot() == Slot.INPUT_LEFT) { if (inputLeftClickListener != null) { inputLeftClickListener.accept(player); } } else if (event.getRawSlot() == Slot.INPUT_RIGHT) { if (inputRightClickListener != null) { inputRightClickListener.accept(player); } } } }",Fix merge stack duplication exploit,https://github.com/WesJD/AnvilGUI/commit/febc00daacf486fc45334ac4f15686dc07591029,,,api/src/main/java/net/wesjd/anvilgui/AnvilGUI.java,3,java,False,2022-12-14T23:16:57Z "@Override protected boolean parseCommand(@NotNull String[] args) { // Validating state of sender if (dataHolder == null || permissionHandler == null) { if (!setDefaultWorldHandler(sender)) return true; } // Validating arguments if ((args.length == 0) || (args.length > 2)) { sender.sendMessage(ChatColor.RED + Messages.getString(""ERROR_REVIEW_ARGUMENTS"") + Messages.getString(""MANULISTP_SYNTAX"")); //$NON-NLS-1$ //$NON-NLS-2$ return true; } if ((GroupManager.getGMConfig().isToggleValidate()) && ((match = validatePlayer(args[0], sender)) == null)) { return false; } if (match != null) { auxUser = dataHolder.getUser(match.toString()); } else { auxUser = dataHolder.getUser(args[0]); } // Validating permission // Seems OK auxString = """"; //$NON-NLS-1$ for (String perm : auxUser.getPermissionList()) { auxString += perm + "", ""; //$NON-NLS-1$ } if (auxString.lastIndexOf("","") > 0) { //$NON-NLS-1$ auxString = auxString.substring(0, auxString.lastIndexOf("","")); //$NON-NLS-1$ sender.sendMessage(ChatColor.YELLOW + String.format(Messages.getString(""USER_HAS_PERMISSIONS""), auxUser.getLastName(), ChatColor.WHITE + auxString)); //$NON-NLS-1$ sender.sendMessage(ChatColor.YELLOW + String.format(Messages.getString(""AND_ALL_PERMISSIONS_GROUPS""), auxUser.getGroupName())); //$NON-NLS-1$ auxString = """"; for (String subGroup : auxUser.subGroupListStringCopy()) { auxString += subGroup + "", ""; } if (auxString.lastIndexOf("","") > 0) { auxString = auxString.substring(0, auxString.lastIndexOf("","")); sender.sendMessage(ChatColor.YELLOW + String.format(Messages.getString(""AND_ALL_PERMISSIONS_SUBGROUPS""), auxString)); //$NON-NLS-1$ } } else { sender.sendMessage(ChatColor.YELLOW + String.format(Messages.getString(""USER_NO_SPECIFIC_PERMISSIONS""), auxUser.getLastName())); //$NON-NLS-1$ sender.sendMessage(ChatColor.YELLOW + String.format(Messages.getString(""AND_ALL_PERMISSIONS_GROUPS""), auxUser.getGroupName())); //$NON-NLS-1$ auxString = """"; //$NON-NLS-1$ for (String subGroup : auxUser.subGroupListStringCopy()) { auxString += subGroup + "", ""; //$NON-NLS-1$ } if (auxString.lastIndexOf("","") > 0) { //$NON-NLS-1$ auxString = auxString.substring(0, auxString.lastIndexOf("","")); sender.sendMessage(ChatColor.YELLOW + String.format(Messages.getString(""AND_ALL_PERMISSIONS_SUBGROUPS""), auxString)); //$NON-NLS-1$ } } // bukkit perms if ((args.length == 2) && (args[1].equalsIgnoreCase(""+""))) { targetPlayer = BukkitWrapper.getInstance().getPlayer(auxUser.getLastName()); if (targetPlayer != null) { sender.sendMessage(ChatColor.YELLOW + Messages.getString(""SUPER_PERMS_REPORTS"")); //$NON-NLS-1$ for (String line : GroupManager.getBukkitPermissions().listPerms(targetPlayer)) sender.sendMessage(ChatColor.YELLOW + line); } } return true; }","@Override protected boolean parseCommand(@NotNull String[] args) { // Validating state of sender if (dataHolder == null || permissionHandler == null) { if (!setDefaultWorldHandler(sender)) return true; } // Validating arguments if ((args.length == 0) || (args.length > 2)) { sender.sendMessage(ChatColor.RED + Messages.getString(""ERROR_REVIEW_ARGUMENTS"") + Messages.getString(""MANULISTP_SYNTAX"")); //$NON-NLS-1$ //$NON-NLS-2$ return true; } if ((GroupManager.getGMConfig().isToggleValidate()) && ((match = validatePlayer(args[0], sender)) == null)) { return false; } if (match != null) { auxUser = dataHolder.getUser(match.toString()); } else { auxUser = dataHolder.getUser(args[0]); } // Validating permission // Seems OK auxString = """"; //$NON-NLS-1$ for (String perm : auxUser.getPermissionList()) { // Prevent over sized strings crashing the parser in BungeeCord if (auxString.length() > 1024) { auxString = auxString.substring(0, auxString.lastIndexOf("","")); //$NON-NLS-1$ sender.sendMessage(ChatColor.YELLOW + String.format(Messages.getString(""USER_HAS_PERMISSIONS""), auxGroup.getName(), ChatColor.WHITE + auxString)); //$NON-NLS-1$ auxString = """"; //$NON-NLS-1$ } auxString += perm + "", ""; //$NON-NLS-1$ } if (auxString.lastIndexOf("","") > 0) { //$NON-NLS-1$ auxString = auxString.substring(0, auxString.lastIndexOf("","")); //$NON-NLS-1$ sender.sendMessage(ChatColor.YELLOW + String.format(Messages.getString(""USER_HAS_PERMISSIONS""), auxUser.getLastName(), ChatColor.WHITE + auxString)); //$NON-NLS-1$ sender.sendMessage(ChatColor.YELLOW + String.format(Messages.getString(""AND_ALL_PERMISSIONS_GROUPS""), auxUser.getGroupName())); //$NON-NLS-1$ auxString = """"; for (String subGroup : auxUser.subGroupListStringCopy()) { auxString += subGroup + "", ""; } if (auxString.lastIndexOf("","") > 0) { auxString = auxString.substring(0, auxString.lastIndexOf("","")); sender.sendMessage(ChatColor.YELLOW + String.format(Messages.getString(""AND_ALL_PERMISSIONS_SUBGROUPS""), auxString)); //$NON-NLS-1$ } } else { sender.sendMessage(ChatColor.YELLOW + String.format(Messages.getString(""USER_NO_SPECIFIC_PERMISSIONS""), auxUser.getLastName())); //$NON-NLS-1$ sender.sendMessage(ChatColor.YELLOW + String.format(Messages.getString(""AND_ALL_PERMISSIONS_GROUPS""), auxUser.getGroupName())); //$NON-NLS-1$ auxString = """"; //$NON-NLS-1$ for (String subGroup : auxUser.subGroupListStringCopy()) { auxString += subGroup + "", ""; //$NON-NLS-1$ } if (auxString.lastIndexOf("","") > 0) { //$NON-NLS-1$ auxString = auxString.substring(0, auxString.lastIndexOf("","")); sender.sendMessage(ChatColor.YELLOW + String.format(Messages.getString(""AND_ALL_PERMISSIONS_SUBGROUPS""), auxString)); //$NON-NLS-1$ } } // bukkit perms if ((args.length == 2) && (args[1].equalsIgnoreCase(""+""))) { targetPlayer = BukkitWrapper.getInstance().getPlayer(auxUser.getLastName()); if (targetPlayer != null) { sender.sendMessage(ChatColor.YELLOW + Messages.getString(""SUPER_PERMS_REPORTS"")); //$NON-NLS-1$ for (String line : GroupManager.getBukkitPermissions().listPerms(targetPlayer)) sender.sendMessage(ChatColor.YELLOW + line); } } return true; }",Prevent over-sized strings crashing the parser in BungeeCord.,https://github.com/ElgarL/GroupManager/commit/496a9edd1aa302787ae544c3c0bc9b33a69a9fd7,,,src/org/anjocaido/groupmanager/commands/ManUListP.java,3,java,False,2021-03-09T23:43:52Z "@GetMapping(value = ""/generateXid"") public ResponseEntity getUniqueXid(HttpServletRequest request) { try { User user = Common.getUser(request); if(user != null && user.isAdmin()) { return new ResponseEntity<>(watchListService.generateUniqueXid(), HttpStatus.OK); } else { return new ResponseEntity<>(HttpStatus.UNAUTHORIZED); } } catch (Exception e) { return new ResponseEntity<>(HttpStatus.INTERNAL_SERVER_ERROR); } }","@GetMapping(value = ""/generateXid"") public ResponseEntity getUniqueXid(HttpServletRequest request) { try { User user = Common.getUser(request); if(user != null) { return new ResponseEntity<>(watchListService.generateUniqueXid(), HttpStatus.OK); } else { return new ResponseEntity<>(HttpStatus.UNAUTHORIZED); } } catch (Exception e) { return new ResponseEntity<>(HttpStatus.INTERNAL_SERVER_ERROR); } }","#2047 Fix access to bussines object for non admin. Allow user to create a watchList based on the DataPoint permission settings. Fix the user not authorized exceptions.",https://github.com/SCADA-LTS/Scada-LTS/commit/4e8f667359b8e520d72085f4c35a6ff41fd42187,,,src/org/scada_lts/web/mvc/api/WatchListAPI.java,3,java,False,2022-01-21T10:40:44Z "public InteractionResult blockLeftClick(Player player, InteractionHand hand, BlockPos pos, Direction face) { if (FTBChunksAPI.getManager().protect(player, hand, pos, Protection.EDIT_BLOCK).get()) { return InteractionResult.FAIL; } return InteractionResult.PASS; }","public InteractionResult blockLeftClick(Player player, InteractionHand hand, BlockPos pos, Direction face) { if (player instanceof ServerPlayer && FTBChunksAPI.getManager().protect(player, hand, pos, Protection.EDIT_BLOCK).get()) { return InteractionResult.FAIL; } return InteractionResult.PASS; }","Added ftbchunks:right_click_whitelist tag, rewrote protection handling, should fix no_wilderness bug",https://github.com/FTBTeam/FTB-Chunks/commit/30be819fd21b16c4dc3a4a9a25afd91db611b147,,,common/src/main/java/dev/ftb/mods/ftbchunks/FTBChunks.java,3,java,False,2021-07-22T10:09:34Z "public static boolean isInstanceOf(TypeRef type, TypeDef targetType, Function function) { if (type instanceof ClassRef) { ClassRef classRef = (ClassRef) type; TypeDef definition = classRef.getDefinition(); if (definition.getFullyQualifiedName().equals(targetType.getFullyQualifiedName())) { return true; } for (TypeRef i : definition.getImplementsList()) { if (function.apply(i)) { return true; } } for (TypeRef e : definition.getExtendsList()) { if (function.apply(e)) { return true; } } } return false; }","public static boolean isInstanceOf(TypeRef type, TypeDef targetType, Function function) { if (type instanceof ClassRef) { ClassRef classRef = (ClassRef) type; TypeDef definition = classRef.getDefinition(); if (definition.getFullyQualifiedName().equals(targetType.getFullyQualifiedName())) { return true; } if (type.equals(Constants.OBJECT_REF)) { return false; } for (TypeRef i : definition.getImplementsList()) { if (function.apply(i)) { return true; } } for (TypeRef e : definition.getExtendsList()) { if (function.apply(e)) { return true; } } } return false; }",fix: Infinite loop in isInstanceOf,https://github.com/sundrio/sundrio/commit/2de7bf2365a5d42df36c5baed35e9fa9cb6a3d95,,,codegen/src/main/java/io/sundr/codegen/utils/TypeUtils.java,3,java,False,2021-03-30T10:01:28Z "@Override public DiplomaticReply receiveOfferPeace(Empire requestor) { log(empire.name(), "" receiving offer of Peace from: "", requestor.name()); if (empire.isPlayerControlled()) { DiplomaticNotification.create(requestor.viewForEmpire(empire), DialogueManager.OFFER_PEACE); return null; } EmpireView v = empire.viewForEmpire(requestor); v.embassy().noteRequest(); if(empire.enemies().size() > 1 && requestor != empire.generalAI().bestVictim()) { if (!v.embassy().readyForPeace()) return v.refuse(DialogueManager.DECLINE_OFFER); v.embassy().resetPeaceTimer(); DiplomaticIncident inc = v.embassy().signPeace(); return v.otherView().accept(DialogueManager.ACCEPT_PEACE, inc); } else { return v.refuse(DialogueManager.DECLINE_OFFER); } }","@Override public DiplomaticReply receiveOfferPeace(Empire requestor) { log(empire.name(), "" receiving offer of Peace from: "", requestor.name()); if (empire.isPlayerControlled()) { DiplomaticNotification.create(requestor.viewForEmpire(empire), DialogueManager.OFFER_PEACE); return null; } int bonus = requestor.diplomacyBonus(); EmpireView v = empire.viewForEmpire(requestor); if ((bonus+random(100)) < leaderDiplomacyAnnoyanceMod(v)) { v.embassy().withdrawAmbassador(); return v.refuse(DialogueManager.DECLINE_ANNOYED); } v.embassy().noteRequest(); if (!v.embassy().readyForPeace()) return v.refuse(DialogueManager.DECLINE_OFFER); v.embassy().resetPeaceTimer(); float autoAccept = bonus/200.0f; //30% chance for humans if ((random() > autoAccept) && !warWeary(v)) return refuseOfferPeace(requestor); DiplomaticIncident inc = v.embassy().signPeace(); return v.otherView().accept(DialogueManager.ACCEPT_PEACE, inc); }","Xilmi ai (#45) * Replaced many isPlayer() by isPlayerControlled() This leads to a more fluent experience on AutoPlay. Note: the council-voting acts weird when you try that there, getting you stuck, and the News-Broadcasts also seem to use a differnt logic and are always shown. * Orion-guard-handling Avoid sending colonization-fleets, when guardian is still alive Increase guardian-power-estimate to 100,000 Don't send and count bombers towards guardian-defeat-force * Fixed Crash from a report on reddit Not sure how that could happen though. Never had this issue in games started on my computer. * Fixed crash after AI defeats orion-guard Tried to access an out-of-bounds-value because it couldn't find the System where the guardian was. So looking to find the Planet with the Orionartifact now, which does find it. * All the forgotten isPlayer()-calls Including the Base- and Modnar-AI-Diplomat * Personalities now play a role in my AI once again Instead of everyone having the same conditions for war, there's now different ones. Some are more aggressive, some are less. * Fixed issue where enemy-fleets weren's seen, when they actually were. Also added a way of guessing when enemy-fleets aren't seen so it shouldn't trickle in tiny fleets that all retreat anymore in the early-game, before they can see the enemy-fleets. And also not later because they now actually can see them. * Update AIDiplomat.java * Delete ShipCombatResults.java * Delete Empire.java * Delete TradeRoute.java * Revert ""Delete TradeRoute.java"" This reverts commit 6e5c5a8604e89bb11a9a6dc63acd5b3f27194c83. * Revert ""Delete Empire.java"" This reverts commit 1a020295e05ebc735dae761f426742eb7bdc8d35. * Revert ""Delete ShipCombatResults.java"" This reverts commit 5f9287289feb666adf1aa809524973c54fbf0cd5. * Update ShipCombatResults.java reverting pull-request... manually because I don't know of a better way 8[ * Update Empire.java * Update TradeRoute.java * Merge with Master * Update TradeRoute.java * Update TradeRoute.java github editor does not allow me to remove a newline oO * AI improvements Added parameter to make the colonizer-function return just the uncolonized planets without substracting the colony-ships. Impelemented a very differnt diplomatic behavior, that supposedly is more suitable to actually winning by waging less war, particularly when big enough to be voted for. Revoked that AI doesn't adjust to enemy-troops when it has a more defensive unit-composition. In lategame going by destructive-power of bombers hasn't much merit, when 1 bombers can pack 60ish neutronium-bombs. Fixed an issue that prevented designing extended-fuel-range-colonizers asap. This once again helps expansion-speed a lot. Security now is only spent against empires actually in range to spy, as it was intended. Contact via council should not increase paranoia. Also Xenophobic-extra-paranoia removed. * Update OrionGuardianShip.java Co-authored-by: rayfowler <58891984+rayfowler@users.noreply.github.com>",https://github.com/rayfowler/rotp-public/commit/e4239ef2d2162d2bc31a5bb2a6aa9134034aa7e6,,,src/rotp/model/ai/xilmi/AIDiplomat.java,3,java,False,2021-03-26T15:26:00Z "static void rpc_init_task(struct rpc_task *task, const struct rpc_task_setup *task_setup_data) { memset(task, 0, sizeof(*task)); atomic_set(&task->tk_count, 1); task->tk_flags = task_setup_data->flags; task->tk_ops = task_setup_data->callback_ops; task->tk_calldata = task_setup_data->callback_data; INIT_LIST_HEAD(&task->tk_task); /* Initialize retry counters */ task->tk_garb_retry = 2; task->tk_cred_retry = 2; task->tk_priority = task_setup_data->priority - RPC_PRIORITY_LOW; task->tk_owner = current->tgid; /* Initialize workqueue for async tasks */ task->tk_workqueue = task_setup_data->workqueue; if (task->tk_ops->rpc_call_prepare != NULL) task->tk_action = rpc_prepare_task; /* starting timestamp */ task->tk_start = ktime_get(); dprintk(""RPC: new task initialized, procpid %u\n"", task_pid_nr(current)); }","static void rpc_init_task(struct rpc_task *task, const struct rpc_task_setup *task_setup_data) { memset(task, 0, sizeof(*task)); atomic_set(&task->tk_count, 1); task->tk_flags = task_setup_data->flags; task->tk_ops = task_setup_data->callback_ops; task->tk_calldata = task_setup_data->callback_data; INIT_LIST_HEAD(&task->tk_task); /* Initialize retry counters */ task->tk_garb_retry = 2; task->tk_cred_retry = 2; task->tk_rebind_retry = 2; task->tk_priority = task_setup_data->priority - RPC_PRIORITY_LOW; task->tk_owner = current->tgid; /* Initialize workqueue for async tasks */ task->tk_workqueue = task_setup_data->workqueue; if (task->tk_ops->rpc_call_prepare != NULL) task->tk_action = rpc_prepare_task; /* starting timestamp */ task->tk_start = ktime_get(); dprintk(""RPC: new task initialized, procpid %u\n"", task_pid_nr(current)); }","NLM: Don't hang forever on NLM unlock requests If the NLM daemon is killed on the NFS server, we can currently end up hanging forever on an 'unlock' request, instead of aborting. Basically, if the rpcbind request fails, or the server keeps returning garbage, we really want to quit instead of retrying. Tested-by: Vasily Averin Signed-off-by: Trond Myklebust Cc: stable@kernel.org",https://github.com/torvalds/linux/commit/0b760113a3a155269a3fba93a409c640031dd68f,,,net/sunrpc/sched.c,3,c,False,2011-05-31T19:15:34Z "public void refreshAuthenticationCredentials() { AuthenticationState authState = this.originalAuthState != null ? originalAuthState : this.authState; if (authState == null) { // Authentication is disabled or there's no local state to refresh return; } else if (getState() != State.Connected || !isActive) { // Connection is either still being established or already closed. return; } else if (!authState.isExpired()) { // Credentials are still valid. Nothing to do at this point return; } else if (originalPrincipal != null && originalAuthState == null) { log.info( ""[{}] Cannot revalidate user credential when using proxy and"" + "" not forwarding the credentials. Closing connection"", remoteAddress); return; } ctx.executor().execute(SafeRun.safeRun(() -> { log.info(""[{}] Refreshing authentication credentials for originalPrincipal {} and authRole {}"", remoteAddress, originalPrincipal, this.authRole); if (!supportsAuthenticationRefresh()) { log.warn(""[{}] Closing connection because client doesn't support auth credentials refresh"", remoteAddress); ctx.close(); return; } if (pendingAuthChallengeResponse) { log.warn(""[{}] Closing connection after timeout on refreshing auth credentials"", remoteAddress); ctx.close(); return; } try { AuthData brokerData = authState.refreshAuthentication(); writeAndFlush(Commands.newAuthChallenge(authMethod, brokerData, getRemoteEndpointProtocolVersion())); if (log.isDebugEnabled()) { log.debug(""[{}] Sent auth challenge to client to refresh credentials with method: {}."", remoteAddress, authMethod); } pendingAuthChallengeResponse = true; } catch (AuthenticationException e) { log.warn(""[{}] Failed to refresh authentication: {}"", remoteAddress, e); ctx.close(); } })); }","private void refreshAuthenticationCredentials() { assert ctx.executor().inEventLoop(); AuthenticationState authState = this.originalAuthState != null ? originalAuthState : this.authState; if (getState() == State.Failed) { // Happens when an exception is thrown that causes this connection to close. return; } else if (!authState.isExpired()) { // Credentials are still valid. Nothing to do at this point return; } else if (originalPrincipal != null && originalAuthState == null) { // This case is only checked when the authState is expired because we've reached a point where // authentication needs to be refreshed, but the protocol does not support it unless the proxy forwards // the originalAuthData. log.info( ""[{}] Cannot revalidate user credential when using proxy and"" + "" not forwarding the credentials. Closing connection"", remoteAddress); ctx.close(); return; } if (!supportsAuthenticationRefresh()) { log.warn(""[{}] Closing connection because client doesn't support auth credentials refresh"", remoteAddress); ctx.close(); return; } if (pendingAuthChallengeResponse) { log.warn(""[{}] Closing connection after timeout on refreshing auth credentials"", remoteAddress); ctx.close(); return; } log.info(""[{}] Refreshing authentication credentials for originalPrincipal {} and authRole {}"", remoteAddress, originalPrincipal, this.authRole); try { AuthData brokerData = authState.refreshAuthentication(); writeAndFlush(Commands.newAuthChallenge(authMethod, brokerData, getRemoteEndpointProtocolVersion())); if (log.isDebugEnabled()) { log.debug(""[{}] Sent auth challenge to client to refresh credentials with method: {}."", remoteAddress, authMethod); } pendingAuthChallengeResponse = true; } catch (AuthenticationException e) { log.warn(""[{}] Failed to refresh authentication: {}"", remoteAddress, e); ctx.close(); } }","[fix][broker] Make authentication refresh threadsafe (#19506) Co-authored-by: Lari Hotari ",https://github.com/apache/pulsar/commit/153e4d4cc3b56aaee224b0a68e0186c08125c975,,,pulsar-broker/src/main/java/org/apache/pulsar/broker/service/ServerCnx.java,3,java,False,2023-02-14T09:09:55Z "@Override public void onStartup(Set> classes, ServletContext servletContext) throws ServletException { WebApplication webApplication = (WebApplication) servletContext; DefaultSecurityManager securityManager = new DefaultSecurityManager(); webApplication.setManager(SecurityManager.class, securityManager); File userFile = new File(""user.properties""); if (!userFile.exists()) { userFile = new File(""etc/user.properties""); } if (userFile.exists()) { Properties userProperties = new Properties(); try ( FileInputStream fileInput = new FileInputStream(userFile)) { userProperties.load(fileInput); } catch (IOException ioe) { } userProperties.entrySet().forEach(entry -> { String username = (String) entry.getKey(); String password = (String) entry.getValue(); securityManager.addUser(username, password); }); } File userRoleFile = new File(""userrole.properties""); if (!userRoleFile.exists()) { userRoleFile = new File(""etc/userrole.properties""); } if (userRoleFile.exists()) { Properties userRoleProperties = new Properties(); try ( FileInputStream fileInput = new FileInputStream(userRoleFile)) { userRoleProperties.load(fileInput); } catch (IOException ioe) { } userRoleProperties.entrySet().forEach(entry -> { String username = (String) entry.getKey(); String roles = (String) entry.getValue(); securityManager.addUserRole(username, roles.split("","")); }); } webApplication.setManager(AuthenticationManager.class, new FileAuthenticationManager(userFile)); FilterRegistration.Dynamic dynamic = webApplication.addFilter( FileAuthenticationFilter.class.getName(), FileAuthenticationFilter.class); dynamic.setAsyncSupported(true); webApplication.addFilterMapping( FileAuthenticationFilter.class.getName(), ""/*""); }","@Override public void onStartup(Set> classes, ServletContext servletContext) throws ServletException { WebApplication webApplication = (WebApplication) servletContext; DefaultSecurityManager securityManager = new DefaultSecurityManager(); webApplication.setManager(SecurityManager.class, securityManager); File userFile = new File(""user.properties""); if (!userFile.exists()) { userFile = new File(""etc/user.properties""); } if (userFile.exists()) { Properties userProperties = new Properties(); try ( FileInputStream fileInput = new FileInputStream(userFile)) { userProperties.load(fileInput); } catch (IOException ioe) { } userProperties.entrySet().forEach(entry -> { String username = (String) entry.getKey(); String password = (String) entry.getValue(); securityManager.addUser(username, password); }); } File userRoleFile = new File(""userrole.properties""); if (!userRoleFile.exists()) { userRoleFile = new File(""etc/userrole.properties""); } if (userRoleFile.exists()) { Properties userRoleProperties = new Properties(); try ( FileInputStream fileInput = new FileInputStream(userRoleFile)) { userRoleProperties.load(fileInput); } catch (IOException ioe) { } userRoleProperties.entrySet().forEach(entry -> { String username = (String) entry.getKey(); String roles = (String) entry.getValue(); securityManager.addUserRole(username, roles.split("","")); }); } webApplication.setAuthenticationManager(new FileAuthenticationManager(userFile)); FilterRegistration.Dynamic dynamic = webApplication.addFilter( FileAuthenticationFilter.class.getName(), FileAuthenticationFilter.class); dynamic.setAsyncSupported(true); webApplication.addFilterMapping( FileAuthenticationFilter.class.getName(), ""/*""); }",Fixes issue #2069 - Make authentication manager an opt-in for DefaultWebApplication,https://github.com/piranhacloud/piranha/commit/95e78d0cfdafbc9207108fe53ada7159fce39af9,,,extension/security-file/src/main/java/cloud/piranha/extension/security/file/FileSecurityInitializer.java,3,java,False,2021-11-07T16:04:56Z "private void verifyForRequest(Map failedTxs, GetTransactionsRequest request) { while (true) { Set notFullyConfirmedTxs = request.getTransactionIds() .stream() .filter(e -> failedTxs.get(e).count < numberOfFailedTransactionConfirmations) .collect(Collectors.toSet()); if (notFullyConfirmedTxs.isEmpty()) { log.info(""Failed transactions are verified for request: {}"", request); return; } GetTransactionsRequest correctedRequest = request.clone(); correctedRequest.setTransactionIds(notFullyConfirmedTxs); Set alreadyUsedPeers = new HashSet<>(); Optional peerResponseOptional = sendToAnother(correctedRequest, alreadyUsedPeers); if (peerResponseOptional.isEmpty()) { log.warn(""Not enough peers to get failed transaction statuses, connected peers {}, already used peers [{}], request: {}"", connectedPublicPeers.size(), alreadyUsedPeers.stream().map(Peer::getHostWithPort).collect(Collectors.joining("","")), correctedRequest); return; } GetTransactionsResponse response = peerResponseOptional.get().getResponse(); Peer peer = peerResponseOptional.get().getPeer(); alreadyUsedPeers.add(peer); Set requestedIds = correctedRequest.getTransactionIds(); if (response.getTransactions().size() > requestedIds.size()) { log.warn(""Possibly malicious {} peer detected: received too many transactions {} instead of {} "", peer.getHostWithPort(), response.getTransactions().size(), requestedIds.size()); peer.blacklist(""Too many transactions supplied for failed transactions validation""); continue; } if (response.getTransactions().size() < requestedIds.size()) { Set receivedIds = response.getTransactions() .stream() .map(UnconfirmedTransactionDTO::getTransaction) .map(Long::parseUnsignedLong) .collect(Collectors.toSet()); receivedIds.removeAll(requestedIds); log.debug(""Peer {} is missing {} transactions for validation: {}"", peer.getHostWithPort(), receivedIds.size(), receivedIds); } for (TransactionDTO tx : response.getTransactions()) { VerifiedError verifiedError = failedTxs.get(Long.parseUnsignedLong(tx.getTransaction())); if (verifiedError == null) { log.warn(""Possibly malicious {} peer detected at height {}: {} is not expected transaction from GetTransactions request: {}"", peer.getHostWithPort(), blockchain.getHeight(), tx.getTransaction(), correctedRequest); peer.blacklist(""Peer returned not expected transaction: "" + tx.getTransaction()); break; } if (!verifiedError.verify(tx.getErrorMessage())) { log.warn(""Blockchain inconsistency may occur. Transaction {} validation & execution results into error message '{}', "" + ""which does not match to {} peer's result '{}'"", tx.getTransaction(), verifiedError.getError(), tx.getErrorMessage(), peer.getHost()); } } } }","private void verifyForRequest(Map failedTxs, GetTransactionsRequest request) { while (true) { Set notFullyConfirmedTxs = request.getTransactionIds() .stream() .filter(e -> failedTxs.get(e).count < numberOfFailedTransactionConfirmations) .collect(Collectors.toSet()); if (notFullyConfirmedTxs.isEmpty()) { log.info(""Transaction's statuses are verified for request: {}"", request); return; } GetTransactionsRequest correctedRequest = request.clone(); correctedRequest.setTransactionIds(notFullyConfirmedTxs); Set alreadyUsedPeers = new HashSet<>(); Optional peerResponseOptional = sendToAnother(correctedRequest, alreadyUsedPeers); if (peerResponseOptional.isEmpty()) { log.warn(""Not enough peers to get failed transaction statuses, connected peers {}, already used peers [{}], request: {}"", connectedPublicPeers.size(), alreadyUsedPeers.stream().map(Peer::getHostWithPort).collect(Collectors.joining("","")), correctedRequest); return; } GetTransactionsResponse response = peerResponseOptional.get().getResponse(); Peer peer = peerResponseOptional.get().getPeer(); alreadyUsedPeers.add(peer); Set requestedIds = new HashSet<>(correctedRequest.getTransactionIds()); if (response.getTransactions().size() > requestedIds.size()) { log.error(""Possibly malicious {} peer detected: received too many transactions {} instead of {} "", peer.getHostWithPort(), response.getTransactions().size(), requestedIds.size()); peer.blacklist(""Too many transactions supplied for failed transactions validation""); connectedPublicPeers.remove(peer); continue; } if (response.getTransactions().size() < requestedIds.size()) { Set receivedIds = response.getTransactions() .stream() .map(UnconfirmedTransactionDTO::getTransaction) .map(Long::parseUnsignedLong) .collect(Collectors.toSet()); requestedIds.removeAll(receivedIds); log.debug(""Peer {} is missing {} transactions for validation: {}"", peer.getHostWithPort(), requestedIds.size(), requestedIds); } for (TransactionDTO tx : response.getTransactions()) { VerifiedError verifiedError = failedTxs.get(Long.parseUnsignedLong(tx.getTransaction())); if (verifiedError == null) { log.error(""Possibly malicious {} peer detected at height {}: {} is not expected transaction from GetTransactions request: {}"", peer.getHostWithPort(), blockchain.getHeight(), tx.getTransaction(), correctedRequest); peer.blacklist(""Peer returned not expected transaction: "" + tx.getTransaction()); connectedPublicPeers.remove(peer); break; } if (!verifiedError.verify(tx.getErrorMessage())) { log.warn(""Blockchain inconsistency may occur. Transaction's {} validation & execution results into an error message '{}', "" + ""which does not match to {} peer's result '{}'"", tx.getTransaction(), verifiedError.getError(), tx.getErrorMessage(), peer.getHost()); } } } }","Add failed transaction processing verification, blacklist peers and remove them from connected list after first incorrect response, add more malicious peers to increase coverage",https://github.com/ApolloFoundation/Apollo/commit/5f9200abb8502a80b51526345c8ded7200f119d5,,,apl-core/src/main/java/com/apollocurrency/aplwallet/apl/core/app/runnable/GetMoreBlocksJob.java,3,java,False,2021-07-12T14:29:30Z "public long requirePreAllocation(int requireSize, int retryMax, long retryIntervalMax) { RequireBufferRequest rpcRequest = RequireBufferRequest.newBuilder().setRequireSize(requireSize).build(); long start = System.currentTimeMillis(); RequireBufferResponse rpcResponse = blockingStub.withDeadlineAfter( RPC_TIMEOUT_DEFAULT_MS, TimeUnit.MILLISECONDS).requireBuffer(rpcRequest); int retry = 0; long result = FAILED_REQUIRE_ID; Random random = new Random(); final int backOffBase = 2000; while (rpcResponse.getStatus() == StatusCode.NO_BUFFER) { LOG.info(""Can't require "" + requireSize + "" bytes from "" + host + "":"" + port + "", sleep and try["" + retry + ""] again""); if (retry >= retryMax) { LOG.warn(""ShuffleServer "" + host + "":"" + port + "" is full and can't send shuffle"" + "" data successfully after retry "" + retryMax + "" times, cost: {}(ms)"", System.currentTimeMillis() - start); return result; } try { long backoffTime = Math.min(retryIntervalMax, backOffBase * (1 << Math.min(retry, 16)) + random.nextInt(backOffBase)); Thread.sleep(backoffTime); } catch (Exception e) { LOG.warn(""Exception happened when require pre allocation from "" + host + "":"" + port, e); } rpcResponse = blockingStub.withDeadlineAfter( RPC_TIMEOUT_DEFAULT_MS, TimeUnit.MILLISECONDS).requireBuffer(rpcRequest); retry++; } if (rpcResponse.getStatus() == StatusCode.SUCCESS) { LOG.info(""Require preAllocated size of {} from {}:{}, cost: {}(ms)"", requireSize, host, port, System.currentTimeMillis() - start); result = rpcResponse.getRequireBufferId(); } return result; }","public long requirePreAllocation(int requireSize, int retryMax, long retryIntervalMax) { RequireBufferRequest rpcRequest = RequireBufferRequest.newBuilder().setRequireSize(requireSize).build(); long start = System.currentTimeMillis(); RequireBufferResponse rpcResponse = getBlockingStub().requireBuffer(rpcRequest); int retry = 0; long result = FAILED_REQUIRE_ID; Random random = new Random(); final int backOffBase = 2000; while (rpcResponse.getStatus() == StatusCode.NO_BUFFER) { LOG.info(""Can't require "" + requireSize + "" bytes from "" + host + "":"" + port + "", sleep and try["" + retry + ""] again""); if (retry >= retryMax) { LOG.warn(""ShuffleServer "" + host + "":"" + port + "" is full and can't send shuffle"" + "" data successfully after retry "" + retryMax + "" times, cost: {}(ms)"", System.currentTimeMillis() - start); return result; } try { long backoffTime = Math.min(retryIntervalMax, backOffBase * (1 << Math.min(retry, 16)) + random.nextInt(backOffBase)); Thread.sleep(backoffTime); } catch (Exception e) { LOG.warn(""Exception happened when require pre allocation from "" + host + "":"" + port, e); } rpcResponse = getBlockingStub().requireBuffer(rpcRequest); retry++; } if (rpcResponse.getStatus() == StatusCode.SUCCESS) { LOG.info(""Require preAllocated size of {} from {}:{}, cost: {}(ms)"", requireSize, host, port, System.currentTimeMillis() - start); result = rpcResponse.getRequireBufferId(); } return result; }","[ISSUE-106][IMPROVEMENT] Set rpc timeout for all rpc interface (#113) ### What changes were proposed in this pull request? Solve issue #106 Set rpc timeout for all rpc interface ### Why are the changes needed? If oom encountered in shuffle server, rpc client will blocked until shuffle server was killed ### Does this PR introduce _any_ user-facing change? No ### How was this patch tested? No need",https://github.com/apache/incubator-uniffle/commit/503f796c494709e18eef19f2f28c5791b2590df2,,,internal-client/src/main/java/org/apache/uniffle/client/impl/grpc/ShuffleServerGrpcClient.java,3,java,False,2022-08-03T02:48:01Z "protected AzureAppService getOrCreateAzureAppServiceClient() { return Azure.az(AzureAppService.class); }","protected AzureAppService getOrCreateAzureAppServiceClient() throws AzureExecutionException { if (appServiceClient == null) { try { final Account account = getAzureAccount(); final List subscriptions = account.getSubscriptions(); final String targetSubscriptionId = getTargetSubscriptionId(getSubscriptionId(), subscriptions, account.getSelectedSubscriptions()); checkSubscription(subscriptions, targetSubscriptionId); appServiceClient = Azure.az(AzureAppService.class).subscription(targetSubscriptionId); } catch (AzureLoginException | AzureExecutionException | IOException e) { throw new AzureExecutionException(String.format(""Cannot authenticate due to error %s"", e.getMessage()), e); } } return appServiceClient; }",Fix authentication issue for web app maven plugin with new account library,https://github.com/microsoft/azure-maven-plugins/commit/292af215fea14f0934649c0e46aff657bbd02d35,,,azure-webapp-maven-plugin/src/main/java/com/microsoft/azure/maven/webapp/AbstractWebAppMojo.java,3,java,False,2021-03-16T08:56:31Z "@GetMapping(value=LICENSE.LIST_AJAX) public @ResponseBody ResponseEntity listAjax( LicenseMaster licenseMaster , HttpServletRequest req , HttpServletResponse res , Model model){ int page = Integer.parseInt(req.getParameter(""page"")); int rows = Integer.parseInt(req.getParameter(""rows"")); String sidx = req.getParameter(""sidx""); String sord = req.getParameter(""sord""); licenseMaster.setCurPage(page); licenseMaster.setPageListSize(rows); licenseMaster.setSortField(sidx); licenseMaster.setSortOrder(sord); if(""search"".equals(req.getParameter(""act""))) { // 검색 조건 저장 putSessionObject(SESSION_KEY_SEARCH, licenseMaster); } else if(getSessionObject(SESSION_KEY_SEARCH) != null) { licenseMaster = (LicenseMaster) getSessionObject(SESSION_KEY_SEARCH); } Map map = null; try { if(isEmpty(licenseMaster.getLicenseNameAllSearchFlag())) { licenseMaster.setLicenseNameAllSearchFlag(CoConstDef.FLAG_NO); } licenseMaster.setTotListSize(licenseService.selectLicenseMasterTotalCount(licenseMaster)); map = licenseService.getLicenseMasterList(licenseMaster); } catch(Exception e) { log.error(e.getMessage(), e); } return makeJsonResponseHeader(map); }","@GetMapping(value=LICENSE.LIST_AJAX) public @ResponseBody ResponseEntity listAjax( LicenseMaster licenseMaster , HttpServletRequest req , HttpServletResponse res , Model model){ int page = Integer.parseInt(req.getParameter(""page"")); int rows = Integer.parseInt(req.getParameter(""rows"")); String sidx = req.getParameter(""sidx""); String sord = req.getParameter(""sord""); licenseMaster.setCurPage(page); licenseMaster.setPageListSize(rows); licenseMaster.setSortField(sidx); licenseMaster.setSortOrder(sord); if(""search"".equals(req.getParameter(""act""))) { // 검색 조건 저장 putSessionObject(SESSION_KEY_SEARCH, licenseMaster); } else if(getSessionObject(SESSION_KEY_SEARCH) != null) { licenseMaster = (LicenseMaster) getSessionObject(SESSION_KEY_SEARCH); } Map map = null; try { if(isEmpty(licenseMaster.getLicenseNameAllSearchFlag())) { licenseMaster.setLicenseNameAllSearchFlag(CoConstDef.FLAG_NO); } licenseMaster.setTotListSize(licenseService.selectLicenseMasterTotalCount(licenseMaster)); map = licenseService.getLicenseMasterList(licenseMaster); } catch(Exception e) { log.error(e.getMessage(), e); } XssFilter.licenseMasterFilter((List) map.get(""rows"")); return makeJsonResponseHeader(map); }","Add Xss filter for list.jsp and autocomplete It is so boring work to add a defence code in view. Becaues list.jsp use jqGrid and autocomplete use jQuery, I may have to amend jqGrid and jQuery code to defend Xss attack in view. So I add Xss filter in controller. Signed-off-by: yugeeklab ",https://github.com/fosslight/fosslight/commit/ed045b308b77f7be65030c2b570db882c321c5d9,,,src/main/java/oss/fosslight/controller/LicenseController.java,3,java,False,2021-11-11T06:51:12Z "private void downloadPeer() { try { long startTime = System.currentTimeMillis(); int numberOfForkConfirmations = blockchain.getHeight() > Constants.LAST_CHECKSUM_BLOCK - Constants.MAX_AUTO_ROLLBACK ? defaultNumberOfForkConfirmations : Math.min(1, defaultNumberOfForkConfirmations); connectedPublicPeers = peersService.getPublicPeers(PeerState.CONNECTED, true); if (connectedPublicPeers.size() <= numberOfForkConfirmations) { log.trace(""downloadPeer connected = {} <= numberOfForkConfirmations = {}"", connectedPublicPeers.size(), numberOfForkConfirmations); return; } peerHasMore = true; final Peer peer = peersService.getWeightedPeer(connectedPublicPeers); if (peer == null) { log.debug(""Can not find weighted peer""); return; } GetCumulativeDifficultyResponse response = peer.send(getCumulativeDifficultyRequest, new GetCumulativeDifficultyResponseParser()); if (response == null) { log.debug(""Null response wile getCumulativeDifficultyRequest from peer {}"", peer.getHostWithPort()); return; } Block lastBlock = blockchain.getLastBlock(); BigInteger curCumulativeDifficulty = lastBlock.getCumulativeDifficulty(); BigInteger peerCumulativeDifficulty = response.getCumulativeDifficulty(); if (peerCumulativeDifficulty == null) { return; } if (peerCumulativeDifficulty.compareTo(curCumulativeDifficulty) < 0) { return; } if (response.getBlockchainHeight() != null) { blockchainProcessorState.setLastBlockchainFeeder(peer); blockchainProcessorState.setLastBlockchainFeederHeight(response.getBlockchainHeight().intValue()); } if (peerCumulativeDifficulty.equals(curCumulativeDifficulty)) { return; } long commonMilestoneBlockId = blockchain.getShardInitialBlock().getId(); if (blockchain.getHeight() > 0) { commonMilestoneBlockId = getCommonMilestoneBlockId(peer); } if (commonMilestoneBlockId == 0 || !peerHasMore) { return; } chainBlockIds = getBlockIdsAfterCommon(peer, commonMilestoneBlockId, false); if (chainBlockIds.size() < 2 || !peerHasMore) { if (commonMilestoneBlockId == blockchain.getShardInitialBlock().getId()) { log.info(""Cannot load blocks after genesis block {} from peer {}, perhaps using different Genesis block"", commonMilestoneBlockId, peer.getAnnouncedAddress()); } return; } final long commonBlockId = chainBlockIds.get(0); final Block commonBlock = blockchain.getBlock(commonBlockId); if (commonBlock == null || blockchain.getHeight() - commonBlock.getHeight() >= Constants.MAX_AUTO_ROLLBACK) { if (commonBlock != null) { log.debug(""Peer {} advertised chain with better difficulty, but the last common block is at height {}, peer info - {}"", peer.getAnnouncedAddress(), commonBlock.getHeight(), peer); } return; } if (!blockchainProcessorState.isDownloading() && blockchainProcessorState.getLastBlockchainFeederHeight() - commonBlock.getHeight() > 10) { log.info(""Blockchain download in progress, set blockchain state isDownloading=true.""); blockchainProcessorState.setDownloading(true); } // TODO Maybe better to find another sync solution globalSync.updateLock(); try { if (peerCumulativeDifficulty.compareTo(blockchain.getLastBlock().getCumulativeDifficulty()) <= 0) { return; } long lastBlockId = blockchain.getLastBlock().getId(); downloadBlockchain(peer, commonBlock, commonBlock.getHeight()); verifyFailedTransactions(commonBlock); if (blockchain.getHeight() - commonBlock.getHeight() <= 10) { return; } int confirmations = 0; for (Peer otherPeer : connectedPublicPeers) { if (confirmations >= numberOfForkConfirmations) { break; } if (peer.getHost().equals(otherPeer.getHost())) { continue; } chainBlockIds = getBlockIdsAfterCommon(otherPeer, commonBlockId, true); if (chainBlockIds.isEmpty()) { continue; } long otherPeerCommonBlockId = chainBlockIds.get(0); if (otherPeerCommonBlockId == blockchain.getLastBlock().getId()) { confirmations++; continue; } Block otherPeerCommonBlock = blockchain.getBlock(otherPeerCommonBlockId); if (blockchain.getHeight() - otherPeerCommonBlock.getHeight() >= Constants.MAX_AUTO_ROLLBACK) { continue; } BigInteger otherPeerCumulativeDifficulty = response.getCumulativeDifficulty(); GetCumulativeDifficultyResponse otherPeerResponse = peer.send(getCumulativeDifficultyRequest, new GetCumulativeDifficultyResponseParser()); if (otherPeerResponse == null || otherPeerCumulativeDifficulty == null) { continue; } if (otherPeerCumulativeDifficulty.compareTo(blockchain.getLastBlock().getCumulativeDifficulty()) <= 0) { continue; } log.debug(""Found a peer with better difficulty: {}"", otherPeer.getHostWithPort()); downloadBlockchain(otherPeer, otherPeerCommonBlock, commonBlock.getHeight()); } log.debug(""Got "" + confirmations + "" confirmations""); if (blockchain.getLastBlock().getId() != lastBlockId) { long time = System.currentTimeMillis() - startTime; totalTime += time; int numBlocks = blockchain.getHeight() - commonBlock.getHeight(); totalBlocks += numBlocks; log.info(""Downloaded "" + numBlocks + "" blocks in "" + time / 1000 + "" s, "" + (totalBlocks * 1000) / totalTime + "" per s, "" + totalTime * (blockchainProcessorState.getLastBlockchainFeederHeight() - blockchain.getHeight()) / ((long) totalBlocks * 1000 * 60) + "" min left""); } else { log.debug(""Did not accept peer's blocks, back to our own fork""); } } finally { globalSync.updateUnlock(); blockchainProcessorState.setDownloading(false); log.debug(""Set blockchain state isDownloading=false.""); } } catch (Exception e) { log.info(""Error in blockchain download thread"", e); } }","private void downloadPeer() { try { long startTime = System.currentTimeMillis(); int numberOfForkConfirmations = blockchain.getHeight() > Constants.LAST_CHECKSUM_BLOCK - Constants.MAX_AUTO_ROLLBACK ? defaultNumberOfForkConfirmations : Math.min(1, defaultNumberOfForkConfirmations); connectedPublicPeers = Collections.synchronizedList(new ArrayList<>(peersService.getPublicPeers(PeerState.CONNECTED, true))); if (connectedPublicPeers.size() <= numberOfForkConfirmations) { log.trace(""downloadPeer connected = {} <= numberOfForkConfirmations = {}"", connectedPublicPeers.size(), numberOfForkConfirmations); return; } peerHasMore = true; final Peer peer = peersService.getWeightedPeer(connectedPublicPeers); if (peer == null) { log.debug(""Can not find weighted peer""); return; } GetCumulativeDifficultyResponse response = peer.send(getCumulativeDifficultyRequest, new GetCumulativeDifficultyResponseParser()); if (response == null) { log.debug(""Null response wile getCumulativeDifficultyRequest from peer {}"", peer.getHostWithPort()); return; } Block lastBlock = blockchain.getLastBlock(); BigInteger curCumulativeDifficulty = lastBlock.getCumulativeDifficulty(); BigInteger peerCumulativeDifficulty = response.getCumulativeDifficulty(); if (peerCumulativeDifficulty == null) { return; } if (peerCumulativeDifficulty.compareTo(curCumulativeDifficulty) < 0) { return; } if (response.getBlockchainHeight() != null) { blockchainProcessorState.setLastBlockchainFeeder(peer); blockchainProcessorState.setLastBlockchainFeederHeight(response.getBlockchainHeight().intValue()); } if (peerCumulativeDifficulty.equals(curCumulativeDifficulty)) { return; } long commonMilestoneBlockId = blockchain.getShardInitialBlock().getId(); if (blockchain.getHeight() > 0) { commonMilestoneBlockId = getCommonMilestoneBlockId(peer); } if (commonMilestoneBlockId == 0 || !peerHasMore) { return; } chainBlockIds = getBlockIdsAfterCommon(peer, commonMilestoneBlockId, false); if (chainBlockIds.size() < 2 || !peerHasMore) { if (commonMilestoneBlockId == blockchain.getShardInitialBlock().getId()) { log.info(""Cannot load blocks after genesis block {} from peer {}, perhaps using different Genesis block"", commonMilestoneBlockId, peer.getAnnouncedAddress()); } return; } final long commonBlockId = chainBlockIds.get(0); final Block commonBlock = blockchain.getBlock(commonBlockId); if (commonBlock == null || blockchain.getHeight() - commonBlock.getHeight() >= Constants.MAX_AUTO_ROLLBACK) { if (commonBlock != null) { log.debug(""Peer {} advertised chain with better difficulty, but the last common block is at height {}, peer info - {}"", peer.getAnnouncedAddress(), commonBlock.getHeight(), peer); } return; } if (!blockchainProcessorState.isDownloading() && blockchainProcessorState.getLastBlockchainFeederHeight() - commonBlock.getHeight() > 10) { log.info(""Blockchain download in progress, set blockchain state isDownloading=true.""); blockchainProcessorState.setDownloading(true); } // TODO Maybe better to find another sync solution globalSync.updateLock(); try { if (peerCumulativeDifficulty.compareTo(blockchain.getLastBlock().getCumulativeDifficulty()) <= 0) { return; } long lastBlockId = blockchain.getLastBlock().getId(); downloadBlockchain(peer, commonBlock, commonBlock.getHeight()); verifyFailedTransactions(commonBlock); if (blockchain.getHeight() - commonBlock.getHeight() <= 10) { return; } int confirmations = 0; for (Peer otherPeer : connectedPublicPeers) { if (confirmations >= numberOfForkConfirmations) { break; } if (peer.getHost().equals(otherPeer.getHost())) { continue; } chainBlockIds = getBlockIdsAfterCommon(otherPeer, commonBlockId, true); if (chainBlockIds.isEmpty()) { continue; } long otherPeerCommonBlockId = chainBlockIds.get(0); if (otherPeerCommonBlockId == blockchain.getLastBlock().getId()) { confirmations++; continue; } Block otherPeerCommonBlock = blockchain.getBlock(otherPeerCommonBlockId); if (blockchain.getHeight() - otherPeerCommonBlock.getHeight() >= Constants.MAX_AUTO_ROLLBACK) { continue; } BigInteger otherPeerCumulativeDifficulty = response.getCumulativeDifficulty(); GetCumulativeDifficultyResponse otherPeerResponse = peer.send(getCumulativeDifficultyRequest, new GetCumulativeDifficultyResponseParser()); if (otherPeerResponse == null || otherPeerCumulativeDifficulty == null) { continue; } if (otherPeerCumulativeDifficulty.compareTo(blockchain.getLastBlock().getCumulativeDifficulty()) <= 0) { continue; } log.debug(""Found a peer with better difficulty: {}"", otherPeer.getHostWithPort()); downloadBlockchain(otherPeer, otherPeerCommonBlock, commonBlock.getHeight()); } log.debug(""Got "" + confirmations + "" confirmations""); if (blockchain.getLastBlock().getId() != lastBlockId) { long time = System.currentTimeMillis() - startTime; totalTime += time; int numBlocks = blockchain.getHeight() - commonBlock.getHeight(); totalBlocks += numBlocks; log.info(""Downloaded "" + numBlocks + "" blocks in "" + time / 1000 + "" s, "" + (totalBlocks * 1000) / totalTime + "" per s, "" + totalTime * (blockchainProcessorState.getLastBlockchainFeederHeight() - blockchain.getHeight()) / ((long) totalBlocks * 1000 * 60) + "" min left""); } else { log.debug(""Did not accept peer's blocks, back to our own fork""); } } finally { globalSync.updateUnlock(); blockchainProcessorState.setDownloading(false); log.debug(""Set blockchain state isDownloading=false.""); } } catch (Exception e) { log.info(""Error in blockchain download thread"", e); } }","Add failed transaction processing verification, blacklist peers and remove them from connected list after first incorrect response, add more malicious peers to increase coverage",https://github.com/ApolloFoundation/Apollo/commit/5f9200abb8502a80b51526345c8ded7200f119d5,,,apl-core/src/main/java/com/apollocurrency/aplwallet/apl/core/app/runnable/GetMoreBlocksJob.java,3,java,False,2021-07-12T14:29:30Z "private static boolean parseCommandLine(Options options, String[] newArgs, HelpFormatter hf) { try { CommandLineParser parser = new DefaultParser(); commandLine = parser.parse(options, newArgs); if (commandLine.hasOption(HELP_ARGS)) { hf.printHelp(IOTDB_CLI_PREFIX, options, true); return false; } if (commandLine.hasOption(RPC_COMPRESS_ARGS)) { Config.rpcThriftCompressionEnable = true; } if (commandLine.hasOption(ISO8601_ARGS)) { timeFormat = RpcUtils.setTimeFormat(""long""); } if (commandLine.hasOption(MAX_PRINT_ROW_COUNT_ARGS)) { maxPrintRowCount = Integer.parseInt(commandLine.getOptionValue(MAX_PRINT_ROW_COUNT_ARGS)); if (maxPrintRowCount <= 0) { println( IOTDB_CLI_PREFIX + ""> error format of max print row count, it should be a number greater than 0""); return false; } } } catch (ParseException e) { println(""Require more params input, please check the following hint.""); hf.printHelp(IOTDB_CLI_PREFIX, options, true); return false; } catch (NumberFormatException e) { println(IOTDB_CLI_PREFIX + ""> error format of max print row count, it should be a number""); return false; } return true; }","private static boolean parseCommandLine(Options options, String[] newArgs, HelpFormatter hf) { try { CommandLineParser parser = new DefaultParser(); commandLine = parser.parse(options, newArgs); if (commandLine.hasOption(HELP_ARGS)) { hf.printHelp(IOTDB_CLI_PREFIX, options, true); return false; } if (commandLine.hasOption(RPC_COMPRESS_ARGS)) { Config.rpcThriftCompressionEnable = true; } if (commandLine.hasOption(ISO8601_ARGS)) { timeFormat = RpcUtils.setTimeFormat(""long""); } if (commandLine.hasOption(MAX_PRINT_ROW_COUNT_ARGS)) { setMaxDisplayNumber(commandLine.getOptionValue(MAX_PRINT_ROW_COUNT_ARGS)); } } catch (ParseException e) { println(""Require more params input, please check the following hint.""); hf.printHelp(IOTDB_CLI_PREFIX, options, true); return false; } catch (NumberFormatException e) { println( IOTDB_CLI_PREFIX + ""> error format of max print row count, it should be an integer number""); return false; } return true; }","[To rel/0.12] cherry-pick two CLI bug fix PRs (#3944) * [IOTDB-1275] Fix backgroup exec for cli -e function causes an infinite loop in writing output file (#3932) * [IOTDB-1659] Fix Windows CLI cannot set maxPRC less than or equal to 0 (#3936)",https://github.com/apache/iotdb/commit/489a51c486c46d2d32bc2bc10dfc35f9394f8aae,,,cli/src/main/java/org/apache/iotdb/cli/WinCli.java,3,java,False,2021-09-10T09:37:17Z "public boolean validateEthSignature(AccountStore accountStore, DynamicPropertiesStore dynamicPropertiesStore, TransferContract contract) throws ValidateSignatureException { if (!isVerified) { if (dynamicPropertiesStore.getAllowEthereumCompatibleTransaction() == 0){ throw new ValidateSignatureException(""EthereumCompatibleTransaction is off, need to be opened by proposal""); } if (this.transaction.getSignatureCount() <= 0 || this.transaction.getRawData().getContractCount() <= 0) { throw new ValidateSignatureException(""miss sig or contract""); } if (this.transaction.getSignatureCount() > dynamicPropertiesStore .getTotalSignNum()) { throw new ValidateSignatureException(""too many signatures""); } if (contract.getType() != 1) { throw new ValidateSignatureException(""not eth contract""); } EthTrx t = new EthTrx(contract.getRlpData().toByteArray()); t.rlpParse(); try { TransferContract contractFromParse = t.rlpParseToTransferContract(); if(!contractFromParse.equals(contract)){ isVerified = false; throw new ValidateSignatureException(""eth sig error""); } if (!validateSignature(this.transaction, t.getRawHash(), accountStore, dynamicPropertiesStore)) { isVerified = false; throw new ValidateSignatureException(""sig error""); } } catch (SignatureException | PermissionException | SignatureFormatException e) { isVerified = false; throw new ValidateSignatureException(e.getMessage()); } isVerified = true; } return true; }","public boolean validateEthSignature(AccountStore accountStore, DynamicPropertiesStore dynamicPropertiesStore, TransferContract contract) throws ValidateSignatureException { if (!isVerified) { if (dynamicPropertiesStore.getAllowEthereumCompatibleTransaction() == 0){ throw new ValidateSignatureException(""EthereumCompatibleTransaction is off, need to be opened by proposal""); } if (this.transaction.getSignatureCount() <= 0 || this.transaction.getRawData().getContractCount() <= 0) { throw new ValidateSignatureException(""miss sig or contract""); } if (this.transaction.getSignatureCount() != 1) { throw new ValidateSignatureException(""eth contract only one signature""); } if (contract.getType() != 1) { throw new ValidateSignatureException(""not eth contract""); } EthTrx t = new EthTrx(contract.getRlpData().toByteArray()); t.rlpParse(); try { TransferContract contractFromParse = t.rlpParseToTransferContract(); if(!contractFromParse.equals(contract)){ isVerified = false; throw new ValidateSignatureException(""eth sig error, vision transaction have been changed,not equal rlp parsed transaction""); } if (!validateSignature(this.transaction, t.getRawHash(), accountStore, dynamicPropertiesStore)) { isVerified = false; throw new ValidateSignatureException(""eth sig error""); } } catch (SignatureException | PermissionException | SignatureFormatException e) { isVerified = false; throw new ValidateSignatureException(e.getMessage()); } isVerified = true; } return true; }","Bugfix/20220108/ethereum compatible replayattack (#113) * update version ultima_v1.0.3 * optimize validateEthSignature and rlpParseContract parameters * update version ultima_v1.0.4",https://github.com/vision-consensus/vision-core/commit/89c1e0742966adf99fb5fa855c6b6e37c63e861f,,,chainstorage/src/main/java/org/vision/core/capsule/TransactionCapsule.java,3,java,False,2022-01-21T13:15:55Z "public boolean validateEthSignature(AccountStore accountStore, DynamicPropertiesStore dynamicPropertiesStore, CreateSmartContract contract) throws ValidateSignatureException { if (!isVerified) { if (dynamicPropertiesStore.getAllowEthereumCompatibleTransaction() == 0){ throw new ValidateSignatureException(""EthereumCompatibleTransaction is off, need to be opened by proposal""); } if (this.transaction.getSignatureCount() <= 0 || this.transaction.getRawData().getContractCount() <= 0) { throw new ValidateSignatureException(""miss sig or contract""); } if (this.transaction.getSignatureCount() > dynamicPropertiesStore .getTotalSignNum()) { throw new ValidateSignatureException(""too many signatures""); } if (contract.getType() != 1) { throw new ValidateSignatureException(""not eth contract""); } EthTrx t = new EthTrx(contract.getRlpData().toByteArray()); t.rlpParse(); try { CreateSmartContract contractFromParse = t.rlpParseToDeployContract(); if(!contractFromParse.equals(contract)){ isVerified = false; throw new ValidateSignatureException(""eth sig error""); } if (!validateSignature(this.transaction, t.getRawHash(), accountStore, dynamicPropertiesStore)) { isVerified = false; throw new ValidateSignatureException(""sig error""); } } catch (SignatureException | PermissionException | SignatureFormatException e) { isVerified = false; throw new ValidateSignatureException(e.getMessage()); } isVerified = true; } return true; }","public boolean validateEthSignature(AccountStore accountStore, DynamicPropertiesStore dynamicPropertiesStore, CreateSmartContract contract) throws ValidateSignatureException { if (!isVerified) { if (dynamicPropertiesStore.getAllowEthereumCompatibleTransaction() == 0){ throw new ValidateSignatureException(""EthereumCompatibleTransaction is off, need to be opened by proposal""); } if (this.transaction.getSignatureCount() <= 0 || this.transaction.getRawData().getContractCount() <= 0) { throw new ValidateSignatureException(""miss sig or contract""); } if (this.transaction.getSignatureCount() != 1) { throw new ValidateSignatureException(""eth contract only one signature""); } if (contract.getType() != 1) { throw new ValidateSignatureException(""not eth contract""); } EthTrx t = new EthTrx(contract.getRlpData().toByteArray()); t.rlpParse(); try { CreateSmartContract contractFromParse = t.rlpParseToDeployContract(); if(!contractFromParse.equals(contract)){ isVerified = false; throw new ValidateSignatureException(""eth sig error, vision transaction have been changed,not equal rlp parsed transaction""); } if (!validateSignature(this.transaction, t.getRawHash(), accountStore, dynamicPropertiesStore)) { isVerified = false; throw new ValidateSignatureException(""eth sig error""); } } catch (SignatureException | PermissionException | SignatureFormatException e) { isVerified = false; throw new ValidateSignatureException(e.getMessage()); } isVerified = true; } return true; }","Bugfix/20220108/ethereum compatible replayattack (#113) * update version ultima_v1.0.3 * optimize validateEthSignature and rlpParseContract parameters * update version ultima_v1.0.4",https://github.com/vision-consensus/vision-core/commit/89c1e0742966adf99fb5fa855c6b6e37c63e861f,,,chainstorage/src/main/java/org/vision/core/capsule/TransactionCapsule.java,3,java,False,2022-01-21T13:15:55Z "private void trigger(@NotNull final Button button) { final int index = actionsList.getListElementIndexByPane(button); final Action action = actions.get(index); final IPermissions permissions = building.getColony().getPermissions(); final Player playerEntity = Minecraft.getInstance().player; if (!permissions.hasPermission(playerEntity, Action.EDIT_PERMISSIONS) || !permissions.canAlterPermission(permissions.getRank(playerEntity), actionsRank, action)) { return; } final boolean trigger = LanguageHandler.format(COM_MINECOLONIES_COREMOD_GUI_WORKERHUTS_RETRIEVE_ON).equals(button.getTextAsString()); Network.getNetwork().sendToServer(new PermissionsMessage.Permission(building.getColony(), PermissionsMessage.MessageType.TOGGLE_PERMISSION, actionsRank, action)); building.getColony().getPermissions().togglePermission(permissions.getRank(playerEntity), actionsRank, action); if (trigger) { button.setText(new TranslatableComponent(COM_MINECOLONIES_COREMOD_GUI_WORKERHUTS_RETRIEVE_OFF)); } else { button.setText(new TranslatableComponent(COM_MINECOLONIES_COREMOD_GUI_WORKERHUTS_RETRIEVE_ON)); } }","private void trigger(@NotNull final Button button) { final int index = actionsList.getListElementIndexByPane(button); final Action action = actions.get(index); final IPermissions permissions = building.getColony().getPermissions(); final Player playerEntity = Minecraft.getInstance().player; final boolean enable = !LanguageHandler.format(COM_MINECOLONIES_COREMOD_GUI_WORKERHUTS_RETRIEVE_ON).equals(button.getTextAsString()); button.disable(); if (!permissions.alterPermission(permissions.getRank(playerEntity), actionsRank, action, enable)) { return; } Network.getNetwork().sendToServer(new PermissionsMessage.Permission(building.getColony(), enable, actionsRank, action)); if (!enable) { button.setText(new TranslatableComponent(COM_MINECOLONIES_COREMOD_GUI_WORKERHUTS_RETRIEVE_OFF)); } else { button.setText(new TranslatableComponent(COM_MINECOLONIES_COREMOD_GUI_WORKERHUTS_RETRIEVE_ON)); } }","Fix permission issues (#7972) Ranks are no longer a static map, which was used as a per-colony map thus causing crashes and desyncs. If the last colony loaded had a custom rank, all other colonies would crash out due to not matching permissions for that rank. Permission/Rank seperation is removed, permission flag is now part of the rank instead of an externally synced map, which also auto-corrects bad stored data to default permissions. UI now has non-changeable permission buttons disabled.",https://github.com/ldtteam/minecolonies/commit/b1b86dffe64dd4c0f9d3060769fc418fd5d2869a,,,src/main/java/com/minecolonies/coremod/client/gui/townhall/WindowPermissionsPage.java,3,java,False,2022-01-23T12:23:45Z "private void initialAcl() { if (!this.serverConfig.isRopAclEnable()) { log.info(""The broker dose not enable acl""); return; } String authToken = this.serverConfig.getBrokerClientAuthenticationParameters(); getRemotingServer().registerRPCHook(new RPCHook() { @Override public void doBeforeRequest(String remoteAddr, RemotingCommand request) { if (request.getExtFields() == null) { // If request's extFields is null,then return """". return; } // token authorization logic String token = request.getExtFields().get(SessionCredentials.ACCESS_KEY); if (Strings.EMPTY.equals(token)) { log.error(""The access key is null, please check.""); return; } AuthenticationProviderToken providerToken = new AuthenticationProviderToken(); if (!providerToken.getAuthMethodName().equals(""token"")) { log.error(""Unsupported form of encryption is used, please check""); return; } AuthenticationService authService = brokerService.getAuthenticationService(); AuthenticationDataCommand authCommand = new AuthenticationDataCommand(token); if (RequestCode.SEND_MESSAGE == request.getCode() || RequestCode.SEND_MESSAGE_V2 == request.getCode() || RequestCode.CONSUMER_SEND_MSG_BACK == request.getCode() || RequestCode.SEND_BATCH_MESSAGE == request.getCode()) { try { SendMessageRequestHeader requestHeader = SendMessageProcessor .parseRequestHeader(request); if (requestHeader == null) { log.warn(""Parse send message request header.""); return; } String roleSubject = authService.authenticate(authCommand, ""token""); String topicName = TopicNameUtils.parseTopicName(requestHeader.getTopic()); Boolean authOK = brokerService.getAuthorizationService() .allowTopicOperationAsync(TopicName.get(topicName), TopicOperation.PRODUCE, roleSubject, authCommand).get(); if (!authOK) { log.error(""[PRODUCE] Token authentication failed, please check""); return; } } catch (Exception e) { e.printStackTrace(); } } else if (RequestCode.PULL_MESSAGE == request.getCode()) { try { final PullMessageRequestHeader requestHeader = (PullMessageRequestHeader) request .decodeCommandCustomHeader(PullMessageRequestHeader.class); String roleSubject = authService.authenticate(authCommand, ""token""); String topicName = TopicNameUtils.parseTopicName(requestHeader.getTopic()); Boolean authOK = brokerService.getAuthorizationService() .allowTopicOperationAsync(TopicName.get(topicName), TopicOperation.PRODUCE, roleSubject, authCommand).get(); if (!authOK) { log.error(""[CONSUME] Token authentication failed, please check""); return; } } catch (Exception e) { e.printStackTrace(); } } else if (RequestCode.UPDATE_AND_CREATE_TOPIC == request.getCode() || RequestCode.DELETE_TOPIC_IN_BROKER == request.getCode() || RequestCode.UPDATE_BROKER_CONFIG == request.getCode() || RequestCode.UPDATE_AND_CREATE_SUBSCRIPTIONGROUP == request.getCode() || RequestCode.DELETE_SUBSCRIPTIONGROUP == request.getCode() || RequestCode.INVOKE_BROKER_TO_RESET_OFFSET == request.getCode()){ if (!authToken.equals(token)) { log.error(""[ADMIN] Token authentication failed, please check""); return; } } log.info(""No auth check.""); } @Override public void doAfterResponse(String remoteAddr, RemotingCommand request, RemotingCommand response) { } }); }","private void initialAcl() { if (!this.serverConfig.isRopAclEnable()) { log.info(""The broker dose not enable acl""); return; } String authToken = this.serverConfig.getBrokerClientAuthenticationParameters(); getRemotingServer().registerRPCHook(new RPCHook() { @Override public void doBeforeRequest(String remoteAddr, RemotingCommand request) { if (request.getExtFields() == null) { // If request's extFields is null,then return """". return; } // token authorization logic String token = request.getExtFields().get(SessionCredentials.ACCESS_KEY); if (Strings.EMPTY.equals(token)) { log.error(""The access key is null, please check.""); throw new AclException(""No accessKey is configured""); } AuthenticationProviderToken providerToken = new AuthenticationProviderToken(); if (!providerToken.getAuthMethodName().equals(""token"")) { log.error(""Unsupported form of encryption is used, please check""); throw new AclException(""Unsupported form of encryption is used""); } AuthenticationService authService = brokerService.getAuthenticationService(); AuthenticationDataCommand authCommand = new AuthenticationDataCommand(token); if (RequestCode.SEND_MESSAGE == request.getCode() || RequestCode.SEND_MESSAGE_V2 == request.getCode() || RequestCode.CONSUMER_SEND_MSG_BACK == request.getCode() || RequestCode.SEND_BATCH_MESSAGE == request.getCode()) { try { SendMessageRequestHeader requestHeader = SendMessageProcessor .parseRequestHeader(request); if (requestHeader == null) { log.warn(""Parse send message request header.""); return; } String roleSubject = authService.authenticate(authCommand, ""token""); String topicName = TopicNameUtils.parseTopicName(requestHeader.getTopic()); Boolean authOK = brokerService.getAuthorizationService() .allowTopicOperationAsync(TopicName.get(topicName), TopicOperation.PRODUCE, roleSubject, authCommand).get(); if (!authOK) { log.error(""[PRODUCE] Token authentication failed, please check""); throw new AclException(""[PRODUCE] Token authentication failed, please check""); } } catch (Exception e) { e.printStackTrace(); } } else if (RequestCode.PULL_MESSAGE == request.getCode()) { try { final PullMessageRequestHeader requestHeader = (PullMessageRequestHeader) request .decodeCommandCustomHeader(PullMessageRequestHeader.class); String roleSubject = authService.authenticate(authCommand, ""token""); String topicName = TopicNameUtils.parseTopicName(requestHeader.getTopic()); Boolean authOK = brokerService.getAuthorizationService() .allowTopicOperationAsync(TopicName.get(topicName), TopicOperation.PRODUCE, roleSubject, authCommand).get(); if (!authOK) { log.error(""[CONSUME] Token authentication failed, please check""); throw new AclException(""[CONSUME] Token authentication failed, please check""); } } catch (Exception e) { e.printStackTrace(); } } else if (RequestCode.UPDATE_AND_CREATE_TOPIC == request.getCode() || RequestCode.DELETE_TOPIC_IN_BROKER == request.getCode() || RequestCode.UPDATE_BROKER_CONFIG == request.getCode() || RequestCode.UPDATE_AND_CREATE_SUBSCRIPTIONGROUP == request.getCode() || RequestCode.DELETE_SUBSCRIPTIONGROUP == request.getCode() || RequestCode.INVOKE_BROKER_TO_RESET_OFFSET == request.getCode()){ if (!authToken.equals(token)) { log.error(""[ADMIN] Token authentication failed, please check""); throw new AclException(""[ADMIN] Token authentication failed, please check""); } } log.info(""No auth check.""); } @Override public void doAfterResponse(String remoteAddr, RemotingCommand request, RemotingCommand response) { } }); }","Fix the logic of authentication failure (#24) Signed-off-by: xiaolongran ",https://github.com/streamnative/rop/commit/9357fa4a6f0c71e5053f5b8ad97232165e604682,,,rocketmq-impl/src/main/java/org/streamnative/pulsar/handlers/rocketmq/inner/RocketMQBrokerController.java,3,java,False,2021-06-21T03:18:02Z "request_rec *ap_read_request(conn_rec *conn) { request_rec *r; apr_pool_t *p; const char *expect; int access_status; apr_bucket_brigade *tmp_bb; apr_socket_t *csd; apr_interval_time_t cur_timeout; apr_pool_create(&p, conn->pool); apr_pool_tag(p, ""request""); r = apr_pcalloc(p, sizeof(request_rec)); AP_READ_REQUEST_ENTRY((intptr_t)r, (uintptr_t)conn); r->pool = p; r->connection = conn; r->server = conn->base_server; r->user = NULL; r->ap_auth_type = NULL; r->allowed_methods = ap_make_method_list(p, 2); r->headers_in = apr_table_make(r->pool, 25); r->trailers_in = apr_table_make(r->pool, 5); r->subprocess_env = apr_table_make(r->pool, 25); r->headers_out = apr_table_make(r->pool, 12); r->err_headers_out = apr_table_make(r->pool, 5); r->trailers_out = apr_table_make(r->pool, 5); r->notes = apr_table_make(r->pool, 5); r->request_config = ap_create_request_config(r->pool); /* Must be set before we run create request hook */ r->proto_output_filters = conn->output_filters; r->output_filters = r->proto_output_filters; r->proto_input_filters = conn->input_filters; r->input_filters = r->proto_input_filters; ap_run_create_request(r); r->per_dir_config = r->server->lookup_defaults; r->sent_bodyct = 0; /* bytect isn't for body */ r->read_length = 0; r->read_body = REQUEST_NO_BODY; r->status = HTTP_OK; /* Until further notice */ r->the_request = NULL; /* Begin by presuming any module can make its own path_info assumptions, * until some module interjects and changes the value. */ r->used_path_info = AP_REQ_DEFAULT_PATH_INFO; r->useragent_addr = conn->client_addr; r->useragent_ip = conn->client_ip; tmp_bb = apr_brigade_create(r->pool, r->connection->bucket_alloc); conn->keepalive = AP_CONN_UNKNOWN; ap_run_pre_read_request(r, conn); /* Get the request... */ if (!read_request_line(r, tmp_bb)) { switch (r->status) { case HTTP_REQUEST_URI_TOO_LARGE: case HTTP_BAD_REQUEST: case HTTP_VERSION_NOT_SUPPORTED: case HTTP_NOT_IMPLEMENTED: if (r->status == HTTP_REQUEST_URI_TOO_LARGE) { ap_log_rerror(APLOG_MARK, APLOG_INFO, 0, r, APLOGNO(00565) ""request failed: client's request-line exceeds LimitRequestLine (longer than %d)"", r->server->limit_req_line); } else if (r->method == NULL) { ap_log_rerror(APLOG_MARK, APLOG_DEBUG, 0, r, APLOGNO(00566) ""request failed: malformed request line""); } access_status = r->status; r->status = HTTP_OK; ap_die(access_status, r); ap_update_child_status(conn->sbh, SERVER_BUSY_LOG, r); ap_run_log_transaction(r); r = NULL; apr_brigade_destroy(tmp_bb); goto traceout; case HTTP_REQUEST_TIME_OUT: ap_update_child_status(conn->sbh, SERVER_BUSY_LOG, NULL); if (!r->connection->keepalives) ap_run_log_transaction(r); apr_brigade_destroy(tmp_bb); goto traceout; default: apr_brigade_destroy(tmp_bb); r = NULL; goto traceout; } } /* We may have been in keep_alive_timeout mode, so toggle back * to the normal timeout mode as we fetch the header lines, * as necessary. */ csd = ap_get_conn_socket(conn); apr_socket_timeout_get(csd, &cur_timeout); if (cur_timeout != conn->base_server->timeout) { apr_socket_timeout_set(csd, conn->base_server->timeout); cur_timeout = conn->base_server->timeout; } if (!r->assbackwards) { const char *tenc, *clen; ap_get_mime_headers_core(r, tmp_bb); if (r->status != HTTP_OK) { ap_log_rerror(APLOG_MARK, APLOG_DEBUG, 0, r, APLOGNO(00567) ""request failed: error reading the headers""); ap_send_error_response(r, 0); ap_update_child_status(conn->sbh, SERVER_BUSY_LOG, r); ap_run_log_transaction(r); apr_brigade_destroy(tmp_bb); goto traceout; } clen = apr_table_get(r->headers_in, ""Content-Length""); if (clen) { apr_off_t cl; if (!ap_parse_strict_length(&cl, clen)) { ap_log_rerror(APLOG_MARK, APLOG_DEBUG, 0, r, APLOGNO(10242) ""client sent invalid Content-Length "" ""(%s): %s"", clen, r->uri); r->status = HTTP_BAD_REQUEST; conn->keepalive = AP_CONN_CLOSE; ap_send_error_response(r, 0); ap_update_child_status(conn->sbh, SERVER_BUSY_LOG, r); ap_run_log_transaction(r); apr_brigade_destroy(tmp_bb); goto traceout; } } tenc = apr_table_get(r->headers_in, ""Transfer-Encoding""); if (tenc) { /* https://tools.ietf.org/html/rfc7230 * Section 3.3.3.3: ""If a Transfer-Encoding header field is * present in a request and the chunked transfer coding is not * the final encoding ...; the server MUST respond with the 400 * (Bad Request) status code and then close the connection"". */ if (!ap_is_chunked(r->pool, tenc)) { ap_log_rerror(APLOG_MARK, APLOG_DEBUG, 0, r, APLOGNO(02539) ""client sent unknown Transfer-Encoding "" ""(%s): %s"", tenc, r->uri); r->status = HTTP_BAD_REQUEST; conn->keepalive = AP_CONN_CLOSE; ap_send_error_response(r, 0); ap_update_child_status(conn->sbh, SERVER_BUSY_LOG, r); ap_run_log_transaction(r); apr_brigade_destroy(tmp_bb); goto traceout; } /* https://tools.ietf.org/html/rfc7230 * Section 3.3.3.3: ""If a message is received with both a * Transfer-Encoding and a Content-Length header field, the * Transfer-Encoding overrides the Content-Length. ... A sender * MUST remove the received Content-Length field"". */ if (clen) { apr_table_unset(r->headers_in, ""Content-Length""); /* Don't reuse this connection anyway to avoid confusion with * intermediaries and request/reponse spltting. */ conn->keepalive = AP_CONN_CLOSE; } } } apr_brigade_destroy(tmp_bb); /* update what we think the virtual host is based on the headers we've * now read. may update status. */ ap_update_vhost_from_headers(r); access_status = r->status; /* Toggle to the Host:-based vhost's timeout mode to fetch the * request body and send the response body, if needed. */ if (cur_timeout != r->server->timeout) { apr_socket_timeout_set(csd, r->server->timeout); cur_timeout = r->server->timeout; } /* we may have switched to another server */ r->per_dir_config = r->server->lookup_defaults; if ((!r->hostname && (r->proto_num >= HTTP_VERSION(1, 1))) || ((r->proto_num == HTTP_VERSION(1, 1)) && !apr_table_get(r->headers_in, ""Host""))) { /* * Client sent us an HTTP/1.1 or later request without telling us the * hostname, either with a full URL or a Host: header. We therefore * need to (as per the 1.1 spec) send an error. As a special case, * HTTP/1.1 mentions twice (S9, S14.23) that a request MUST contain * a Host: header, and the server MUST respond with 400 if it doesn't. */ access_status = HTTP_BAD_REQUEST; ap_log_rerror(APLOG_MARK, APLOG_DEBUG, 0, r, APLOGNO(00569) ""client sent HTTP/1.1 request without hostname "" ""(see RFC2616 section 14.23): %s"", r->uri); } /* * Add the HTTP_IN filter here to ensure that ap_discard_request_body * called by ap_die and by ap_send_error_response works correctly on * status codes that do not cause the connection to be dropped and * in situations where the connection should be kept alive. */ ap_add_input_filter_handle(ap_http_input_filter_handle, NULL, r, r->connection); if (access_status != HTTP_OK || (access_status = ap_run_post_read_request(r))) { ap_die(access_status, r); ap_update_child_status(conn->sbh, SERVER_BUSY_LOG, r); ap_run_log_transaction(r); r = NULL; goto traceout; } if (((expect = apr_table_get(r->headers_in, ""Expect"")) != NULL) && (expect[0] != '\0')) { /* * The Expect header field was added to HTTP/1.1 after RFC 2068 * as a means to signal when a 100 response is desired and, * unfortunately, to signal a poor man's mandatory extension that * the server must understand or return 417 Expectation Failed. */ if (ap_cstr_casecmp(expect, ""100-continue"") == 0) { r->expecting_100 = 1; } else { r->status = HTTP_EXPECTATION_FAILED; ap_log_rerror(APLOG_MARK, APLOG_INFO, 0, r, APLOGNO(00570) ""client sent an unrecognized expectation value of "" ""Expect: %s"", expect); ap_send_error_response(r, 0); ap_update_child_status(conn->sbh, SERVER_BUSY_LOG, r); ap_run_log_transaction(r); goto traceout; } } AP_READ_REQUEST_SUCCESS((uintptr_t)r, (char *)r->method, (char *)r->uri, (char *)r->server->defn_name, r->status); return r; traceout: AP_READ_REQUEST_FAILURE((uintptr_t)r); return r; }","request_rec *ap_read_request(conn_rec *conn) { int access_status; apr_bucket_brigade *tmp_bb; request_rec *r = ap_create_request(conn); tmp_bb = apr_brigade_create(r->pool, r->connection->bucket_alloc); conn->keepalive = AP_CONN_UNKNOWN; ap_run_pre_read_request(r, conn); /* Get the request... */ if (!read_request_line(r, tmp_bb) || !ap_parse_request_line(r)) { apr_brigade_cleanup(tmp_bb); switch (r->status) { case HTTP_REQUEST_URI_TOO_LARGE: case HTTP_BAD_REQUEST: case HTTP_VERSION_NOT_SUPPORTED: case HTTP_NOT_IMPLEMENTED: if (r->status == HTTP_REQUEST_URI_TOO_LARGE) { ap_log_rerror(APLOG_MARK, APLOG_INFO, 0, r, APLOGNO(00565) ""request failed: client's request-line exceeds LimitRequestLine (longer than %d)"", r->server->limit_req_line); } else if (r->method == NULL) { ap_log_rerror(APLOG_MARK, APLOG_DEBUG, 0, r, APLOGNO(00566) ""request failed: malformed request line""); } access_status = r->status; goto die_unusable_input; case HTTP_REQUEST_TIME_OUT: /* Just log, no further action on this connection. */ ap_update_child_status(conn->sbh, SERVER_BUSY_LOG, NULL); if (!r->connection->keepalives) ap_run_log_transaction(r); break; } /* Not worth dying with. */ conn->keepalive = AP_CONN_CLOSE; apr_pool_destroy(r->pool); goto ignore; } apr_brigade_cleanup(tmp_bb); /* We may have been in keep_alive_timeout mode, so toggle back * to the normal timeout mode as we fetch the header lines, * as necessary. */ apply_server_config(r); if (!r->assbackwards) { const char *tenc, *clen; ap_get_mime_headers_core(r, tmp_bb); apr_brigade_cleanup(tmp_bb); if (r->status != HTTP_OK) { ap_log_rerror(APLOG_MARK, APLOG_DEBUG, 0, r, APLOGNO(00567) ""request failed: error reading the headers""); access_status = r->status; goto die_unusable_input; } clen = apr_table_get(r->headers_in, ""Content-Length""); if (clen) { apr_off_t cl; if (!ap_parse_strict_length(&cl, clen)) { ap_log_rerror(APLOG_MARK, APLOG_DEBUG, 0, r, APLOGNO(10242) ""client sent invalid Content-Length "" ""(%s): %s"", clen, r->uri); access_status = HTTP_BAD_REQUEST; goto die_unusable_input; } } tenc = apr_table_get(r->headers_in, ""Transfer-Encoding""); if (tenc) { /* https://tools.ietf.org/html/rfc7230 * Section 3.3.3.3: ""If a Transfer-Encoding header field is * present in a request and the chunked transfer coding is not * the final encoding ...; the server MUST respond with the 400 * (Bad Request) status code and then close the connection"". */ if (!ap_is_chunked(r->pool, tenc)) { ap_log_rerror(APLOG_MARK, APLOG_DEBUG, 0, r, APLOGNO(02539) ""client sent unknown Transfer-Encoding "" ""(%s): %s"", tenc, r->uri); access_status = HTTP_BAD_REQUEST; goto die_unusable_input; } /* https://tools.ietf.org/html/rfc7230 * Section 3.3.3.3: ""If a message is received with both a * Transfer-Encoding and a Content-Length header field, the * Transfer-Encoding overrides the Content-Length. ... A sender * MUST remove the received Content-Length field"". */ if (clen) { apr_table_unset(r->headers_in, ""Content-Length""); /* Don't reuse this connection anyway to avoid confusion with * intermediaries and request/reponse spltting. */ conn->keepalive = AP_CONN_CLOSE; } } } /* * Add the HTTP_IN filter here to ensure that ap_discard_request_body * called by ap_die and by ap_send_error_response works correctly on * status codes that do not cause the connection to be dropped and * in situations where the connection should be kept alive. */ ap_add_input_filter_handle(ap_http_input_filter_handle, NULL, r, r->connection); /* Validate Host/Expect headers and select vhost. */ if (!ap_check_request_header(r)) { /* we may have switched to another server still */ apply_server_config(r); access_status = r->status; goto die_before_hooks; } /* we may have switched to another server */ apply_server_config(r); if ((access_status = ap_run_post_read_request(r))) { goto die; } AP_READ_REQUEST_SUCCESS((uintptr_t)r, (char *)r->method, (char *)r->uri, (char *)r->server->defn_name, r->status); return r; /* Everything falls through on failure */ die_unusable_input: /* Input filters are in an undeterminate state, cleanup (including * CORE_IN's socket) such that any further attempt to read is EOF. */ { ap_filter_t *f = conn->input_filters; while (f) { if (f->frec == ap_core_input_filter_handle) { core_net_rec *net = f->ctx; apr_brigade_cleanup(net->in_ctx->b); break; } ap_remove_input_filter(f); f = f->next; } conn->input_filters = r->input_filters = f; conn->keepalive = AP_CONN_CLOSE; } die_before_hooks: /* First call to ap_die() (non recursive) */ r->status = HTTP_OK; die: ap_die(access_status, r); /* ap_die() sent the response through the output filters, we must now * end the request with an EOR bucket for stream/pipeline accounting. */ { apr_bucket_brigade *eor_bb; eor_bb = apr_brigade_create(conn->pool, conn->bucket_alloc); APR_BRIGADE_INSERT_TAIL(eor_bb, ap_bucket_eor_create(conn->bucket_alloc, r)); ap_pass_brigade(conn->output_filters, eor_bb); apr_brigade_cleanup(eor_bb); } ignore: r = NULL; AP_READ_REQUEST_FAILURE((uintptr_t)r); return NULL; }","Merged r1734009,r1734231,r1734281,r1838055,r1838079,r1840229,r1876664,r1876674,r1876784,r1879078,r1881620,r1887311,r1888871 from trunk: *) core: Split ap_create_request() from ap_read_request(). [Graham Leggett] *) core, h2: common ap_parse_request_line() and ap_check_request_header() code. [Yann Ylavic] *) core: Add StrictHostCheck to allow unconfigured hostnames to be rejected. [Eric Covener] git-svn-id: https://svn.apache.org/repos/asf/httpd/httpd/branches/2.4.x@1890245 13f79535-47bb-0310-9956-ffa450edef68",https://github.com/apache/httpd/commit/ecebcc035ccd8d0e2984fe41420d9e944f456b3c,,,server/protocol.c,3,c,False,2021-05-27T13:08:21Z "def image(self, request, pk): obj = self.get_object() if obj.get_space() != request.space: raise PermissionDenied(detail='You do not have the required permission to perform this action', code=403) serializer = self.serializer_class(obj, data=request.data, partial=True) if serializer.is_valid(): serializer.save() image = None filetype = "".jpeg"" # fall-back to .jpeg, even if wrong, at least users will know it's an image and most image viewers can open it correctly anyways if 'image' in serializer.validated_data: image = obj.image filetype = mimetypes.guess_extension(serializer.validated_data['image'].content_type) or filetype elif 'image_url' in serializer.validated_data: try: response = requests.get(serializer.validated_data['image_url']) image = File(io.BytesIO(response.content)) filetype = mimetypes.guess_extension(response.headers['content-type']) or filetype except UnidentifiedImageError as e: print(e) pass except MissingSchema as e: print(e) pass except Exception as e: print(e) pass if image is not None: img = handle_image(request, image, filetype) obj.image = File(img, name=f'{uuid.uuid4()}_{obj.pk}{filetype}') obj.save() return Response(serializer.data) return Response(serializer.errors, 400)","def image(self, request, pk): obj = self.get_object() if obj.get_space() != request.space: raise PermissionDenied(detail='You do not have the required permission to perform this action', code=403) serializer = self.serializer_class(obj, data=request.data, partial=True) if serializer.is_valid(): serializer.save() image = None filetype = "".jpeg"" # fall-back to .jpeg, even if wrong, at least users will know it's an image and most image viewers can open it correctly anyways if 'image' in serializer.validated_data: image = obj.image filetype = mimetypes.guess_extension(serializer.validated_data['image'].content_type) or filetype elif 'image_url' in serializer.validated_data: try: url = serializer.validated_data['image_url'] if validators.url(url, public=True): response = requests.get(url) image = File(io.BytesIO(response.content)) filetype = mimetypes.guess_extension(response.headers['content-type']) or filetype except UnidentifiedImageError as e: print(e) pass except MissingSchema as e: print(e) pass except Exception as e: print(e) pass if image is not None: img = handle_image(request, image, filetype) obj.image = File(img, name=f'{uuid.uuid4()}_{obj.pk}{filetype}') obj.save() return Response(serializer.data) return Response(serializer.errors, 400)",added url validation to all server requests,https://github.com/TandoorRecipes/recipes/commit/d48fe26a3529cc1ee903ffb2758dfd8f7efaba8c,,,cookbook/views/api.py,3,py,False,2022-05-17T16:04:43Z "@Override public int getMemoryEstimate() { synchronized (largeBody) { if (memoryEstimate == -1) { // The body won't be on memory (aways on-file), so we don't consider this for paging memoryEstimate = getHeadersAndPropertiesEncodeSize() + DataConstants.SIZE_INT + getEncodeSize() + (16 + 4) * 2 + 1; } return memoryEstimate; } }","@Override public int getMemoryEstimate() { synchronized (largeBody) { if (memoryEstimate == -1) { // The body won't be on memory (always on-file), so we don't consider this for paging memoryEstimate = MEMORY_OFFSET + getHeadersAndPropertiesEncodeSize() + DataConstants.SIZE_INT + getEncodeSize() + (16 + 4) * 2 + 1; } return memoryEstimate; } }",ARTEMIS-3021 OOM due to wrong CORE clustered message memory estimation,https://github.com/apache/activemq-artemis/commit/ad4f6a133af9130f206a78e43ad387d4e3ee5f8f,,,artemis-server/src/main/java/org/apache/activemq/artemis/core/persistence/impl/journal/LargeServerMessageImpl.java,3,java,False,2020-12-05T23:07:29Z "@RequestMapping(value = ""/noauth/resetPasswordByEmail"", method = RequestMethod.POST) @ResponseStatus(value = HttpStatus.OK) public void requestResetPasswordByEmail ( @RequestBody JsonNode resetPasswordByEmailRequest, HttpServletRequest request) throws ThingsboardException { try { String email = resetPasswordByEmailRequest.get(""email"").asText(); UserCredentials userCredentials = userService.requestPasswordReset(TenantId.SYS_TENANT_ID, email); User user = userService.findUserById(TenantId.SYS_TENANT_ID, userCredentials.getUserId()); String baseUrl = systemSecurityService.getBaseUrl(user.getTenantId(), user.getCustomerId(), request); String resetUrl = String.format(""%s/api/noauth/resetPassword?resetToken=%s"", baseUrl, userCredentials.getResetToken()); mailService.sendResetPasswordEmail(resetUrl, email); } catch (Exception e) { throw handleException(e); } }","@RequestMapping(value = ""/noauth/resetPasswordByEmail"", method = RequestMethod.POST) @ResponseStatus(value = HttpStatus.OK) public void requestResetPasswordByEmail( @RequestBody JsonNode resetPasswordByEmailRequest, HttpServletRequest request) throws ThingsboardException { try { String email = resetPasswordByEmailRequest.get(""email"").asText(); UserCredentials userCredentials = userService.requestPasswordReset(TenantId.SYS_TENANT_ID, email); User user = userService.findUserById(TenantId.SYS_TENANT_ID, userCredentials.getUserId()); String baseUrl = systemSecurityService.getBaseUrl(user.getTenantId(), user.getCustomerId(), request); String resetUrl = String.format(""%s/api/noauth/resetPassword?resetToken=%s"", baseUrl, userCredentials.getResetToken()); mailService.sendResetPasswordEmailAsync(resetUrl, email); } catch (Exception e) { log.warn(""Error occurred: {}"", e.getMessage()); } }","[PROD-678] Authorization and password reset vulnerability fix (#4569) * Fixed vulnerabilities for password reset and authorization * Improvements to check user and credentials for null * Correct messages and logs * Improvements * Reset Password Test: added delay after resetting password to synchronize test with server * Executor removed from controller * Correct method calling * Formatting cleaned",https://github.com/thingsboard/thingsboard-edge/commit/228fddb8cd92bf4ec89f16760aef7f190a45bb96,,,application/src/main/java/org/thingsboard/server/controller/AuthController.java,3,java,False,2021-07-06T14:24:35Z "def patch(self, request, **kwargs): playbook_id = kwargs.get('pk') playbook = get_object_or_404(Playbook, id=playbook_id) work_path = playbook.work_dir file_key = request.data.get('key', '') new_name = request.data.get('new_name', '') if file_key in self.protected_files and new_name: return Response({'msg': '{} can not be rename'.format(file_key)}, status=status.HTTP_400_BAD_REQUEST) if os.path.dirname(file_key) == 'root': file_key = os.path.basename(file_key) content = request.data.get('content', '') is_directory = request.data.get('is_directory', False) if not file_key or file_key == 'root': return Response(status=status.HTTP_400_BAD_REQUEST) file_path = os.path.join(work_path, file_key) # rename if new_name: new_file_path = os.path.join(os.path.dirname(file_path), new_name) if new_file_path == file_path: return Response(status=status.HTTP_200_OK) if os.path.exists(new_file_path): return Response({'msg': '{} already exists'.format(new_name)}, status=status.HTTP_400_BAD_REQUEST) os.rename(file_path, new_file_path) # edit content else: if not is_directory: with open(file_path, 'w') as f: f.write(content) return Response(status=status.HTTP_200_OK)","def patch(self, request, **kwargs): playbook_id = kwargs.get('pk') playbook = get_object_or_404(Playbook, id=playbook_id) work_path = playbook.work_dir file_key = request.data.get('key', '') new_name = request.data.get('new_name', '') if file_key in self.protected_files and new_name: raise JMSException(code='this_file_can_not_be_rename', detail={""msg"": _(""This file can not be rename"")}) if os.path.dirname(file_key) == 'root': file_key = os.path.basename(file_key) content = request.data.get('content', '') is_directory = request.data.get('is_directory', False) if not file_key or file_key == 'root': return Response(status=status.HTTP_400_BAD_REQUEST) file_path = safe_join(work_path, file_key) # rename if new_name: try: new_file_path = safe_join(os.path.dirname(file_path), new_name) if new_file_path == file_path: return Response(status=status.HTTP_200_OK) if os.path.exists(new_file_path): raise JMSException(code='file_already exists', detail={""msg"": _(""File already exists"")}) os.rename(file_path, new_file_path) except SuspiciousFileOperation: raise JMSException(code='invalid_file_path', detail={""msg"": _(""Invalid file path"")}) # edit content else: if not is_directory: with open(file_path, 'w') as f: f.write(content) return Response(status=status.HTTP_200_OK)",perf: 优化 Playbook 文件创建逻辑,https://github.com/jumpserver/jumpserver/commit/d0321a74f1713d031560341c8fd0a1859e6510d8,,,apps/ops/api/playbook.py,3,py,False,2023-09-19T10:04:24Z "public InputStream getInputStream() throws IOException { InputStream iStream = this.item.getInputStream(); // if marking is supported, then it is likely already buffered if (iStream.markSupported()) { return iStream; } return new BufferedInputStream(iStream); }","public InputStream getInputStream() throws IOException { InputStream iStream = this.item.getInputStream(); if (FILE_READ_GUARD) { // Put data in memory because some streams get stuck on skip (e.g. CipherInputStream) // and may cause an infinite look in writeTo method. // Use markSupported method may also return true (stream wrapping) if (iStream.available() == 0) { byte[] byteArr = ByteStreams.toByteArray(new DicomInputStream(iStream)); InputStream fisRescue = new BufferedInputStream(new ByteArrayInputStream(byteArr)); return fisRescue; } } // if marking is supported, then it is likely already buffered if (iStream.markSupported()) { return iStream; } return new BufferedInputStream(iStream); }","[C-MOVE] Fix problem related with infinite loop if skip IS returns 0 (#638) * [C-MOVE] Fix problem related with infinite loop if the skip method of InputStream implementantion does not do the job and returns 0 * Eagerly read data to array on system property - make safeguard on file inputstream impls opt-in * Reimplement skipping in DicoogleDcmSend#writeTo - use also reads to ensure consumption without getting stuck --------- Co-authored-by: Eduardo Pinho ",https://github.com/bioinformatics-ua/dicoogle/commit/031537a9fc2498942b326369f79c4d9f2a5f751e,,,dicoogle/src/main/java/pt/ua/dicoogle/server/queryretrieve/DicoogleDcmSend.java,3,java,False,2023-02-13T09:58:03Z "static void fpm_child_init(struct fpm_worker_pool_s *wp) /* {{{ */ { fpm_globals.max_requests = wp->config->pm_max_requests; if (0 > fpm_stdio_init_child(wp) || 0 > fpm_log_init_child(wp) || 0 > fpm_status_init_child(wp) || 0 > fpm_unix_init_child(wp) || 0 > fpm_signals_init_child() || 0 > fpm_env_init_child(wp) || 0 > fpm_php_init_child(wp)) { zlog(ZLOG_ERROR, ""[pool %s] child failed to initialize"", wp->config->name); exit(FPM_EXIT_SOFTWARE); } }","static void fpm_child_init(struct fpm_worker_pool_s *wp) /* {{{ */ { fpm_globals.max_requests = wp->config->pm_max_requests; fpm_globals.listening_socket = dup(wp->listening_socket); if (0 > fpm_stdio_init_child(wp) || 0 > fpm_log_init_child(wp) || 0 > fpm_status_init_child(wp) || 0 > fpm_unix_init_child(wp) || 0 > fpm_signals_init_child() || 0 > fpm_env_init_child(wp) || 0 > fpm_php_init_child(wp)) { zlog(ZLOG_ERROR, ""[pool %s] child failed to initialize"", wp->config->name); exit(FPM_EXIT_SOFTWARE); } }","Fixed bug #73342 Directly listen on socket, instead of duping it to STDIN and listening on that.",https://github.com/php/php-src/commit/69dee5c732fe982c82edb17d0dbc3e79a47748d8,,,sapi/fpm/fpm/fpm_children.c,3,c,False,2018-06-12T18:34:01Z "@Override public void onError(@Modality int modality, String error) { mBiometricView.onError(modality, error); }","@Override public void onError(@Modality int modality, String error) { if (mBiometricView != null) { mBiometricView.onError(modality, error); } else { Log.e(TAG, ""onError(): mBiometricView is null""); } }","Fix NPEs in AuthContainerView Bug: 243493226 Test: N/A Change-Id: Ia3a677302ec3a270d421f44e746c12a701eb41a6",https://github.com/LineageOS/android_frameworks_base/commit/852108800780fac2edfcaaa1285c17a99c79eea1,,,packages/SystemUI/src/com/android/systemui/biometrics/AuthContainerView.java,3,java,False,2022-08-30T19:55:38Z "int snmp_engine_get_next(snmp_header_t *header, snmp_varbind_t *varbinds, uint32_t varbinds_length) { snmp_mib_resource_t *resource; uint32_t i; for(i = 0; i < varbinds_length; i++) { resource = snmp_mib_find_next(varbinds[i].oid); if(!resource) { switch(header->version) { case SNMP_VERSION_1: header->error_status_non_repeaters.error_status = SNMP_STATUS_NO_SUCH_NAME; /* * Varbinds are 1 indexed */ header->error_index_max_repetitions.error_index = i + 1; break; case SNMP_VERSION_2C: (&varbinds[i])->value_type = SNMP_DATA_TYPE_END_OF_MIB_VIEW; break; default: header->error_status_non_repeaters.error_status = SNMP_STATUS_NO_SUCH_NAME; header->error_index_max_repetitions.error_index = 0; } } else { resource->handler(&varbinds[i], resource->oid); } } return 0; }","static inline int snmp_engine_get_next(snmp_header_t *header, snmp_varbind_t *varbinds) { snmp_mib_resource_t *resource; uint8_t i; i = 0; while(varbinds[i].value_type != BER_DATA_TYPE_EOC && i < SNMP_MAX_NR_VALUES) { resource = snmp_mib_find_next(&varbinds[i].oid); if(!resource) { switch(header->version) { case SNMP_VERSION_1: header->error_status = SNMP_STATUS_NO_SUCH_NAME; /* * Varbinds are 1 indexed */ header->error_index = i + 1; break; case SNMP_VERSION_2C: (&varbinds[i])->value_type = BER_DATA_TYPE_END_OF_MIB_VIEW; break; default: header->error_status = SNMP_STATUS_NO_SUCH_NAME; header->error_index = 0; } } else { resource->handler(&varbinds[i], &resource->oid); } i++; } return 0; }",Refactored SNMP engine after vulnerabilities,https://github.com/contiki-ng/contiki-ng/commit/12c824386ab60de757de5001974d73b32e19ad71,,,os/net/app-layer/snmp/snmp-engine.c,3,c,False,2020-09-08T19:09:31Z "public ProblemInfoVO getProblemInfo(String problemId, Long gid) throws StatusNotFoundException, StatusForbiddenException { boolean isRoot = SecurityUtils.getSubject().hasRole(""root""); QueryWrapper wrapper = new QueryWrapper().eq(""problem_id"", problemId); //查询题目详情,题目标签,题目语言,题目做题情况 Problem problem = problemEntityService.getOne(wrapper, false); if (problem == null) { throw new StatusNotFoundException(""该题号对应的题目不存在""); } if (problem.getAuth() != 1) { throw new StatusForbiddenException(""该题号对应题目并非公开题目,不支持访问!""); } if (problem.getIsGroup() && gid == null && !isRoot) { throw new StatusForbiddenException(""题目为团队所属,此处不支持访问,请前往团队查看!""); } QueryWrapper problemTagQueryWrapper = new QueryWrapper<>(); problemTagQueryWrapper.eq(""pid"", problem.getId()); // 获取该题号对应的标签id List tidList = new LinkedList<>(); problemTagEntityService.list(problemTagQueryWrapper).forEach(problemTag -> { tidList.add(problemTag.getTid()); }); List tags = new ArrayList<>(); if (tidList.size() > 0) { tags = (List) tagEntityService.listByIds(tidList); } // 记录 languageId对应的name HashMap tmpMap = new HashMap<>(); // 获取题目提交的代码支持的语言 List languagesStr = new LinkedList<>(); QueryWrapper problemLanguageQueryWrapper = new QueryWrapper<>(); problemLanguageQueryWrapper.eq(""pid"", problem.getId()).select(""lid""); List lidList = problemLanguageEntityService.list(problemLanguageQueryWrapper) .stream().map(ProblemLanguage::getLid).collect(Collectors.toList()); if (CollectionUtil.isNotEmpty(lidList)) { Collection languages = languageEntityService.listByIds(lidList); languages = languages.stream().sorted(Comparator.comparing(Language::getSeq, Comparator.reverseOrder()) .thenComparing(Language::getId)) .collect(Collectors.toList()); languages.forEach(language -> { languagesStr.add(language.getName()); tmpMap.put(language.getId(), language.getName()); }); } // 获取题目的提交记录 ProblemCountVO problemCount = judgeEntityService.getProblemCount(problem.getId(), gid); // 获取题目的代码模板 QueryWrapper codeTemplateQueryWrapper = new QueryWrapper<>(); codeTemplateQueryWrapper.eq(""pid"", problem.getId()).eq(""status"", true); List codeTemplates = codeTemplateEntityService.list(codeTemplateQueryWrapper); HashMap LangNameAndCode = new HashMap<>(); if (CollectionUtil.isNotEmpty(codeTemplates)) { for (CodeTemplate codeTemplate : codeTemplates) { LangNameAndCode.put(tmpMap.get(codeTemplate.getLid()), codeTemplate.getCode()); } } // 屏蔽一些题目参数 problem.setJudgeExtraFile(null) .setSpjCode(null) .setSpjLanguage(null); // 将数据统一写入到一个Vo返回数据实体类中 return new ProblemInfoVO(problem, tags, languagesStr, problemCount, LangNameAndCode); }","public ProblemInfoVO getProblemInfo(String problemId, Long gid) throws StatusNotFoundException, StatusForbiddenException { boolean isRoot = SecurityUtils.getSubject().hasRole(""root""); QueryWrapper wrapper = new QueryWrapper().eq(""problem_id"", problemId); //查询题目详情,题目标签,题目语言,题目做题情况 Problem problem = problemEntityService.getOne(wrapper, false); if (problem == null) { throw new StatusNotFoundException(""该题号对应的题目不存在""); } if (problem.getAuth() != 1) { throw new StatusForbiddenException(""该题号对应题目并非公开题目,不支持访问!""); } AccountProfile userRolesVo = (AccountProfile) SecurityUtils.getSubject().getPrincipal(); if (problem.getIsGroup() && !isRoot) { if (gid == null){ throw new StatusForbiddenException(""题目为团队所属,此处不支持访问,请前往团队查看!""); } if(!groupValidator.isGroupMember(userRolesVo.getUid(), problem.getGid())) { throw new StatusForbiddenException(""对不起,您并非该题目所属的团队内成员,无权查看题目!""); } } QueryWrapper problemTagQueryWrapper = new QueryWrapper<>(); problemTagQueryWrapper.eq(""pid"", problem.getId()); // 获取该题号对应的标签id List tidList = new LinkedList<>(); problemTagEntityService.list(problemTagQueryWrapper).forEach(problemTag -> { tidList.add(problemTag.getTid()); }); List tags = new ArrayList<>(); if (tidList.size() > 0) { tags = (List) tagEntityService.listByIds(tidList); } // 记录 languageId对应的name HashMap tmpMap = new HashMap<>(); // 获取题目提交的代码支持的语言 List languagesStr = new LinkedList<>(); QueryWrapper problemLanguageQueryWrapper = new QueryWrapper<>(); problemLanguageQueryWrapper.eq(""pid"", problem.getId()).select(""lid""); List lidList = problemLanguageEntityService.list(problemLanguageQueryWrapper) .stream().map(ProblemLanguage::getLid).collect(Collectors.toList()); if (CollectionUtil.isNotEmpty(lidList)) { Collection languages = languageEntityService.listByIds(lidList); languages = languages.stream().sorted(Comparator.comparing(Language::getSeq, Comparator.reverseOrder()) .thenComparing(Language::getId)) .collect(Collectors.toList()); languages.forEach(language -> { languagesStr.add(language.getName()); tmpMap.put(language.getId(), language.getName()); }); } // 获取题目的提交记录 ProblemCountVO problemCount = judgeEntityService.getProblemCount(problem.getId(), gid); // 获取题目的代码模板 QueryWrapper codeTemplateQueryWrapper = new QueryWrapper<>(); codeTemplateQueryWrapper.eq(""pid"", problem.getId()).eq(""status"", true); List codeTemplates = codeTemplateEntityService.list(codeTemplateQueryWrapper); HashMap LangNameAndCode = new HashMap<>(); if (CollectionUtil.isNotEmpty(codeTemplates)) { for (CodeTemplate codeTemplate : codeTemplates) { LangNameAndCode.put(tmpMap.get(codeTemplate.getLid()), codeTemplate.getCode()); } } // 屏蔽一些题目参数 problem.setJudgeExtraFile(null) .setSpjCode(null) .setSpjLanguage(null); // 将数据统一写入到一个Vo返回数据实体类中 return new ProblemInfoVO(problem, tags, languagesStr, problemCount, LangNameAndCode); }",fix: access group problem auth,https://github.com/HimitZH/HOJ/commit/8de015f70c2c56d5eade6aa2e4f9a4be3eec8279,,,hoj-springboot/DataBackup/src/main/java/top/hcode/hoj/manager/oj/ProblemManager.java,3,java,False,2022-11-24T13:54:53Z "@EventHandler(ignoreCancelled = true) public void onEntityDamaged(OCMEntityDamageByEntityEvent event) { final Entity damager = event.getDamager(); if(event.getCause() == EntityDamageEvent.DamageCause.THORNS) return; final World world = damager.getWorld(); if (!isEnabled(world)) return; final Material weaponMaterial = event.getWeapon().getType(); if (!isTool(weaponMaterial)) return; final double weaponDamage = WeaponDamages.getDamage(weaponMaterial); if (weaponDamage <= 0) { debug(""Unknown tool type: "" + weaponMaterial, damager); return; } final double oldBaseDamage = event.getBaseDamage(); // If the raw is not what we expect for 1.9 we should ignore it, for compatibility with other plugins final float expectedDamage = ToolDamage.getDamage(weaponMaterial); if (oldBaseDamage == expectedDamage) event.setBaseDamage(weaponDamage); debug(""Old "" + weaponMaterial + "" damage: "" + oldBaseDamage + "" New tool damage: "" + weaponDamage, damager); // Set sharpness to 1.8 damage value final double newSharpnessDamage = DamageUtils.getOldSharpnessDamage(event.getSharpnessLevel()); debug(""Old sharpness damage: "" + event.getSharpnessDamage() + "" New: "" + newSharpnessDamage, damager); event.setSharpnessDamage(newSharpnessDamage); }","@EventHandler(ignoreCancelled = true) public void onEntityDamaged(OCMEntityDamageByEntityEvent event) { final Entity damager = event.getDamager(); if (event.getCause() == EntityDamageEvent.DamageCause.THORNS) return; final Entity damagee = event.getDamagee(); final World world = damager.getWorld(); if (!isEnabled(world)) return; final Material weaponMaterial = event.getWeapon().getType(); if (!isTool(weaponMaterial)) return; double weaponDamage = WeaponDamages.getDamage(weaponMaterial); if (weaponDamage <= 0) { debug(""Unknown tool type: "" + weaponMaterial, damager); return; } final double oldBaseDamage = event.getBaseDamage(); double expectedDamage = ToolDamage.getDamage(weaponMaterial); if (event.wasInvulnerabilityOverdamage() && damagee instanceof LivingEntity) { // We must subtract previous damage from new weapon damage for this attack final LivingEntity livingDamagee = (LivingEntity) damagee; final double lastDamage = livingDamagee.getLastDamage(); expectedDamage -= lastDamage; weaponDamage -= lastDamage; } // If the raw is not what we expect for 1.9 we should ignore it, for compatibility with other plugins if (oldBaseDamage == expectedDamage) event.setBaseDamage(weaponDamage); debug(""Old "" + weaponMaterial + "" damage: "" + oldBaseDamage + "" New tool damage: "" + weaponDamage + (event.wasInvulnerabilityOverdamage() ? "" (overdamage)"" : """"), damager); // Set sharpness to 1.8 damage value final double newSharpnessDamage = DamageUtils.getOldSharpnessDamage(event.getSharpnessLevel()); debug(""Old sharpness damage: "" + event.getSharpnessDamage() + "" New: "" + newSharpnessDamage, damager); event.setSharpnessDamage(newSharpnessDamage); }",Account for invulnerability overdamage in old tool module. Closes #458,https://github.com/kernitus/BukkitOldCombatMechanics/commit/c2aad88d71c9d619f74b0bfbd82861d16011a7be,,,src/main/java/kernitus/plugin/OldCombatMechanics/module/ModuleOldToolDamage.java,3,java,False,2021-06-15T15:47:23Z "@Override protected void notifyReadClosed() { try { this.getSourceChannel().shutdownReads(); } catch (IOException e) { e.printStackTrace(); } }","@Override protected void notifyReadClosed() { try { this.getSourceChannel().shutdownReads(); } catch (IOException e) { log.error(""Error in read close"", e); } }","Fix CVE-2022-0084 Do not print stack traces, use the logger.",https://github.com/xnio/xnio/commit/b05531de0433f498af26f9aec6c0e944c3c1689c,,,api/src/main/java/org/xnio/StreamConnection.java,3,java,False,2022-05-26T10:32:18Z "public void close() throws IOException { dnsNameResolver.close(); if (discoveryProvider != null) { discoveryProvider.close(); } if (listenChannel != null) { listenChannel.close(); } if (listenChannelTls != null) { listenChannelTls.close(); } if (statsExecutor != null) { statsExecutor.shutdown(); } if (proxyAdditionalServlets != null) { proxyAdditionalServlets.close(); proxyAdditionalServlets = null; } if (localMetadataStore != null) { try { localMetadataStore.close(); } catch (Exception e) { throw new IOException(e); } } if (configMetadataStore != null) { try { configMetadataStore.close(); } catch (Exception e) { throw new IOException(e); } } acceptorGroup.shutdownGracefully(); workerGroup.shutdownGracefully(); }","public void close() throws IOException { dnsAddressResolverGroup.close(); if (discoveryProvider != null) { discoveryProvider.close(); } if (listenChannel != null) { listenChannel.close(); } if (listenChannelTls != null) { listenChannelTls.close(); } if (statsExecutor != null) { statsExecutor.shutdown(); } if (proxyAdditionalServlets != null) { proxyAdditionalServlets.close(); proxyAdditionalServlets = null; } if (localMetadataStore != null) { try { localMetadataStore.close(); } catch (Exception e) { throw new IOException(e); } } if (configMetadataStore != null) { try { configMetadataStore.close(); } catch (Exception e) { throw new IOException(e); } } acceptorGroup.shutdownGracefully(); workerGroup.shutdownGracefully(); }","[Proxy/Client] Fix DNS server denial-of-service issue when DNS entry expires (#15403) (cherry picked from commit 40d71691dab2a09d3457f8fa638b19ebc2e28dd7)",https://github.com/apache/pulsar/commit/3673973a89525f89da27ec6f3c875e8658be5ad3,,,pulsar-proxy/src/main/java/org/apache/pulsar/proxy/server/ProxyService.java,3,java,False,2022-05-03T02:59:19Z "private void authenticate(final Tokens tokens) { this.tokens = tokens; accessToken = identity.authentication().verifyToken(tokens.getAccessToken()); userDetails = accessToken.getUserDetails(); if (!getPermissions().contains(Permission.READ)) { throw new InsufficientAuthenticationException(""No read permissions""); } setAuthenticated(true); }","public void authenticate(final Tokens tokens) { if (tokens != null) { this.tokens = tokens; } final AccessToken accessToken = getIdentity().authentication().verifyToken(this.tokens.getAccessToken()); final UserDetails userDetails = accessToken.getUserDetails(); id = userDetails.getId(); name = userDetails.getName().orElse(""""); permissions = accessToken.getPermissions(); if (!getPermissions().contains(Permission.READ)) { throw new InsufficientAuthenticationException(""No read permissions""); } subject = accessToken.getToken().getSubject(); expires = accessToken.getToken().getExpiresAt(); if (!hasExpired()) { setAuthenticated(true); } }","fix(backend): add additional checks for error on migration (#1828) Related with #1821",https://github.com/camunda/zeebe/commit/f723cf98397e3fa8f5cc692e2e99551de0c5b25e,,,webapp/src/main/java/io/camunda/tasklist/webapp/security/identity/IdentityAuthentication.java,3,java,False,2022-06-07T09:28:00Z "private static final void disableLocal(@NonNull String name) { synchronized (sCorkLock) { sDisabledKeys.add(name); for (PropertyInvalidatedCache cache : sCaches.keySet()) { if (name.equals(cache.mCacheName)) { cache.disableInstance(); } } } }","private static final void disableLocal(@NonNull String name) { synchronized (sGlobalLock) { if (sDisabledKeys.contains(name)) { // The key is already in recorded so there is no further work to be done. return; } for (PropertyInvalidatedCache cache : sCaches.keySet()) { if (name.equals(cache.mCacheName)) { cache.disableInstance(); } } // Record the disabled key after the iteration. If an exception occurs during the // iteration above, and the code is retried, the function should not exit early. sDisabledKeys.add(name); } }","Refactor PropertyInvalidatedCache locks Bug: 241763149 Refactor the sCorkLock into sCorkLock, which protects code that specifically supports corking, and sGlobalLock, which protects all other code that touches global objects (like the list of all caches). Deadlock was not actually observed in the bug and has never been reported, but the possibility was identified and is being fixed here. Bypass the bulk of disableLocal(name) if the name has already been bypassed. This speeds repeated calls to disableLocal() by not iterating over sCaches. Many threads were terminated by a watchdog while iterating over sCaches inside disableLocal(). It is not known why this block of code was running so often when the time out expired. An open question is whether or not disabled caches should be removed from the sCaches array. The only reason to leave them in the array is to report on them during dumpsys, but this seems like a small benefit Test: atest * FrameworksCoreTests:IpcDataCacheTest * FrameworksCoreTests:PropertyInvalidatedCacheTests * CtsOsTestCases:IpcDataCacheTest Change-Id: I4c298f380044c0be93cdb47d66d7d7e2b260004f",https://github.com/LineageOS/android_frameworks_base/commit/a6b4f410f286a5385acdbbd5437b374b02883abd,,,core/java/android/app/PropertyInvalidatedCache.java,3,java,False,2022-09-08T20:09:35Z "private boolean isRedeliveryExhausted(Exception exception) { return (exception instanceof MessageRedeliveredException); }","private boolean isRedeliveryExhausted(Exception exception) { if (exception instanceof MessagingException) { Optional error = ((MessagingException) exception).getEvent().getError(); return error.map(e -> redeliveryExhaustedMatcher.match(e.getErrorType())) .orElse(false); } return false; }","MULE-19915: Redelivery Policy: infinite loop when the redelivery is e… (#10958) MULE-19915: Redelivery Policy: infinite loop when the redelivery is exhausted in a source configured with transactions (#10951)",https://github.com/mulesoft/mule/commit/c02bf452f39066e6fef21fe8783549115f7ba48a,,,core/src/main/java/org/mule/runtime/core/internal/exception/OnErrorPropagateHandler.java,3,java,False,2021-11-15T13:34:00Z "private Node composeNode(Node parent) { blockCommentsCollector.collectEvents(); if (parent != null) recursiveNodes.add(parent); final Node node; if (parser.checkEvent(Event.ID.Alias)) { AliasEvent event = (AliasEvent) parser.getEvent(); String anchor = event.getAnchor(); if (!anchors.containsKey(anchor)) { throw new ComposerException(null, null, ""found undefined alias "" + anchor, event.getStartMark()); } node = anchors.get(anchor); if (!(node instanceof ScalarNode)) { this.nonScalarAliasesCount++; if (this.nonScalarAliasesCount > loadingConfig.getMaxAliasesForCollections()) { throw new YAMLException(""Number of aliases for non-scalar nodes exceeds the specified max="" + loadingConfig.getMaxAliasesForCollections()); } } if (recursiveNodes.remove(node)) { node.setTwoStepsConstruction(true); } // drop comments, they can not be supported here blockCommentsCollector.consume(); inlineCommentsCollector.collectEvents().consume(); } else { NodeEvent event = (NodeEvent) parser.peekEvent(); String anchor = event.getAnchor(); // the check for duplicate anchors has been removed (issue 174) if (parser.checkEvent(Event.ID.Scalar)) { node = composeScalarNode(anchor, blockCommentsCollector.consume()); } else if (parser.checkEvent(Event.ID.SequenceStart)) { node = composeSequenceNode(anchor); } else { node = composeMappingNode(anchor); } } recursiveNodes.remove(parent); return node; }","private Node composeNode(Node parent) { blockCommentsCollector.collectEvents(); if (parent != null) recursiveNodes.add(parent); final Node node; if (parser.checkEvent(Event.ID.Alias)) { AliasEvent event = (AliasEvent) parser.getEvent(); String anchor = event.getAnchor(); if (!anchors.containsKey(anchor)) { throw new ComposerException(null, null, ""found undefined alias "" + anchor, event.getStartMark()); } node = anchors.get(anchor); if (!(node instanceof ScalarNode)) { this.nonScalarAliasesCount++; if (this.nonScalarAliasesCount > loadingConfig.getMaxAliasesForCollections()) { throw new YAMLException(""Number of aliases for non-scalar nodes exceeds the specified max="" + loadingConfig.getMaxAliasesForCollections()); } } if (recursiveNodes.remove(node)) { node.setTwoStepsConstruction(true); } // drop comments, they can not be supported here blockCommentsCollector.consume(); inlineCommentsCollector.collectEvents().consume(); } else { NodeEvent event = (NodeEvent) parser.peekEvent(); String anchor = event.getAnchor(); increaseNestingDepth(); // the check for duplicate anchors has been removed (issue 174) if (parser.checkEvent(Event.ID.Scalar)) { node = composeScalarNode(anchor, blockCommentsCollector.consume()); } else if (parser.checkEvent(Event.ID.SequenceStart)) { node = composeSequenceNode(anchor); } else { node = composeMappingNode(anchor); } decreaseNestingDepth(); } recursiveNodes.remove(parent); return node; }",Restrict nested depth for collections to avoid DoS attacks,https://github.com/snakeyaml/snakeyaml/commit/fc300780da21f4bb92c148bc90257201220cf174,,,src/main/java/org/yaml/snakeyaml/composer/Composer.java,3,java,False,2022-04-28T12:38:16Z "private CompletableFuture isTopicOperationAllowed(TopicName topicName, String subscriptionName, TopicOperation operation) { if (service.isAuthorizationEnabled()) { if (authenticationData == null) { authenticationData = new AuthenticationDataCommand("""", subscriptionName); } else { authenticationData.setSubscription(subscriptionName); } if (originalAuthData != null) { originalAuthData.setSubscription(subscriptionName); } return isTopicOperationAllowed(topicName, operation); } else { return CompletableFuture.completedFuture(true); } }","private CompletableFuture isTopicOperationAllowed(TopicName topicName, String subscriptionName, TopicOperation operation) { if (service.isAuthorizationEnabled()) { AuthenticationDataSource authData = new AuthenticationDataSubscription(getAuthenticationData(), subscriptionName); return isTopicOperationAllowed(topicName, operation, authData); } else { return CompletableFuture.completedFuture(true); } }","Avoid AuthenticationDataSource mutation for subscription name (#16065) ### Motivation The `authenticationData` field in `ServerCnx` is being mutated to add the `subscription` field that will be passed on to the authorization plugin. The problem is that `authenticationData` is scoped to the whole connection and it should be getting mutated for each consumer that is created on the connection. The current code leads to a race condition where the subscription name used in the authz plugin is already modified while we're looking at it. Instead, we should create a new object and enforce the final modifier.",https://github.com/apache/pulsar/commit/e6b12c64b043903eb5ff2dc5186fe8030f157cfc,,,pulsar-broker/src/main/java/org/apache/pulsar/broker/service/ServerCnx.java,3,java,False,2022-06-15T07:00:28Z "void drawFrame(boolean force) { if (!force && SystemClock.elapsedRealtime() - lastDraw < 1000 / fps) { return; } final SurfaceHolder surfaceHolder = getSurfaceHolder(); if (!surfaceHolder.getSurface().isValid()) { // Prevents IllegalStateException when surface is not ready return; } Canvas canvas = null; try { if (VERSION.SDK_INT >= VERSION_CODES.O && useGpu) { canvas = surfaceHolder.lockHardwareCanvas(); } else { canvas = surfaceHolder.lockCanvas(); } if (canvas != null) { // ZOOM float intensity = zoomIntensity / 10f; double finalZoomLauncher = isZoomLauncherEnabled ? zoomLauncher * intensity : 0; double finalZoomUnlock = isZoomUnlockEnabled ? zoomUnlock * intensity : 0; svgDrawable.setZoom((float) (finalZoomLauncher + finalZoomUnlock)); svgDrawable.draw(canvas); lastDraw = SystemClock.elapsedRealtime(); } } finally { if (canvas != null) { surfaceHolder.unlockCanvasAndPost(canvas); } } }","void drawFrame(boolean force) { if ((!force && SystemClock.elapsedRealtime() - lastDraw < 1000 / fps) || !isSurfaceAvailable || getSurfaceHolder().getSurface() == null // Prevents IllegalStateException when surface is not ready || !getSurfaceHolder().getSurface().isValid() ) { // Cancel drawing request return; } final SurfaceHolder surfaceHolder = getSurfaceHolder(); Canvas canvas = null; try { if (VERSION.SDK_INT >= VERSION_CODES.O && useGpu) { canvas = surfaceHolder.lockHardwareCanvas(); } else { canvas = surfaceHolder.lockCanvas(); } if (canvas != null) { // ZOOM float intensity = zoomIntensity / 10f; double finalZoomLauncher = isZoomLauncherEnabled ? zoomLauncher * intensity : 0; double finalZoomUnlock = isZoomUnlockEnabled ? zoomUnlock * intensity : 0; svgDrawable.setZoom((float) (finalZoomLauncher + finalZoomUnlock)); svgDrawable.draw(canvas); lastDraw = SystemClock.elapsedRealtime(); } } catch (Exception e) { Log.e(TAG, ""drawFrame: unexpected exception: "" + e); } finally { if (canvas != null && isSurfaceAvailable) { surfaceHolder.unlockCanvasAndPost(canvas); } } }",Try to catch more exceptions and fix wallpaper crashes,https://github.com/patzly/doodle-android/commit/d3c1cc7d18b5a5b5f89e3b5b2ff7ee2865cbebcd,,,app/src/main/java/xyz/zedler/patrick/doodle/service/LiveWallpaperService.java,3,java,False,2021-08-01T14:50:25Z "public static boolean isRTL(Context ctx) { Locale locale = getPrimaryLocale(ctx); final int direction = Character.getDirectionality(locale.getDisplayName().charAt(0)); return direction == Character.DIRECTIONALITY_RIGHT_TO_LEFT || direction == Character.DIRECTIONALITY_RIGHT_TO_LEFT_ARABIC; }","public static boolean isRTL(Context ctx) { String locale_name = getPrimaryLocale(ctx).getDisplayName(); if(locale_name.isEmpty()) return false; final int direction = Character.getDirectionality(locale_name.charAt(0)); return direction == Character.DIRECTIONALITY_RIGHT_TO_LEFT || direction == Character.DIRECTIONALITY_RIGHT_TO_LEFT_ARABIC; }","Fix possible crash in Utils.isRTL The returned locale_name may be empty",https://github.com/emanuele-f/PCAPdroid/commit/fd4d36cad9048fbf3804d8d07e6a4c2027352599,,,app/src/main/java/com/emanuelef/remote_capture/Utils.java,3,java,False,2023-02-04T11:16:26Z "public void startLegacyVpnPrivileged(VpnProfile profile, KeyStore keyStore, LinkProperties egress) { UserManager mgr = UserManager.get(mContext); UserInfo user = mgr.getUserInfo(mUserHandle); if (user.isRestricted() || mgr.hasUserRestriction(UserManager.DISALLOW_CONFIG_VPN, new UserHandle(mUserHandle))) { throw new SecurityException(""Restricted users cannot establish VPNs""); } final RouteInfo ipv4DefaultRoute = findIPv4DefaultRoute(egress); final String gateway = ipv4DefaultRoute.getGateway().getHostAddress(); final String iface = ipv4DefaultRoute.getInterface(); // Load certificates. String privateKey = """"; String userCert = """"; String caCert = """"; String serverCert = """"; if (!profile.ipsecUserCert.isEmpty()) { privateKey = Credentials.USER_PRIVATE_KEY + profile.ipsecUserCert; byte[] value = keyStore.get(Credentials.USER_CERTIFICATE + profile.ipsecUserCert); userCert = (value == null) ? null : new String(value, StandardCharsets.UTF_8); } if (!profile.ipsecCaCert.isEmpty()) { byte[] value = keyStore.get(Credentials.CA_CERTIFICATE + profile.ipsecCaCert); caCert = (value == null) ? null : new String(value, StandardCharsets.UTF_8); } if (!profile.ipsecServerCert.isEmpty()) { byte[] value = keyStore.get(Credentials.USER_CERTIFICATE + profile.ipsecServerCert); serverCert = (value == null) ? null : new String(value, StandardCharsets.UTF_8); } if (userCert == null || caCert == null || serverCert == null) { throw new IllegalStateException(""Cannot load credentials""); } // Prepare arguments for racoon. String[] racoon = null; switch (profile.type) { case VpnProfile.TYPE_IKEV2_IPSEC_RSA: // Secret key is still just the alias (not the actual private key). The private key // is retrieved from the KeyStore during conversion of the VpnProfile to an // Ikev2VpnProfile. profile.ipsecSecret = Ikev2VpnProfile.PREFIX_KEYSTORE_ALIAS + privateKey; profile.ipsecUserCert = userCert; // Fallthrough case VpnProfile.TYPE_IKEV2_IPSEC_USER_PASS: profile.ipsecCaCert = caCert; // Start VPN profile profile.setAllowedAlgorithms(Ikev2VpnProfile.DEFAULT_ALGORITHMS); startVpnProfilePrivileged(profile, VpnConfig.LEGACY_VPN, keyStore); return; case VpnProfile.TYPE_IKEV2_IPSEC_PSK: // Ikev2VpnProfiles expect a base64-encoded preshared key. profile.ipsecSecret = Ikev2VpnProfile.encodeForIpsecSecret(profile.ipsecSecret.getBytes()); // Start VPN profile profile.setAllowedAlgorithms(Ikev2VpnProfile.DEFAULT_ALGORITHMS); startVpnProfilePrivileged(profile, VpnConfig.LEGACY_VPN, keyStore); return; case VpnProfile.TYPE_L2TP_IPSEC_PSK: racoon = new String[] { iface, profile.server, ""udppsk"", profile.ipsecIdentifier, profile.ipsecSecret, ""1701"", }; break; case VpnProfile.TYPE_L2TP_IPSEC_RSA: racoon = new String[] { iface, profile.server, ""udprsa"", privateKey, userCert, caCert, serverCert, ""1701"", }; break; case VpnProfile.TYPE_IPSEC_XAUTH_PSK: racoon = new String[] { iface, profile.server, ""xauthpsk"", profile.ipsecIdentifier, profile.ipsecSecret, profile.username, profile.password, """", gateway, }; break; case VpnProfile.TYPE_IPSEC_XAUTH_RSA: racoon = new String[] { iface, profile.server, ""xauthrsa"", privateKey, userCert, caCert, serverCert, profile.username, profile.password, """", gateway, }; break; case VpnProfile.TYPE_IPSEC_HYBRID_RSA: racoon = new String[] { iface, profile.server, ""hybridrsa"", caCert, serverCert, profile.username, profile.password, """", gateway, }; break; } // Prepare arguments for mtpd. String[] mtpd = null; switch (profile.type) { case VpnProfile.TYPE_PPTP: mtpd = new String[] { iface, ""pptp"", profile.server, ""1723"", ""name"", profile.username, ""password"", profile.password, ""linkname"", ""vpn"", ""refuse-eap"", ""nodefaultroute"", ""usepeerdns"", ""idle"", ""1800"", ""mtu"", ""1400"", ""mru"", ""1400"", (profile.mppe ? ""+mppe"" : ""nomppe""), }; break; case VpnProfile.TYPE_L2TP_IPSEC_PSK: case VpnProfile.TYPE_L2TP_IPSEC_RSA: mtpd = new String[] { iface, ""l2tp"", profile.server, ""1701"", profile.l2tpSecret, ""name"", profile.username, ""password"", profile.password, ""linkname"", ""vpn"", ""refuse-eap"", ""nodefaultroute"", ""usepeerdns"", ""idle"", ""1800"", ""mtu"", ""1400"", ""mru"", ""1400"", }; break; } VpnConfig config = new VpnConfig(); config.legacy = true; config.user = profile.key; config.interfaze = iface; config.session = profile.name; config.isMetered = false; config.proxyInfo = profile.proxy; config.addLegacyRoutes(profile.routes); if (!profile.dnsServers.isEmpty()) { config.dnsServers = Arrays.asList(profile.dnsServers.split("" +"")); } if (!profile.searchDomains.isEmpty()) { config.searchDomains = Arrays.asList(profile.searchDomains.split("" +"")); } startLegacyVpn(config, racoon, mtpd, profile); }","public void startLegacyVpnPrivileged(VpnProfile profile, KeyStore keyStore, LinkProperties egress) { UserManager mgr = UserManager.get(mContext); UserInfo user = mgr.getUserInfo(mUserHandle); if (user.isRestricted() || mgr.hasUserRestriction(UserManager.DISALLOW_CONFIG_VPN, new UserHandle(mUserHandle))) { throw new SecurityException(""Restricted users cannot establish VPNs""); } final RouteInfo ipv4DefaultRoute = findIPv4DefaultRoute(egress); final String gateway = ipv4DefaultRoute.getGateway().getHostAddress(); final String iface = ipv4DefaultRoute.getInterface(); // Load certificates. String privateKey = """"; String userCert = """"; String caCert = """"; String serverCert = """"; if (!profile.ipsecUserCert.isEmpty()) { privateKey = Credentials.USER_PRIVATE_KEY + profile.ipsecUserCert; byte[] value = keyStore.get(Credentials.USER_CERTIFICATE + profile.ipsecUserCert); userCert = (value == null) ? null : new String(value, StandardCharsets.UTF_8); } if (!profile.ipsecCaCert.isEmpty()) { byte[] value = keyStore.get(Credentials.CA_CERTIFICATE + profile.ipsecCaCert); caCert = (value == null) ? null : new String(value, StandardCharsets.UTF_8); } if (!profile.ipsecServerCert.isEmpty()) { byte[] value = keyStore.get(Credentials.USER_CERTIFICATE + profile.ipsecServerCert); serverCert = (value == null) ? null : new String(value, StandardCharsets.UTF_8); } if (userCert == null || caCert == null || serverCert == null) { throw new IllegalStateException(""Cannot load credentials""); } // Prepare arguments for racoon. String[] racoon = null; switch (profile.type) { case VpnProfile.TYPE_IKEV2_IPSEC_RSA: // Secret key is still just the alias (not the actual private key). The private key // is retrieved from the KeyStore during conversion of the VpnProfile to an // Ikev2VpnProfile. profile.ipsecSecret = Ikev2VpnProfile.PREFIX_KEYSTORE_ALIAS + privateKey; profile.ipsecUserCert = userCert; // Fallthrough case VpnProfile.TYPE_IKEV2_IPSEC_USER_PASS: profile.ipsecCaCert = caCert; // Start VPN profile profile.setAllowedAlgorithms(Ikev2VpnProfile.DEFAULT_ALGORITHMS); startVpnProfilePrivileged(profile, VpnConfig.LEGACY_VPN, keyStore); return; case VpnProfile.TYPE_IKEV2_IPSEC_PSK: // Ikev2VpnProfiles expect a base64-encoded preshared key. profile.ipsecSecret = Ikev2VpnProfile.encodeForIpsecSecret(profile.ipsecSecret.getBytes()); // Start VPN profile profile.setAllowedAlgorithms(Ikev2VpnProfile.DEFAULT_ALGORITHMS); startVpnProfilePrivileged(profile, VpnConfig.LEGACY_VPN, keyStore); return; case VpnProfile.TYPE_L2TP_IPSEC_PSK: racoon = new String[] { iface, profile.server, ""udppsk"", profile.ipsecIdentifier, profile.ipsecSecret, ""1701"", }; break; case VpnProfile.TYPE_L2TP_IPSEC_RSA: racoon = new String[] { iface, profile.server, ""udprsa"", privateKey, userCert, caCert, serverCert, ""1701"", }; break; case VpnProfile.TYPE_IPSEC_XAUTH_PSK: racoon = new String[] { iface, profile.server, ""xauthpsk"", profile.ipsecIdentifier, profile.ipsecSecret, profile.username, profile.password, """", gateway, }; break; case VpnProfile.TYPE_IPSEC_XAUTH_RSA: racoon = new String[] { iface, profile.server, ""xauthrsa"", privateKey, userCert, caCert, serverCert, profile.username, profile.password, """", gateway, }; break; case VpnProfile.TYPE_IPSEC_HYBRID_RSA: racoon = new String[] { iface, profile.server, ""hybridrsa"", caCert, serverCert, profile.username, profile.password, """", gateway, }; break; } // Prepare arguments for mtpd. String[] mtpd = null; switch (profile.type) { case VpnProfile.TYPE_PPTP: mtpd = new String[] { iface, ""pptp"", profile.server, ""1723"", ""name"", profile.username, ""password"", profile.password, ""linkname"", ""vpn"", ""refuse-eap"", ""nodefaultroute"", ""usepeerdns"", ""idle"", ""1800"", ""mtu"", ""1400"", ""mru"", ""1400"", (profile.mppe ? ""+mppe"" : ""nomppe""), }; if (profile.mppe) { // Disallow PAP authentication when MPPE is requested, as MPPE cannot work // with PAP anyway, and users may not expect PAP (plain text) to be used when // MPPE was requested. mtpd = Arrays.copyOf(mtpd, mtpd.length + 1); mtpd[mtpd.length - 1] = ""-pap""; } break; case VpnProfile.TYPE_L2TP_IPSEC_PSK: case VpnProfile.TYPE_L2TP_IPSEC_RSA: mtpd = new String[] { iface, ""l2tp"", profile.server, ""1701"", profile.l2tpSecret, ""name"", profile.username, ""password"", profile.password, ""linkname"", ""vpn"", ""refuse-eap"", ""nodefaultroute"", ""usepeerdns"", ""idle"", ""1800"", ""mtu"", ""1400"", ""mru"", ""1400"", }; break; } VpnConfig config = new VpnConfig(); config.legacy = true; config.user = profile.key; config.interfaze = iface; config.session = profile.name; config.isMetered = false; config.proxyInfo = profile.proxy; config.addLegacyRoutes(profile.routes); if (!profile.dnsServers.isEmpty()) { config.dnsServers = Arrays.asList(profile.dnsServers.split("" +"")); } if (!profile.searchDomains.isEmpty()) { config.searchDomains = Arrays.asList(profile.searchDomains.split("" +"")); } startLegacyVpn(config, racoon, mtpd, profile); }","Disallow PAP authentication when MPPE is requested MPPE cannot work if PAP is used as authentication, so it is not useful to allow PAP authentication when MPPE is enforced: establishing the tunnel would fail anyway with ""MPPE required, but MS-CHAP[v2] auth not performed"". Also users enforcing MPPE may assume that this means PAP will not be used for authentication, so without this change MPPE enforcement gives a false sense of security, as PAP uses plain-text credentials. Bug: 201660636 Test: atest VpnTest Merged-In: Ie318d45fe44294e97cf38da7f1834cf014cb4417 Change-Id: Ie318d45fe44294e97cf38da7f1834cf014cb4417 (cherry picked from commit 997a4a39268b4f3af7ccc388269b5eb1972d3624) (cherry picked from commit 4f319df8ff5a4b9f2bc62cb17df972e40b57fc81) Merged-In: Ie318d45fe44294e97cf38da7f1834cf014cb4417",https://github.com/LineageOS/android_frameworks_base/commit/392c061ae4393460b456ebc0c1e9f1518bc288e5,,,services/core/java/com/android/server/connectivity/Vpn.java,3,java,False,2022-02-28T09:02:27Z "@Override public NbtCheck.NbtCheckResult check(INbtTagCompound tag, String itemName, IPanilla panilla) { INbtTagList itemsTagList = tag.getList(getName()); // Bundles should only have 64 items if (itemsTagList.size() > 64) { return NbtCheckResult.FAIL; } // Check for air // Can cause a server crash if bundles have air items /* net.minecraft.ReportedException: Ticking player at net.minecraft.server.level.ServerPlayer.doTick(ServerPlayer.java:754) ~[?:?] at net.minecraft.server.network.ServerGamePacketListenerImpl.tick(ServerGamePacketListenerImpl.java:314) ~[?:?] at net.minecraft.network.Connection.tick(Connection.java:567) ~[?:?] at net.minecraft.server.network.ServerConnectionListener.tick(ServerConnectionListener.java:231) ~[?:?] at net.minecraft.server.MinecraftServer.tickChildren(MinecraftServer.java:1623) ~[paper-1.18.2.jar:git-Paper-388] at net.minecraft.server.dedicated.DedicatedServer.tickChildren(DedicatedServer.java:483) ~[paper-1.18.2.jar:git-Paper-388] at net.minecraft.server.MinecraftServer.tickServer(MinecraftServer.java:1456) ~[paper-1.18.2.jar:git-Paper-388] at net.minecraft.server.MinecraftServer.runServer(MinecraftServer.java:1226) ~[paper-1.18.2.jar:git-Paper-388] at net.minecraft.server.MinecraftServer.lambda$spin$0(MinecraftServer.java:316) ~[paper-1.18.2.jar:git-Paper-388] at java.lang.Thread.run(Thread.java:833) ~[?:?] Caused by: java.lang.IllegalArgumentException: item is null or air */ for (int i = 0; i < itemsTagList.size(); i++) { if (itemsTagList.getCompound(i).hasKey(""id"")) { if (itemsTagList.getCompound(i).getString(""id"").equals(""minecraft:air"")) { return NbtCheckResult.FAIL; } } } FailedNbt failedNbt = NbtCheck_BlockEntityTag.checkItems(getName(), itemsTagList, itemName, panilla); if (FailedNbt.fails(failedNbt)) { return failedNbt.result; } else { return NbtCheck.NbtCheckResult.PASS; } }","@Override public NbtCheck.NbtCheckResult check(INbtTagCompound tag, String itemName, IPanilla panilla) { INbtTagList itemsTagList = tag.getList(getName()); // Bundles should only have 64 items if (itemsTagList.size() > 64) { return NbtCheckResult.CRITICAL; } // Check for air // Can cause a server crash if bundles have air items /* net.minecraft.ReportedException: Ticking player at net.minecraft.server.level.ServerPlayer.doTick(ServerPlayer.java:754) ~[?:?] at net.minecraft.server.network.ServerGamePacketListenerImpl.tick(ServerGamePacketListenerImpl.java:314) ~[?:?] at net.minecraft.network.Connection.tick(Connection.java:567) ~[?:?] at net.minecraft.server.network.ServerConnectionListener.tick(ServerConnectionListener.java:231) ~[?:?] at net.minecraft.server.MinecraftServer.tickChildren(MinecraftServer.java:1623) ~[paper-1.18.2.jar:git-Paper-388] at net.minecraft.server.dedicated.DedicatedServer.tickChildren(DedicatedServer.java:483) ~[paper-1.18.2.jar:git-Paper-388] at net.minecraft.server.MinecraftServer.tickServer(MinecraftServer.java:1456) ~[paper-1.18.2.jar:git-Paper-388] at net.minecraft.server.MinecraftServer.runServer(MinecraftServer.java:1226) ~[paper-1.18.2.jar:git-Paper-388] at net.minecraft.server.MinecraftServer.lambda$spin$0(MinecraftServer.java:316) ~[paper-1.18.2.jar:git-Paper-388] at java.lang.Thread.run(Thread.java:833) ~[?:?] Caused by: java.lang.IllegalArgumentException: item is null or air */ for (int i = 0; i < itemsTagList.size(); i++) { if (itemsTagList.getCompound(i).hasKey(""id"")) { if (itemsTagList.getCompound(i).getString(""id"").equals(""minecraft:air"")) { return NbtCheckResult.CRITICAL; } } } FailedNbt failedNbt = NbtCheck_BlockEntityTag.checkItems(getName(), itemsTagList, itemName, panilla); if (FailedNbt.fails(failedNbt)) { return failedNbt.result; } else { return NbtCheck.NbtCheckResult.PASS; } }","Prevent class cast exception, make Items crash check fail CRITICAL",https://github.com/ds58/Panilla/commit/5a453f9e8f0cb164153fec502d0dbdb62b2ffa4e,,,api/src/main/java/com/ruinscraft/panilla/api/nbt/checks/NbtCheck_Items.java,3,java,False,2023-01-28T17:02:01Z "@SuppressWarnings(""checkstyle:emptyblock"") private static List internalParse( final InputStream input, final boolean endpointVerification) throws IOException { Document document; try { DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance(); DocumentBuilder documentBuilder = factory.newDocumentBuilder(); document = documentBuilder.parse(input); } catch (IOException exception) { throw exception; } catch (Exception exception) { throw new IOException(""Unable to parse region metadata file: "" + exception.getMessage(), exception); } finally { try { input.close(); } catch (IOException exception) { } } NodeList regionNodes = document.getElementsByTagName(REGION_TAG); List regions = new ArrayList(); for (int i = 0; i < regionNodes.getLength(); i++) { Node node = regionNodes.item(i); if (node.getNodeType() == Node.ELEMENT_NODE) { Element element = (Element) node; regions.add(parseRegionElement(element, endpointVerification)); } } return regions; }","@SuppressWarnings(""checkstyle:emptyblock"") private static List internalParse( final InputStream input, final boolean endpointVerification) throws IOException { Document document; try { DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance(); factory.setFeature(""http://apache.org/xml/features/disallow-doctype-decl"", true); factory.setXIncludeAware(false); factory.setExpandEntityReferences(false); DocumentBuilder documentBuilder = factory.newDocumentBuilder(); document = documentBuilder.parse(input); } catch (IOException exception) { throw exception; } catch (Exception exception) { throw new IOException(""Unable to parse region metadata file: "" + exception.getMessage(), exception); } finally { try { input.close(); } catch (IOException exception) { } } NodeList regionNodes = document.getElementsByTagName(REGION_TAG); List regions = new ArrayList(); for (int i = 0; i < regionNodes.getLength(); i++) { Node node = regionNodes.item(i); if (node.getNodeType() == Node.ELEMENT_NODE) { Element element = (Element) node; regions.add(parseRegionElement(element, endpointVerification)); } } return regions; }","release: AWS SDK for Android 2.59.0 (#3088) Co-authored-by: awsmobilesdk-dev+ghops ",https://github.com/aws-amplify/aws-sdk-android/commit/c3e6d69422e1f0c80fe53f2d757b8df97619af2b,,,aws-android-sdk-core/src/main/java/com/amazonaws/regions/RegionMetadataParser.java,3,java,False,2022-12-05T07:56:38Z "@Override public Future run() { this.hasRun = true; Iterator iterator = this.tasks.iterator(); int totalTicks = 0; while (iterator.hasNext()) { TickedFunction next = iterator.next(); if (!iterator.hasNext()) { return Scheduler.schedule(totalTicks + next.ticks, () -> { if (this.getInterpreter().getThreadHandler().getRunning()) { return next.function.invoke(this.getInterpreter().branch(), List.of()); } return this.getInterpreter().getNull(); }); } totalTicks += next.ticks; Scheduler.schedule(totalTicks, () -> { if (this.getInterpreter().getThreadHandler().getRunning()) { next.function.invoke(this.getInterpreter().branch(), List.of()); } }); } return CompletableFuture.completedFuture(this.getInterpreter().getNull()); }","@Override public Future run() { this.hasRun = true; Iterator iterator = this.tasks.iterator(); int totalTicks = 0; while (iterator.hasNext()) { TickedFunction next = iterator.next(); if (!iterator.hasNext()) { return Scheduler.schedule(totalTicks + next.ticks, () -> { Interpreter interpreter = this.getInterpreter(); return ClientScriptUtils.wrapSafe(() -> { if (interpreter.getThreadHandler().getRunning()) { return next.function.invoke(interpreter.branch(), List.of()); } return interpreter.getNull(); }, interpreter); }); } totalTicks += next.ticks; Scheduler.schedule(totalTicks, () -> { Interpreter interpreter = this.getInterpreter(); ClientScriptUtils.wrapSafe(() -> { if (interpreter.getThreadHandler().getRunning()) { next.function.invoke(interpreter.branch(), List.of()); } }, interpreter); }); } return CompletableFuture.completedFuture(this.getInterpreter().getNull()); }",Fixed some NPE and fatal error crashes,https://github.com/senseiwells/EssentialClient/commit/973a3e6154e28d6d592edf8cbc42a1c7bd850e38,,,src/main/java/me/senseiwells/essentialclient/utils/clientscript/impl/ScriptTask.java,3,java,False,2022-12-24T21:38:57Z "@Bean @Order(0) SecurityWebFilterChain webFilterChain(ServerHttpSecurity http) { http.authorizeExchange(exchanges -> exchanges.pathMatchers( ""/actuator/**"" ).permitAll()) .authorizeExchange(exchanges -> exchanges.anyExchange().authenticated()) .cors(withDefaults()) .httpBasic(withDefaults()) .formLogin(withDefaults()) .csrf().csrfTokenRepository(new CookieServerCsrfTokenRepository()).and() .logout(withDefaults()); return http.build(); }","@Bean @Order(0) SecurityWebFilterChain webFilterChain(ServerHttpSecurity http) { http.authorizeExchange(exchanges -> exchanges.pathMatchers( ""/actuator/**"" ).permitAll()) .cors(corsSpec -> corsSpec.configurationSource(apiCorsConfigurationSource())) .authorizeExchange(exchanges -> exchanges.anyExchange().authenticated()) .cors(withDefaults()) .httpBasic(withDefaults()) .formLogin(withDefaults()) .csrf().csrfTokenRepository(CookieServerCsrfTokenRepository.withHttpOnlyFalse()).and() .logout(withDefaults()); return http.build(); }","refactor: configure the api request to allow credentials and X-XSRF-TOKEN,COOKIE headers (#2227) Signed-off-by: Ryan Wang ",https://github.com/halo-dev/halo/commit/c97804780bf972cb7ca3e9bca28633e2d97c8224,,,src/main/java/run/halo/app/config/WebServerSecurityConfig.java,3,java,False,2022-07-08T09:44:13Z "@Override public synchronized void done(boolean success) { if(success || (!success && !supportedAuths.contains(""password""))) { ((PasswordAuthenticator)authenticator).done(success); } super.done(success); }","@Override public synchronized void done(boolean success) { if(success || (!success && !supportedAuths.contains(""password""))) { ((PasswordAuthenticator)authenticator).done(success); } else { if(supportedAuths.contains(""password"")) { authenticators.addLast(authenticator); } } super.done(success); }",HOTFIX: Premature change of authentication mechansim causes SSH_MSG_UNIMPLEMENTED,https://github.com/sshtools/maverick-synergy/commit/9074f25b600518795ccb3e98f00ca4eecb91d41e,,,maverick-synergy-client/src/main/java/com/sshtools/client/AuthenticationProtocolClient.java,3,java,False,2022-07-26T19:59:11Z "private static void setDocumentContent(IDocument document, IStorage storage, String encoding, IProgressMonitor monitor, boolean skipUTF8BOM) throws CoreException { Reader in= null; InputStream contentStream= storage.getContents(); try { if (skipUTF8BOM) { for (int i= 0; i < 3; i++) if (contentStream.read() == -1) { throw new IOException(QuickDiffMessages.getString(""LastSaveReferenceProvider.LastSaveReferenceProvider.error.notEnoughBytesForBOM"")); //$NON-NLS-1$ } } final int DEFAULT_FILE_SIZE= 15 * 1024; if (encoding == null) in= new BufferedReader(new InputStreamReader(contentStream), DEFAULT_FILE_SIZE); else in= new BufferedReader(new InputStreamReader(contentStream, encoding), DEFAULT_FILE_SIZE); StringBuilder buffer= new StringBuilder(DEFAULT_FILE_SIZE); char[] readBuffer= new char[2048]; int n= in.read(readBuffer); while (n > 0) { if (monitor != null && monitor.isCanceled()) return; buffer.append(readBuffer, 0, n); n= in.read(readBuffer); } document.set(buffer.toString()); } catch (IOException x) { throw new CoreException(new Status(IStatus.ERROR, EditorsUI.PLUGIN_ID, IStatus.OK, ""Failed to access or read underlying storage"", x)); //$NON-NLS-1$ } finally { try { if (in != null) in.close(); else contentStream.close(); } catch (IOException x) { // ignore } } }","private static void setDocumentContent(IDocument document, IStorage storage, String encoding, IProgressMonitor monitor, boolean skipUTF8BOM) throws CoreException { Reader in= null; InputStream contentStream= storage.getContents(); try { if (skipUTF8BOM) { for (int i= 0; i < 3; i++) if (contentStream.read() == -1) { throw new IOException(QuickDiffMessages.getString(""LastSaveReferenceProvider.LastSaveReferenceProvider.error.notEnoughBytesForBOM"")); //$NON-NLS-1$ } } final int DEFAULT_FILE_SIZE= 15 * 1024; if (encoding == null) in= new BufferedReader(new InputStreamReader(contentStream), DEFAULT_FILE_SIZE); else in= new BufferedReader(new InputStreamReader(contentStream, encoding), DEFAULT_FILE_SIZE); StringBuilder buffer= new StringBuilder(DEFAULT_FILE_SIZE); char[] readBuffer= new char[2048]; int n= in.read(readBuffer); try { while (n > 0) { if (monitor != null && monitor.isCanceled()) return; buffer.append(readBuffer, 0, n); n= in.read(readBuffer); } } catch (OutOfMemoryError e) { throw new IOException(""OutOfMemoryError occurred while reading "" + storage.getFullPath(), e); //$NON-NLS-1$ } document.set(buffer.toString()); } catch (IOException x) { throw new CoreException(Status.error(""Failed to access or read "" + storage.getFullPath(), x)); //$NON-NLS-1$ } finally { try { if (in != null) in.close(); else contentStream.close(); } catch (IOException x) { // ignore } } }","Bug 575641 - Text editor fails to open for very large text files This change adds a catch for OutOfMemoryError to setDocumentContent() in ResourceTextFileBuffer, FileStoreTextFileBuffer and LastSaveReferenceProvider. The OOM is wrapped in an IOException and is rethrown as a CoreException, relying on the CoreException handling further up in the call stack trace. Change-Id: I1ad32be1c1733106c3516c5914ab7784fcc57972 Signed-off-by: Simeon Andreev Reviewed-on: https://git.eclipse.org/r/c/platform/eclipse.platform.text/+/184513 Tested-by: Andrey Loskutov Tested-by: Platform Bot Reviewed-by: Jörg Kubitz Reviewed-by: Andrey Loskutov ",https://github.com/eclipse-platform/eclipse.platform.ui/commit/19ac38fe9ca3adc54f3c1671f188304c3bab412a,,,org.eclipse.ui.editors/src/org/eclipse/ui/internal/editors/quickdiff/LastSaveReferenceProvider.java,3,java,False,2021-08-27T08:41:34Z "private boolean doesAddToastWindowRequireToken(String packageName, int callingUid, WindowState attachedWindow) { // Try using the target SDK of the root window if (attachedWindow != null) { return attachedWindow.mActivityRecord != null && attachedWindow.mActivityRecord.mTargetSdk >= Build.VERSION_CODES.O; } else { // Otherwise, look at the package try { ApplicationInfo appInfo = mContext.getPackageManager() .getApplicationInfoAsUser(packageName, 0, UserHandle.getUserId(callingUid)); if (appInfo.uid != callingUid) { throw new SecurityException(""Package "" + packageName + "" not in UID "" + callingUid); } if (appInfo.targetSdkVersion >= Build.VERSION_CODES.O) { return true; } } catch (PackageManager.NameNotFoundException e) { /* ignore */ } } return false; }","private boolean doesAddToastWindowRequireToken(String packageName, int callingUid, WindowState attachedWindow) { // Try using the target SDK of the root window if (attachedWindow != null) { return attachedWindow.mActivityRecord != null && attachedWindow.mActivityRecord.mTargetSdk >= Build.VERSION_CODES.O; } else { // Otherwise, look at the package final ApplicationInfo appInfo = mPmInternal.getApplicationInfo( packageName, 0 /* flags */, SYSTEM_UID, UserHandle.getUserId(callingUid)); if (appInfo == null || appInfo.uid != callingUid) { throw new SecurityException(""Package "" + packageName + "" not in UID "" + callingUid); } return appInfo.targetSdkVersion >= Build.VERSION_CODES.O; } }","Fix side channel information disclosure This method reacts differently when the given package name isn't installed, and is installed but not belonging to the caller. This subtle difference leaves the possibility that malicious code could do a side channel attack. Bug: 249058614 Test: atest CtsWindowManagerDeviceTestCases:ToastWindowTest Test: atest CtsWindowManagerDeviceTestCases:WindowContextPolicyTests Test: atest CtsWindowManagerDeviceTestCases:WindowUntrustedTouchTest Test: atest CtsToastLegacyTestCases:ToastTest Test: atest CtsToastTestCases:LegacyToastTest Test: atest FrameworksCoreTests:ViewRootImplTest Test: atest FrameworksUiServicesTests:NotificationManagerServiceTest Change-Id: I37f28b6a660c4a3d2cd92b25d3f68066902c692f Change-Id: I52372bec19355ea8855ead28fcb0ab250c527f19",https://github.com/aosp-mirror/platform_frameworks_base/commit/0594d55d3295ab78fcba890b77c63431124ca51e,,,services/core/java/com/android/server/wm/WindowManagerService.java,3,java,False,2022-11-03T06:38:48Z "@EventHandler(priority = EventPriority.MONITOR) public void disenchanter(InventoryClickEvent event) { if (event.isCancelled()) return; if (blockDisabled(Ability.DISENCHANTER)) return; if (!VersionUtils.isAtLeastVersion(14)) return; // This ability requires at least 1.14 if (event.getWhoClicked() instanceof Player) { Player player = (Player) event.getWhoClicked(); if (blockAbility(player)) return; Inventory inventory = event.getClickedInventory(); if (inventory == null) return; ClickType click = event.getClick(); // Only allow right and left clicks if inventory full if (click != ClickType.LEFT && click != ClickType.RIGHT && ItemUtils.isInventoryFull(player)) return; if (event.getResult() != Event.Result.ALLOW) return; // Make sure the click was successful if (event.getClickedInventory().getType() == InventoryType.GRINDSTONE) { if (event.getSlotType() == InventoryType.SlotType.RESULT) { PlayerData playerData = plugin.getPlayerManager().getPlayerData(player); if (playerData == null) return; if (playerData.getAbilityLevel(Ability.DISENCHANTER) == 0) return; Location location = inventory.getLocation(); if (location == null) return; ItemStack first = inventory.getItem(0); ItemStack second = inventory.getItem(1); if (first != null && second != null) { // If two items, make sure items are the same type if (first.getType() != second.getType()) { return; } } Set enchants = new HashSet<>(); // Add enchants to disenchant checkEnchants(first, enchants); checkEnchants(second, enchants); if (enchants.size() == 0) return; // Calculate the sum try { int sum = 0; for (EnchantmentValue value : enchants) { String enchantName = value.getEnchantment().getKey().getKey().toUpperCase(Locale.ENGLISH); if (containsEnchant(enchantName)) { sum += GrindstoneEnchant.valueOf(enchantName).getLevel(value.getLevel()); } } int average = (sum + (int) Math.ceil(((double) sum) / 2)) / 2; // Get the average experience that would drop int added = (int) Math.round(average * (getValue(Ability.DISENCHANTER, playerData) / 100)); World world = location.getWorld(); if (world != null) { world.spawn(location, ExperienceOrb.class).setExperience(added); } } catch (IllegalArgumentException ignored) {} } } } }","@EventHandler(priority = EventPriority.MONITOR) public void disenchanter(InventoryClickEvent event) { if (event.isCancelled()) return; if (blockDisabled(Ability.DISENCHANTER)) return; if (!VersionUtils.isAtLeastVersion(14)) return; // This ability requires at least 1.14 if (event.getWhoClicked() instanceof Player) { Player player = (Player) event.getWhoClicked(); if (blockAbility(player)) return; Inventory inventory = event.getClickedInventory(); if (inventory == null) return; ClickType click = event.getClick(); // Only allow right and left clicks if inventory full if (click != ClickType.LEFT && click != ClickType.RIGHT && ItemUtils.isInventoryFull(player)) return; if (event.getResult() != Event.Result.ALLOW) return; // Make sure the click was successful if (player.getItemOnCursor().getType() != Material.AIR) return; // Make sure cursor is empty if (event.getClickedInventory().getType() == InventoryType.GRINDSTONE) { if (event.getSlotType() == InventoryType.SlotType.RESULT) { PlayerData playerData = plugin.getPlayerManager().getPlayerData(player); if (playerData == null) return; if (playerData.getAbilityLevel(Ability.DISENCHANTER) == 0) return; Location location = inventory.getLocation(); if (location == null) return; ItemStack first = inventory.getItem(0); ItemStack second = inventory.getItem(1); if (first != null && second != null) { // If two items, make sure items are the same type if (first.getType() != second.getType()) { return; } } Set enchants = new HashSet<>(); // Add enchants to disenchant checkEnchants(first, enchants); checkEnchants(second, enchants); if (enchants.size() == 0) return; // Calculate the sum try { int sum = 0; for (EnchantmentValue value : enchants) { String enchantName = value.getEnchantment().getKey().getKey().toUpperCase(Locale.ENGLISH); if (containsEnchant(enchantName)) { sum += GrindstoneEnchant.valueOf(enchantName).getLevel(value.getLevel()); } } int average = (sum + (int) Math.ceil(((double) sum) / 2)) / 2; // Get the average experience that would drop int added = (int) Math.round(average * (getValue(Ability.DISENCHANTER, playerData) / 100)); World world = location.getWorld(); if (world != null) { world.spawn(location, ExperienceOrb.class).setExperience(added); } } catch (IllegalArgumentException ignored) {} } } } }",Fix Forging XP exploit,https://github.com/Archy-X/AuraSkills/commit/4eb3444924b1a52e6406ee5513ea8534807ecd71,,,src/main/java/com/archyx/aureliumskills/skills/forging/ForgingAbilities.java,3,java,False,2021-12-31T06:13:05Z "private ServiceResponse executeDeleteEntitySet(ServiceRequest request, ServiceResponse response, ResourcePath path) { PersistenceManager pm = null; try { PathElementEntitySet mainEntity = (PathElementEntitySet) path.getMainElement(); if (mainEntity != path.getLastElement()) { return errorResponse(response, 400, ""DELETE not allowed on properties.""); } pm = getPm(); if (!pm.validatePath(path)) { maybeCommitAndClose(); return errorResponse(response, 404, NOTHING_FOUND_RESPONSE); } return handleDeleteSet(request, response, pm, path); } catch (Exception e) { LOGGER.error("""", e); if (pm != null) { pm.rollbackAndClose(); } return errorResponse(response, 400, e.getMessage()); } finally { maybeRollbackAndClose(); } }","private ServiceResponse executeDeleteEntitySet(ServiceRequest request, ServiceResponse response, ResourcePath path) { PersistenceManager pm = null; try { PathElementEntitySet mainEntity = (PathElementEntitySet) path.getMainElement(); if (mainEntity != path.getLastElement()) { return errorResponse(response, 400, ""DELETE not allowed on properties.""); } pm = getPm(); if (!pm.validatePath(path)) { maybeCommitAndClose(); return errorResponse(response, 404, NOTHING_FOUND_RESPONSE); } return handleDeleteSet(request, response, pm, path); } catch (UnauthorizedException e) { rollbackAndClose(pm); return errorResponse(response, 401, e.getMessage()); } catch (ForbiddenException e) { rollbackAndClose(pm); return errorResponse(response, 403, e.getMessage()); } catch (Exception e) { LOGGER.error("""", e); rollbackAndClose(pm); return errorResponse(response, 400, e.getMessage()); } finally { maybeRollbackAndClose(); } }",Added Forbidden- and UnauthorizedExceptions,https://github.com/FraunhoferIOSB/FROST-Server/commit/e72e4ee2e7d33b58da29c434d0ff63de5f656ee4,,,FROST-Server.Core/src/main/java/de/fraunhofer/iosb/ilt/frostserver/service/Service.java,3,java,False,2021-12-01T19:48:43Z "@Override public Uni authenticate(RoutingContext context, IdentityProviderManager identityProviderManager) { if (authEnabled) { if (clientSecret.isPresent()) { //Extracts username, password pair from the header and request a token to keycloak String jwtToken = new BearerTokenExtractor(context, authServerUrl, authRealm, clientId, clientSecret.get()).getBearerToken(); if (jwtToken != null) { //If we manage to get a token from basic credentials, try to authenticate it using the fetched token using the identity provider manager return identityProviderManager .authenticate(new TokenAuthenticationRequest(new AccessTokenCredential(jwtToken, context))); } } return oidcAuthenticationMechanism.authenticate(context, identityProviderManager); } else { return Uni.createFrom().nullItem(); } }","@Override public Uni authenticate(RoutingContext context, IdentityProviderManager identityProviderManager) { if (authEnabled) { if (clientSecret.isEmpty()) { //if no secret is present, try to authenticate with oidc provider return oidcAuthenticationMechanism.authenticate(context, identityProviderManager); } else { //Extracts username, password pair from the header and request a token to keycloak String jwtToken = new BearerTokenExtractor(context, authServerUrl, authRealm, clientId, clientSecret.get()).getBearerToken(); if (jwtToken != null) { //If we manage to get a token from basic credentials, try to authenticate it using the fetched token using the identity provider manager return identityProviderManager .authenticate(new TokenAuthenticationRequest(new AccessTokenCredential(jwtToken, context))); } else { //If we cannot get a token, then try to authenticate using oidc provider as last resource return oidcAuthenticationMechanism.authenticate(context, identityProviderManager); } } } return Uni.createFrom().nullItem(); }","Improve custom authentication mechanism (#1663) * Improve custom authentication mechanism * Fix custom authentication mechanism and improve bad property name",https://github.com/Apicurio/apicurio-registry/commit/5541c4223cf6eaee4c983852a153f2b1e4415f3e,,,app/src/main/java/io/apicurio/registry/services/auth/CustomAuthenticationMechanism.java,3,java,False,2021-07-12T11:21:49Z "private Response getResponse(Request request) { Server server = serverInfo.getServer(); if (!webServer.get().isAuthRequired()) { String redirectTo = server.isProxy() ? ""network"" : ""server/"" + Html.encodeToURL(server.getIdentifiableName()); return responseFactory.redirectResponse(redirectTo); } WebUser user = request.getUser() .orElseThrow(() -> new WebUserAuthException(FailReason.NO_USER_PRESENT)); if (user.hasPermission(""page.server"")) { return responseFactory.redirectResponse(server.isProxy() ? ""network"" : ""server/"" + Html.encodeToURL(server.getIdentifiableName())); } else if (user.hasPermission(""page.players"")) { return responseFactory.redirectResponse(""players""); } else if (user.hasPermission(""page.player.self"")) { return responseFactory.redirectResponse(""player/"" + Html.encodeToURL(user.getName())); } else { return responseFactory.forbidden403(user.getName() + "" has insufficient permissions to be redirected to any page. Needs one of: 'page.server', 'page.players' or 'page.player.self'""); } }","private Response getResponse(Request request) { Server server = serverInfo.getServer(); if (!webServer.get().isAuthRequired()) { String redirectTo = server.isProxy() ? ""network"" : ""server/"" + Html.encodeToURL(server.getIdentifiableName()); return responseFactory.redirectResponse(redirectTo); } WebUser user = request.getUser() .orElseThrow(() -> new WebUserAuthException(FailReason.EXPIRED_COOKIE)); if (user.hasPermission(""page.server"")) { return responseFactory.redirectResponse(server.isProxy() ? ""network"" : ""server/"" + Html.encodeToURL(server.getIdentifiableName())); } else if (user.hasPermission(""page.players"")) { return responseFactory.redirectResponse(""players""); } else if (user.hasPermission(""page.player.self"")) { return responseFactory.redirectResponse(""player/"" + Html.encodeToURL(user.getName())); } else { return responseFactory.forbidden403(user.getName() + "" has insufficient permissions to be redirected to any page. Needs one of: 'page.server', 'page.players' or 'page.player.self'""); } }","Implemented persistent cookies Fixed security vulnerability with cookies not being invalidated properly Request headers were not properly set for the Request object, leading to the Cookie header missing when logging out, which then left the cookie in memory. Rogue actor who gained access to the cookie could then use the cookie to access the panel. Made cookie expiry configurable with 'Webserver.Security.Cookie_expires_after' Due to cookie persistence there is no way to log everyone out of the panel. This will be addressed in a future commit with addition of a command. Affects issues: - Close #1740",https://github.com/plan-player-analytics/Plan/commit/fb4b272844263d33f5a6e85af29ac7e6e25ff80a,,,Plan/common/src/main/java/com/djrapitops/plan/delivery/webserver/resolver/RootPageResolver.java,3,java,False,2021-03-20T10:02:02Z "void flush_tlb_page(struct vm_area_struct *vma, unsigned long start) { struct mm_struct *mm = vma->vm_mm; preempt_disable(); if (current->active_mm == mm) { if (current->mm) __flush_tlb_one(start); else leave_mm(smp_processor_id()); } if (cpumask_any_but(mm_cpumask(mm), smp_processor_id()) < nr_cpu_ids) flush_tlb_others(mm_cpumask(mm), mm, start, 0UL); preempt_enable(); }","void flush_tlb_page(struct vm_area_struct *vma, unsigned long start) { struct mm_struct *mm = vma->vm_mm; preempt_disable(); if (current->active_mm == mm) { if (current->mm) { /* * Implicit full barrier (INVLPG) that synchronizes * with switch_mm. */ __flush_tlb_one(start); } else { leave_mm(smp_processor_id()); /* Synchronize with switch_mm. */ smp_mb(); } } if (cpumask_any_but(mm_cpumask(mm), smp_processor_id()) < nr_cpu_ids) flush_tlb_others(mm_cpumask(mm), mm, start, 0UL); preempt_enable(); }","x86/mm: Add barriers and document switch_mm()-vs-flush synchronization When switch_mm() activates a new PGD, it also sets a bit that tells other CPUs that the PGD is in use so that TLB flush IPIs will be sent. In order for that to work correctly, the bit needs to be visible prior to loading the PGD and therefore starting to fill the local TLB. Document all the barriers that make this work correctly and add a couple that were missing. Signed-off-by: Andy Lutomirski Cc: Andrew Morton Cc: Andy Lutomirski Cc: Borislav Petkov Cc: Brian Gerst Cc: Dave Hansen Cc: Denys Vlasenko Cc: H. Peter Anvin Cc: Linus Torvalds Cc: Peter Zijlstra Cc: Rik van Riel Cc: Thomas Gleixner Cc: linux-mm@kvack.org Cc: stable@vger.kernel.org Signed-off-by: Ingo Molnar ",https://github.com/torvalds/linux/commit/71b3c126e61177eb693423f2e18a1914205b165e,,,arch/x86/mm/tlb.c,3,c,False,2016-01-06T20:21:01Z "public void showPrompts(String name, String instruction, KeyboardInteractivePrompt[] prompts, KeyboardInteractivePromptCompletor completor) { for (int i = 0; i < prompts.length; i++) { prompts[i].setResponse(password); } completor.complete(); }","public void showPrompts(String name, String instruction, KeyboardInteractivePrompt[] prompts, KeyboardInteractivePromptCompletor completor) { for (int i = 0; i < prompts.length; i++) { prompts[i].setResponse(auth.getPassword()); } completor.complete(); }","HOTFIX: Defer collecting password until authentication is being performed. Always covert to keyboard-interactive regardless of policy if password is not supported.",https://github.com/sshtools/maverick-synergy/commit/72407b74948bc2a6e88ddaf1cd6fbc8f4139f743,,,maverick-synergy-client/src/main/java/com/sshtools/client/PasswordOverKeyboardInteractiveCallback.java,3,java,False,2021-08-26T12:37:47Z "private synchronized boolean prepareToPreFetch() { if (!isDnsOpen()) { return false; } if (isPrefetching()) { return false; } String localIp = AndroidNetwork.getHostIP(); if (localIp == null || getDnsCacheInfo() == null || !(localIp.equals(getDnsCacheInfo().getLocalIp()))) { clearPreHosts(); } setPrefetching(true); return true; }","private synchronized boolean prepareToPreFetch() { if (!isDnsOpen()) { return false; } if (isPrefetching()) { return false; } String localIp = AndroidNetwork.getHostIP(); if (localIp == null || getDnsCacheInfo() == null || !(localIp.equals(getDnsCacheInfo().getLocalIp()))) { clearMemoryCache(); } setPrefetching(true); return true; }",handle dns hijacked & dns prefetch add doh,https://github.com/qiniu/android-sdk/commit/ada3c8feb608ed37fe8d64ba2d10ac672a207525,,,library/src/main/java/com/qiniu/android/http/dns/DnsPrefetcher.java,3,java,False,2021-08-27T10:02:18Z "function apiWorkspaceEndpoints(app) { if (!app) return; app.post(""/v1/workspace/new"", [validApiKey], async (request, response) => { /* #swagger.tags = ['Workspaces'] #swagger.description = 'Create a new workspace' #swagger.requestBody = { description: 'JSON object containing new display name of workspace.', required: true, type: 'object', content: { ""application/json"": { example: { name: ""My New Workspace"", } } } } #swagger.responses[200] = { content: { ""application/json"": { schema: { type: 'object', example: { workspace: { ""id"": 79, ""name"": ""Sample workspace"", ""slug"": ""sample-workspace"", ""createdAt"": ""2023-08-17 00:45:03"", ""openAiTemp"": null, ""lastUpdatedAt"": ""2023-08-17 00:45:03"", ""openAiHistory"": 20, ""openAiPrompt"": null }, message: 'Workspace created' } } } } } #swagger.responses[403] = { schema: { ""$ref"": ""#/definitions/InvalidAPIKey"" } } */ try { const { name = null } = reqBody(request); const { workspace, message } = await Workspace.new(name); await Telemetry.sendTelemetry(""workspace_created"", { multiUserMode: multiUserMode(response), LLMSelection: process.env.LLM_PROVIDER || ""openai"", VectorDbSelection: process.env.VECTOR_DB || ""pinecone"", }); response.status(200).json({ workspace, message }); } catch (e) { console.log(e.message, e); response.sendStatus(500).end(); } }); app.get(""/v1/workspaces"", [validApiKey], async (request, response) => { /* #swagger.tags = ['Workspaces'] #swagger.description = 'List all current workspaces' #swagger.responses[200] = { content: { ""application/json"": { schema: { type: 'object', example: { workspaces: [ { ""id"": 79, ""name"": ""Sample workspace"", ""slug"": ""sample-workspace"", ""createdAt"": ""2023-08-17 00:45:03"", ""openAiTemp"": null, ""lastUpdatedAt"": ""2023-08-17 00:45:03"", ""openAiHistory"": 20, ""openAiPrompt"": null } ], } } } } } #swagger.responses[403] = { schema: { ""$ref"": ""#/definitions/InvalidAPIKey"" } } */ try { const workspaces = await Workspace.where(); response.status(200).json({ workspaces }); } catch (e) { console.log(e.message, e); response.sendStatus(500).end(); } }); app.get(""/v1/workspace/:slug"", [validApiKey], async (request, response) => { /* #swagger.tags = ['Workspaces'] #swagger.description = 'Get a workspace by its unique slug.' #swagger.path = '/v1/workspace/{slug}' #swagger.parameters['slug'] = { in: 'path', description: 'Unique slug of workspace to find', required: true, type: 'string' } #swagger.responses[200] = { content: { ""application/json"": { schema: { type: 'object', example: { workspace: { ""id"": 79, ""name"": ""My workspace"", ""slug"": ""my-workspace-123"", ""createdAt"": ""2023-08-17 00:45:03"", ""openAiTemp"": null, ""lastUpdatedAt"": ""2023-08-17 00:45:03"", ""openAiHistory"": 20, ""openAiPrompt"": null, ""documents"": [] } } } } } } #swagger.responses[403] = { schema: { ""$ref"": ""#/definitions/InvalidAPIKey"" } } */ try { const { slug } = request.params; const workspace = await Workspace.get(`slug = '${slug}'`); response.status(200).json({ workspace }); } catch (e) { console.log(e.message, e); response.sendStatus(500).end(); } }); app.delete( ""/v1/workspace/:slug"", [validApiKey], async (request, response) => { /* #swagger.tags = ['Workspaces'] #swagger.description = 'Deletes a workspace by its slug.' #swagger.path = '/v1/workspace/{slug}' #swagger.parameters['slug'] = { in: 'path', description: 'Unique slug of workspace to delete', required: true, type: 'string' } #swagger.responses[403] = { schema: { ""$ref"": ""#/definitions/InvalidAPIKey"" } } */ try { const { slug = """" } = request.params; const VectorDb = getVectorDbClass(); const workspace = await Workspace.get(`slug = '${slug}'`); if (!workspace) { response.sendStatus(400).end(); return; } await Workspace.delete(`slug = '${slug.toLowerCase()}'`); await DocumentVectors.deleteForWorkspace(workspace.id); await Document.delete(`workspaceId = ${Number(workspace.id)}`); await WorkspaceChats.delete(`workspaceId = ${Number(workspace.id)}`); try { await VectorDb[""delete-namespace""]({ namespace: slug }); } catch (e) { console.error(e.message); } response.sendStatus(200).end(); } catch (e) { console.log(e.message, e); response.sendStatus(500).end(); } } ); app.post( ""/v1/workspace/:slug/update"", [validApiKey], async (request, response) => { /* #swagger.tags = ['Workspaces'] #swagger.description = 'Update workspace settings by its unique slug.' #swagger.path = '/v1/workspace/{slug}/update' #swagger.parameters['slug'] = { in: 'path', description: 'Unique slug of workspace to find', required: true, type: 'string' } #swagger.requestBody = { description: 'JSON object containing new settings to update a workspace. All keys are optional and will not update unless provided', required: true, type: 'object', content: { ""application/json"": { example: { ""name"": 'Updated Workspace Name', ""openAiTemp"": 0.2, ""openAiHistory"": 20, ""openAiPrompt"": ""Respond to all inquires and questions in binary - do not respond in any other format."" } } } } #swagger.responses[200] = { content: { ""application/json"": { schema: { type: 'object', example: { workspace: { ""id"": 79, ""name"": ""My workspace"", ""slug"": ""my-workspace-123"", ""createdAt"": ""2023-08-17 00:45:03"", ""openAiTemp"": null, ""lastUpdatedAt"": ""2023-08-17 00:45:03"", ""openAiHistory"": 20, ""openAiPrompt"": null, ""documents"": [] }, message: null, } } } } } #swagger.responses[403] = { schema: { ""$ref"": ""#/definitions/InvalidAPIKey"" } } */ try { const { slug = null } = request.params; const data = reqBody(request); const currWorkspace = await Workspace.get(`slug = '${slug}'`); if (!currWorkspace) { response.sendStatus(400).end(); return; } const { workspace, message } = await Workspace.update( currWorkspace.id, data ); response.status(200).json({ workspace, message }); } catch (e) { console.log(e.message, e); response.sendStatus(500).end(); } } ); app.get( ""/v1/workspace/:slug/chats"", [validApiKey], async (request, response) => { /* #swagger.tags = ['Workspaces'] #swagger.description = 'Get a workspaces chats regardless of user by its unique slug.' #swagger.path = '/v1/workspace/{slug}/chats' #swagger.parameters['slug'] = { in: 'path', description: 'Unique slug of workspace to find', required: true, type: 'string' } #swagger.responses[200] = { content: { ""application/json"": { schema: { type: 'object', example: { history: [ { ""role"": ""user"", ""content"": ""What is AnythingLLM?"", ""sentAt"": 1692851630 }, { ""role"": ""assistant"", ""content"": ""AnythingLLM is a platform that allows you to convert notes, PDFs, and other source materials into a chatbot. It ensures privacy, cites its answers, and allows multiple people to interact with the same documents simultaneously. It is particularly useful for businesses to enhance the visibility and readability of various written communications such as SOPs, contracts, and sales calls. You can try it out with a free trial to see if it meets your business needs."", ""sources"": [{""source"": ""object about source document and snippets used""}] } ] } } } } } #swagger.responses[403] = { schema: { ""$ref"": ""#/definitions/InvalidAPIKey"" } } */ try { const { slug } = request.params; const workspace = await Workspace.get(`slug = '${slug}'`); if (!workspace) { response.sendStatus(400).end(); return; } const history = await WorkspaceChats.forWorkspace(workspace.id); response.status(200).json({ history: convertToChatHistory(history) }); } catch (e) { console.log(e.message, e); response.sendStatus(500).end(); } } ); app.post( ""/v1/workspace/:slug/update-embeddings"", [validApiKey], async (request, response) => { /* #swagger.tags = ['Workspaces'] #swagger.description = 'Add or remove documents from a workspace by its unique slug.' #swagger.path = '/v1/workspace/{slug}/update-embeddings' #swagger.parameters['slug'] = { in: 'path', description: 'Unique slug of workspace to find', required: true, type: 'string' } #swagger.requestBody = { description: 'JSON object of additions and removals of documents to add to update a workspace. The value should be the folder + filename with the exclusions of the top-level documents path.', required: true, type: 'object', content: { ""application/json"": { example: { adds: [], deletes: [""custom-documents/anythingllm-hash.json""] } } } } #swagger.responses[200] = { content: { ""application/json"": { schema: { type: 'object', example: { workspace: { ""id"": 79, ""name"": ""My workspace"", ""slug"": ""my-workspace-123"", ""createdAt"": ""2023-08-17 00:45:03"", ""openAiTemp"": null, ""lastUpdatedAt"": ""2023-08-17 00:45:03"", ""openAiHistory"": 20, ""openAiPrompt"": null, ""documents"": [] }, message: null, } } } } } #swagger.responses[403] = { schema: { ""$ref"": ""#/definitions/InvalidAPIKey"" } } */ try { const { slug = null } = request.params; const { adds = [], deletes = [] } = reqBody(request); const currWorkspace = await Workspace.get(`slug = '${slug}'`); if (!currWorkspace) { response.sendStatus(400).end(); return; } await Document.removeDocuments(currWorkspace, deletes); await Document.addDocuments(currWorkspace, adds); const updatedWorkspace = await Workspace.get(`slug = '${slug}'`); response.status(200).json({ workspace: updatedWorkspace }); } catch (e) { console.log(e.message, e); response.sendStatus(500).end(); } } ); }","function apiWorkspaceEndpoints(app) { if (!app) return; app.post(""/v1/workspace/new"", [validApiKey], async (request, response) => { /* #swagger.tags = ['Workspaces'] #swagger.description = 'Create a new workspace' #swagger.requestBody = { description: 'JSON object containing new display name of workspace.', required: true, type: 'object', content: { ""application/json"": { example: { name: ""My New Workspace"", } } } } #swagger.responses[200] = { content: { ""application/json"": { schema: { type: 'object', example: { workspace: { ""id"": 79, ""name"": ""Sample workspace"", ""slug"": ""sample-workspace"", ""createdAt"": ""2023-08-17 00:45:03"", ""openAiTemp"": null, ""lastUpdatedAt"": ""2023-08-17 00:45:03"", ""openAiHistory"": 20, ""openAiPrompt"": null }, message: 'Workspace created' } } } } } #swagger.responses[403] = { schema: { ""$ref"": ""#/definitions/InvalidAPIKey"" } } */ try { const { name = null } = reqBody(request); const { workspace, message } = await Workspace.new(name); await Telemetry.sendTelemetry(""workspace_created"", { multiUserMode: multiUserMode(response), LLMSelection: process.env.LLM_PROVIDER || ""openai"", VectorDbSelection: process.env.VECTOR_DB || ""pinecone"", }); response.status(200).json({ workspace, message }); } catch (e) { console.log(e.message, e); response.sendStatus(500).end(); } }); app.get(""/v1/workspaces"", [validApiKey], async (request, response) => { /* #swagger.tags = ['Workspaces'] #swagger.description = 'List all current workspaces' #swagger.responses[200] = { content: { ""application/json"": { schema: { type: 'object', example: { workspaces: [ { ""id"": 79, ""name"": ""Sample workspace"", ""slug"": ""sample-workspace"", ""createdAt"": ""2023-08-17 00:45:03"", ""openAiTemp"": null, ""lastUpdatedAt"": ""2023-08-17 00:45:03"", ""openAiHistory"": 20, ""openAiPrompt"": null } ], } } } } } #swagger.responses[403] = { schema: { ""$ref"": ""#/definitions/InvalidAPIKey"" } } */ try { const workspaces = await Workspace.where(); response.status(200).json({ workspaces }); } catch (e) { console.log(e.message, e); response.sendStatus(500).end(); } }); app.get(""/v1/workspace/:slug"", [validApiKey], async (request, response) => { /* #swagger.tags = ['Workspaces'] #swagger.description = 'Get a workspace by its unique slug.' #swagger.path = '/v1/workspace/{slug}' #swagger.parameters['slug'] = { in: 'path', description: 'Unique slug of workspace to find', required: true, type: 'string' } #swagger.responses[200] = { content: { ""application/json"": { schema: { type: 'object', example: { workspace: { ""id"": 79, ""name"": ""My workspace"", ""slug"": ""my-workspace-123"", ""createdAt"": ""2023-08-17 00:45:03"", ""openAiTemp"": null, ""lastUpdatedAt"": ""2023-08-17 00:45:03"", ""openAiHistory"": 20, ""openAiPrompt"": null, ""documents"": [] } } } } } } #swagger.responses[403] = { schema: { ""$ref"": ""#/definitions/InvalidAPIKey"" } } */ try { const { slug } = request.params; const workspace = await Workspace.get(`slug = ${escape(slug)}`); response.status(200).json({ workspace }); } catch (e) { console.log(e.message, e); response.sendStatus(500).end(); } }); app.delete( ""/v1/workspace/:slug"", [validApiKey], async (request, response) => { /* #swagger.tags = ['Workspaces'] #swagger.description = 'Deletes a workspace by its slug.' #swagger.path = '/v1/workspace/{slug}' #swagger.parameters['slug'] = { in: 'path', description: 'Unique slug of workspace to delete', required: true, type: 'string' } #swagger.responses[403] = { schema: { ""$ref"": ""#/definitions/InvalidAPIKey"" } } */ try { const { slug = """" } = request.params; const VectorDb = getVectorDbClass(); const workspace = await Workspace.get(`slug = ${escape(slug)}`); if (!workspace) { response.sendStatus(400).end(); return; } await Workspace.delete(`id = ${Number(workspace.id)}`); await DocumentVectors.deleteForWorkspace(workspace.id); await Document.delete(`workspaceId = ${Number(workspace.id)}`); await WorkspaceChats.delete(`workspaceId = ${Number(workspace.id)}`); try { await VectorDb[""delete-namespace""]({ namespace: slug }); } catch (e) { console.error(e.message); } response.sendStatus(200).end(); } catch (e) { console.log(e.message, e); response.sendStatus(500).end(); } } ); app.post( ""/v1/workspace/:slug/update"", [validApiKey], async (request, response) => { /* #swagger.tags = ['Workspaces'] #swagger.description = 'Update workspace settings by its unique slug.' #swagger.path = '/v1/workspace/{slug}/update' #swagger.parameters['slug'] = { in: 'path', description: 'Unique slug of workspace to find', required: true, type: 'string' } #swagger.requestBody = { description: 'JSON object containing new settings to update a workspace. All keys are optional and will not update unless provided', required: true, type: 'object', content: { ""application/json"": { example: { ""name"": 'Updated Workspace Name', ""openAiTemp"": 0.2, ""openAiHistory"": 20, ""openAiPrompt"": ""Respond to all inquires and questions in binary - do not respond in any other format."" } } } } #swagger.responses[200] = { content: { ""application/json"": { schema: { type: 'object', example: { workspace: { ""id"": 79, ""name"": ""My workspace"", ""slug"": ""my-workspace-123"", ""createdAt"": ""2023-08-17 00:45:03"", ""openAiTemp"": null, ""lastUpdatedAt"": ""2023-08-17 00:45:03"", ""openAiHistory"": 20, ""openAiPrompt"": null, ""documents"": [] }, message: null, } } } } } #swagger.responses[403] = { schema: { ""$ref"": ""#/definitions/InvalidAPIKey"" } } */ try { const { slug = null } = request.params; const data = reqBody(request); const currWorkspace = await Workspace.get(`slug = ${escape(slug)}`); if (!currWorkspace) { response.sendStatus(400).end(); return; } const { workspace, message } = await Workspace.update( currWorkspace.id, data ); response.status(200).json({ workspace, message }); } catch (e) { console.log(e.message, e); response.sendStatus(500).end(); } } ); app.get( ""/v1/workspace/:slug/chats"", [validApiKey], async (request, response) => { /* #swagger.tags = ['Workspaces'] #swagger.description = 'Get a workspaces chats regardless of user by its unique slug.' #swagger.path = '/v1/workspace/{slug}/chats' #swagger.parameters['slug'] = { in: 'path', description: 'Unique slug of workspace to find', required: true, type: 'string' } #swagger.responses[200] = { content: { ""application/json"": { schema: { type: 'object', example: { history: [ { ""role"": ""user"", ""content"": ""What is AnythingLLM?"", ""sentAt"": 1692851630 }, { ""role"": ""assistant"", ""content"": ""AnythingLLM is a platform that allows you to convert notes, PDFs, and other source materials into a chatbot. It ensures privacy, cites its answers, and allows multiple people to interact with the same documents simultaneously. It is particularly useful for businesses to enhance the visibility and readability of various written communications such as SOPs, contracts, and sales calls. You can try it out with a free trial to see if it meets your business needs."", ""sources"": [{""source"": ""object about source document and snippets used""}] } ] } } } } } #swagger.responses[403] = { schema: { ""$ref"": ""#/definitions/InvalidAPIKey"" } } */ try { const { slug } = request.params; const workspace = await Workspace.get(`slug = ${escape(slug)}`); if (!workspace) { response.sendStatus(400).end(); return; } const history = await WorkspaceChats.forWorkspace(workspace.id); response.status(200).json({ history: convertToChatHistory(history) }); } catch (e) { console.log(e.message, e); response.sendStatus(500).end(); } } ); app.post( ""/v1/workspace/:slug/update-embeddings"", [validApiKey], async (request, response) => { /* #swagger.tags = ['Workspaces'] #swagger.description = 'Add or remove documents from a workspace by its unique slug.' #swagger.path = '/v1/workspace/{slug}/update-embeddings' #swagger.parameters['slug'] = { in: 'path', description: 'Unique slug of workspace to find', required: true, type: 'string' } #swagger.requestBody = { description: 'JSON object of additions and removals of documents to add to update a workspace. The value should be the folder + filename with the exclusions of the top-level documents path.', required: true, type: 'object', content: { ""application/json"": { example: { adds: [], deletes: [""custom-documents/anythingllm-hash.json""] } } } } #swagger.responses[200] = { content: { ""application/json"": { schema: { type: 'object', example: { workspace: { ""id"": 79, ""name"": ""My workspace"", ""slug"": ""my-workspace-123"", ""createdAt"": ""2023-08-17 00:45:03"", ""openAiTemp"": null, ""lastUpdatedAt"": ""2023-08-17 00:45:03"", ""openAiHistory"": 20, ""openAiPrompt"": null, ""documents"": [] }, message: null, } } } } } #swagger.responses[403] = { schema: { ""$ref"": ""#/definitions/InvalidAPIKey"" } } */ try { const { slug = null } = request.params; const { adds = [], deletes = [] } = reqBody(request); const currWorkspace = await Workspace.get(`slug = ${escape(slug)}`); if (!currWorkspace) { response.sendStatus(400).end(); return; } await Document.removeDocuments(currWorkspace, deletes); await Document.addDocuments(currWorkspace, adds); const updatedWorkspace = await Workspace.get( `id = ${Number(currWorkspace.id)}` ); response.status(200).json({ workspace: updatedWorkspace }); } catch (e) { console.log(e.message, e); response.sendStatus(500).end(); } } ); }",patch SQL injection opportunities [LOW RISK] (#234),https://github.com/mintplex-labs/anything-llm/commit/dc3dfbf31495fe316b21ee184b9317b38101d30e,CVE-2023-4898,"['NVD-CWE-Other', 'CWE-305']",server/endpoints/api/workspace/index.js,3,js,False,2023-09-11T23:27:04Z "public static void assembleJigsawStructure( RegistryAccess dynamicRegistryManager, JigsawConfiguration jigsawConfig, ChunkGenerator chunkGenerator, StructureManager templateManager, BlockPos startPos, List components, Random random, boolean doBoundaryAdjustments, boolean useHeightmap, LevelHeightAccessor heightLimitView, ResourceLocation structureID, int maxY, int minY ) { // Get jigsaw pool registry WritableRegistry jigsawPoolRegistry = dynamicRegistryManager.ownedRegistryOrThrow(Registry.TEMPLATE_POOL_REGISTRY); // Get a random orientation for the starting piece Rotation rotation = Rotation.getRandom(random); // Get starting pool StructureTemplatePool startPool = jigsawConfig.startPool().get(); if(startPool.size() == 0){ RepurposedStructures.LOGGER.warn(""Repurposed Structures: Empty or nonexistent start pool: {} Crash is imminent"", startPool.getName()); } // Grab a random starting piece from the start pool. This is just the piece design itself, without rotation or position information. // Think of it as a blueprint. StructurePoolElement startPieceBlueprint = startPool.getRandomTemplate(random); // Instantiate a piece using the ""blueprint"" we just got. PoolElementStructurePiece startPiece = new PoolElementStructurePiece( templateManager, startPieceBlueprint, startPos, startPieceBlueprint.getGroundLevelDelta(), rotation, startPieceBlueprint.getBoundingBox(templateManager, startPos, rotation) ); // Store center position of starting piece's bounding box BoundingBox pieceBoundingBox = startPiece.getBoundingBox(); int pieceCenterX = (pieceBoundingBox.maxX() + pieceBoundingBox.minX()) / 2; int pieceCenterZ = (pieceBoundingBox.maxZ() + pieceBoundingBox.minZ()) / 2; int pieceCenterY = useHeightmap ? startPos.getY() + chunkGenerator.getFirstFreeHeight(pieceCenterX, pieceCenterZ, Heightmap.Types.WORLD_SURFACE_WG, heightLimitView) : startPos.getY(); int yAdjustment = pieceBoundingBox.minY() + startPiece.getGroundLevelDelta(); startPiece.move(0, pieceCenterY - yAdjustment, 0); Map requiredPieces = StructurePiecesBehavior.REQUIRED_PIECES_COUNT.get(structureID); boolean runOnce = requiredPieces == null; for(int attempts = 0; runOnce || doesNotHaveAllRequiredPieces(components, requiredPieces); attempts++){ if(attempts == 100){ RepurposedStructures.LOGGER.error( """""" ------------------------------------------------------------------- Repurposed Structures: Failed to create valid structure with all required pieces starting from this pool file: {}. Required pieces are: {} Make sure the max height and min height for this structure in the config is not too close together. If min and max height is super close together, the structure's pieces may not be able to fit in the narrow range and spawn. Otherwise, if the min and max height ranges aren't close and this message still appears, please report the issue to Repurposed Structures's dev with latest.log file! """""", startPool.getName(), Arrays.toString(requiredPieces.keySet().toArray())); break; } components.clear(); components.add(startPiece); // Add start piece to list of pieces if (jigsawConfig.maxDepth() > 0) { AABB axisAlignedBB = new AABB(pieceCenterX - 80, pieceCenterY - 120, pieceCenterZ - 80, pieceCenterX + 80 + 1, pieceCenterY + 180 + 1, pieceCenterZ + 80 + 1); BoxOctree boxOctree = new BoxOctree(axisAlignedBB); // The maximum boundary of the entire structure boxOctree.addBox(AABB.of(pieceBoundingBox)); Entry startPieceEntry = new Entry(startPiece, new MutableObject<>(boxOctree), pieceCenterY + 80, 0); Assembler assembler = new Assembler(jigsawPoolRegistry, jigsawConfig.maxDepth(), chunkGenerator, templateManager, components, random, requiredPieces, maxY, minY); assembler.availablePieces.addLast(startPieceEntry); while (!assembler.availablePieces.isEmpty()) { Entry entry = assembler.availablePieces.removeFirst(); assembler.generatePiece(entry.piece, entry.boxOctreeMutableObject, entry.topYLimit, entry.depth, doBoundaryAdjustments, heightLimitView); } } if(runOnce) break; } }","public static void assembleJigsawStructure( RegistryAccess dynamicRegistryManager, JigsawConfiguration jigsawConfig, ChunkGenerator chunkGenerator, StructureManager templateManager, BlockPos startPos, List components, Random random, boolean doBoundaryAdjustments, boolean useHeightmap, LevelHeightAccessor heightLimitView, ResourceLocation structureID, int maxY, int minY ) { // Get jigsaw pool registry WritableRegistry jigsawPoolRegistry = dynamicRegistryManager.ownedRegistryOrThrow(Registry.TEMPLATE_POOL_REGISTRY); // Get a random orientation for the starting piece Rotation rotation = Rotation.getRandom(random); // Get starting pool StructureTemplatePool startPool = jigsawConfig.startPool().get(); if(startPool == null || startPool.size() == 0){ RepurposedStructures.LOGGER.warn(""Repurposed Structures: Empty or nonexistent start pool: {} Crash is imminent"", startPool.getName()); } // Grab a random starting piece from the start pool. This is just the piece design itself, without rotation or position information. // Think of it as a blueprint. StructurePoolElement startPieceBlueprint = startPool.getRandomTemplate(random); // Instantiate a piece using the ""blueprint"" we just got. PoolElementStructurePiece startPiece = new PoolElementStructurePiece( templateManager, startPieceBlueprint, startPos, startPieceBlueprint.getGroundLevelDelta(), rotation, startPieceBlueprint.getBoundingBox(templateManager, startPos, rotation) ); // Store center position of starting piece's bounding box BoundingBox pieceBoundingBox = startPiece.getBoundingBox(); int pieceCenterX = (pieceBoundingBox.maxX() + pieceBoundingBox.minX()) / 2; int pieceCenterZ = (pieceBoundingBox.maxZ() + pieceBoundingBox.minZ()) / 2; int pieceCenterY = useHeightmap ? startPos.getY() + chunkGenerator.getFirstFreeHeight(pieceCenterX, pieceCenterZ, Heightmap.Types.WORLD_SURFACE_WG, heightLimitView) : startPos.getY(); int yAdjustment = pieceBoundingBox.minY() + startPiece.getGroundLevelDelta(); startPiece.move(0, pieceCenterY - yAdjustment, 0); Map requiredPieces = StructurePiecesBehavior.REQUIRED_PIECES_COUNT.get(structureID); boolean runOnce = requiredPieces == null; for(int attempts = 0; runOnce || doesNotHaveAllRequiredPieces(components, requiredPieces); attempts++){ if(attempts == 100){ RepurposedStructures.LOGGER.error( """""" ------------------------------------------------------------------- Repurposed Structures: Failed to create valid structure with all required pieces starting from this pool file: {}. Required pieces are: {} Make sure the max height and min height for this structure in the config is not too close together. If min and max height is super close together, the structure's pieces may not be able to fit in the narrow range and spawn. Otherwise, if the min and max height ranges aren't close and this message still appears, please report the issue to Repurposed Structures's dev with latest.log file! """""", startPool.getName(), Arrays.toString(requiredPieces.keySet().toArray())); break; } components.clear(); components.add(startPiece); // Add start piece to list of pieces if (jigsawConfig.maxDepth() > 0) { AABB axisAlignedBB = new AABB(pieceCenterX - 80, pieceCenterY - 120, pieceCenterZ - 80, pieceCenterX + 80 + 1, pieceCenterY + 180 + 1, pieceCenterZ + 80 + 1); BoxOctree boxOctree = new BoxOctree(axisAlignedBB); // The maximum boundary of the entire structure boxOctree.addBox(AABB.of(pieceBoundingBox)); Entry startPieceEntry = new Entry(startPiece, new MutableObject<>(boxOctree), pieceCenterY + 80, 0); Assembler assembler = new Assembler(jigsawPoolRegistry, jigsawConfig.maxDepth(), chunkGenerator, templateManager, components, random, requiredPieces, maxY, minY); assembler.availablePieces.addLast(startPieceEntry); while (!assembler.availablePieces.isEmpty()) { Entry entry = assembler.availablePieces.removeFirst(); assembler.generatePiece(entry.piece, entry.boxOctreeMutableObject, entry.topYLimit, entry.depth, doBoundaryAdjustments, heightLimitView); } } if(runOnce) break; } }",fixed null pool crashing jigsaw manager without logging,https://github.com/TelepathicGrunt/RepurposedStructures-Quilt/commit/16951828f84d84157262122a13c41dc1648a57b2,,,src/main/java/com/telepathicgrunt/repurposedstructures/world/structures/pieces/PieceLimitedJigsawManager.java,3,java,False,2021-10-17T14:12:16Z "LogEntryBuilder withAuthentication(Authentication authentication) { logEntry.with(PRINCIPAL_FIELD_NAME, authentication.getUser().principal()); logEntry.with(AUTHENTICATION_TYPE_FIELD_NAME, authentication.getAuthenticationType().toString()); if (authentication.isAuthenticatedWithApiKey()) { logEntry.with(API_KEY_ID_FIELD_NAME, (String) authentication.getMetadata().get(AuthenticationField.API_KEY_ID_KEY)); String apiKeyName = (String) authentication.getMetadata().get(AuthenticationField.API_KEY_NAME_KEY); if (apiKeyName != null) { logEntry.with(API_KEY_NAME_FIELD_NAME, apiKeyName); } String creatorRealmName = (String) authentication.getMetadata().get(AuthenticationField.API_KEY_CREATOR_REALM_NAME); if (creatorRealmName != null) { // can be null for API keys created before version 7.7 logEntry.with(PRINCIPAL_REALM_FIELD_NAME, creatorRealmName); } } else { if (authentication.getUser().isRunAs()) { logEntry.with(PRINCIPAL_REALM_FIELD_NAME, authentication.getLookedUpBy().getName()) .with(PRINCIPAL_RUN_BY_FIELD_NAME, authentication.getUser().authenticatedUser().principal()) .with(PRINCIPAL_RUN_BY_REALM_FIELD_NAME, authentication.getAuthenticatedBy().getName()); } else { logEntry.with(PRINCIPAL_REALM_FIELD_NAME, authentication.getAuthenticatedBy().getName()); } } if (authentication.isAuthenticatedWithServiceAccount()) { logEntry.with(SERVICE_TOKEN_NAME_FIELD_NAME, (String) authentication.getMetadata().get(TOKEN_NAME_FIELD)) .with( SERVICE_TOKEN_TYPE_FIELD_NAME, ServiceAccountSettings.REALM_TYPE + ""_"" + authentication.getMetadata().get(TOKEN_SOURCE_FIELD) ); } return this; }","LogEntryBuilder withAuthentication(Authentication authentication) { logEntry.with(PRINCIPAL_FIELD_NAME, authentication.getUser().principal()); logEntry.with(AUTHENTICATION_TYPE_FIELD_NAME, authentication.getAuthenticationType().toString()); if (authentication.isApiKey()) { logEntry.with(API_KEY_ID_FIELD_NAME, (String) authentication.getMetadata().get(AuthenticationField.API_KEY_ID_KEY)); String apiKeyName = (String) authentication.getMetadata().get(AuthenticationField.API_KEY_NAME_KEY); if (apiKeyName != null) { logEntry.with(API_KEY_NAME_FIELD_NAME, apiKeyName); } final String creatorRealmName = ApiKeyService.getCreatorRealmName(authentication); if (creatorRealmName != null) { // can be null for API keys created before version 7.7 logEntry.with(PRINCIPAL_REALM_FIELD_NAME, creatorRealmName); } } else { if (authentication.getUser().isRunAs()) { logEntry.with(PRINCIPAL_REALM_FIELD_NAME, authentication.getLookedUpBy().getName()) .with(PRINCIPAL_RUN_BY_FIELD_NAME, authentication.getUser().authenticatedUser().principal()) // API key can run-as, when that happens, the following field will be _es_api_key, // not the API key owner user's realm. .with(PRINCIPAL_RUN_BY_REALM_FIELD_NAME, authentication.getAuthenticatedBy().getName()); // TODO: API key can run-as which means we could use extra fields (#84394) } else { logEntry.with(PRINCIPAL_REALM_FIELD_NAME, authentication.getAuthenticatedBy().getName()); } } // TODO: service token info is logged in a separate authentication field (#84394) if (authentication.isAuthenticatedWithServiceAccount()) { logEntry.with(SERVICE_TOKEN_NAME_FIELD_NAME, (String) authentication.getMetadata().get(TOKEN_NAME_FIELD)) .with( SERVICE_TOKEN_TYPE_FIELD_NAME, ServiceAccountSettings.REALM_TYPE + ""_"" + authentication.getMetadata().get(TOKEN_SOURCE_FIELD) ); } return this; }","Fix owner user realm check for API key authentication (#84325) API Key can run-as since #79809. There are places in the code where we assume API key cannot run-as. Most of them are corrected in #81564. But there are still a few things got missed. This PR fixes the methods for checking owner user realm for API key. This means, when API Keys ""running-as"" (impersonating other users), we do not expose the authenticating key ID and name to the end-user such as the Authenticate API and the SetSecurityUseringest processor. Only the effective user is revealed, just like in the regular case of a realm user run as. For audit logging, the key's ID and name are not exposed either. But this is mainly because there are no existing fields suitable for these information. We do intend to add them later (#84394) because auditing logging is to consumed by system admin instead of end-users. Note the resource sharing check (canAccessResourcesOf) also needs to be fixed, this will be handled by #84277",https://github.com/elastic/elasticsearch/commit/ba958e2f2d0fe9c7028ead46496593c5eb3033a6,,,x-pack/plugin/security/src/main/java/org/elasticsearch/xpack/security/audit/logfile/LoggingAuditTrail.java,3,java,False,2022-02-28T01:39:26Z "@GuardedBy(""mSessions"") private void readSessionsLocked() { if (LOGD) Slog.v(TAG, ""readSessionsLocked()""); mSessions.clear(); FileInputStream fis = null; try { fis = mSessionsFile.openRead(); final TypedXmlPullParser in = Xml.resolvePullParser(fis); int type; while ((type = in.next()) != END_DOCUMENT) { if (type == START_TAG) { final String tag = in.getName(); if (PackageInstallerSession.TAG_SESSION.equals(tag)) { final PackageInstallerSession session; try { session = PackageInstallerSession.readFromXml(in, mInternalCallback, mContext, mPm, mInstallThread.getLooper(), mStagingManager, mSessionsDir, this); } catch (Exception e) { Slog.e(TAG, ""Could not read session"", e); continue; } final long age = System.currentTimeMillis() - session.createdMillis; final long timeSinceUpdate = System.currentTimeMillis() - session.getUpdatedMillis(); final boolean valid; if (session.isStaged()) { if (timeSinceUpdate >= MAX_TIME_SINCE_UPDATE_MILLIS && session.isStagedAndInTerminalState()) { valid = false; } else { valid = true; } } else if (age >= MAX_AGE_MILLIS) { Slog.w(TAG, ""Abandoning old session created at "" + session.createdMillis); valid = false; } else { valid = true; } if (valid) { mSessions.put(session.sessionId, session); } else { // Since this is early during boot we don't send // any observer events about the session, but we // keep details around for dumpsys. addHistoricalSessionLocked(session); } mAllocatedSessions.put(session.sessionId, true); } } } } catch (FileNotFoundException e) { // Missing sessions are okay, probably first boot } catch (IOException | XmlPullParserException e) { Slog.wtf(TAG, ""Failed reading install sessions"", e); } finally { IoUtils.closeQuietly(fis); } // After reboot housekeeping. for (int i = 0; i < mSessions.size(); ++i) { PackageInstallerSession session = mSessions.valueAt(i); session.onAfterSessionRead(mSessions); } }","@GuardedBy(""mSessions"") private void readSessionsLocked() { if (LOGD) Slog.v(TAG, ""readSessionsLocked()""); mSessions.clear(); FileInputStream fis = null; try { fis = mSessionsFile.openRead(); final TypedXmlPullParser in = Xml.resolvePullParser(fis); int type; while ((type = in.next()) != END_DOCUMENT) { if (type == START_TAG) { final String tag = in.getName(); if (PackageInstallerSession.TAG_SESSION.equals(tag)) { final PackageInstallerSession session; try { session = PackageInstallerSession.readFromXml(in, mInternalCallback, mContext, mPm, mInstallThread.getLooper(), mStagingManager, mSessionsDir, this, mSilentUpdatePolicy); } catch (Exception e) { Slog.e(TAG, ""Could not read session"", e); continue; } final long age = System.currentTimeMillis() - session.createdMillis; final long timeSinceUpdate = System.currentTimeMillis() - session.getUpdatedMillis(); final boolean valid; if (session.isStaged()) { if (timeSinceUpdate >= MAX_TIME_SINCE_UPDATE_MILLIS && session.isStagedAndInTerminalState()) { valid = false; } else { valid = true; } } else if (age >= MAX_AGE_MILLIS) { Slog.w(TAG, ""Abandoning old session created at "" + session.createdMillis); valid = false; } else { valid = true; } if (valid) { mSessions.put(session.sessionId, session); } else { // Since this is early during boot we don't send // any observer events about the session, but we // keep details around for dumpsys. addHistoricalSessionLocked(session); } mAllocatedSessions.put(session.sessionId, true); } } } } catch (FileNotFoundException e) { // Missing sessions are okay, probably first boot } catch (IOException | XmlPullParserException e) { Slog.wtf(TAG, ""Failed reading install sessions"", e); } finally { IoUtils.closeQuietly(fis); } // After reboot housekeeping. for (int i = 0; i < mSessions.size(); ++i) { PackageInstallerSession session = mSessions.valueAt(i); session.onAfterSessionRead(mSessions); } }","Throttle the repeated silent installation requests To avoid a non-system installer repeatedly silent updates and 'denial-of-service' against another app on the device. This CL tracks for all the silent updated installs where the `requireUserAction' is not required. And fall back to user action required if a repeated silent update is requested within the throttle time. Bug: 185878964 Test: atest SilentUpdateHostsideTests Test: atest StagingManagerTest Test: atest PackageInstallerSessionTest Change-Id: I4ea287bf66d8661eec2676b604f9109f6f9add28 Merged-In: I4ea287bf66d8661eec2676b604f9109f6f9add28",https://github.com/PixelExperience/frameworks_base/commit/ec065a8333fff9f39d697877bee2663e39cbdb1f,,,services/core/java/com/android/server/pm/PackageInstallerService.java,3,java,False,2021-05-07T13:32:23Z "@Override protected void initChannel(Channel ch) throws Exception { ch.pipeline() .addLast(READ_TIMEOUT, new ReadTimeoutHandler(server.getConfiguration().getReadTimeout(), TimeUnit.MILLISECONDS)) .addLast(FRAME_DECODER, new MinecraftVarintFrameDecoder()) .addLast(FRAME_ENCODER, MinecraftVarintLengthEncoder.INSTANCE) .addLast(MINECRAFT_DECODER, new MinecraftDecoder(ProtocolUtils.Direction.CLIENTBOUND)) .addLast(MINECRAFT_ENCODER, new MinecraftEncoder(ProtocolUtils.Direction.SERVERBOUND)); ch.pipeline().addLast(HANDLER, new MinecraftConnection(ch, server)); }","@Override protected void initChannel(Channel ch) throws Exception { ch.pipeline() .addLast(FRAME_DECODER, new MinecraftVarintFrameDecoder()) .addLast(READ_TIMEOUT, new ReadTimeoutHandler(server.getConfiguration().getReadTimeout(), TimeUnit.MILLISECONDS)) .addLast(FRAME_ENCODER, MinecraftVarintLengthEncoder.INSTANCE) .addLast(MINECRAFT_DECODER, new MinecraftDecoder(ProtocolUtils.Direction.CLIENTBOUND)) .addLast(MINECRAFT_ENCODER, new MinecraftEncoder(ProtocolUtils.Direction.SERVERBOUND)); ch.pipeline().addLast(HANDLER, new MinecraftConnection(ch, server)); }","Move timeout handler to after frame decoder Mitigates attacks like the one described in SpigotMC/BungeeCord#3066. This cannot be considered a full protection, only a mitigation that expects full packets. The attack described is essentially the infamous Slowloris attack.",https://github.com/PaperMC/Velocity/commit/f1cb3eb1a28bc5003d8dd844b5cdf990970ab89d,,,proxy/src/main/java/com/velocitypowered/proxy/server/VelocityRegisteredServer.java,3,java,False,2021-04-16T02:56:37Z "private static boolean isChangeEnabled(String changeName, long changeId) { boolean enabled = Compatibility.isChangeEnabled(changeId); // Compatibility changes aren't available in the system process, but this should never be // enabled for it. if (Process.myUid() == Process.SYSTEM_UID) { enabled = false; } logEnabled(changeName, enabled); return enabled; }","private static boolean isChangeEnabled(String changeName, long changeId) { boolean enabled = Compatibility.isChangeEnabled(changeId); // Compatibility changes aren't available in the system process, but this should never be // enabled for it or other core ""android"" system processes (such as the android:ui process // used for chooser and resolver activities). if (UserHandle.getAppId(Process.myUid()) == Process.SYSTEM_UID) { enabled = false; } logEnabled(changeName, enabled); return enabled; }","gmscompat: Fix detection of system processes in secondary users The chooser and resolver activities run as a special system UI process belonging to the core ""android"" package, separate from both system_server and com.android.systemui. This process, named ""android:ui"", runs separately under each user with the special app ID 1000 (SYSTEM_UID). Check the app ID instead of the UID to fix detection of SYSTEM_UID processes in secondary users. This fixes the following crash: FATAL EXCEPTION: AsyncTask #2 Process: system:ui, PID: 8982 java.lang.RuntimeException: An error occurred while executing doInBackground() at android.os.AsyncTask$4.done(AsyncTask.java:415) at java.util.concurrent.FutureTask.finishCompletion(FutureTask.java:383) at java.util.concurrent.FutureTask.setException(FutureTask.java:252) at java.util.concurrent.FutureTask.run(FutureTask.java:271) at android.os.AsyncTask$SerialExecutor$1.run(AsyncTask.java:305) at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1167) at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:641) at java.lang.Thread.run(Thread.java:923) Caused by: java.lang.RuntimeException: No data directory found for package android at android.app.ContextImpl.getDataDir(ContextImpl.java:2560) at com.android.internal.gmscompat.dynamite.client.DynamiteContext.(DynamiteContext.java:58) at com.android.internal.gmscompat.dynamite.GmsDynamiteHooks.getClientContext(GmsDynamiteHooks.java:64) at com.android.internal.gmscompat.dynamite.GmsDynamiteHooks.loadAssetsFromPath(GmsDynamiteHooks.java:93) at android.content.res.ApkAssets.loadFromPath(ApkAssets.java:143) at android.app.ResourcesManager.loadApkAssets(ResourcesManager.java:374) at android.app.ResourcesManager.access$000(ResourcesManager.java:67) at android.app.ResourcesManager$ApkAssetsSupplier.load(ResourcesManager.java:146) at android.app.ResourcesManager.createApkAssetsSupplierNotLocked(ResourcesManager.java:833) at android.app.ResourcesManager.getResources(ResourcesManager.java:937) at android.app.ActivityThread.getTopLevelResources(ActivityThread.java:2226) at android.app.ApplicationPackageManager.getResourcesForApplication(ApplicationPackageManager.java:1682) at com.android.internal.app.ResolverListAdapter$TargetPresentationGetter.getIconBitmap(ResolverListAdapter.java:920) at com.android.internal.app.ResolverListAdapter$ActivityInfoPresentationGetter.getIconBitmap(ResolverListAdapter.java:843) at com.android.internal.app.ResolverListAdapter$TargetPresentationGetter.getIcon(ResolverListAdapter.java:908) at com.android.internal.app.ResolverListAdapter$ActivityInfoPresentationGetter.getIcon(ResolverListAdapter.java:843) at com.android.internal.app.ResolverListAdapter.loadIconForResolveInfo(ResolverListAdapter.java:599) at com.android.internal.app.ResolverListAdapter$LoadIconTask.doInBackground(ResolverListAdapter.java:782) at com.android.internal.app.ResolverListAdapter$LoadIconTask.doInBackground(ResolverListAdapter.java:769) at android.os.AsyncTask$3.call(AsyncTask.java:394) at java.util.concurrent.FutureTask.run(FutureTask.java:266) ... 4 more Change-Id: I928db502d2cc24e50ed2798575e0e8a37475cd97",https://github.com/GrapheneOS/platform_frameworks_base/commit/439e7de8d256a0bf96b4f540f845c70dc2d2abde,,,core/java/android/app/compat/gms/GmsCompat.java,3,java,False,2021-08-18T03:54:15Z "private @Nullable RestrictionBypass verifyAndGetBypass(int uid, String packageName, @Nullable String attributionTag, @Nullable String proxyPackageName) { if (uid == Process.ROOT_UID) { // For backwards compatibility, don't check package name for root UID. return null; } // Do not check if uid/packageName/attributionTag is already known synchronized (this) { UidState uidState = mUidStates.get(uid); if (uidState != null && uidState.pkgOps != null) { Ops ops = uidState.pkgOps.get(packageName); if (ops != null && (attributionTag == null || ops.knownAttributionTags.contains( attributionTag)) && ops.bypass != null) { return ops.bypass; } } } int callingUid = Binder.getCallingUid(); int userId = UserHandle.getUserId(uid); RestrictionBypass bypass = null; // Allow any attribution tag for resolvable uids int pkgUid = resolveUid(packageName); if (pkgUid != Process.INVALID_UID) { // Special case for the shell which is a package but should be able // to bypass app attribution tag restrictions. if (pkgUid != UserHandle.getAppId(uid)) { throw new SecurityException(""Specified package "" + packageName + "" under uid "" + UserHandle.getAppId(uid) + "" but it is really "" + pkgUid); } return RestrictionBypass.UNRESTRICTED; } final long ident = Binder.clearCallingIdentity(); try { boolean isAttributionTagValid = false; PackageManagerInternal pmInt = LocalServices.getService(PackageManagerInternal.class); AndroidPackage pkg = pmInt.getPackage(packageName); if (pkg != null) { isAttributionTagValid = isAttributionInPackage(pkg, attributionTag); pkgUid = UserHandle.getUid(userId, UserHandle.getAppId(pkg.getUid())); bypass = getBypassforPackage(pkg); } if (!isAttributionTagValid) { AndroidPackage proxyPkg = proxyPackageName != null ? pmInt.getPackage(proxyPackageName) : null; boolean foundInProxy = isAttributionInPackage(proxyPkg, attributionTag); String msg; if (pkg != null && foundInProxy) { msg = ""attributionTag "" + attributionTag + "" declared in manifest of the proxy"" + "" package "" + proxyPackageName + "", this is not advised""; } else if (pkg != null) { msg = ""attributionTag "" + attributionTag + "" not declared in manifest of "" + packageName; } else { msg = ""package "" + packageName + "" not found, can't check for "" + ""attributionTag "" + attributionTag; } try { if (mPlatformCompat.isChangeEnabledByPackageName( SECURITY_EXCEPTION_ON_INVALID_ATTRIBUTION_TAG_CHANGE, packageName, userId) && mPlatformCompat.isChangeEnabledByUid( SECURITY_EXCEPTION_ON_INVALID_ATTRIBUTION_TAG_CHANGE, callingUid) && !foundInProxy) { throw new SecurityException(msg); } else { Slog.e(TAG, msg); } } catch (RemoteException neverHappens) { } } } finally { Binder.restoreCallingIdentity(ident); } if (pkgUid != uid) { throw new SecurityException(""Specified package "" + packageName + "" under uid "" + uid + "" but it is really "" + pkgUid); } return bypass; }","private @Nullable RestrictionBypass verifyAndGetBypass(int uid, String packageName, @Nullable String attributionTag, @Nullable String proxyPackageName) { if (uid == Process.ROOT_UID) { // For backwards compatibility, don't check package name for root UID. return null; } // Do not check if uid/packageName/attributionTag is already known synchronized (this) { UidState uidState = mUidStates.get(uid); if (uidState != null && uidState.pkgOps != null) { Ops ops = uidState.pkgOps.get(packageName); if (ops != null && (attributionTag == null || ops.knownAttributionTags.contains( attributionTag)) && ops.bypass != null) { return ops.bypass; } } } int callingUid = Binder.getCallingUid(); int userId = UserHandle.getUserId(uid); RestrictionBypass bypass = null; // Allow any attribution tag for resolvable uids int pkgUid = resolveUid(packageName); if (pkgUid != Process.INVALID_UID) { // Special case for the shell which is a package but should be able // to bypass app attribution tag restrictions. if (pkgUid != UserHandle.getAppId(uid)) { throw new SecurityException(""Specified package "" + packageName + "" under uid "" + UserHandle.getAppId(uid) + "" but it is really "" + pkgUid); } return RestrictionBypass.UNRESTRICTED; } final long ident = Binder.clearCallingIdentity(); try { boolean isAttributionTagValid = false; PackageManagerInternal pmInt = LocalServices.getService(PackageManagerInternal.class); AndroidPackage pkg = pmInt.getPackage(packageName); if (pkg != null) { isAttributionTagValid = isAttributionInPackage(pkg, attributionTag); pkgUid = UserHandle.getUid(userId, UserHandle.getAppId(pkg.getUid())); bypass = getBypassforPackage(pkg); } if (!isAttributionTagValid) { AndroidPackage proxyPkg = proxyPackageName != null ? pmInt.getPackage(proxyPackageName) : null; boolean foundInProxy = isAttributionInPackage(proxyPkg, attributionTag); String msg; if (pkg != null && foundInProxy) { msg = ""attributionTag "" + attributionTag + "" declared in manifest of the proxy"" + "" package "" + proxyPackageName + "", this is not advised""; } else if (pkg != null) { msg = ""attributionTag "" + attributionTag + "" not declared in manifest of "" + packageName; bypass.setIsAttributionTagNotFound(true); } else { msg = ""package "" + packageName + "" not found, can't check for "" + ""attributionTag "" + attributionTag; } try { if (mPlatformCompat.isChangeEnabledByPackageName( SECURITY_EXCEPTION_ON_INVALID_ATTRIBUTION_TAG_CHANGE, packageName, userId) && mPlatformCompat.isChangeEnabledByUid( SECURITY_EXCEPTION_ON_INVALID_ATTRIBUTION_TAG_CHANGE, callingUid) && !foundInProxy) { Slog.e(TAG, msg); } else { Slog.e(TAG, msg); } } catch (RemoteException neverHappens) { } } } finally { Binder.restoreCallingIdentity(ident); } if (pkgUid != uid) { throw new SecurityException(""Specified package "" + packageName + "" under uid "" + uid + "" but it is really "" + pkgUid); } return bypass; }","Avoid a SecurityExcetion crash 1. Instead of throwing SecurityException, log the error. 2. Set isAttributionTagNotFound to true when the attributionTag is not null but not found in the package attributions. Fix: 188549667 Test: N/A Change-Id: I75a217893353ee5fe5d191e2b78ccf391847adb6",https://github.com/PixelExperience/frameworks_base/commit/b8488603d6932262e652b740cbf75b9d580caffb,,,services/core/java/com/android/server/appop/AppOpsService.java,3,java,False,2021-05-18T18:12:40Z "@Override public void mouseClicked(int mouseX, int mouseY, int mouseButton) throws IOException { ScaledResolution res = new ScaledResolution(McIf.mc()); int posX = ((res.getScaledWidth() / 2) - mouseX); int posY = ((res.getScaledHeight() / 2) - mouseY); super.mouseClicked(mouseX, mouseY, mouseButton); if (selectedEntry != null && search.get(currentPage - 1).size() > selected) { handleEntryClick(selectedEntry, mouseButton); } checkForwardAndBackButtons(posX, posY); }","@Override public void mouseClicked(int mouseX, int mouseY, int mouseButton) throws IOException { ScaledResolution res = new ScaledResolution(McIf.mc()); int posX = ((res.getScaledWidth() / 2) - mouseX); int posY = ((res.getScaledHeight() / 2) - mouseY); super.mouseClicked(mouseX, mouseY, mouseButton); if (selectedEntry != null && search.size() >= currentPage && search.get(currentPage - 1).size() > selected) { handleEntryClick(selectedEntry, mouseButton); } checkForwardAndBackButtons(posX, posY); }","Fix 14 issues found in ticket backlog (#502) * Fix IndexOutOfBoundsException in QuestBookListPage Signed-off-by: kristofbolyai * Fix crash if OverlayConfig.GameUpdate.INSTANCE.messageMaxLength is 1 Signed-off-by: kristofbolyai * Fix crash related to deleting chat tabs and ChatGUI not updating Signed-off-by: kristofbolyai * Fix crash related to deleting chat tabs and ChatGUI not updating Signed-off-by: kristofbolyai * Fix translation cache becoming null Signed-off-by: kristofbolyai * Fix objective parsing if player is in party Signed-off-by: kristofbolyai * Fix guild objective not being removed upon completion Signed-off-by: kristofbolyai * Fix race condition in ServerEvents Signed-off-by: kristofbolyai * Fix race condition in ClientEvents Signed-off-by: kristofbolyai * Fix NPE in ServerEvents Signed-off-by: kristofbolyai * Fix AreaDPS value not being correct Signed-off-by: kristofbolyai * Fix NPE in fix :) Signed-off-by: kristofbolyai * Fix quest dialogue spoofing Signed-off-by: kristofbolyai * Fix Keyholder related crash Signed-off-by: kristofbolyai * Fix totem tracking Signed-off-by: kristofbolyai * Dialogue Page gets updated correctly Signed-off-by: kristofbolyai * Register ChatGUI correctly Signed-off-by: kristofbolyai * Use MC's GameSettings to check for isKeyDown Signed-off-by: kristofbolyai * Make multi line if have braces Signed-off-by: kristofbolyai ",https://github.com/Wynntils/Wynntils/commit/c8f6effe187ff68f17bcff809d2bc440ec07128d,,,src/main/java/com/wynntils/modules/questbook/instances/QuestBookListPage.java,3,java,False,2022-04-15T17:16:00Z "constructor(setup) { const { networking, cbor } = setup; const config = new Config({ setup }); this._config = config; const crypto = new Crypto({ config }); // LEGACY const { cryptography } = setup; networking.init(config); const tokenManager = new TokenManager(config, cbor); this._tokenManager = tokenManager; const telemetryManager = new TelemetryManager({ maximumSamplesCount: 60000, }); this._telemetryManager = telemetryManager; const modules = { config, networking, crypto, cryptography, tokenManager, telemetryManager, PubNubFile: setup.PubNubFile, }; this.File = setup.PubNubFile; this.encryptFile = (key, file) => cryptography.encryptFile(key, file, this.File); this.decryptFile = (key, file) => cryptography.decryptFile(key, file, this.File); const timeEndpoint = endpointCreator.bind(this, modules, timeEndpointConfig); const leaveEndpoint = endpointCreator.bind(this, modules, presenceLeaveEndpointConfig); const heartbeatEndpoint = endpointCreator.bind(this, modules, presenceHeartbeatEndpointConfig); const setStateEndpoint = endpointCreator.bind(this, modules, presenceSetStateConfig); const subscribeEndpoint = endpointCreator.bind(this, modules, subscribeEndpointConfig); // managers const listenerManager = new ListenerManager(); this._listenerManager = listenerManager; this.iAmHere = endpointCreator.bind(this, modules, presenceHeartbeatEndpointConfig); this.iAmAway = endpointCreator.bind(this, modules, presenceLeaveEndpointConfig); this.setPresenceState = endpointCreator.bind(this, modules, presenceSetStateConfig); this.handshake = endpointCreator.bind(this, modules, handshakeEndpointConfig); this.receiveMessages = endpointCreator.bind(this, modules, receiveMessagesConfig); if (config.enableSubscribeBeta === true) { const eventEngine = new EventEngine({ handshake: this.handshake, receiveEvents: this.receiveMessages }); this.subscribe = eventEngine.subscribe.bind(eventEngine); this.unsubscribe = eventEngine.unsubscribe.bind(eventEngine); this.eventEngine = eventEngine; } else { const subscriptionManager = new SubscriptionManager({ timeEndpoint, leaveEndpoint, heartbeatEndpoint, setStateEndpoint, subscribeEndpoint, crypto: modules.crypto, config: modules.config, listenerManager, getFileUrl: (params) => getFileUrlFunction(modules, params), }); this.subscribe = subscriptionManager.adaptSubscribeChange.bind(subscriptionManager); this.unsubscribe = subscriptionManager.adaptUnsubscribeChange.bind(subscriptionManager); this.disconnect = subscriptionManager.disconnect.bind(subscriptionManager); this.reconnect = subscriptionManager.reconnect.bind(subscriptionManager); this.unsubscribeAll = subscriptionManager.unsubscribeAll.bind(subscriptionManager); this.getSubscribedChannels = subscriptionManager.getSubscribedChannels.bind(subscriptionManager); this.getSubscribedChannelGroups = subscriptionManager.getSubscribedChannelGroups.bind(subscriptionManager); this.setState = subscriptionManager.adaptStateChange.bind(subscriptionManager); this.presence = subscriptionManager.adaptPresenceChange.bind(subscriptionManager); this.destroy = (isOffline) => { subscriptionManager.unsubscribeAll(isOffline); subscriptionManager.disconnect(); }; } this.addListener = listenerManager.addListener.bind(listenerManager); this.removeListener = listenerManager.removeListener.bind(listenerManager); this.removeAllListeners = listenerManager.removeAllListeners.bind(listenerManager); this.parseToken = tokenManager.parseToken.bind(tokenManager); this.setToken = tokenManager.setToken.bind(tokenManager); this.getToken = tokenManager.getToken.bind(tokenManager); /* channel groups */ this.channelGroups = { listGroups: endpointCreator.bind(this, modules, listChannelGroupsConfig), listChannels: endpointCreator.bind(this, modules, listChannelsInChannelGroupConfig), addChannels: endpointCreator.bind(this, modules, addChannelsChannelGroupConfig), removeChannels: endpointCreator.bind(this, modules, removeChannelsChannelGroupConfig), deleteGroup: endpointCreator.bind(this, modules, deleteChannelGroupConfig), }; /* push */ this.push = { addChannels: endpointCreator.bind(this, modules, addPushChannelsConfig), removeChannels: endpointCreator.bind(this, modules, removePushChannelsConfig), deleteDevice: endpointCreator.bind(this, modules, removeDevicePushConfig), listChannels: endpointCreator.bind(this, modules, listPushChannelsConfig), }; /* presence */ this.hereNow = endpointCreator.bind(this, modules, presenceHereNowConfig); this.whereNow = endpointCreator.bind(this, modules, presenceWhereNowEndpointConfig); this.getState = endpointCreator.bind(this, modules, presenceGetStateConfig); /* PAM */ this.grant = endpointCreator.bind(this, modules, grantEndpointConfig); this.grantToken = endpointCreator.bind(this, modules, grantTokenEndpointConfig); this.audit = endpointCreator.bind(this, modules, auditEndpointConfig); this.revokeToken = endpointCreator.bind(this, modules, revokeTokenEndpointConfig); this.publish = endpointCreator.bind(this, modules, publishEndpointConfig); this.fire = (args, callback) => { args.replicate = false; args.storeInHistory = false; return this.publish(args, callback); }; this.signal = endpointCreator.bind(this, modules, signalEndpointConfig); this.history = endpointCreator.bind(this, modules, historyEndpointConfig); this.deleteMessages = endpointCreator.bind(this, modules, deleteMessagesEndpointConfig); this.messageCounts = endpointCreator.bind(this, modules, messageCountsEndpointConfig); this.fetchMessages = endpointCreator.bind(this, modules, fetchMessagesEndpointConfig); // Actions API this.addMessageAction = endpointCreator.bind(this, modules, addMessageActionEndpointConfig); this.removeMessageAction = endpointCreator.bind(this, modules, removeMessageActionEndpointConfig); this.getMessageActions = endpointCreator.bind(this, modules, getMessageActionEndpointConfig); // File Upload API v1 this.listFiles = endpointCreator.bind(this, modules, listFilesEndpointConfig); const generateUploadUrl = endpointCreator.bind(this, modules, generateUploadUrlEndpointConfig); this.publishFile = endpointCreator.bind(this, modules, publishFileEndpointConfig); this.sendFile = sendFileFunction({ generateUploadUrl, publishFile: this.publishFile, modules, }); this.getFileUrl = (params) => getFileUrlFunction(modules, params); this.downloadFile = endpointCreator.bind(this, modules, downloadFileEndpointConfig); this.deleteFile = endpointCreator.bind(this, modules, deleteFileEndpointConfig); // Objects API v2 this.objects = { getAllUUIDMetadata: endpointCreator.bind(this, modules, getAllUUIDMetadataEndpointConfig), getUUIDMetadata: endpointCreator.bind(this, modules, getUUIDMetadataEndpointConfig), setUUIDMetadata: endpointCreator.bind(this, modules, setUUIDMetadataEndpointConfig), removeUUIDMetadata: endpointCreator.bind(this, modules, removeUUIDMetadataEndpointConfig), getAllChannelMetadata: endpointCreator.bind(this, modules, getAllChannelMetadataEndpointConfig), getChannelMetadata: endpointCreator.bind(this, modules, getChannelMetadataEndpointConfig), setChannelMetadata: endpointCreator.bind(this, modules, setChannelMetadataEndpointConfig), removeChannelMetadata: endpointCreator.bind(this, modules, removeChannelMetadataEndpointConfig), getChannelMembers: endpointCreator.bind(this, modules, getMembersV2EndpointConfig), setChannelMembers: (parameters, ...rest) => endpointCreator.call( this, modules, setMembersV2EndpointConfig, { type: 'set', ...parameters, }, ...rest, ), removeChannelMembers: (parameters, ...rest) => endpointCreator.call( this, modules, setMembersV2EndpointConfig, { type: 'delete', ...parameters, }, ...rest, ), getMemberships: endpointCreator.bind(this, modules, getMembershipsV2EndpointConfig), setMemberships: (parameters, ...rest) => endpointCreator.call( this, modules, setMembershipsV2EndpointConfig, { type: 'set', ...parameters, }, ...rest, ), removeMemberships: (parameters, ...rest) => endpointCreator.call( this, modules, setMembershipsV2EndpointConfig, { type: 'delete', ...parameters, }, ...rest, ), }; // User Apis this.createUser = (args) => this.objects.setUUIDMetadata({ uuid: args.userId, data: args.data, include: args.include, }); this.updateUser = this.createUser; this.removeUser = (args) => this.objects.removeUUIDMetadata({ uuid: args?.userId, }); this.fetchUser = (args) => this.objects.getUUIDMetadata({ uuid: args?.userId, include: args?.include, }); this.fetchUsers = this.objects.getAllUUIDMetadata; // Space apis this.createSpace = (args) => this.objects.setChannelMetadata({ channel: args.spaceId, data: args.data, include: args.include, }); this.updateSpace = this.createSpace; this.removeSpace = (args) => this.objects.removeChannelMetadata({ channel: args.spaceId, }); this.fetchSpace = (args) => this.objects.getChannelMetadata({ channel: args.spaceId, include: args.include, }); this.fetchSpaces = this.objects.getAllChannelMetadata; // Membership apis this.addMemberships = (parameters) => { if (typeof parameters.spaceId === 'string') { return this.objects.setChannelMembers({ channel: parameters.spaceId, uuids: parameters.users?.map((user) => { if (typeof user === 'string') { return user; } return { id: user.userId, custom: user.custom, status: user.status, }; }), limit: 0, }); } else { return this.objects.setMemberships({ uuid: parameters.userId, channels: parameters.spaces?.map((space) => { if (typeof space === 'string') { return space; } return { id: space.spaceId, custom: space.custom, status: space.status, }; }), limit: 0, }); } }; this.updateMemberships = this.addMemberships; this.removeMemberships = (parameters) => { if (typeof parameters.spaceId === 'string') { return this.objects.removeChannelMembers({ channel: parameters.spaceId, uuids: parameters.userIds, limit: 0, }); } else { return this.objects.removeMemberships({ uuid: parameters.userId, channels: parameters.spaceIds, limit: 0, }); } }; this.fetchMemberships = (params) => { if (typeof params.spaceId === 'string') { return this.objects .getChannelMembers({ channel: params.spaceId, filter: params.filter, limit: params.limit, page: params.page, include: { customFields: params.include.customFields, UUIDFields: params.include.userFields, customUUIDFields: params.include.customUserFields, totalCount: params.include.totalCount, }, sort: params.sort != null ? Object.fromEntries(Object.entries(params.sort).map(([k, v]) => [k.replace('user', 'uuid'), v])) : null, }) .then((res) => { res.data = res.data?.map((m) => { return { user: m.uuid, custom: m.custom, updated: m.updated, eTag: m.eTag, }; }); return res; }); } else { return this.objects .getMemberships({ uuid: params.userId, filter: params.filter, limit: params.limit, page: params.page, include: { customFields: params.include.customFields, channelFields: params.include.spaceFields, customChannelFields: params.include.customSpaceFields, totalCount: params.include.totalCount, }, sort: params.sort != null ? Object.fromEntries(Object.entries(params.sort).map(([k, v]) => [k.replace('space', 'channel'), v])) : null, }) .then((res) => { res.data = res.data?.map((m) => { return { space: m.channel, custom: m.custom, updated: m.updated, eTag: m.eTag, }; }); return res; }); } }; this.time = timeEndpoint; // --- deprecated ------------------ this.stop = this.destroy; // -------- // --- deprecated ------------------ // mount crypto this.encrypt = crypto.encrypt.bind(crypto); this.decrypt = crypto.decrypt.bind(crypto); /* config */ this.getAuthKey = modules.config.getAuthKey.bind(modules.config); this.setAuthKey = modules.config.setAuthKey.bind(modules.config); this.setCipherKey = modules.config.setCipherKey.bind(modules.config); this.getUUID = modules.config.getUUID.bind(modules.config); this.setUUID = modules.config.setUUID.bind(modules.config); this.getUserId = modules.config.getUserId.bind(modules.config); this.setUserId = modules.config.setUserId.bind(modules.config); this.getFilterExpression = modules.config.getFilterExpression.bind(modules.config); this.setFilterExpression = modules.config.setFilterExpression.bind(modules.config); this.setHeartbeatInterval = modules.config.setHeartbeatInterval.bind(modules.config); if (networking.hasModule('proxy')) { this.setProxy = (proxy) => { modules.config.setProxy(proxy); this.reconnect(); }; } }","constructor(setup) { const { networking, cbor } = setup; const config = new Config({ setup }); this._config = config; const crypto = new Crypto({ config }); // LEGACY const { cryptography } = setup; networking.init(config); const tokenManager = new TokenManager(config, cbor); this._tokenManager = tokenManager; const telemetryManager = new TelemetryManager({ maximumSamplesCount: 60000, }); this._telemetryManager = telemetryManager; const cryptoModule = this._config.cryptoModule; const modules = { config, networking, crypto, cryptography, tokenManager, telemetryManager, PubNubFile: setup.PubNubFile, cryptoModule: cryptoModule, }; this.File = setup.PubNubFile; this.encryptFile = function (key, file) { if (arguments.length == 1 && typeof key != 'string' && modules.cryptoModule) { file = key; return modules.cryptoModule.encryptFile(file, this.File); } return cryptography.encryptFile(key, file, this.File); }; this.decryptFile = function (key, file) { if (arguments.length == 1 && typeof key != 'string' && modules.cryptoModule) { file = key; return modules.cryptoModule.decryptFile(file, this.File); } return cryptography.decryptFile(key, file, this.File); }; const timeEndpoint = endpointCreator.bind(this, modules, timeEndpointConfig); const leaveEndpoint = endpointCreator.bind(this, modules, presenceLeaveEndpointConfig); const heartbeatEndpoint = endpointCreator.bind(this, modules, presenceHeartbeatEndpointConfig); const setStateEndpoint = endpointCreator.bind(this, modules, presenceSetStateConfig); const subscribeEndpoint = endpointCreator.bind(this, modules, subscribeEndpointConfig); // managers const listenerManager = new ListenerManager(); this._listenerManager = listenerManager; this.iAmHere = endpointCreator.bind(this, modules, presenceHeartbeatEndpointConfig); this.iAmAway = endpointCreator.bind(this, modules, presenceLeaveEndpointConfig); this.setPresenceState = endpointCreator.bind(this, modules, presenceSetStateConfig); this.handshake = endpointCreator.bind(this, modules, handshakeEndpointConfig); this.receiveMessages = endpointCreator.bind(this, modules, receiveMessagesConfig); if (config.enableSubscribeBeta === true) { const eventEngine = new EventEngine({ handshake: this.handshake, receiveEvents: this.receiveMessages }); this.subscribe = eventEngine.subscribe.bind(eventEngine); this.unsubscribe = eventEngine.unsubscribe.bind(eventEngine); this.eventEngine = eventEngine; } else { const subscriptionManager = new SubscriptionManager({ timeEndpoint, leaveEndpoint, heartbeatEndpoint, setStateEndpoint, subscribeEndpoint, crypto: modules.crypto, config: modules.config, listenerManager, getFileUrl: (params) => getFileUrlFunction(modules, params), cryptoModule: modules.cryptoModule, }); this.subscribe = subscriptionManager.adaptSubscribeChange.bind(subscriptionManager); this.unsubscribe = subscriptionManager.adaptUnsubscribeChange.bind(subscriptionManager); this.disconnect = subscriptionManager.disconnect.bind(subscriptionManager); this.reconnect = subscriptionManager.reconnect.bind(subscriptionManager); this.unsubscribeAll = subscriptionManager.unsubscribeAll.bind(subscriptionManager); this.getSubscribedChannels = subscriptionManager.getSubscribedChannels.bind(subscriptionManager); this.getSubscribedChannelGroups = subscriptionManager.getSubscribedChannelGroups.bind(subscriptionManager); this.setState = subscriptionManager.adaptStateChange.bind(subscriptionManager); this.presence = subscriptionManager.adaptPresenceChange.bind(subscriptionManager); this.destroy = (isOffline) => { subscriptionManager.unsubscribeAll(isOffline); subscriptionManager.disconnect(); }; } this.addListener = listenerManager.addListener.bind(listenerManager); this.removeListener = listenerManager.removeListener.bind(listenerManager); this.removeAllListeners = listenerManager.removeAllListeners.bind(listenerManager); this.parseToken = tokenManager.parseToken.bind(tokenManager); this.setToken = tokenManager.setToken.bind(tokenManager); this.getToken = tokenManager.getToken.bind(tokenManager); /* channel groups */ this.channelGroups = { listGroups: endpointCreator.bind(this, modules, listChannelGroupsConfig), listChannels: endpointCreator.bind(this, modules, listChannelsInChannelGroupConfig), addChannels: endpointCreator.bind(this, modules, addChannelsChannelGroupConfig), removeChannels: endpointCreator.bind(this, modules, removeChannelsChannelGroupConfig), deleteGroup: endpointCreator.bind(this, modules, deleteChannelGroupConfig), }; /* push */ this.push = { addChannels: endpointCreator.bind(this, modules, addPushChannelsConfig), removeChannels: endpointCreator.bind(this, modules, removePushChannelsConfig), deleteDevice: endpointCreator.bind(this, modules, removeDevicePushConfig), listChannels: endpointCreator.bind(this, modules, listPushChannelsConfig), }; /* presence */ this.hereNow = endpointCreator.bind(this, modules, presenceHereNowConfig); this.whereNow = endpointCreator.bind(this, modules, presenceWhereNowEndpointConfig); this.getState = endpointCreator.bind(this, modules, presenceGetStateConfig); /* PAM */ this.grant = endpointCreator.bind(this, modules, grantEndpointConfig); this.grantToken = endpointCreator.bind(this, modules, grantTokenEndpointConfig); this.audit = endpointCreator.bind(this, modules, auditEndpointConfig); this.revokeToken = endpointCreator.bind(this, modules, revokeTokenEndpointConfig); this.publish = endpointCreator.bind(this, modules, publishEndpointConfig); this.fire = (args, callback) => { args.replicate = false; args.storeInHistory = false; return this.publish(args, callback); }; this.signal = endpointCreator.bind(this, modules, signalEndpointConfig); this.history = endpointCreator.bind(this, modules, historyEndpointConfig); this.deleteMessages = endpointCreator.bind(this, modules, deleteMessagesEndpointConfig); this.messageCounts = endpointCreator.bind(this, modules, messageCountsEndpointConfig); this.fetchMessages = endpointCreator.bind(this, modules, fetchMessagesEndpointConfig); // Actions API this.addMessageAction = endpointCreator.bind(this, modules, addMessageActionEndpointConfig); this.removeMessageAction = endpointCreator.bind(this, modules, removeMessageActionEndpointConfig); this.getMessageActions = endpointCreator.bind(this, modules, getMessageActionEndpointConfig); // File Upload API v1 this.listFiles = endpointCreator.bind(this, modules, listFilesEndpointConfig); const generateUploadUrl = endpointCreator.bind(this, modules, generateUploadUrlEndpointConfig); this.publishFile = endpointCreator.bind(this, modules, publishFileEndpointConfig); this.sendFile = sendFileFunction({ generateUploadUrl, publishFile: this.publishFile, modules, }); this.getFileUrl = (params) => getFileUrlFunction(modules, params); this.downloadFile = endpointCreator.bind(this, modules, downloadFileEndpointConfig); this.deleteFile = endpointCreator.bind(this, modules, deleteFileEndpointConfig); // Objects API v2 this.objects = { getAllUUIDMetadata: endpointCreator.bind(this, modules, getAllUUIDMetadataEndpointConfig), getUUIDMetadata: endpointCreator.bind(this, modules, getUUIDMetadataEndpointConfig), setUUIDMetadata: endpointCreator.bind(this, modules, setUUIDMetadataEndpointConfig), removeUUIDMetadata: endpointCreator.bind(this, modules, removeUUIDMetadataEndpointConfig), getAllChannelMetadata: endpointCreator.bind(this, modules, getAllChannelMetadataEndpointConfig), getChannelMetadata: endpointCreator.bind(this, modules, getChannelMetadataEndpointConfig), setChannelMetadata: endpointCreator.bind(this, modules, setChannelMetadataEndpointConfig), removeChannelMetadata: endpointCreator.bind(this, modules, removeChannelMetadataEndpointConfig), getChannelMembers: endpointCreator.bind(this, modules, getMembersV2EndpointConfig), setChannelMembers: (parameters, ...rest) => endpointCreator.call( this, modules, setMembersV2EndpointConfig, { type: 'set', ...parameters, }, ...rest, ), removeChannelMembers: (parameters, ...rest) => endpointCreator.call( this, modules, setMembersV2EndpointConfig, { type: 'delete', ...parameters, }, ...rest, ), getMemberships: endpointCreator.bind(this, modules, getMembershipsV2EndpointConfig), setMemberships: (parameters, ...rest) => endpointCreator.call( this, modules, setMembershipsV2EndpointConfig, { type: 'set', ...parameters, }, ...rest, ), removeMemberships: (parameters, ...rest) => endpointCreator.call( this, modules, setMembershipsV2EndpointConfig, { type: 'delete', ...parameters, }, ...rest, ), }; // User Apis this.createUser = (args) => this.objects.setUUIDMetadata({ uuid: args.userId, data: args.data, include: args.include, }); this.updateUser = this.createUser; this.removeUser = (args) => this.objects.removeUUIDMetadata({ uuid: args?.userId, }); this.fetchUser = (args) => this.objects.getUUIDMetadata({ uuid: args?.userId, include: args?.include, }); this.fetchUsers = this.objects.getAllUUIDMetadata; // Space apis this.createSpace = (args) => this.objects.setChannelMetadata({ channel: args.spaceId, data: args.data, include: args.include, }); this.updateSpace = this.createSpace; this.removeSpace = (args) => this.objects.removeChannelMetadata({ channel: args.spaceId, }); this.fetchSpace = (args) => this.objects.getChannelMetadata({ channel: args.spaceId, include: args.include, }); this.fetchSpaces = this.objects.getAllChannelMetadata; // Membership apis this.addMemberships = (parameters) => { if (typeof parameters.spaceId === 'string') { return this.objects.setChannelMembers({ channel: parameters.spaceId, uuids: parameters.users?.map((user) => { if (typeof user === 'string') { return user; } return { id: user.userId, custom: user.custom, status: user.status, }; }), limit: 0, }); } else { return this.objects.setMemberships({ uuid: parameters.userId, channels: parameters.spaces?.map((space) => { if (typeof space === 'string') { return space; } return { id: space.spaceId, custom: space.custom, status: space.status, }; }), limit: 0, }); } }; this.updateMemberships = this.addMemberships; this.removeMemberships = (parameters) => { if (typeof parameters.spaceId === 'string') { return this.objects.removeChannelMembers({ channel: parameters.spaceId, uuids: parameters.userIds, limit: 0, }); } else { return this.objects.removeMemberships({ uuid: parameters.userId, channels: parameters.spaceIds, limit: 0, }); } }; this.fetchMemberships = (params) => { if (typeof params.spaceId === 'string') { return this.objects .getChannelMembers({ channel: params.spaceId, filter: params.filter, limit: params.limit, page: params.page, include: { customFields: params.include.customFields, UUIDFields: params.include.userFields, customUUIDFields: params.include.customUserFields, totalCount: params.include.totalCount, }, sort: params.sort != null ? Object.fromEntries(Object.entries(params.sort).map(([k, v]) => [k.replace('user', 'uuid'), v])) : null, }) .then((res) => { res.data = res.data?.map((m) => { return { user: m.uuid, custom: m.custom, updated: m.updated, eTag: m.eTag, }; }); return res; }); } else { return this.objects .getMemberships({ uuid: params.userId, filter: params.filter, limit: params.limit, page: params.page, include: { customFields: params.include.customFields, channelFields: params.include.spaceFields, customChannelFields: params.include.customSpaceFields, totalCount: params.include.totalCount, }, sort: params.sort != null ? Object.fromEntries(Object.entries(params.sort).map(([k, v]) => [k.replace('space', 'channel'), v])) : null, }) .then((res) => { res.data = res.data?.map((m) => { return { space: m.channel, custom: m.custom, updated: m.updated, eTag: m.eTag, }; }); return res; }); } }; this.time = timeEndpoint; // --- deprecated ------------------ this.stop = this.destroy; // -------- // --- deprecated ------------------ // mount crypto this.encrypt = function (data, key) { if (typeof key === 'undefined' && modules.cryptoModule) { const encrypted = modules.cryptoModule.encrypt(data); return typeof encrypted === 'string' ? encrypted : encode(encrypted); } else { return crypto.encrypt(data, key); } }; this.decrypt = function (data, key) { if (typeof key === 'undefined' && cryptoModule) { const decrypted = modules.cryptoModule.decrypt(data); return decrypted instanceof ArrayBuffer ? encode(decrypted) : decrypted; } else { return crypto.decrypt(data, key); } }; /* config */ this.getAuthKey = modules.config.getAuthKey.bind(modules.config); this.setAuthKey = modules.config.setAuthKey.bind(modules.config); this.getUUID = modules.config.getUUID.bind(modules.config); this.setUUID = modules.config.setUUID.bind(modules.config); this.getUserId = modules.config.getUserId.bind(modules.config); this.setUserId = modules.config.setUserId.bind(modules.config); this.getFilterExpression = modules.config.getFilterExpression.bind(modules.config); this.setFilterExpression = modules.config.setFilterExpression.bind(modules.config); // this.setCipherKey = modules.config.setCipherKey.bind(modules.config); this.setCipherKey = (key) => modules.config.setCipherKey(key, setup, modules); this.setHeartbeatInterval = modules.config.setHeartbeatInterval.bind(modules.config); if (networking.hasModule('proxy')) { this.setProxy = (proxy) => { modules.config.setProxy(proxy); this.reconnect(); }; } }","feat/CryptoModule (#339) * ref: decoupling cryptor module * cryptoModule * lint * rever cryptors in config * lint fixes * CryptoModule for web and node * step definitions for contract tests * lib files * fix:es-lint * let vs const * and some more ts not wanting me to specific about trivials * access modfiers * refactor-1 * lint, cleanup test * refactor - 2 * code cleanup in stream encryption with new cryptor * fix: lint issue. * refactor: eliminate ts-ignores by defining file reated types * * integration of crypto module * refactoring cryptoModule * lib and dist * support for setCipherKey * fix: setCipherKey() * lib and dist files * fix: staticIV support * lib and dist * refactor: cryptoModule, * added support for PubNub.CryptoModule factory * fix: types * dist and libs * fix: test- customEncrypt function * fix: legacy crypto init, tests * refactor: typecheck on incoming data for aescbc cryptor * code cleanup, * fix: broken file cryptography operations on web * lib and dist directories * refactor: crypto initialiser apis default value initialisation * LICENSE * reverted last commit 11351ec * update LICENSE * PubNub SDK v7.4.0 release. --------- Co-authored-by: PubNub Release Bot <120067856+pubnub-release-bot@users.noreply.github.com>",https://github.com/pubnub/javascript/commit/fb6cd0417cbb4ba87ea2d5d86a9c94774447e119,CVE-2023-26154,['CWE-331'],src/core/pubnub-common.js,3,js,False,2023-10-16T11:14:10Z "public static void verify(Consumer errorConsumer, PluginDescription... plugins) { JsonArray root = new JsonArray(); String hash; for (PluginDescription desc : plugins) { hash = desc.sha256(); if (hash != null) root.add(hash); } try { MultipartRequest req = new MultipartRequest(); req.addField(""hashes"", root.toString().getBytes(""UTF-8"")); String json = new String(req.send(new URL(pluginVerifyURL)), ""utf-8""); JsonArray ar = JsonParser.parseString(json).getAsJsonArray(); for (JsonElement el : ar) { if (el instanceof JsonPrimitive) { cache.put(el.getAsString(), true); } } } catch (Exception e) { e.printStackTrace(); errorConsumer.accept(e); } }","public static void verify(Consumer errorConsumer, PluginDescription... plugins) { JsonArray root = new JsonArray(); String hash; for (PluginDescription desc : plugins) { hash = desc.sha256(); if (hash != null) root.add(hash); } try { MultipartRequest req = new MultipartRequest(); req.addField(""hashes"", root.toString().getBytes(""UTF-8"")); String json = new String(req.send(new URL(pluginVerifyURL)), ""utf-8""); JsonObject reg = JsonParser.parseString(json).getAsJsonObject(); for (JsonElement el : reg.get(""verified"").getAsJsonArray()) { if (el instanceof JsonPrimitive) { cache.put(el.getAsString(), true); } } for (JsonElement el : reg.get(""malicious"").getAsJsonArray()) { if (el instanceof JsonPrimitive) { cache.put(el.getAsString(), false); } } } catch (Exception e) { e.printStackTrace(); errorConsumer.accept(e); } }",Added malicious flag for plugins,https://github.com/Defective4/Another-Minecraft-Chat-Client/commit/3f4320358058166e2002397b0a5c30579bdca88f,,,amcc-app/src/main/java/net/defekt/mc/chatclient/plugins/Plugins.java,3,java,False,2023-01-12T19:28:25Z "@Override public ActionResult useOnBlock(ItemUsageContext contextIn) { if (contextIn.getPlayer() != null) { MoaEntity moa = new MoaEntity(contextIn.getWorld(), AetherAPI.instance().getMoa(contextIn.getStack().getTag().getInt(""moaType""))); moa.refreshPositionAndAngles(contextIn.getBlockPos().up(), 1.0F, 1.0F); moa.setPlayerGrown(true); if (!contextIn.getWorld().isClient) contextIn.getWorld().spawnEntity(moa); return ActionResult.SUCCESS; } return super.useOnBlock(contextIn); }","@Override public ActionResult useOnBlock(ItemUsageContext contextIn) { if (contextIn.getPlayer() != null) { MoaEntity moa = new MoaEntity(contextIn.getWorld(), AetherAPI.instance().getMoa(contextIn.getStack().getTag().getInt(""moaType""))); moa.refreshPositionAndAngles(contextIn.getBlockPos().up(), 1.0F, 1.0F); moa.setPlayerGrown(true); if (!contextIn.getWorld().isClient) contextIn.getWorld().spawnEntity(moa); if (!contextIn.getPlayer().isCreative()) { contextIn.getStack().decrement(1); if (contextIn.getStack().isEmpty()) { contextIn.getPlayer().getInventory().removeOne(contextIn.getStack()); } } return ActionResult.SUCCESS; } return super.useOnBlock(contextIn); }",[Fix] Fixed critical exploit with infinite moa eggs,https://github.com/devs-immortal/Paradise-Lost/commit/26b516d046a74c891c5e78099cf9c83e026eb089,,,src/main/java/com/aether/items/MoaEgg.java,3,java,False,2021-06-27T23:46:44Z "public Vulnerability updateVulnerability(String record) { var v = gson.fromJson(record, Vulnerability.class); logger.info(""Read vulnerability statement "" + v.getId() + "" from "" + consumeTopics.toString()); v.getEcosystems().forEach(ecosystem -> getDbContext(ecosystem). transaction(configuration -> { logger.info(v.getId() + "": Inserting vulnerability into the database for ecosystem: "" + ""\"""" + ecosystem + ""\"".""); var vulnerabilityForEcosystem = gson.fromJson(record, Vulnerability.class); restrictByEcosystem(vulnerabilityForEcosystem, ecosystem); updateVulnerability(vulnerabilityForEcosystem, DSL.using(configuration)); })); return v; }","public Vulnerability updateVulnerability(String record) { var v = gson.fromJson(record, Vulnerability.class); logger.info(""Read vulnerability statement "" + v.getId() + "" from "" + consumeTopics.toString()); contexts.keySet().forEach(ecosystem -> getDbContext(ecosystem). transaction(configuration -> { logger.info(v.getId() + "": Inserting vulnerability into the database for ecosystem: "" + ""\"""" + ecosystem + ""\"".""); var vulnerabilityForEcosystem = gson.fromJson(record, Vulnerability.class); restrictByEcosystem(vulnerabilityForEcosystem, ecosystem); updateVulnerability(vulnerabilityForEcosystem, DSL.using(configuration)); })); return v; }","Changed clean-up process to remove vulnerability data in each ecosystem DB prior to insertion of new data. Vulnerability data will then only be inserted in DBs that were found relevant.",https://github.com/fasten-project/fasten/commit/b3b4deb8ff296c9a91e1f9fc0532e3920923352b,,,analyzer/vulnerability-statements-processor/src/main/java/eu/fasten/analyzer/vulnerabilitystatementsprocessor/VulnerabilityStatementsProcessor.java,3,java,False,2022-01-28T11:08:03Z "public static Expression make(InferenceVariable binding, Equations equations) { InferenceReferenceExpression result = new InferenceReferenceExpression(binding); if (!equations.supportsExpressions()) { return result; } if (!binding.resetClassCall()) { return result; } Expression type = binding.getType().normalize(NormalizationMode.WHNF); ClassCallExpression classCall = type.cast(ClassCallExpression.class); if (classCall != null && !classCall.getDefinition().getFields().isEmpty()) { result.myImplementedFields = new HashSet<>(); for (ClassField field : classCall.getDefinition().getFields()) { if (!field.isProperty()) { Expression impl = classCall.getImplementation(field, result); if (impl != null) { equations.addEquation(FieldCallExpression.make(field, classCall.getLevels(), result), impl.normalize(NormalizationMode.WHNF), classCall.getDefinition().getFieldType(field, classCall.getLevels(), result), CMP.EQ, binding.getSourceNode(), binding, impl.getStuckInferenceVariable(), false); if (result.getSubstExpression() != null) { return result.getSubstExpression(); } result.myImplementedFields.add(field); } } } type = new ClassCallExpression(classCall.getDefinition(), classCall.getLevels()); } binding.setType(type); return result; }","public static Expression make(InferenceVariable binding, Equations equations) { InferenceReferenceExpression result = new InferenceReferenceExpression(binding); if (!equations.supportsExpressions()) { return result; } if (!binding.resetClassCall()) { return result; } Expression type = binding.getType().normalize(NormalizationMode.WHNF); ClassCallExpression classCall = type.cast(ClassCallExpression.class); if (classCall != null && !classCall.getDefinition().getFields().isEmpty()) { type = new ClassCallExpression(classCall.getDefinition(), classCall.getLevels()); binding.setType(type); result.myImplementedFields = new HashSet<>(); for (ClassField field : classCall.getDefinition().getFields()) { if (!field.isProperty()) { Expression impl = classCall.getImplementation(field, result); if (impl != null) { equations.addEquation(FieldCallExpression.make(field, classCall.getLevels(), result), impl.normalize(NormalizationMode.WHNF), classCall.getDefinition().getFieldType(field, classCall.getLevels(), result), CMP.EQ, binding.getSourceNode(), binding, impl.getStuckInferenceVariable(), false); if (result.getSubstExpression() != null) { Expression solution = result.getSubstExpression(); binding.setType(classCall); binding.unsolve(); return equations.solve(binding, solution) ? solution : result; } result.myImplementedFields.add(field); } } } } return result; }",Fix stackoverflow,https://github.com/JetBrains/Arend/commit/a9611bcdfe78de37da4ca022ca6ad4e0ad0d0061,,,base/src/main/java/org/arend/core/expr/InferenceReferenceExpression.java,3,java,False,2021-05-12T10:20:49Z "public int intValue() { return (int) getValue(); }","public int intValue() { if (getValue() > (double) Integer.MAX_VALUE) { return Integer.MAX_VALUE; } else { return (int) getValue(); } }","Add safe guards to avoid OOM on parsing xref structures Add ability to set max size of xref array Ignore flaky tests in LtvVerificationTest class DEVSIX-6247",https://github.com/itext/itext-java/commit/75b236479a077a658fb38e76e44c5a3deeec516f,,,kernel/src/main/java/com/itextpdf/kernel/pdf/PdfNumber.java,3,java,False,2022-02-03T03:01:20Z "void constructOutlines(PdfDictionary outlineRoot, Map names) { if (outlineRoot == null) { return; } PdfDictionary current = outlineRoot.getAsDictionary(PdfName.First); outlines = new PdfOutline(OutlineRoot, outlineRoot, getDocument()); PdfOutline parentOutline = outlines; // map `PdfOutline` to the next sibling to process in the hierarchy HashMap positionMap = new HashMap<>(); while (current != null) { PdfDictionary parent = current.getAsDictionary(PdfName.Parent); if (null == parent) { throw new PdfException( MessageFormatUtil.format( KernelExceptionMessageConstant.CORRUPTED_OUTLINE_NO_PARENT_ENTRY, current.indirectReference)); } PdfString title = current.getAsString(PdfName.Title); if (null == title) { throw new PdfException( MessageFormatUtil.format( KernelExceptionMessageConstant.CORRUPTED_OUTLINE_NO_TITLE_ENTRY, current.indirectReference)); } PdfOutline currentOutline = new PdfOutline(title.toUnicodeString(), current, parentOutline); addOutlineToPage(currentOutline, current, names); parentOutline.getAllChildren().add(currentOutline); PdfDictionary first = current.getAsDictionary(PdfName.First); PdfDictionary next = current.getAsDictionary(PdfName.Next); if (first != null) { // Down in hierarchy; when returning up, process `next` positionMap.put(parentOutline, next); parentOutline = currentOutline; current = first; } else if (next != null) { // Next sibling in hierarchy current = next; } else { // Up in hierarchy using `positionMap` current = null; while (current == null && parentOutline != null) { parentOutline = parentOutline.getParent(); if (parentOutline != null) { current = positionMap.get(parentOutline); } } } } }","void constructOutlines(PdfDictionary outlineRoot, Map names) { if (outlineRoot == null) { return; } PdfReader reader = getDocument().getReader(); final boolean isLenientLevel = reader == null || StrictnessLevel.CONSERVATIVE.isStricter(reader.getStrictnessLevel()); PdfDictionary current = outlineRoot.getAsDictionary(PdfName.First); outlines = new PdfOutline(ROOT_OUTLINE_TITLE, outlineRoot, getDocument()); PdfOutline parentOutline = outlines; Map nextUnprocessedChildForParentMap = new HashMap<>(); Set alreadyVisitedOutlinesSet = new HashSet<>(); while (current != null) { PdfDictionary parent = current.getAsDictionary(PdfName.Parent); if (null == parent && !isLenientLevel) { throw new PdfException( MessageFormatUtil.format( KernelExceptionMessageConstant.CORRUPTED_OUTLINE_NO_PARENT_ENTRY, current.indirectReference)); } PdfString title = current.getAsString(PdfName.Title); if (null == title) { throw new PdfException( MessageFormatUtil.format( KernelExceptionMessageConstant.CORRUPTED_OUTLINE_NO_TITLE_ENTRY, current.indirectReference)); } PdfOutline currentOutline = new PdfOutline(title.toUnicodeString(), current, parentOutline); alreadyVisitedOutlinesSet.add(current); addOutlineToPage(currentOutline, current, names); parentOutline.getAllChildren().add(currentOutline); PdfDictionary first = current.getAsDictionary(PdfName.First); PdfDictionary next = current.getAsDictionary(PdfName.Next); if (first != null) { if (alreadyVisitedOutlinesSet.contains(first)) { if (!isLenientLevel) { throw new PdfException(MessageFormatUtil.format( KernelExceptionMessageConstant.CORRUPTED_OUTLINE_DICTIONARY_HAS_INFINITE_LOOP, first)); } LOGGER.warn(MessageFormatUtil.format( KernelLogMessageConstant.CORRUPTED_OUTLINE_DICTIONARY_HAS_INFINITE_LOOP, first)); return; } // Down in hierarchy; when returning up, process `next`. nextUnprocessedChildForParentMap.put(parentOutline, next); parentOutline = currentOutline; current = first; } else if (next != null) { if (alreadyVisitedOutlinesSet.contains(next)) { if (!isLenientLevel) { throw new PdfException(MessageFormatUtil.format( KernelExceptionMessageConstant.CORRUPTED_OUTLINE_DICTIONARY_HAS_INFINITE_LOOP, next)); } LOGGER.warn(MessageFormatUtil.format( KernelLogMessageConstant.CORRUPTED_OUTLINE_DICTIONARY_HAS_INFINITE_LOOP, next)); return; } // Next sibling in hierarchy current = next; } else { // Up in hierarchy using 'nextUnprocessedChildForParentMap'. current = null; while (current == null && parentOutline != null) { parentOutline = parentOutline.getParent(); if (parentOutline != null) { current = nextUnprocessedChildForParentMap.get(parentOutline); } } } } }","Fix problem with infinite loop occurs Add flexibily to PdfCatalog#constructOutlines logic relying on PdfReader#StrictnessLevel Unignore some tests relying to problems with infinite loop in outlines while merging DEVSIX-3703",https://github.com/itext/itext-java/commit/b57af5ffa23b49bfb3dc4c740bc5d67d04692c60,,,kernel/src/main/java/com/itextpdf/kernel/pdf/PdfCatalog.java,3,java,False,2020-08-17T07:38:11Z "@Override public void deleteCache(String uid, boolean isRemoveSession) { //从缓存中获取Session Collection sessions = redisSessionDAO.getActiveSessions(); for (Session sessionInfo : sessions) { //遍历Session,找到该用户名称对应的Session Object attribute = sessionInfo.getAttribute(DefaultSubjectContext.PRINCIPALS_SESSION_KEY); if (attribute == null) { continue; } AccountProfile accountProfile = (AccountProfile) ((SimplePrincipalCollection) attribute).getPrimaryPrincipal(); if (accountProfile == null) { continue; } // 如果该session是指定的uid用户的 if (Objects.equals(accountProfile.getUid(), uid)) { deleteSession(isRemoveSession, sessionInfo, attribute); } } }","@Override public void deleteCache(String uid, boolean isRemoveSession) { //从缓存中获取Session // Collection sessions = redisSessionDAO.getActiveSessions(); // for (Session sessionInfo : sessions) { // //遍历Session,找到该用户名称对应的Session // Object attribute = sessionInfo.getAttribute(DefaultSubjectContext.PRINCIPALS_SESSION_KEY); // if (attribute == null) { // continue; // } // AccountProfile accountProfile = (AccountProfile) ((SimplePrincipalCollection) attribute).getPrimaryPrincipal(); // if (accountProfile == null) { // continue; // } // // 如果该session是指定的uid用户的 // if (Objects.equals(accountProfile.getUid(), uid)) { // deleteSession(isRemoveSession, sessionInfo, uid); // } // } if (isRemoveSession) { redisUtils.del(ShiroConstant.SHIRO_TOKEN_KEY + uid, ShiroConstant.SHIRO_TOKEN_REFRESH + uid, ShiroConstant.SHIRO_AUTHORIZATION_CACHE + uid); }else{ redisUtils.del(ShiroConstant.SHIRO_AUTHORIZATION_CACHE + uid); } }",fix:change user auth cache,https://github.com/HimitZH/HOJ/commit/a463d6a9fbe9b5ca6a1a3ff33008944d0d958785,,,hoj-springboot/DataBackup/src/main/java/top/hcode/hoj/dao/user/impl/UserRoleEntityServiceImpl.java,3,java,False,2022-12-04T06:26:49Z "@Override public boolean test(ActivityRecord r) { // End processing if we have reached the root. if (r == mRoot) return true; mAllActivities.add(r); final int flags = r.info.flags; final boolean finishOnTaskLaunch = (flags & ActivityInfo.FLAG_FINISH_ON_TASK_LAUNCH) != 0; final boolean allowTaskReparenting = (flags & ActivityInfo.FLAG_ALLOW_TASK_REPARENTING) != 0; final boolean clearWhenTaskReset = (r.intent.getFlags() & Intent.FLAG_ACTIVITY_CLEAR_WHEN_TASK_RESET) != 0; if (mIsTargetTask) { if (!finishOnTaskLaunch && !clearWhenTaskReset) { if (r.resultTo != null) { // If this activity is sending a reply to a previous activity, we can't do // anything with it now until we reach the start of the reply chain. // NOTE: that we are assuming the result is always to the previous activity, // which is almost always the case but we really shouldn't count on. mResultActivities.add(r); return false; } if (allowTaskReparenting && r.taskAffinity != null && !r.taskAffinity.equals(mTask.affinity)) { // If this activity has an affinity for another task, then we need to move // it out of here. We will move it as far out of the way as possible, to the // bottom of the activity root task. This also keeps it correctly ordered with // any activities we previously moved. // Handle this activity after we have done traversing the hierarchy. mPendingReparentActivities.add(r); return false; } } if (mForceReset || finishOnTaskLaunch || clearWhenTaskReset) { // If the activity should just be removed either because it asks for it, or the // task should be cleared, then finish it and anything that is part of its reply // chain. if (clearWhenTaskReset) { // In this case, we want to finish this activity and everything above it, // so be sneaky and pretend like these are all in the reply chain. finishActivities(mAllActivities, ""clearWhenTaskReset""); } else { mResultActivities.add(r); finishActivities(mResultActivities, ""reset-task""); } mResultActivities.clear(); return false; } else { // If we were in the middle of a chain, well the activity that started it all // doesn't want anything special, so leave it all as-is. mResultActivities.clear(); } return false; } else { mResultActivities.add(r); if (r.resultTo != null) { // If this activity is sending a reply to a previous activity, we can't do // anything with it now until we reach the start of the reply chain. // NOTE: that we are assuming the result is always to the previous activity, // which is almost always the case but we really shouldn't count on. return false; } else if (mTargetTaskFound && allowTaskReparenting && mTargetTask.affinity != null && mTargetTask.affinity.equals(r.taskAffinity)) { // This activity has an affinity for our task. Either remove it if we are // clearing or move it over to our task. Note that we currently punt on the case // where we are resetting a task that is not at the top but who has activities // above with an affinity to it... this is really not a normal case, and we will // need to later pull that task to the front and usually at that point we will // do the reset and pick up those remaining activities. (This only happens if // someone starts an activity in a new task from an activity in a task that is // not currently on top.) if (mForceReset || finishOnTaskLaunch) { finishActivities(mResultActivities, ""move-affinity""); return false; } if (mActivityReparentPosition == -1) { mActivityReparentPosition = mTargetTask.getChildCount(); } processResultActivities( r, mTargetTask, mActivityReparentPosition, false, false); // Now we've moved it in to place...but what if this is a singleTop activity and // we have put it on top of another instance of the same activity? Then we drop // the instance below so it remains singleTop. if (r.info.launchMode == ActivityInfo.LAUNCH_SINGLE_TOP) { final ActivityRecord p = mTargetTask.getActivityBelow(r); if (p != null) { if (p.intent.getComponent().equals(r.intent.getComponent())) { p.finishIfPossible(""replace"", false /* oomAdj */); } } } } return false; } }","@Override public boolean test(ActivityRecord r) { // End processing if we have reached the root. if (r == mRoot) return true; mAllActivities.add(r); final int flags = r.info.flags; final boolean finishOnTaskLaunch = (flags & ActivityInfo.FLAG_FINISH_ON_TASK_LAUNCH) != 0; final boolean allowTaskReparenting = (flags & ActivityInfo.FLAG_ALLOW_TASK_REPARENTING) != 0; final boolean clearWhenTaskReset = (r.intent.getFlags() & Intent.FLAG_ACTIVITY_CLEAR_WHEN_TASK_RESET) != 0; if (mIsTargetTask) { if (!finishOnTaskLaunch && !clearWhenTaskReset) { if (r.resultTo != null) { // If this activity is sending a reply to a previous activity, we can't do // anything with it now until we reach the start of the reply chain. // NOTE: that we are assuming the result is always to the previous activity, // which is almost always the case but we really shouldn't count on. mResultActivities.add(r); return false; } if (allowTaskReparenting && r.taskAffinity != null && !r.taskAffinity.equals(mTask.affinity)) { // If this activity has an affinity for another task, then we need to move // it out of here. We will move it as far out of the way as possible, to the // bottom of the activity root task. This also keeps it correctly ordered with // any activities we previously moved. // Handle this activity after we have done traversing the hierarchy. mPendingReparentActivities.add(r); return false; } } if (mForceReset || finishOnTaskLaunch || clearWhenTaskReset) { // If the activity should just be removed either because it asks for it, or the // task should be cleared, then finish it and anything that is part of its reply // chain. if (clearWhenTaskReset) { // In this case, we want to finish this activity and everything above it, // so be sneaky and pretend like these are all in the reply chain. finishActivities(mAllActivities, ""clearWhenTaskReset""); } else { mResultActivities.add(r); finishActivities(mResultActivities, ""reset-task""); } mResultActivities.clear(); return false; } else { // If we were in the middle of a chain, well the activity that started it all // doesn't want anything special, so leave it all as-is. mResultActivities.clear(); } return false; } else { if (r.resultTo != null) { // If this activity is sending a reply to a previous activity, we can't do // anything with it now until we reach the start of the reply chain. // NOTE: that we are assuming the result is always to the previous activity, // which is almost always the case but we really shouldn't count on. mResultActivities.add(r); return false; } else if (mTargetTaskFound && allowTaskReparenting && mTargetTask.affinity != null && mTargetTask.affinity.equals(r.taskAffinity)) { mResultActivities.add(r); // This activity has an affinity for our task. Either remove it if we are // clearing or move it over to our task. Note that we currently punt on the case // where we are resetting a task that is not at the top but who has activities // above with an affinity to it... this is really not a normal case, and we will // need to later pull that task to the front and usually at that point we will // do the reset and pick up those remaining activities. (This only happens if // someone starts an activity in a new task from an activity in a task that is // not currently on top.) if (mForceReset || finishOnTaskLaunch) { finishActivities(mResultActivities, ""move-affinity""); return false; } if (mActivityReparentPosition == -1) { mActivityReparentPosition = mTargetTask.getChildCount(); } processResultActivities( r, mTargetTask, mActivityReparentPosition, false, false); // Now we've moved it in to place...but what if this is a singleTop activity and // we have put it on top of another instance of the same activity? Then we drop // the instance below so it remains singleTop. if (r.info.launchMode == ActivityInfo.LAUNCH_SINGLE_TOP) { final ActivityRecord p = mTargetTask.getActivityBelow(r); if (p != null) { if (p.intent.getComponent().equals(r.intent.getComponent())) { p.finishIfPossible(""replace"", false /* oomAdj */); } } } } return false; } }","Allow activity to be reparent while allowTaskReparenting is applied Any malicious application could hijack tasks by android:allowTaskReparenting. This vulnerability can perform UI spoofing or spying on user’s activities. This CL only allows activities to be reparent while android:allowTaskReparenting is applied and the affinity of activity is same with the target task. Bug: 240663194 Test: atest IntentTests Change-Id: I73abb9ec05af95bc14f887ae825a9ada9600f771 Merged-In: I73abb9ec05af95bc14f887ae825a9ada9600f771 (cherry picked from commit f19d69f26fefb95d2f349cc66459691f434ac0a6)",https://github.com/LineageOS/android_frameworks_base/commit/f63ee3bb84b6a6ebf34475f433471cf4c28fb3c7,,,services/core/java/com/android/server/wm/ResetTargetTaskHelper.java,3,java,False,2022-09-05T13:38:50Z "@WorkerThread private void showCreateNewProjectDialog() { if (!createNewProjectDialog.isShowing()) { createNewProjectDialog.show(); EditText input = createNewProjectDialog.findViewById(android.R.id.text1); Button createBtn = createNewProjectDialog.findViewById(android.R.id.button1); createBtn.setOnClickListener( v -> { var projectName = input.getText().toString().trim(); if (projectName.isEmpty()) { return; } try { var project = JavaProject.newProject(projectName); if (mListener != null) { runOnUiThread( () -> { if (createNewProjectDialog.isShowing()) createNewProjectDialog.dismiss(); mListener.onProjectCreated(project); }); } } catch (IOException e) { e.printStackTrace(); } }); input.setText(""""); } }","@WorkerThread private void showCreateNewProjectDialog() { if (!createNewProjectDialog.isShowing()) { createNewProjectDialog.show(); EditText input = createNewProjectDialog.findViewById(android.R.id.text1); Button createBtn = createNewProjectDialog.findViewById(android.R.id.button1); createBtn.setOnClickListener( v -> { var projectName = input.getText().toString().trim().replace("".."", """"); if (projectName.isEmpty()) { return; } try { var project = JavaProject.newProject(projectName); if (mListener != null) { runOnUiThread( () -> { if (createNewProjectDialog.isShowing()) createNewProjectDialog.dismiss(); mListener.onProjectCreated(project); }); } } catch (IOException e) { e.printStackTrace(); } }); input.setText(""""); } }",Fix Path Transversal vulnerability,https://github.com/Cosmic-Ide/Cosmic-IDE/commit/59dc928893108aedf13df3a59665c2e19287b9de,,,app/src/main/java/org/cosmic/ide/ProjectActivity.java,3,java,False,2022-08-14T07:57:18Z "public T getTaskAndCheckAuthentication( TaskManager taskManager, AsyncExecutionId asyncExecutionId, Class tClass ) throws IOException { T asyncTask = getTask(taskManager, asyncExecutionId, tClass); if (asyncTask == null) { return null; } // Check authentication for the user final Authentication auth = securityContext.getAuthentication(); if (ensureAuthenticatedUserIsSame(asyncTask.getOriginHeaders(), auth) == false) { throw new ResourceNotFoundException(asyncExecutionId.getEncoded() + "" not found""); } return asyncTask; }","public T getTaskAndCheckAuthentication( TaskManager taskManager, AsyncExecutionId asyncExecutionId, Class tClass ) throws IOException { T asyncTask = getTask(taskManager, asyncExecutionId, tClass); if (asyncTask == null) { return null; } // Check authentication for the user if (false == securityContext.canIAccessResourcesCreatedWithHeaders(asyncTask.getOriginHeaders())) { throw new ResourceNotFoundException(asyncExecutionId.getEncoded() + "" not found""); } return asyncTask; }","Fix can access resource checks for API Keys with run as (#84277) This fixes two things for the ""can access"" authz check: * API Keys running as, have access to the resources created by the effective run as user * tokens created by API Keys (with the client credentials) have access to the API Key's resources In addition, this PR moves some of the authz plumbing code from the Async and Scroll services classes under the Security Context class (as a minor refactoring).",https://github.com/elastic/elasticsearch/commit/2f0733d1b5dc9458ec901efe2f7141742d9dfed8,,,x-pack/plugin/core/src/main/java/org/elasticsearch/xpack/core/async/AsyncTaskIndexService.java,3,java,False,2022-02-28T14:00:54Z "private void startExistingRecentsIfPossibleInner(ActivityOptions options, ActivityRecord r, Task rootTask, ActivityMetricsLogger.LaunchingState launchingState, RemoteTransition remoteTransition, Transition transition) { final Task task = r.getTask(); mService.deferWindowLayout(); try { r.mTransitionController.requestStartTransition(transition, task, remoteTransition, null /* displayChange */); r.mTransitionController.collect(task); r.mTransitionController.setTransientLaunch(r, TaskDisplayArea.getRootTaskAbove(rootTask)); task.moveToFront(""startExistingRecents""); task.mInResumeTopActivity = true; task.resumeTopActivity(null /* prev */, options, true /* deferPause */); mSupervisor.getActivityMetricsLogger().notifyActivityLaunched(launchingState, ActivityManager.START_TASK_TO_FRONT, false, r, options); } finally { task.mInResumeTopActivity = false; mService.continueWindowLayout(); } }","private void startExistingRecentsIfPossibleInner(ActivityOptions options, ActivityRecord r, Task rootTask, ActivityMetricsLogger.LaunchingState launchingState, RemoteTransition remoteTransition, Transition transition) { final Task task = r.getTask(); mService.deferWindowLayout(); try { final TransitionController controller = r.mTransitionController; if (controller.getTransitionPlayer() != null) { controller.requestStartTransition(transition, task, remoteTransition, null /* displayChange */); controller.collect(task); controller.setTransientLaunch(r, TaskDisplayArea.getRootTaskAbove(rootTask)); } else { // The transition player might be died when executing the queued transition. transition.abort(); } task.moveToFront(""startExistingRecents""); task.mInResumeTopActivity = true; task.resumeTopActivity(null /* prev */, options, true /* deferPause */); mSupervisor.getActivityMetricsLogger().notifyActivityLaunched(launchingState, ActivityManager.START_TASK_TO_FRONT, false, r, options); } finally { task.mInResumeTopActivity = false; mService.continueWindowLayout(); } }","Avoid getting crashed by slow transition This avoids extreme cases when the device is slow or the load of system/systemui is heavy. SystemUI crashes: 1. OPEN transition T1 2. Swipe up, queued transition T2 3. T1 timed out, moveToPlaying (added to mPlayingTransitions) 4. T2 starts collecting 5. startTransition of T1 (STATE_PLAYING -> STATE_STARTED) 6. finishTransition from RemoteTransitionHandler 7. Got crash by ""Can't finish a non-playing transition"" (in mPlayingTransitions but with STATE_STARTED) System server crashes: When executing a non-CHANGE transition with a display change, (open an activity and request to change display orientation) if IDisplayChangeWindowCallback#continueDisplayChange is called from remote after transition timeout, the exception ""Trying to rotate outside a transition"" will throw at display thread. Bug: 265852118 Bug: 261645736 Test: Set break point at WindowOrganizerController#startTransition to simulate the slowness. Launch app, swipe up, rotate. The device still works normally after resuming the break point. Test: CtsWindowManagerDeviceTestCases Change-Id: Ia0d97823886eff1c935a0cd7f6f6ac6abf3659d5",https://github.com/PixelExperience/frameworks_base/commit/46ecdc5cb55403a9fb8c319588bad531e72b25cc,,,services/core/java/com/android/server/wm/ActivityStartController.java,3,java,False,2023-02-07T13:24:49Z "@Override public synchronized void memoryLow(Phaser phaser) { if (entryBatch.isEmpty()) { log.info(""{} No data to save. Immediately signalling memory manager."", taskID); phaser.register(); phaser.arriveAndDeregister(); return; } dataDumpNotifyingPhaser = phaser; dataDumpNotifyingPhaser.register(); log.info(""{} Setting dumpData to true"", taskID); dumpData.set(true); }","@Override public void memoryLow(Phaser phaser) { if (dataDumpNotifyingPhaserRef.compareAndSet(null, phaser)) { log.info(""{} registering to low memory notification phaser"", taskID); phaser.register(); } else { log.warn(""{} already has a low memory notification phaser."", taskID); } }","OAK-9576: Multithreaded download synchronization issues (#383) * OAK-9576 - Multithreaded download synchronization issues * Fixing a problem with test * OAK-9576: Multithreaded download synchronization issues * Fixing synchronization issues * Fixing OOM issue * Adding delay between download retries * OAK-9576: Multithreaded download synchronization issues * Using linkedlist in tasks for freeing memory early * Dumping if data is greater than one MB * OAK-9576: Multithreaded download synchronization issues * Closing node state entry traversors using try with * trivial - removing unused object * OAK-9576: Multithreaded download synchronization issues * Incorporating some feedback from review comments * OAK-9576: Multithreaded download synchronization issues * Replacing explicit synchronization with atomic operations * OAK-9576: Multithreaded download synchronization issues * Using same memory manager across retries * trivial - removing unwanted method * OAK-9576: Multithreaded download synchronization issues * Moving retry delay to exception block * trivial - correcting variable name Co-authored-by: amrverma ",https://github.com/apache/jackrabbit-oak/commit/c04aff5d970beccd41ff15c1c907f7ea6d0720fb,,,oak-run-commons/src/main/java/org/apache/jackrabbit/oak/index/indexer/document/flatfile/TraverseAndSortTask.java,3,java,False,2021-12-01T07:03:04Z "@Override public void openURL(String url, Promise promise) { if (url == null || url.isEmpty()) { promise.reject(new JSApplicationIllegalArgumentException(""Invalid URL: "" + url)); return; } try { Activity currentActivity = getCurrentActivity(); Intent intent = new Intent(Intent.ACTION_VIEW, Uri.parse(url).normalizeScheme()); String selfPackageName = getReactApplicationContext().getPackageName(); ComponentName componentName = intent.resolveActivity(getReactApplicationContext().getPackageManager()); String otherPackageName = (componentName != null ? componentName.getPackageName() : """"); // If there is no currentActivity or we are launching to a different package we need to set // the FLAG_ACTIVITY_NEW_TASK flag if (currentActivity == null || !selfPackageName.equals(otherPackageName)) { intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK); } if (currentActivity != null) { currentActivity.startActivity(intent); } else { getReactApplicationContext().startActivity(intent); } promise.resolve(true); } catch (Exception e) { promise.reject( new JSApplicationIllegalArgumentException( ""Could not open URL '"" + url + ""': "" + e.getMessage())); } }","@Override public void openURL(String url, Promise promise) { if (url == null || url.isEmpty()) { promise.reject(new JSApplicationIllegalArgumentException(""Invalid URL: "" + url)); return; } try { Intent intent = new Intent(Intent.ACTION_VIEW, Uri.parse(url).normalizeScheme()); sendOSIntent(intent, false); promise.resolve(true); } catch (Exception e) { promise.reject( new JSApplicationIllegalArgumentException( ""Could not open URL '"" + url + ""': "" + e.getMessage())); } }","Fix: Set ""new task flag"" for intent method (#29000) Summary: Addresses https://github.com/facebook/react-native/issues/28934 ## Changelog [Android] [Fixed] - When sending OS intents, always set ""FLAG_ACTIVITY_NEW_TASK"" flag (required by OS). Pull Request resolved: https://github.com/facebook/react-native/pull/29000 Test Plan: 1. Open RNTester on Android 2. Go to Linking section 3. Try opening ""POWER_USAGE_SUMMARY"" intent 4. App should open settings, instead of crashing Reviewed By: cortinico Differential Revision: D30876645 Pulled By: lunaleaps fbshipit-source-id: e427bfeadf9fb1ae38bf05bfeafd88e6776d71de",https://github.com/react-native-tvos/react-native-tvos/commit/04fe3ed80d9c201a483a2b477aeebd3d4169fd6d,,,ReactAndroid/src/main/java/com/facebook/react/modules/intent/IntentModule.java,3,java,False,2021-09-13T19:54:58Z "public static void main(String[] args) throws IOException { SlackSession session = SlackSessionFactory.getSlackSessionBuilder(""my-bot-auth-token"").build(); session.connect(); }","public static void main(String[] args) throws IOException { SlackSession session = SlackSessionFactory.getSlackSessionBuilder(""my-bot-auth-token"", ""my-bot-app-level-token"").build(); session.connect(); }","Merge pull request #1 from moults31/moults31/issue283-auth Fix #283, move to new auth token format",https://github.com/Itiviti/simple-slack-api/commit/172ddc4c6952d2c2f9a100abdd7a4eb3897fdb8d,,,samples/connection/src/main/java/com/ullink/slack/simpleslackapi/samples/connection/SlackDirectConnectionWithBuilder.java,3,java,False,2021-10-25T00:57:55Z "@NeverInline(""access stack pointer"") private Integer yield1() { Pointer leafSP = KnownIntrinsics.readCallerStackPointer(); CodePointer leafIP = KnownIntrinsics.readReturnAddress(); Pointer rootSP = sp; CodePointer rootIP = ip; int preemptStatus = StoredContinuationImpl.allocateFromCurrentStack(this, rootSP, leafSP, leafIP); if (preemptStatus != 0) { return preemptStatus; } sp = leafSP; ip = leafIP; KnownIntrinsics.farReturn(0, rootSP, rootIP, false); throw VMError.shouldNotReachHere(); }","@NeverInline(""access stack pointer"") private Integer yield1() { Pointer leafSP = KnownIntrinsics.readCallerStackPointer(); CodePointer leafIP = KnownIntrinsics.readReturnAddress(); Pointer returnSP = sp; CodePointer returnIP = ip; int preemptStatus = StoredContinuationImpl.allocateFromCurrentStack(this, bottomSP, leafSP, leafIP); if (preemptStatus != 0) { return preemptStatus; } ip = leafIP; sp = WordFactory.nullPointer(); bottomSP = WordFactory.nullPointer(); KnownIntrinsics.farReturn(0, returnSP, returnIP, false); throw VMError.shouldNotReachHere(); }","Fix Continuation.enter1 overwriting its own frame, check for stack overflow, and avoid extra heap buffer.",https://github.com/oracle/graal/commit/aadbff556c457e107f5f44706750b11cf569e404,,,substratevm/src/com.oracle.svm.core/src/com/oracle/svm/core/thread/Continuation.java,3,java,False,2022-03-02T18:51:14Z "AvatarStorageResult store(Profile profile, String url);","boolean store(Profile profile, String url);","added ImgurAvatarRepository, removed support for adding insecure custom avatar links",https://github.com/Erudika/scoold/commit/78f60b679d20a48f98ced178b9d93206e02c2637,,,src/main/java/com/erudika/scoold/utils/avatars/AvatarRepository.java,3,java,False,2022-01-19T16:36:35Z "public static void load(String originalName, ClassLoader loader) { // Adjust expected name to support shading of native libraries. String packagePrefix = calculatePackagePrefix().replace('.', '_'); String name = packagePrefix + originalName; List suppressed = new ArrayList<>(); try { // first try to load from java.library.path loadLibrary(loader, name, false); return; } catch (Throwable ex) { suppressed.add(ex); } String libname = System.mapLibraryName(name); String path = NATIVE_RESOURCE_HOME + libname; InputStream in = null; OutputStream out = null; File tmpFile = null; URL url; if (loader == null) { url = ClassLoader.getSystemResource(path); } else { url = loader.getResource(path); } try { if (url == null) { if (PlatformDependent.isOsx()) { String fileName = path.endsWith("".jnilib"") ? NATIVE_RESOURCE_HOME + ""lib"" + name + "".dynlib"" : NATIVE_RESOURCE_HOME + ""lib"" + name + "".jnilib""; if (loader == null) { url = ClassLoader.getSystemResource(fileName); } else { url = loader.getResource(fileName); } if (url == null) { FileNotFoundException fnf = new FileNotFoundException(fileName); ThrowableUtil.addSuppressedAndClear(fnf, suppressed); throw fnf; } } else { FileNotFoundException fnf = new FileNotFoundException(path); ThrowableUtil.addSuppressedAndClear(fnf, suppressed); throw fnf; } } int index = libname.lastIndexOf('.'); String prefix = libname.substring(0, index); String suffix = libname.substring(index); tmpFile = PlatformDependent.createTempFile(prefix, suffix, WORKDIR); in = url.openStream(); out = new FileOutputStream(tmpFile); if (shouldShadedLibraryIdBePatched(packagePrefix)) { patchShadedLibraryId(in, out, originalName, name); } else { byte[] buffer = new byte[8192]; int length; while ((length = in.read(buffer)) > 0) { out.write(buffer, 0, length); } } out.flush(); // Close the output stream before loading the unpacked library, // because otherwise Windows will refuse to load it when it's in use by other process. closeQuietly(out); out = null; loadLibrary(loader, tmpFile.getPath(), true); } catch (UnsatisfiedLinkError e) { try { if (tmpFile != null && tmpFile.isFile() && tmpFile.canRead() && !NoexecVolumeDetector.canExecuteExecutable(tmpFile)) { // Pass ""io.netty.native.workdir"" as an argument to allow shading tools to see // the string. Since this is printed out to users to tell them what to do next, // we want the value to be correct even when shading. logger.info(""{} exists but cannot be executed even when execute permissions set; "" + ""check volume for \""noexec\"" flag; use -D{}=[path] "" + ""to set native working directory separately."", tmpFile.getPath(), ""io.netty.native.workdir""); } } catch (Throwable t) { suppressed.add(t); logger.debug(""Error checking if {} is on a file store mounted with noexec"", tmpFile, t); } // Re-throw to fail the load ThrowableUtil.addSuppressedAndClear(e, suppressed); throw e; } catch (Exception e) { UnsatisfiedLinkError ule = new UnsatisfiedLinkError(""could not load a native library: "" + name); ule.initCause(e); ThrowableUtil.addSuppressedAndClear(ule, suppressed); throw ule; } finally { closeQuietly(in); closeQuietly(out); // After we load the library it is safe to delete the file. // We delete the file immediately to free up resources as soon as possible, // and if this fails fallback to deleting on JVM exit. if (tmpFile != null && (!DELETE_NATIVE_LIB_AFTER_LOADING || !tmpFile.delete())) { tmpFile.deleteOnExit(); } } }","public static void load(String originalName, ClassLoader loader) { // Adjust expected name to support shading of native libraries. String packagePrefix = calculatePackagePrefix().replace('.', '_'); String name = packagePrefix + originalName; List suppressed = new ArrayList<>(); try { // first try to load from java.library.path loadLibrary(loader, name, false); return; } catch (Throwable ex) { suppressed.add(ex); } String libname = System.mapLibraryName(name); String path = NATIVE_RESOURCE_HOME + libname; InputStream in = null; OutputStream out = null; File tmpFile = null; URL url; if (loader == null) { url = ClassLoader.getSystemResource(path); } else { url = loader.getResource(path); } try { if (url == null) { if (PlatformDependent.isOsx()) { String fileName = path.endsWith("".jnilib"") ? NATIVE_RESOURCE_HOME + ""lib"" + name + "".dynlib"" : NATIVE_RESOURCE_HOME + ""lib"" + name + "".jnilib""; if (loader == null) { url = ClassLoader.getSystemResource(fileName); } else { url = loader.getResource(fileName); } if (url == null) { FileNotFoundException fnf = new FileNotFoundException(fileName); ThrowableUtil.addSuppressedAndClear(fnf, suppressed); throw fnf; } } else { FileNotFoundException fnf = new FileNotFoundException(path); ThrowableUtil.addSuppressedAndClear(fnf, suppressed); throw fnf; } } int index = libname.lastIndexOf('.'); String prefix = libname.substring(0, index); String suffix = libname.substring(index); tmpFile = PlatformDependent.createTempFile(prefix, suffix, WORKDIR); in = url.openStream(); out = new FileOutputStream(tmpFile); byte[] buffer = new byte[8192]; int length; while ((length = in.read(buffer)) > 0) { out.write(buffer, 0, length); } out.flush(); if (shouldShadedLibraryIdBePatched(packagePrefix)) { // Let's try to patch the id and re-sign it. This is a best-effort and might fail if a // SecurityManager is setup or the right executables are not installed :/ tryPatchShadedLibraryIdAndSign(tmpFile, originalName); } // Close the output stream before loading the unpacked library, // because otherwise Windows will refuse to load it when it's in use by other process. closeQuietly(out); out = null; loadLibrary(loader, tmpFile.getPath(), true); } catch (UnsatisfiedLinkError e) { try { if (tmpFile != null && tmpFile.isFile() && tmpFile.canRead() && !NoexecVolumeDetector.canExecuteExecutable(tmpFile)) { // Pass ""io.netty.native.workdir"" as an argument to allow shading tools to see // the string. Since this is printed out to users to tell them what to do next, // we want the value to be correct even when shading. logger.info(""{} exists but cannot be executed even when execute permissions set; "" + ""check volume for \""noexec\"" flag; use -D{}=[path] "" + ""to set native working directory separately."", tmpFile.getPath(), ""io.netty.native.workdir""); } } catch (Throwable t) { suppressed.add(t); logger.debug(""Error checking if {} is on a file store mounted with noexec"", tmpFile, t); } // Re-throw to fail the load ThrowableUtil.addSuppressedAndClear(e, suppressed); throw e; } catch (Exception e) { UnsatisfiedLinkError ule = new UnsatisfiedLinkError(""could not load a native library: "" + name); ule.initCause(e); ThrowableUtil.addSuppressedAndClear(ule, suppressed); throw ule; } finally { closeQuietly(in); closeQuietly(out); // After we load the library it is safe to delete the file. // We delete the file immediately to free up resources as soon as possible, // and if this fails fallback to deleting on JVM exit. if (tmpFile != null && (!DELETE_NATIVE_LIB_AFTER_LOADING || !tmpFile.delete())) { tmpFile.deleteOnExit(); } } }","Use install_tool_name and codesign to patch id of shaded library (#11734) Motivation: How we did patch the id of the shaded library could lead to JVM crashes if signature validation was used on macOS. This is the case on m1 for example. Modifications: - Replace our ""hand-rolled"" way of patching the id with using install_tool_name - Re-sign the library after patching the id Result: No more crashes due adjusted id on m1 when shading is used",https://github.com/netty/netty/commit/c1949950258174f0e64942e6b246ebd0763b86ae,,,common/src/main/java/io/netty/util/internal/NativeLibraryLoader.java,3,java,False,2021-10-07T08:54:29Z "protected void initiateTrain(ActionEvent e) { // set Dispatcher defaults _TrainsFrom = _dispatcher.getTrainsFrom(); _ActiveTrainsList = _dispatcher.getActiveTrainsList(); // create window if needed if (initiateFrame == null) { initiateFrame = this; initiateFrame.setTitle(Bundle.getMessage(""AddTrainTitle"")); initiateFrame.addHelpMenu(""package.jmri.jmrit.dispatcher.NewTrain"", true); initiatePane = initiateFrame.getContentPane(); initiatePane.setLayout(new BoxLayout(initiatePane, BoxLayout.Y_AXIS)); // add buttons to load and save train information JPanel p0 = new JPanel(); p0.setLayout(new FlowLayout()); p0.add(loadButton = new JButton(Bundle.getMessage(""LoadButton""))); loadButton.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { loadTrainInfo(e); } }); loadButton.setToolTipText(Bundle.getMessage(""LoadButtonHint"")); p0.add(saveButton = new JButton(Bundle.getMessage(""SaveButton""))); saveButton.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { saveTrainInfo(e,true); } }); saveButton.setToolTipText(Bundle.getMessage(""SaveButtonHint"")); p0.add(deleteButton = new JButton(Bundle.getMessage(""DeleteButton""))); deleteButton.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { deleteTrainInfo(e); } }); deleteButton.setToolTipText(Bundle.getMessage(""DeleteButtonHint"")); // add items relating to both manually run and automatic trains. // Trains From choices. JPanel p0a = new JPanel(); p0a.setBorder(BorderFactory.createTitledBorder(Bundle.getMessage(""TrainsFrom""))); p0a.setLayout(new FlowLayout()); trainsFromButtonGroup.add(radioTrainsFromRoster); trainsFromButtonGroup.add(radioTrainsFromOps); trainsFromButtonGroup.add(radioTrainsFromUser); p0a.add(radioTrainsFromRoster); radioTrainsFromRoster.setToolTipText(Bundle.getMessage(""TrainsFromRosterHint"")); p0a.add(radioTrainsFromOps); radioTrainsFromOps.setToolTipText(Bundle.getMessage(""TrainsFromTrainsHint"")); p0a.add(radioTrainsFromUser); radioTrainsFromUser.setToolTipText(Bundle.getMessage(""TrainsFromUserHint"")); radioTrainsFromOps.addItemListener(new ItemListener() { @Override public void itemStateChanged(ItemEvent e) { if (e.getStateChange() == ItemEvent.SELECTED) { _TrainsFrom = TrainsFrom.TRAINSFROMOPS; setTrainsFromOptions(_TrainsFrom); } } }); radioTrainsFromRoster.addItemListener(new ItemListener() { @Override public void itemStateChanged(ItemEvent e) { if (e.getStateChange() == ItemEvent.SELECTED) { _TrainsFrom = TrainsFrom.TRAINSFROMROSTER; setTrainsFromOptions(_TrainsFrom); } } }); radioTrainsFromUser.addItemListener(new ItemListener() { @Override public void itemStateChanged(ItemEvent e) { if (e.getStateChange() == ItemEvent.SELECTED) { _TrainsFrom = TrainsFrom.TRAINSFROMUSER; setTrainsFromOptions(_TrainsFrom); } } }); p0a.add(allocateCustomSpinner); initiatePane.add(p0a); JPanel p1 = new JPanel(); p1.setLayout(new FlowLayout()); p1.add(new JLabel(Bundle.getMessage(""TransitBoxLabel"") + "" :"")); p1.add(transitSelectBox); transitSelectBox.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { handleTransitSelectionChanged(e); } }); transitSelectBox.setToolTipText(Bundle.getMessage(""TransitBoxHint"")); p1.add(trainBoxLabel); p1.add(trainSelectBox); trainSelectBox.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { handleTrainSelectionChanged(); } }); trainSelectBox.setToolTipText(Bundle.getMessage(""TrainBoxHint"")); rosterComboBox = new RosterEntryComboBox(); initializeFreeRosterEntriesCombo(); rosterComboBox.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { handleRosterSelectionChanged(e); } }); p1.add(rosterComboBox); initiatePane.add(p1); JPanel p1a = new JPanel(); p1a.setLayout(new FlowLayout()); p1a.add(trainFieldLabel); p1a.add(trainNameField); trainNameField.setToolTipText(Bundle.getMessage(""TrainFieldHint"")); p1a.add(dccAddressFieldLabel); p1a.add(dccAddressSpinner); dccAddressSpinner.setToolTipText(Bundle.getMessage(""DccAddressFieldHint"")); initiatePane.add(p1a); JPanel p2 = new JPanel(); p2.setLayout(new FlowLayout()); p2.add(inTransitBox); inTransitBox.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { handleInTransitClick(e); } }); inTransitBox.setToolTipText(Bundle.getMessage(""InTransitBoxHint"")); initiatePane.add(p2); JPanel p3 = new JPanel(); p3.setLayout(new FlowLayout()); p3.add(new JLabel(Bundle.getMessage(""StartingBlockBoxLabel"") + "" :"")); p3.add(startingBlockBox); startingBlockBox.setToolTipText(Bundle.getMessage(""StartingBlockBoxHint"")); startingBlockBox.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { handleStartingBlockSelectionChanged(e); } }); initiatePane.add(p3); JPanel p4 = new JPanel(); p4.setLayout(new FlowLayout()); p4.add(new JLabel(Bundle.getMessage(""DestinationBlockBoxLabel"") + "":"")); p4.add(destinationBlockBox); destinationBlockBox.setToolTipText(Bundle.getMessage(""DestinationBlockBoxHint"")); initiatePane.add(p4); JPanel p4b = new JPanel(); p4b.setBorder(BorderFactory.createTitledBorder(Bundle.getMessage(""AllocateMethodLabel""))); p4b.setLayout(new FlowLayout()); allocateMethodButtonGroup.add(allocateAllTheWayRadioButton); allocateMethodButtonGroup.add(allocateBySafeRadioButton); allocateMethodButtonGroup.add(allocateNumberOfBlocks); p4b.add(allocateAllTheWayRadioButton); allocateAllTheWayRadioButton.setToolTipText(Bundle.getMessage(""AllocateAllTheWayHint"")); p4b.add(allocateBySafeRadioButton); allocateBySafeRadioButton.setToolTipText(Bundle.getMessage(""AllocateSafeHint"")); p4b.add(allocateNumberOfBlocks); allocateNumberOfBlocks.setToolTipText(Bundle.getMessage(""AllocateMethodHint"")); allocateAllTheWayRadioButton.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { handleAllocateAllTheWayButtonChanged(e); } }); allocateBySafeRadioButton.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { handleAllocateBySafeButtonChanged(e); } }); allocateNumberOfBlocks.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { handleAllocateNumberOfBlocksButtonChanged(e); } }); p4b.add(allocateCustomSpinner); allocateCustomSpinner.setToolTipText(Bundle.getMessage(""AllocateMethodHint"")); initiatePane.add(p4b); JPanel p6 = new JPanel(); p6.setLayout(new FlowLayout()); p6.add(resetWhenDoneBox); resetWhenDoneBox.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { handleResetWhenDoneClick(e); } }); resetWhenDoneBox.setToolTipText(Bundle.getMessage(""ResetWhenDoneBoxHint"")); initiatePane.add(p6); JPanel p6a = new JPanel(); p6a.setLayout(new FlowLayout()); ((FlowLayout) p6a.getLayout()).setVgap(1); p6a.add(delayedReStartLabel); p6a.add(delayedReStartBox); p6a.add(resetRestartSensorBox); resetRestartSensorBox.setToolTipText(Bundle.getMessage(""ResetRestartSensorHint"")); resetRestartSensorBox.setSelected(true); delayedReStartBox.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { handleResetWhenDoneClick(e); } }); delayedReStartBox.setToolTipText(Bundle.getMessage(""DelayedReStartHint"")); initiatePane.add(p6a); JPanel p6b = new JPanel(); p6b.setLayout(new FlowLayout()); ((FlowLayout) p6b.getLayout()).setVgap(1); p6b.add(delayMinLabel); p6b.add(delayMinSpinner); // already set to 0 delayMinSpinner.setToolTipText(Bundle.getMessage(""RestartTimedHint"")); p6b.add(delayReStartSensorLabel); p6b.add(delayReStartSensor); delayReStartSensor.setAllowNull(true); handleResetWhenDoneClick(null); initiatePane.add(p6b); initiatePane.add(new JSeparator()); JPanel p10 = new JPanel(); p10.setLayout(new FlowLayout()); p10.add(reverseAtEndBox); reverseAtEndBox.setToolTipText(Bundle.getMessage(""ReverseAtEndBoxHint"")); initiatePane.add(p10); reverseAtEndBox.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { handleReverseAtEndBoxClick(e); } }); JPanel pDelayReverseRestartDetails = new JPanel(); pDelayReverseRestartDetails.setLayout(new FlowLayout()); ((FlowLayout) pDelayReverseRestartDetails.getLayout()).setVgap(1); pDelayReverseRestartDetails.add(delayReverseReStartLabel); pDelayReverseRestartDetails.add(reverseDelayedRestartType); pDelayReverseRestartDetails.add(delayReverseResetSensorBox); delayReverseResetSensorBox.setToolTipText(Bundle.getMessage(""ReverseResetRestartSensorHint"")); delayReverseResetSensorBox.setSelected(true); reverseDelayedRestartType.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { handleReverseAtEndBoxClick(e); } }); reverseDelayedRestartType.setToolTipText(Bundle.getMessage(""ReverseDelayedReStartHint"")); initiatePane.add(pDelayReverseRestartDetails); JPanel pDelayReverseRestartDetails2 = new JPanel(); pDelayReverseRestartDetails2.setLayout(new FlowLayout()); ((FlowLayout) pDelayReverseRestartDetails2.getLayout()).setVgap(1); pDelayReverseRestartDetails2.add(delayReverseMinLabel); pDelayReverseRestartDetails2.add(delayReverseMinSpinner); // already set to 0 delayReverseMinSpinner.setToolTipText(Bundle.getMessage(""ReverseRestartTimedHint"")); pDelayReverseRestartDetails2.add(delayReverseReStartSensorLabel); pDelayReverseRestartDetails2.add(delayReverseReStartSensor); delayReverseReStartSensor.setAllowNull(true); handleReverseAtEndBoxClick(null); initiatePane.add(pDelayReverseRestartDetails2); initiatePane.add(new JSeparator()); JPanel p10a = new JPanel(); p10a.setLayout(new FlowLayout()); p10a.add(terminateWhenDoneBox); terminateWhenDoneBox.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { handleTerminateWhenDoneBoxClick(e); } }); initiatePane.add(p10a); terminateWhenDoneDetails.setLayout(new FlowLayout()); terminateWhenDoneDetails.add(nextTrainLabel); terminateWhenDoneDetails.add(nextTrain); nextTrain.setToolTipText(Bundle.getMessage(""TerminateWhenDoneNextTrainHint"")); initiatePane.add(terminateWhenDoneDetails); handleTerminateWhenDoneBoxClick(null); initiatePane.add(new JSeparator()); JPanel p8 = new JPanel(); p8.setLayout(new FlowLayout()); p8.add(new JLabel(Bundle.getMessage(""PriorityLabel"") + "":"")); p8.add(prioritySpinner); // already set to 5 prioritySpinner.setToolTipText(Bundle.getMessage(""PriorityHint"")); p8.add(new JLabel("" "")); p8.add(new JLabel(Bundle.getMessage(""TrainTypeBoxLabel""))); initializeTrainTypeBox(); p8.add(trainTypeBox); trainTypeBox.setSelectedIndex(1); trainTypeBox.setToolTipText(Bundle.getMessage(""TrainTypeBoxHint"")); initiatePane.add(p8); JPanel p9 = new JPanel(); p9.setLayout(new FlowLayout()); p9.add(new JLabel(Bundle.getMessage(""DelayedStart""))); p9.add(delayedStartBox); delayedStartBox.setToolTipText(Bundle.getMessage(""DelayedStartHint"")); delayedStartBox.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { handleDelayStartClick(e); } }); p9.add(departureTimeLabel); departureHrSpinner.setEditor(new JSpinner.NumberEditor(departureHrSpinner, ""00"")); p9.add(departureHrSpinner); departureHrSpinner.setValue(8); departureHrSpinner.setToolTipText(Bundle.getMessage(""DepartureTimeHrHint"")); p9.add(departureSepLabel); departureMinSpinner.setEditor(new JSpinner.NumberEditor(departureMinSpinner, ""00"")); p9.add(departureMinSpinner); departureMinSpinner.setValue(0); departureMinSpinner.setToolTipText(Bundle.getMessage(""DepartureTimeMinHint"")); p9.add(delaySensor); delaySensor.setAllowNull(true); p9.add(resetStartSensorBox); resetStartSensorBox.setToolTipText(Bundle.getMessage(""ResetStartSensorHint"")); resetStartSensorBox.setSelected(true); handleDelayStartClick(null); initiatePane.add(p9); JPanel p11 = new JPanel(); p11.setLayout(new FlowLayout()); p11.add(loadAtStartupBox); loadAtStartupBox.setToolTipText(Bundle.getMessage(""LoadAtStartupBoxHint"")); loadAtStartupBox.setSelected(false); initiatePane.add(p11); initiatePane.add(new JSeparator()); JPanel p5 = new JPanel(); p5.setLayout(new FlowLayout()); p5.add(autoRunBox); autoRunBox.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { handleAutoRunClick(e); } }); autoRunBox.setToolTipText(Bundle.getMessage(""AutoRunBoxHint"")); autoRunBox.setSelected(false); initiatePane.add(p5); initializeAutoRunItems(); JPanel p7 = new JPanel(); p7.setLayout(new FlowLayout()); JButton cancelButton = null; p7.add(cancelButton = new JButton(Bundle.getMessage(""ButtonCancel""))); cancelButton.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { cancelInitiateTrain(e); } }); cancelButton.setToolTipText(Bundle.getMessage(""CancelButtonHint"")); p7.add(addNewTrainButton = new JButton(Bundle.getMessage(""ButtonCreate""))); addNewTrainButton.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { addNewTrain(e); } }); addNewTrainButton.setToolTipText(Bundle.getMessage(""AddNewTrainButtonHint"")); JPanel mainPane = new JPanel(); mainPane.setLayout(new BoxLayout(mainPane, BoxLayout.Y_AXIS)); JScrollPane scrPane = new JScrollPane(initiatePane); mainPane.add(p0); mainPane.add(scrPane); mainPane.add(p7); initiateFrame.setContentPane(mainPane); switch (_TrainsFrom) { case TRAINSFROMROSTER: radioTrainsFromRoster.setSelected(true); break; case TRAINSFROMOPS: radioTrainsFromOps.setSelected(true); break; case TRAINSFROMUSER: default: radioTrainsFromUser.setSelected(true); } } setAutoRunDefaults(); autoRunBox.setSelected(false); loadAtStartupBox.setSelected(false); initializeFreeTransitsCombo(new ArrayList()); nextTrain.addItem(""""); refreshNextTrainCombo(); setTrainsFromOptions(_TrainsFrom); initiateFrame.pack(); initiateFrame.setVisible(true); }","protected void initiateTrain(ActionEvent e) { // set Dispatcher defaults _TrainsFrom = _dispatcher.getTrainsFrom(); _ActiveTrainsList = _dispatcher.getActiveTrainsList(); // create window if needed if (initiateFrame == null) { initiateFrame = this; initiateFrame.setTitle(Bundle.getMessage(""AddTrainTitle"")); initiateFrame.addHelpMenu(""package.jmri.jmrit.dispatcher.NewTrain"", true); initiatePane = initiateFrame.getContentPane(); initiatePane.setLayout(new BoxLayout(initiatePane, BoxLayout.Y_AXIS)); // add buttons to load and save train information JPanel p0 = new JPanel(); p0.setLayout(new FlowLayout()); p0.add(loadButton = new JButton(Bundle.getMessage(""LoadButton""))); loadButton.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { loadTrainInfo(e); } }); loadButton.setToolTipText(Bundle.getMessage(""LoadButtonHint"")); p0.add(saveButton = new JButton(Bundle.getMessage(""SaveButton""))); saveButton.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { saveTrainInfo(e,_TrainsFrom == TrainsFrom.TRAINSFROMSETLATER ? true : false ); } }); saveButton.setToolTipText(Bundle.getMessage(""SaveButtonHint"")); p0.add(deleteButton = new JButton(Bundle.getMessage(""DeleteButton""))); deleteButton.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { deleteTrainInfo(e); } }); deleteButton.setToolTipText(Bundle.getMessage(""DeleteButtonHint"")); // add items relating to both manually run and automatic trains. // Trains From choices. JPanel p0a = new JPanel(); p0a.setBorder(BorderFactory.createTitledBorder(Bundle.getMessage(""TrainsFrom""))); p0a.setLayout(new FlowLayout()); trainsFromButtonGroup.add(radioTrainsFromRoster); trainsFromButtonGroup.add(radioTrainsFromOps); trainsFromButtonGroup.add(radioTrainsFromUser); trainsFromButtonGroup.add(radioTrainsFromSetLater); p0a.add(radioTrainsFromRoster); radioTrainsFromRoster.setToolTipText(Bundle.getMessage(""TrainsFromRosterHint"")); p0a.add(radioTrainsFromOps); radioTrainsFromOps.setToolTipText(Bundle.getMessage(""TrainsFromTrainsHint"")); p0a.add(radioTrainsFromUser); radioTrainsFromUser.setToolTipText(Bundle.getMessage(""TrainsFromUserHint"")); p0a.add(radioTrainsFromSetLater); radioTrainsFromSetLater.setToolTipText(Bundle.getMessage(""TrainsFromSetLaterHint"")); radioTrainsFromOps.addItemListener(new ItemListener() { @Override public void itemStateChanged(ItemEvent e) { if (e.getStateChange() == ItemEvent.SELECTED) { _TrainsFrom = TrainsFrom.TRAINSFROMOPS; setTrainsFromOptions(_TrainsFrom); } } }); radioTrainsFromRoster.addItemListener(new ItemListener() { @Override public void itemStateChanged(ItemEvent e) { if (e.getStateChange() == ItemEvent.SELECTED) { _TrainsFrom = TrainsFrom.TRAINSFROMROSTER; setTrainsFromOptions(_TrainsFrom); } } }); radioTrainsFromUser.addItemListener(new ItemListener() { @Override public void itemStateChanged(ItemEvent e) { if (e.getStateChange() == ItemEvent.SELECTED) { _TrainsFrom = TrainsFrom.TRAINSFROMUSER; setTrainsFromOptions(_TrainsFrom); } } }); radioTrainsFromSetLater.addItemListener(new ItemListener() { @Override public void itemStateChanged(ItemEvent e) { if (e.getStateChange() == ItemEvent.SELECTED) { _TrainsFrom = TrainsFrom.TRAINSFROMSETLATER; setTrainsFromOptions(_TrainsFrom); } } }); p0a.add(allocateCustomSpinner); initiatePane.add(p0a); JPanel p1 = new JPanel(); p1.setLayout(new FlowLayout()); p1.add(new JLabel(Bundle.getMessage(""TransitBoxLabel"") + "" :"")); p1.add(transitSelectBox); transitSelectBox.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { handleTransitSelectionChanged(e); } }); transitSelectBox.setToolTipText(Bundle.getMessage(""TransitBoxHint"")); p1.add(trainBoxLabel); p1.add(trainSelectBox); trainSelectBox.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { handleTrainSelectionChanged(); } }); trainSelectBox.setToolTipText(Bundle.getMessage(""TrainBoxHint"")); rosterComboBox = new RosterEntryComboBox(); initializeFreeRosterEntriesCombo(); rosterComboBox.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { handleRosterSelectionChanged(e); } }); p1.add(rosterComboBox); initiatePane.add(p1); JPanel p1a = new JPanel(); p1a.setLayout(new FlowLayout()); p1a.add(trainFieldLabel); p1a.add(trainNameField); trainNameField.setToolTipText(Bundle.getMessage(""TrainFieldHint"")); p1a.add(dccAddressFieldLabel); p1a.add(dccAddressSpinner); dccAddressSpinner.setToolTipText(Bundle.getMessage(""DccAddressFieldHint"")); initiatePane.add(p1a); JPanel p2 = new JPanel(); p2.setLayout(new FlowLayout()); p2.add(inTransitBox); inTransitBox.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { handleInTransitClick(e); } }); inTransitBox.setToolTipText(Bundle.getMessage(""InTransitBoxHint"")); initiatePane.add(p2); JPanel p3 = new JPanel(); p3.setLayout(new FlowLayout()); p3.add(new JLabel(Bundle.getMessage(""StartingBlockBoxLabel"") + "" :"")); p3.add(startingBlockBox); startingBlockBox.setToolTipText(Bundle.getMessage(""StartingBlockBoxHint"")); startingBlockBox.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { handleStartingBlockSelectionChanged(e); } }); initiatePane.add(p3); JPanel p4 = new JPanel(); p4.setLayout(new FlowLayout()); p4.add(new JLabel(Bundle.getMessage(""DestinationBlockBoxLabel"") + "":"")); p4.add(destinationBlockBox); destinationBlockBox.setToolTipText(Bundle.getMessage(""DestinationBlockBoxHint"")); initiatePane.add(p4); JPanel p4b = new JPanel(); p4b.setBorder(BorderFactory.createTitledBorder(Bundle.getMessage(""AllocateMethodLabel""))); p4b.setLayout(new FlowLayout()); allocateMethodButtonGroup.add(allocateAllTheWayRadioButton); allocateMethodButtonGroup.add(allocateBySafeRadioButton); allocateMethodButtonGroup.add(allocateNumberOfBlocks); p4b.add(allocateAllTheWayRadioButton); allocateAllTheWayRadioButton.setToolTipText(Bundle.getMessage(""AllocateAllTheWayHint"")); p4b.add(allocateBySafeRadioButton); allocateBySafeRadioButton.setToolTipText(Bundle.getMessage(""AllocateSafeHint"")); p4b.add(allocateNumberOfBlocks); allocateNumberOfBlocks.setToolTipText(Bundle.getMessage(""AllocateMethodHint"")); allocateAllTheWayRadioButton.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { handleAllocateAllTheWayButtonChanged(e); } }); allocateBySafeRadioButton.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { handleAllocateBySafeButtonChanged(e); } }); allocateNumberOfBlocks.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { handleAllocateNumberOfBlocksButtonChanged(e); } }); p4b.add(allocateCustomSpinner); allocateCustomSpinner.setToolTipText(Bundle.getMessage(""AllocateMethodHint"")); initiatePane.add(p4b); JPanel p6 = new JPanel(); p6.setLayout(new FlowLayout()); p6.add(resetWhenDoneBox); resetWhenDoneBox.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { handleResetWhenDoneClick(e); } }); resetWhenDoneBox.setToolTipText(Bundle.getMessage(""ResetWhenDoneBoxHint"")); initiatePane.add(p6); JPanel p6a = new JPanel(); p6a.setLayout(new FlowLayout()); ((FlowLayout) p6a.getLayout()).setVgap(1); p6a.add(delayedReStartLabel); p6a.add(delayedReStartBox); p6a.add(resetRestartSensorBox); resetRestartSensorBox.setToolTipText(Bundle.getMessage(""ResetRestartSensorHint"")); resetRestartSensorBox.setSelected(true); delayedReStartBox.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { handleResetWhenDoneClick(e); } }); delayedReStartBox.setToolTipText(Bundle.getMessage(""DelayedReStartHint"")); initiatePane.add(p6a); JPanel p6b = new JPanel(); p6b.setLayout(new FlowLayout()); ((FlowLayout) p6b.getLayout()).setVgap(1); p6b.add(delayMinLabel); p6b.add(delayMinSpinner); // already set to 0 delayMinSpinner.setToolTipText(Bundle.getMessage(""RestartTimedHint"")); p6b.add(delayReStartSensorLabel); p6b.add(delayReStartSensor); delayReStartSensor.setAllowNull(true); handleResetWhenDoneClick(null); initiatePane.add(p6b); initiatePane.add(new JSeparator()); JPanel p10 = new JPanel(); p10.setLayout(new FlowLayout()); p10.add(reverseAtEndBox); reverseAtEndBox.setToolTipText(Bundle.getMessage(""ReverseAtEndBoxHint"")); initiatePane.add(p10); reverseAtEndBox.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { handleReverseAtEndBoxClick(e); } }); JPanel pDelayReverseRestartDetails = new JPanel(); pDelayReverseRestartDetails.setLayout(new FlowLayout()); ((FlowLayout) pDelayReverseRestartDetails.getLayout()).setVgap(1); pDelayReverseRestartDetails.add(delayReverseReStartLabel); pDelayReverseRestartDetails.add(reverseDelayedRestartType); pDelayReverseRestartDetails.add(delayReverseResetSensorBox); delayReverseResetSensorBox.setToolTipText(Bundle.getMessage(""ReverseResetRestartSensorHint"")); delayReverseResetSensorBox.setSelected(true); reverseDelayedRestartType.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { handleReverseAtEndBoxClick(e); } }); reverseDelayedRestartType.setToolTipText(Bundle.getMessage(""ReverseDelayedReStartHint"")); initiatePane.add(pDelayReverseRestartDetails); JPanel pDelayReverseRestartDetails2 = new JPanel(); pDelayReverseRestartDetails2.setLayout(new FlowLayout()); ((FlowLayout) pDelayReverseRestartDetails2.getLayout()).setVgap(1); pDelayReverseRestartDetails2.add(delayReverseMinLabel); pDelayReverseRestartDetails2.add(delayReverseMinSpinner); // already set to 0 delayReverseMinSpinner.setToolTipText(Bundle.getMessage(""ReverseRestartTimedHint"")); pDelayReverseRestartDetails2.add(delayReverseReStartSensorLabel); pDelayReverseRestartDetails2.add(delayReverseReStartSensor); delayReverseReStartSensor.setAllowNull(true); handleReverseAtEndBoxClick(null); initiatePane.add(pDelayReverseRestartDetails2); initiatePane.add(new JSeparator()); JPanel p10a = new JPanel(); p10a.setLayout(new FlowLayout()); p10a.add(terminateWhenDoneBox); terminateWhenDoneBox.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { handleTerminateWhenDoneBoxClick(e); } }); initiatePane.add(p10a); terminateWhenDoneDetails.setLayout(new FlowLayout()); terminateWhenDoneDetails.add(nextTrainLabel); terminateWhenDoneDetails.add(nextTrain); nextTrain.setToolTipText(Bundle.getMessage(""TerminateWhenDoneNextTrainHint"")); initiatePane.add(terminateWhenDoneDetails); handleTerminateWhenDoneBoxClick(null); initiatePane.add(new JSeparator()); JPanel p8 = new JPanel(); p8.setLayout(new FlowLayout()); p8.add(new JLabel(Bundle.getMessage(""PriorityLabel"") + "":"")); p8.add(prioritySpinner); // already set to 5 prioritySpinner.setToolTipText(Bundle.getMessage(""PriorityHint"")); p8.add(new JLabel("" "")); p8.add(new JLabel(Bundle.getMessage(""TrainTypeBoxLabel""))); initializeTrainTypeBox(); p8.add(trainTypeBox); trainTypeBox.setSelectedIndex(1); trainTypeBox.setToolTipText(Bundle.getMessage(""TrainTypeBoxHint"")); initiatePane.add(p8); JPanel p9 = new JPanel(); p9.setLayout(new FlowLayout()); p9.add(new JLabel(Bundle.getMessage(""DelayedStart""))); p9.add(delayedStartBox); delayedStartBox.setToolTipText(Bundle.getMessage(""DelayedStartHint"")); delayedStartBox.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { handleDelayStartClick(e); } }); p9.add(departureTimeLabel); departureHrSpinner.setEditor(new JSpinner.NumberEditor(departureHrSpinner, ""00"")); p9.add(departureHrSpinner); departureHrSpinner.setValue(8); departureHrSpinner.setToolTipText(Bundle.getMessage(""DepartureTimeHrHint"")); p9.add(departureSepLabel); departureMinSpinner.setEditor(new JSpinner.NumberEditor(departureMinSpinner, ""00"")); p9.add(departureMinSpinner); departureMinSpinner.setValue(0); departureMinSpinner.setToolTipText(Bundle.getMessage(""DepartureTimeMinHint"")); p9.add(delaySensor); delaySensor.setAllowNull(true); p9.add(resetStartSensorBox); resetStartSensorBox.setToolTipText(Bundle.getMessage(""ResetStartSensorHint"")); resetStartSensorBox.setSelected(true); handleDelayStartClick(null); initiatePane.add(p9); JPanel p11 = new JPanel(); p11.setLayout(new FlowLayout()); p11.add(loadAtStartupBox); loadAtStartupBox.setToolTipText(Bundle.getMessage(""LoadAtStartupBoxHint"")); loadAtStartupBox.setSelected(false); initiatePane.add(p11); initiatePane.add(new JSeparator()); JPanel p5 = new JPanel(); p5.setLayout(new FlowLayout()); p5.add(autoRunBox); autoRunBox.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { handleAutoRunClick(e); } }); autoRunBox.setToolTipText(Bundle.getMessage(""AutoRunBoxHint"")); autoRunBox.setSelected(false); initiatePane.add(p5); initializeAutoRunItems(); JPanel p7 = new JPanel(); p7.setLayout(new FlowLayout()); JButton cancelButton = null; p7.add(cancelButton = new JButton(Bundle.getMessage(""ButtonCancel""))); cancelButton.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { cancelInitiateTrain(e); } }); cancelButton.setToolTipText(Bundle.getMessage(""CancelButtonHint"")); p7.add(addNewTrainButton = new JButton(Bundle.getMessage(""ButtonCreate""))); addNewTrainButton.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { addNewTrain(e); } }); addNewTrainButton.setToolTipText(Bundle.getMessage(""AddNewTrainButtonHint"")); JPanel mainPane = new JPanel(); mainPane.setLayout(new BoxLayout(mainPane, BoxLayout.Y_AXIS)); JScrollPane scrPane = new JScrollPane(initiatePane); mainPane.add(p0); mainPane.add(scrPane); mainPane.add(p7); initiateFrame.setContentPane(mainPane); switch (_TrainsFrom) { case TRAINSFROMROSTER: radioTrainsFromRoster.setSelected(true); break; case TRAINSFROMOPS: radioTrainsFromOps.setSelected(true); break; case TRAINSFROMUSER: radioTrainsFromUser.setSelected(true); break; case TRAINSFROMSETLATER: default: radioTrainsFromSetLater.setSelected(true); } } setAutoRunDefaults(); autoRunBox.setSelected(false); loadAtStartupBox.setSelected(false); initializeFreeTransitsCombo(new ArrayList()); nextTrain.addItem(""""); refreshNextTrainCombo(); setTrainsFromOptions(_TrainsFrom); initiateFrame.pack(); initiateFrame.setVisible(true); }","Make it explicit that the user is saving a template. Fix crash in create, reload traininfo file.",https://github.com/JMRI/JMRI/commit/9776f71876fbb6485b4f90ab1738cdd03d87af97,,,java/src/jmri/jmrit/dispatcher/ActivateTrainFrame.java,3,java,False,2022-06-24T00:08:56Z "public void exitPrivateMode() { if (!mPrivateMode) { return; } mPrivateMode = false; if (mFocusedWindow != null) { mPrivateWindowPlacement = mFocusedWindow.getWindowPlacement(); } else { mPrivateWindowPlacement = WindowPlacement.FRONT; } for (int i=0; i { webview = new WebView(); webview.getEngine().load(url); jfxP.setScene(new Scene(webview)); }); setVisible(true); }","private void build(String url) { ProxyManager.enforceGlobalProxySetting(); setLayout(new BorderLayout()); JFXPanel jfxP = new JFXPanel(); add(jfxP, BorderLayout.CENTER); setResizable(false); setMinimumSize(new Dimension(600, 800)); setDefaultCloseOperation(DISPOSE_ON_CLOSE); pack(); setLocationRelativeTo(getParent()); Jobs.runJFXLater(() -> { webview = new WebView(); webview.getEngine().load(url); jfxP.setScene(new Scene(webview)); }); setVisible(true); }",Fixed missing proxy usage for WebView and AuthService,https://github.com/boecker-lab/sirius/commit/43746f8e339484cad07c054fb6e2a8d1cb091f2e,,,sirius_gui/src/main/java/de/unijena/bioinf/ms/gui/webView/WebViewBrowserDialog.java,3,java,False,2021-10-13T15:18:26Z "private PendingIntent getPendingIntent(Intent intent, int flag) { return PendingIntent.getService(context, 0, intent, flag); }","private PendingIntent getPendingIntent(Intent intent, int flag) { // Android 31+ requires FLAG_IMMUTABLE explicitly return PendingIntent.getService(context, 0, intent, flag | PendingIntent.FLAG_IMMUTABLE); }","chore: fix to support android-12+ (#400) Fix for android 12+ support (app crashes with PendingIntent flag requirement when built with targetSdkVersion=31) - upgrade dependency ""androidx.work:work-runtime"" to 2.7.1 - add ""android:exported"" to test-app activities - upgrade compileSDKVersion/targetSDKVersion to 32",https://github.com/optimizely/android-sdk/commit/7575bad6fa506667c0cd65abd813e98be3223afe,,,shared/src/main/java/com/optimizely/ab/android/shared/ServiceScheduler.java,3,java,False,2022-04-01T22:46:18Z "public Set getParents() { if (parents == null) { parents = new HashSet<>(); if (value.getSuperName() != null) { InheritanceVertex parentVertex = lookup.apply(value.getSuperName()); if (parentVertex != null) parents.add(parentVertex); } for (String itf : value.getInterfaces()) { InheritanceVertex itfVertex = lookup.apply(itf); if (itfVertex != null) parents.add(itfVertex); } } return parents; }","public Set getParents() { String name = getName(); if (parents == null) { parents = new HashSet<>(); String superName = value.getSuperName(); if (superName != null && !name.equals(superName)) { InheritanceVertex parentVertex = lookup.apply(superName); if (parentVertex != null) parents.add(parentVertex); } for (String itf : value.getInterfaces()) { InheritanceVertex itfVertex = lookup.apply(itf); if (itfVertex != null && !name.equals(itf)) parents.add(itfVertex); } } return parents; }",Prevent inheritance graph infinite loops with 'x extends x' logic,https://github.com/Col-E/Recaf/commit/53da1d3adf0e831e89f5f580c1bf4e08d81c9a6c,,,recaf-core/src/main/java/me/coley/recaf/graph/InheritanceVertex.java,3,java,False,2022-01-08T08:33:46Z "public boolean isAuthenticated() { return (!securityService.isIntegratedSecurity()) || subject != null; }","public boolean isAuthenticated() { return (!securityService.isEnabled()) || subject != null; }","GEODE-9676: Limit array and string sizes for unauthenticated Radish connections (#6994) - This applies the same fix as introduced by CVE-2021-32675 for Redis. When security is enabled, unuauthenticated requests limit the size of arrays and bulk strings to 10 and 16384 respectively. Once connections are authenticated, the size restriction is not applied. - When security is not enabled, this restriction does not apply. - Re-enable the relevant Redis TCL test.",https://github.com/apache/geode/commit/4398bec6eac70ee7bfa3b296655a8326543fc3b7,,,geode-for-redis/src/main/java/org/apache/geode/redis/internal/netty/ExecutionHandlerContext.java,3,java,False,2021-10-19T15:29:54Z "function serializeToString(node,buf,isHTML,nodeFilter,visibleNamespaces){ if(nodeFilter){ node = nodeFilter(node); if(node){ if(typeof node == 'string'){ buf.push(node); return; } }else{ return; } //buf.sort.apply(attrs, attributeSorter); } switch(node.nodeType){ case ELEMENT_NODE: if (!visibleNamespaces) visibleNamespaces = []; var startVisibleNamespaces = visibleNamespaces.length; var attrs = node.attributes; var len = attrs.length; var child = node.firstChild; var nodeName = node.tagName; isHTML = (htmlns === node.namespaceURI) ||isHTML buf.push('<',nodeName); for(var i=0;i'); //if is cdata child node if(isHTML && /^script$/i.test(nodeName)){ while(child){ if(child.data){ buf.push(child.data); }else{ serializeToString(child,buf,isHTML,nodeFilter,visibleNamespaces); } child = child.nextSibling; } }else { while(child){ serializeToString(child,buf,isHTML,nodeFilter,visibleNamespaces); child = child.nextSibling; } } buf.push(''); }else{ buf.push('/>'); } // remove added visible namespaces //visibleNamespaces.length = startVisibleNamespaces; return; case DOCUMENT_NODE: case DOCUMENT_FRAGMENT_NODE: var child = node.firstChild; while(child){ serializeToString(child,buf,isHTML,nodeFilter,visibleNamespaces); child = child.nextSibling; } return; case ATTRIBUTE_NODE: return buf.push(' ',node.name,'=""',node.value.replace(/[&""]/g,_xmlEncoder),'""'); case TEXT_NODE: /** * The ampersand character (&) and the left angle bracket (<) must not appear in their literal form, * except when used as markup delimiters, or within a comment, a processing instruction, or a CDATA section. * If they are needed elsewhere, they must be escaped using either numeric character references or the strings * `&` and `<` respectively. * The right angle bracket (>) may be represented using the string "" > "", and must, for compatibility, * be escaped using either `>` or a character reference when it appears in the string `]]>` in content, * when that string is not marking the end of a CDATA section. * * In the content of elements, character data is any string of characters * which does not contain the start-delimiter of any markup * and does not include the CDATA-section-close delimiter, `]]>`. * * @see https://www.w3.org/TR/xml/#NT-CharData */ return buf.push(node.data .replace(/[<&]/g,_xmlEncoder) .replace(/]]>/g, ']]>') ); case CDATA_SECTION_NODE: return buf.push( ''); case COMMENT_NODE: return buf.push( """"); case DOCUMENT_TYPE_NODE: var pubid = node.publicId; var sysid = node.systemId; buf.push(''); }else if(sysid && sysid!='.'){ buf.push(' SYSTEM ""',sysid,'"">'); }else{ var sub = node.internalSubset; if(sub){ buf.push("" ["",sub,""]""); } buf.push("">""); } return; case PROCESSING_INSTRUCTION_NODE: return buf.push( """"); case ENTITY_REFERENCE_NODE: return buf.push( '&',node.nodeName,';'); //case ENTITY_NODE: //case NOTATION_NODE: default: buf.push('??',node.nodeName); } }","function serializeToString(node,buf,isHTML,nodeFilter,visibleNamespaces){ if(nodeFilter){ node = nodeFilter(node); if(node){ if(typeof node == 'string'){ buf.push(node); return; } }else{ return; } //buf.sort.apply(attrs, attributeSorter); } switch(node.nodeType){ case ELEMENT_NODE: if (!visibleNamespaces) visibleNamespaces = []; var startVisibleNamespaces = visibleNamespaces.length; var attrs = node.attributes; var len = attrs.length; var child = node.firstChild; var nodeName = node.tagName; isHTML = (htmlns === node.namespaceURI) ||isHTML buf.push('<',nodeName); for(var i=0;i'); //if is cdata child node if(isHTML && /^script$/i.test(nodeName)){ while(child){ if(child.data){ buf.push(child.data); }else{ serializeToString(child,buf,isHTML,nodeFilter,visibleNamespaces); } child = child.nextSibling; } }else { while(child){ serializeToString(child,buf,isHTML,nodeFilter,visibleNamespaces); child = child.nextSibling; } } buf.push(''); }else{ buf.push('/>'); } // remove added visible namespaces //visibleNamespaces.length = startVisibleNamespaces; return; case DOCUMENT_NODE: case DOCUMENT_FRAGMENT_NODE: var child = node.firstChild; while(child){ serializeToString(child,buf,isHTML,nodeFilter,visibleNamespaces); child = child.nextSibling; } return; case ATTRIBUTE_NODE: return buf.push(' ',node.name,'=""',node.value.replace(/[&""]/g,_xmlEncoder),'""'); case TEXT_NODE: /** * The ampersand character (&) and the left angle bracket (<) must not appear in their literal form, * except when used as markup delimiters, or within a comment, a processing instruction, or a CDATA section. * If they are needed elsewhere, they must be escaped using either numeric character references or the strings * `&` and `<` respectively. * The right angle bracket (>) may be represented using the string "" > "", and must, for compatibility, * be escaped using either `>` or a character reference when it appears in the string `]]>` in content, * when that string is not marking the end of a CDATA section. * * In the content of elements, character data is any string of characters * which does not contain the start-delimiter of any markup * and does not include the CDATA-section-close delimiter, `]]>`. * * @see https://www.w3.org/TR/xml/#NT-CharData */ return buf.push(node.data .replace(/[<&]/g,_xmlEncoder) .replace(/]]>/g, ']]>') ); case CDATA_SECTION_NODE: return buf.push( ''); case COMMENT_NODE: return buf.push( """"); case DOCUMENT_TYPE_NODE: var pubid = node.publicId; var sysid = node.systemId; buf.push(''); }else if(sysid && sysid!='.'){ buf.push(' SYSTEM ', sysid, '>'); }else{ var sub = node.internalSubset; if(sub){ buf.push("" ["",sub,""]""); } buf.push("">""); } return; case PROCESSING_INSTRUCTION_NODE: return buf.push( """"); case ENTITY_REFERENCE_NODE: return buf.push( '&',node.nodeName,';'); //case ENTITY_NODE: //case NOTATION_NODE: default: buf.push('??',node.nodeName); } }","Merge pull request from GHSA-h6q6-9hqw-rwfv * fix!: Preserve quotes in DOCTYPE declaration Since the only purpose of parsing the DOCTYPE is to be able to restore it when serializing, we decided that it would be best to leave the parsed publicId and systemId as is, including any quotes. BREAKING CHANGE: If somebody relies on the actual unquoted values of those ids, they will need to take care of either single or double quotes and the right escaping. (Without this change this would not have been possible because the SAX parser already dropped the information about the quotes that have been used in the source.) https://www.w3.org/TR/2006/REC-xml11-20060816/#dtd https://www.w3.org/TR/2006/REC-xml11-20060816/#IDAX1KS (External Entity Declaration) Co-authored-by: Christian Bewernitz Co-authored-by: Chris Brody * feat(security): Improve error reporting; throw on duplicate attribute BREAKING CHANGE: It is currently not clear how to consistently deal with duplicate attributes, so it is also safer for our users to fail when detecting them. It is possible to configure the `DOMParser.errorHandler` before parsing, to handle those errors differently. To accomplish this and also be able to verify it in tests we needed to: - create a new `Error` type `ParseError` and export it - Throw `ParseError` from `errorHandler.fatalError` and prevent those from being caught in `XMLReader`. - export `DOMHandler` constructor as `__DOMHandler` Co-authored-by: Christian Bewernitz Co-authored-by: Chris Brody Co-authored-by: Christian Bewernitz ",https://github.com/xmldom/xmldom/commit/d4201b9dfbf760049f457f9f08a3888d48835135,CVE-2021-21366,"['CWE-115', 'CWE-436']",lib/dom.js,3,js,False,2021-03-09T03:21:56Z "public int getStyle() { return (mStyle == ReactTextShadowNode.UNSET ? 0 : mStyle); }","public int getStyle() { return mStyle == ReactBaseTextShadowNode.UNSET ? Typeface.NORMAL : mStyle; }","RN: Unify Typeface Logic (Android) Summary: Refactors how `Typeface` style and weight are applied in React Native on Android. - Unifies all style and weight normalization logic into a new `TypefaceStyle` class. - Fixes font weight support for the Fabric renderer. - De-duplicates code with `TextAttributeProps`. - Simplified normalization logic. - Fixes a rare crash due to `Typeface.sDefaultTypeface` (Android SDK) being `null`. - Adds a new example to test font weights in `TextInput`. - Adds missing `Nullsafe` and `Nullable` annotations. - Clean up a bunch of obsolete inline comments. Changelog: [Android][Fixed] - Fixed a rare crash due to `Typeface.sDefaultTypeface` (Android SDK) being `null`. [Android][Fixed] - Fixed font weight support for the Fabric renderer. [Android][Added] - Added a new example to test font weights in `TextInput`. Reviewed By: JoshuaGross Differential Revision: D29631134 fbshipit-source-id: 3f227d84253104fa828a5561b77ba7a9cbc030c4",https://github.com/react-native-tvos/react-native-tvos/commit/9d2fedc6e22ca1b45fbc2059971cd194de5d0170,,,ReactAndroid/src/main/java/com/facebook/react/views/text/CustomStyleSpan.java,3,java,False,2021-07-13T05:16:00Z "@Override public boolean canAuthenticate(RequestContext requestContext) { if (isJWTEnabled(requestContext)) { String authHeaderValue = retrieveAuthHeaderValue(requestContext); return authHeaderValue != null && authHeaderValue.trim().split(""\\s+"").length == 2 && authHeaderValue.split(""\\."").length == 3; } return false; }","@Override public boolean canAuthenticate(RequestContext requestContext) { if (isJWTEnabled(requestContext)) { String authHeaderValue = retrieveAuthHeaderValue(requestContext); // Check keyword bearer in header to prevent conflicts with custom authentication // (that maybe added with custom filters / interceptors / opa) // which also includes a jwt in the auth header yet with a scheme other than 'bearer'. // // StringUtils.startsWithIgnoreCase(null, ""bearer"") = false // StringUtils.startsWithIgnoreCase(""abc"", ""bearer"") = false // StringUtils.startsWithIgnoreCase(""Bearer abc"", ""bearer"") = true return StringUtils.startsWithIgnoreCase(authHeaderValue, JWTConstants.BEARER) && authHeaderValue.trim().split(""\\s+"").length == 2 && authHeaderValue.split(""\\."").length == 3; } return false; }","Check keyword bearer in the canAuthenticate method for oauth token This prevents conflicts with custom authentication (that maybe added with custom filters / interceptors / opa) which also includes a jwt in the auth header yet with a scheme other than ""bearer"".",https://github.com/wso2/product-microgateway/commit/7185316d4a65661c665a43d5f261958704f8c45d,,,enforcer-parent/enforcer/src/main/java/org/wso2/choreo/connect/enforcer/security/jwt/JWTAuthenticator.java,3,java,False,2022-08-19T06:27:04Z "private ByteBuffer softCopy(long position, int length) { final int offset = toIntExact(position); return wrap(actingBuffer.array(), offset, min(length, actingBuffer.limit() - offset)).slice(); }","private ByteBuffer softCopy(long position, int length) { final int offset = toIntExact(position); return wrap(actingBuffer.array(), offset + actingBuffer.arrayOffset(), min(length, actingBuffer.limit() - offset)).slice(); }",Fixing buffer overflow issues after memory management changes,https://github.com/mulesoft/mule/commit/e778e5f8ab9083a3a9676ff59a6d795a74458097,,,core/src/main/java/org/mule/runtime/core/internal/streaming/bytes/InMemoryStreamBuffer.java,3,java,False,2022-02-05T22:52:07Z "@Bean public Docket createRestApi() { return new Docket(DocumentationType.OAS_30) .enable(swaggerEnabled) .apiInfo(apiInfo()) .securitySchemes( Collections.singletonList( HttpAuthenticationScheme.JWT_BEARER_BUILDER.name(""BearerToken"").build())) .securityContexts( Collections.singletonList( new SecurityContextBuilder() .securityReferences( Collections.singletonList( SecurityReference.builder() .scopes(new AuthorizationScope[0]) .reference(""BearerToken"") .build())) .operationSelector(s -> true) .build())) .select() .apis(RequestHandlerSelectors.withMethodAnnotation(ApiOperation.class)) .paths(PathSelectors.any()) .build(); }","@Bean public Docket createRestApi() { return new Docket(DocumentationType.OAS_30) .enable(swaggerEnabled) .apiInfo(apiInfo()) .securitySchemes( Collections.singletonList(new ApiKey(""Authorization"", ""Authorization"", ""header""))) .securityContexts( Collections.singletonList( new SecurityContextBuilder() .securityReferences( Collections.singletonList( SecurityReference.builder() .scopes(new AuthorizationScope[0]) .reference(""Authorization"") .build())) .operationSelector(s -> true) .build())) .select() .apis(RequestHandlerSelectors.withMethodAnnotation(ApiOperation.class)) .paths(PathSelectors.any()) .build(); }",[Bug] fix token authorization failed from swagger-ui (#2289),https://github.com/apache/incubator-streampark/commit/de93204101312386eb1f7311f2e51ea41891e0ba,,,streampark-console/streampark-console-service/src/main/java/org/apache/streampark/console/base/config/SwaggerConfig.java,3,java,False,2023-02-02T04:59:51Z "static int peer_recv_callback(rdpTransport* transport, wStream* s, void* extra) { freerdp_peer* client = (freerdp_peer*) extra; rdpRdp* rdp = client->context->rdp; switch (rdp->state) { case CONNECTION_STATE_INITIAL: if (!rdp_server_accept_nego(rdp, s)) return -1; if (rdp->nego->selected_protocol & PROTOCOL_NLA) { sspi_CopyAuthIdentity(&client->identity, &(rdp->nego->transport->credssp->identity)); IFCALLRET(client->Logon, client->authenticated, client, &client->identity, TRUE); credssp_free(rdp->nego->transport->credssp); } else { IFCALLRET(client->Logon, client->authenticated, client, &client->identity, FALSE); } break; case CONNECTION_STATE_NEGO: if (!rdp_server_accept_mcs_connect_initial(rdp, s)) return -1; break; case CONNECTION_STATE_MCS_CONNECT: if (!rdp_server_accept_mcs_erect_domain_request(rdp, s)) return -1; break; case CONNECTION_STATE_MCS_ERECT_DOMAIN: if (!rdp_server_accept_mcs_attach_user_request(rdp, s)) return -1; break; case CONNECTION_STATE_MCS_ATTACH_USER: if (!rdp_server_accept_mcs_channel_join_request(rdp, s)) return -1; break; case CONNECTION_STATE_MCS_CHANNEL_JOIN: if (rdp->settings->DisableEncryption) { if (!rdp_server_accept_client_keys(rdp, s)) return -1; break; } rdp->state = CONNECTION_STATE_ESTABLISH_KEYS; /* FALLTHROUGH */ case CONNECTION_STATE_ESTABLISH_KEYS: if (!rdp_server_accept_client_info(rdp, s)) return -1; IFCALL(client->Capabilities, client); if (!rdp_send_demand_active(rdp)) return -1; break; case CONNECTION_STATE_LICENSE: if (!rdp_server_accept_confirm_active(rdp, s)) { /** * During reactivation sequence the client might sent some input or channel data * before receiving the Deactivate All PDU. We need to process them as usual. */ Stream_SetPosition(s, 0); return peer_recv_pdu(client, s); } break; case CONNECTION_STATE_ACTIVE: if (peer_recv_pdu(client, s) < 0) return -1; break; default: fprintf(stderr, ""Invalid state %d\n"", rdp->state); return -1; } return 0; }","static int peer_recv_callback(rdpTransport* transport, wStream* s, void* extra) { freerdp_peer* client = (freerdp_peer*) extra; rdpRdp* rdp = client->context->rdp; switch (rdp->state) { case CONNECTION_STATE_INITIAL: if (!rdp_server_accept_nego(rdp, s)) return -1; if (rdp->nego->selected_protocol & PROTOCOL_NLA) { sspi_CopyAuthIdentity(&client->identity, &(rdp->nego->transport->credssp->identity)); IFCALLRET(client->Logon, client->authenticated, client, &client->identity, TRUE); credssp_free(rdp->nego->transport->credssp); rdp->nego->transport->credssp = NULL; } else { IFCALLRET(client->Logon, client->authenticated, client, &client->identity, FALSE); } break; case CONNECTION_STATE_NEGO: if (!rdp_server_accept_mcs_connect_initial(rdp, s)) return -1; break; case CONNECTION_STATE_MCS_CONNECT: if (!rdp_server_accept_mcs_erect_domain_request(rdp, s)) return -1; break; case CONNECTION_STATE_MCS_ERECT_DOMAIN: if (!rdp_server_accept_mcs_attach_user_request(rdp, s)) return -1; break; case CONNECTION_STATE_MCS_ATTACH_USER: if (!rdp_server_accept_mcs_channel_join_request(rdp, s)) return -1; break; case CONNECTION_STATE_MCS_CHANNEL_JOIN: if (rdp->settings->DisableEncryption) { if (!rdp_server_accept_client_keys(rdp, s)) return -1; break; } rdp->state = CONNECTION_STATE_ESTABLISH_KEYS; /* FALLTHROUGH */ case CONNECTION_STATE_ESTABLISH_KEYS: if (!rdp_server_accept_client_info(rdp, s)) return -1; IFCALL(client->Capabilities, client); if (!rdp_send_demand_active(rdp)) return -1; break; case CONNECTION_STATE_LICENSE: if (!rdp_server_accept_confirm_active(rdp, s)) { /** * During reactivation sequence the client might sent some input or channel data * before receiving the Deactivate All PDU. We need to process them as usual. */ Stream_SetPosition(s, 0); return peer_recv_pdu(client, s); } break; case CONNECTION_STATE_ACTIVE: if (peer_recv_pdu(client, s) < 0) return -1; break; default: fprintf(stderr, ""Invalid state %d\n"", rdp->state); return -1; } return 0; }","nla: invalidate sec handle after creation If sec pointer isn't invalidated after creation it is not possible to check if the upper and lower pointers are valid. This fixes a segfault in the server part if the client disconnects before the authentication was finished.",https://github.com/FreeRDP/FreeRDP/commit/0773bb9303d24473fe1185d85a424dfe159aff53,,,libfreerdp/core/peer.c,3,c,False,2013-07-01T17:24:19Z "@Override public int registerNetworkProvider(Messenger messenger, String name) { enforceNetworkFactoryOrSettingsPermission(); NetworkProviderInfo npi = new NetworkProviderInfo(name, messenger, nextNetworkProviderId(), () -> unregisterNetworkProvider(messenger)); mHandler.sendMessage(mHandler.obtainMessage(EVENT_REGISTER_NETWORK_PROVIDER, npi)); return npi.providerId; }","@Override public int registerNetworkProvider(Messenger messenger, String name) { enforceNetworkFactoryOrSettingsPermission(); Objects.requireNonNull(messenger, ""messenger must be non-null""); NetworkProviderInfo npi = new NetworkProviderInfo(name, messenger, nextNetworkProviderId(), () -> unregisterNetworkProvider(messenger)); mHandler.sendMessage(mHandler.obtainMessage(EVENT_REGISTER_NETWORK_PROVIDER, npi)); return npi.providerId; }","Handle null pointer cases in ConnectivityService If a method is called by adb command ""service call"" with no parameters. It will cause to crash because of a null object reference. Add a null check for them to avoid system server crash. Bug: 172885426 Test: FrameworksNetTest adb shell service call connectivity # Change-Id: I8748fc5c6a7a6e82db3581e3026a3f75909a357e",https://github.com/omnirom/android_frameworks_base/commit/abbee6e7c6568b588c9354660256bb55ac47e6a0,,,services/core/java/com/android/server/ConnectivityService.java,3,java,False,2021-04-09T04:06:42Z "@Override public void commit() throws RemoteException { if (mPid == 0) { throw new RemoteException(""Invalid process""); } synchronized (mGlobalLock) { final WindowProcessController wpc = mProcessMap.getProcess(mPid); if (wpc == null) { Slog.w(TAG, ""Override application configuration: cannot find application""); return; } if (wpc.getNightMode() == mNightMode) { return; } if (!wpc.setOverrideNightMode(mNightMode)) { return; } wpc.updateNightModeForAllActivities(mNightMode); mPackageConfigPersister.updateFromImpl(wpc.mName, wpc.mUserId, this); } }","@Override public void commit() { synchronized (mGlobalLock) { final long ident = Binder.clearCallingIdentity(); try { final WindowProcessController wpc = mProcessMap.getProcess(mPid); if (wpc == null) { Slog.w(TAG, ""Override application configuration: cannot find pid "" + mPid); return; } if (wpc.getNightMode() == mNightMode) { return; } if (!wpc.setOverrideNightMode(mNightMode)) { return; } wpc.updateNightModeForAllActivities(mNightMode); mPackageConfigPersister.updateFromImpl(wpc.mName, wpc.mUserId, this); } finally { Binder.restoreCallingIdentity(ident); } } }","Fix setApplicationNightMode crash due to permission denial. Test activity crash when calling UiModeManager#setApplicationNightMode. There should call clearCallingIdentity before updating configuration in system server. Also clear some code around those methods. Fixes: 189166288 Test: atest SplashscreenTests#testSetApplicationNightMode Change-Id: I163919927030f81739aa3d9520e2012a92028793",https://github.com/omnirom/android_frameworks_base/commit/d22e8b14034c27ea45962b01a6dc31edafac6763,,,services/core/java/com/android/server/wm/ActivityTaskManagerService.java,3,java,False,2021-05-25T08:31:45Z "@GuardedBy(""mSessions"") private void reconcileStagesLocked(String volumeUuid) { final ArraySet unclaimedStages = getStagingDirsOnVolume(volumeUuid); // Ignore stages claimed by active sessions for (int i = 0; i < mSessions.size(); i++) { final PackageInstallerSession session = mSessions.valueAt(i); unclaimedStages.remove(session.stageDir); } removeStagingDirs(unclaimedStages); }","@GuardedBy(""mSessions"") private void reconcileStagesLocked(String volumeUuid) { final File stagingDir = getTmpSessionDir(volumeUuid); final ArraySet unclaimedStages = newArraySet( stagingDir.listFiles(sStageFilter)); // Ignore stages claimed by active sessions for (int i = 0; i < mSessions.size(); i++) { final PackageInstallerSession session = mSessions.valueAt(i); unclaimedStages.remove(session.stageDir); } // Clean up orphaned staging directories for (File stage : unclaimedStages) { Slog.w(TAG, ""Deleting orphan stage "" + stage); synchronized (mPm.mInstallLock) { mPm.removeCodePathLI(stage); } } }","[RESTRICT AUTOMERGE] Revert ""Revert ""Revert ""[pm] remove old stage dirs on low storage"""""" This reverts commit 3e28df68fa23add99c84507bdcd9f0270311f1fc. Reason for revert: Reverting CVE-2021-39624 on qt-dev Change-Id: I26c0abd06e2a49e05f45d153c4247f7c0a269897",https://github.com/LineageOS/android_frameworks_base/commit/dde06fe41d59d7106c604fc848d46be3d17d2942,,,services/core/java/com/android/server/pm/PackageInstallerService.java,3,java,False,2022-06-28T01:08:51Z "@Override public T get(DbKey dbKey) { T t = cache.getIfPresent(dbKey); if (t == null) { t = super.get(dbKey); if (t != null) { log.info(""{} PUT MISSING FROM THE DB dbKey: {}, height: {}, entity: {}"", tableLogHeader(), dbKey, t.getHeight(), t); cache.put(dbKey, t); } } return t; }","@Override public T get(DbKey dbKey) { T t = cache.getIfPresent(dbKey); if (t == null) { t = super.get(dbKey); if (t != null) { synchronized (lock) { t = super.get(dbKey); if (t != null) { log.info(""{} PUT MISSING FROM THE DB dbKey: {}, height: {}, entity: {}"", tableLogHeader(), dbKey, t.getHeight(), t); cache.put(dbKey, t); } } } } return t; }","Add synchronization of the CachedTable inner cache updates, bcause 'T get(DbKey key)' method lead to cache inconsistency during rollback/truncate/deleteAtHeight/insert operations cause the previous stale version could be loaded. Fix failed pop off infinite loop, add stacktrace logs",https://github.com/ApolloFoundation/Apollo/commit/732034707384ee817c692684042304020f1f4e3c,,,apl-core/src/main/java/com/apollocurrency/aplwallet/apl/core/dao/state/derived/CachedTable.java,3,java,False,2021-06-01T15:05:45Z "public void handlePartitionMetadataResponse(CommandPartitionedTopicMetadata partitionMetadata) { partitionsMetadataRequests.inc(); if (log.isDebugEnabled()) { log.debug(""[{}] Received PartitionMetadataLookup"", clientAddress); } final long clientRequestId = partitionMetadata.getRequestId(); if (this.service.getLookupRequestSemaphore().tryAcquire()) { handlePartitionMetadataResponse(partitionMetadata, clientRequestId); this.service.getLookupRequestSemaphore().release(); } else { rejectedPartitionsMetadataRequests.inc(); if (log.isDebugEnabled()) { log.debug(""PartitionMetaData Request ID {} from {} rejected - {}."", clientRequestId, clientAddress, throttlingErrorMessage); } proxyConnection.ctx().writeAndFlush(Commands.newPartitionMetadataResponse(ServerError.ServiceNotReady, throttlingErrorMessage, clientRequestId)); } }","public void handlePartitionMetadataResponse(CommandPartitionedTopicMetadata partitionMetadata) { partitionsMetadataRequests.inc(); if (log.isDebugEnabled()) { log.debug(""[{}] Received PartitionMetadataLookup"", clientAddress); } final long clientRequestId = partitionMetadata.getRequestId(); if (lookupRequestSemaphore.tryAcquire()) { try { handlePartitionMetadataResponse(partitionMetadata, clientRequestId); } finally { lookupRequestSemaphore.release(); } } else { rejectedPartitionsMetadataRequests.inc(); if (log.isDebugEnabled()) { log.debug(""PartitionMetaData Request ID {} from {} rejected - {}."", clientRequestId, clientAddress, throttlingErrorMessage); } proxyConnection.ctx().writeAndFlush(Commands.newPartitionMetadataResponse(ServerError.ServiceNotReady, throttlingErrorMessage, clientRequestId)); } }","[Proxy] Prevent leak of unreleased lookupRequestSemaphore permits (#13812) * [Proxy] Prevent leak of unreleased lookupRequestSemaphore permits - should release permit in try-finally block * Cleanup code in LookupProxyHandler (cherry picked from commit 85b62e050b01b591a4b5751aab48b418ac9e4e76) (cherry picked from commit dcc07e8ebacec86a3779b289e235dd7731aa208e)",https://github.com/apache/pulsar/commit/dbe0518554bfb4306adf23335d62eb8959b83b27,,,pulsar-proxy/src/main/java/org/apache/pulsar/proxy/server/LookupProxyHandler.java,3,java,False,2022-01-19T04:41:12Z "public void writeJsonOutput(ScanRequest request, Object report, Logger log) throws MachinaException { try { ObjectMapper mapper = new ObjectMapper(); mapper.setSerializationInclusion(JsonInclude.Include.NON_NULL); mapper.writeValue(new File(request.getFilename()), report); } catch (IOException e) { log.error(""Issue occurred while writing file {}"", request.getFilename(), e); throw new MachinaException(); } }","public void writeJsonOutput(ScanRequest request, Object report, Logger log) throws MachinaException { try { ObjectMapper mapper = new ObjectMapper(); mapper.setSerializationInclusion(JsonInclude.Include.NON_NULL); mapper.writeValue(new File(request.getFilename()).getCanonicalFile(), report); } catch (IOException e) { log.error(""Issue occurred while writing file {}"", request.getFilename(), e); throw new MachinaException(); } }","Saras fix vulnerabilities (#738) fix input path not canonicalize vulnerabilities",https://github.com/checkmarx-ltd/cx-flow/commit/60920be1b2764f71fad8dfa5a4940090e2a32c63,,,src/main/java/com/checkmarx/flow/custom/ImmutableIssueTracker.java,3,java,False,2021-05-19T06:57:34Z "@Override protected void configure(HttpSecurity http) throws Exception { http.csrf().disable() .exceptionHandling() .defaultAuthenticationEntryPointFor( samlEntryPoint, getRedirectRequestMatcher()) .defaultAuthenticationEntryPointFor( new RestAuthenticationEntryPoint(), new AntPathRequestMatcher(getSecuredResources())) .and() .requestMatcher(getFullRequestMatcher()) .authorizeRequests() .antMatchers(HttpMethod.OPTIONS).permitAll() .antMatchers(getUnsecuredResources()).permitAll() .antMatchers(getAnonymousResources()) .hasAnyAuthority(DefaultRoles.ROLE_ADMIN.getName(), DefaultRoles.ROLE_USER.getName(), DefaultRoles.ROLE_ANONYMOUS_USER.getName()) .antMatchers(getSecuredResources()) .hasAnyAuthority(DefaultRoles.ROLE_ADMIN.getName(), DefaultRoles.ROLE_USER.getName()) .and() .sessionManagement().sessionCreationPolicy( disableJwtSession ? SessionCreationPolicy.NEVER : SessionCreationPolicy.IF_REQUIRED) .and() .requestCache().requestCache(requestCache()) .and() .addFilterBefore(getJwtAuthenticationFilter(), UsernamePasswordAuthenticationFilter.class); }","@Override protected void configure(HttpSecurity http) throws Exception { http.csrf().disable() .exceptionHandling() .defaultAuthenticationEntryPointFor( samlEntryPoint, getRedirectRequestMatcher()) .defaultAuthenticationEntryPointFor( new RestAuthenticationEntryPoint(), new AntPathRequestMatcher(getSecuredResources())) .and() .requestMatcher(getFullRequestMatcher()) .authorizeRequests() .antMatchers(HttpMethod.OPTIONS).permitAll() .antMatchers(getUnsecuredResources()).permitAll() .antMatchers(getAnonymousResources()) .hasAnyAuthority(DefaultRoles.ROLE_ADMIN.getName(), DefaultRoles.ROLE_USER.getName(), DefaultRoles.ROLE_ANONYMOUS_USER.getName()) .antMatchers(getImpersonationStartUrl()) .hasAuthority(DefaultRoles.ROLE_ADMIN.getName()) .antMatchers(getSecuredResources()) .hasAnyAuthority(DefaultRoles.ROLE_ADMIN.getName(), DefaultRoles.ROLE_USER.getName()) .and() .sessionManagement().sessionCreationPolicy( disableJwtSession ? SessionCreationPolicy.NEVER : SessionCreationPolicy.IF_REQUIRED) .and() .requestCache().requestCache(requestCache()) .and() .addFilterBefore(getJwtAuthenticationFilter(), UsernamePasswordAuthenticationFilter.class); }","Issue #2144 User impersonation (#2150) * Issue #2144 Configure SwitchUserFilter to perform impersonation * Issue #2144 Change impersonation operations root URL, fix auth matcher order",https://github.com/epam/cloud-pipeline/commit/e16b85060f0c35109e8a5f92de8a9eb4dbed5bca,,,api/src/main/java/com/epam/pipeline/app/JWTSecurityConfiguration.java,3,java,False,2021-09-06T13:51:46Z "@VisibleForTesting CharSequence getLabel() { return mConversationInfo != null ? mConversationInfo.getLabel() : mChannel.getName(); }","@VisibleForTesting CharSequence getLabel() { CharSequence label = null; if (mConversationInfo != null) { label = mConversationInfo.getLabel(); } else if (mChannel != null) { label = mChannel.getName(); } return label; }","Fix potential NPE crash in ConversationHeaderPreferenceController mChannel is nullable and we have to do a null-check before calling its method. Bug: 245506600 Test: manual and atest Change-Id: Ib739f0f66f1a2aee1b2741263e7c206341782892",https://github.com/LineageOS/android_packages_apps_Settings/commit/78fc8a21a4747832df528633d5ddf3b3edd6b201,,,src/com/android/settings/notification/app/ConversationHeaderPreferenceController.java,3,java,False,2022-09-08T03:50:33Z "@Override public void appendHoverText(ItemStack stack, @Nullable Level level, List tooltip, TooltipFlag flag) { super.appendHoverText(stack, level, tooltip, flag); if (!stack.hasTag()) { return; } ICraftingPattern pattern = fromCache(level, stack); if (pattern.isValid()) { if (Screen.hasShiftDown() || isProcessing(stack)) { tooltip.add(new TranslatableComponent(""misc.refinedstorage.pattern.inputs"").setStyle(Styles.YELLOW)); RenderUtils.addCombinedItemsToTooltip(tooltip, true, pattern.getInputs().stream().map(i -> !i.isEmpty() ? i.get(0) : ItemStack.EMPTY).collect(Collectors.toList())); RenderUtils.addCombinedFluidsToTooltip(tooltip, true, pattern.getFluidInputs().stream().map(i -> !i.isEmpty() ? i.get(0) : FluidStack.EMPTY).collect(Collectors.toList())); tooltip.add(new TranslatableComponent(""misc.refinedstorage.pattern.outputs"").setStyle(Styles.YELLOW)); } RenderUtils.addCombinedItemsToTooltip(tooltip, true, pattern.getOutputs()); RenderUtils.addCombinedFluidsToTooltip(tooltip, true, pattern.getFluidOutputs()); if (pattern instanceof CraftingPattern && ((CraftingPattern) pattern).getAllowedTagList() != null) { addAllowedTags(tooltip, (CraftingPattern) pattern); } if (isExact(stack)) { tooltip.add(new TranslatableComponent(""misc.refinedstorage.pattern.exact"").setStyle(Styles.BLUE)); } if (isProcessing(stack)) { tooltip.add(new TranslatableComponent(""misc.refinedstorage.processing"").setStyle(Styles.BLUE)); } } else { tooltip.add(new TranslatableComponent(""misc.refinedstorage.pattern.invalid"").setStyle(Styles.RED)); tooltip.add(pattern.getErrorMessage().plainCopy().setStyle(Styles.GRAY)); } }","@Override public void appendHoverText(ItemStack stack, @Nullable Level level, List tooltip, TooltipFlag flag) { super.appendHoverText(stack, level, tooltip, flag); if (!stack.hasTag() || level == null) { return; } ICraftingPattern pattern = fromCache(level, stack); if (pattern.isValid()) { if (Screen.hasShiftDown() || isProcessing(stack)) { tooltip.add(new TranslatableComponent(""misc.refinedstorage.pattern.inputs"").setStyle(Styles.YELLOW)); RenderUtils.addCombinedItemsToTooltip(tooltip, true, pattern.getInputs().stream().map(i -> !i.isEmpty() ? i.get(0) : ItemStack.EMPTY).collect(Collectors.toList())); RenderUtils.addCombinedFluidsToTooltip(tooltip, true, pattern.getFluidInputs().stream().map(i -> !i.isEmpty() ? i.get(0) : FluidStack.EMPTY).collect(Collectors.toList())); tooltip.add(new TranslatableComponent(""misc.refinedstorage.pattern.outputs"").setStyle(Styles.YELLOW)); } RenderUtils.addCombinedItemsToTooltip(tooltip, true, pattern.getOutputs()); RenderUtils.addCombinedFluidsToTooltip(tooltip, true, pattern.getFluidOutputs()); if (pattern instanceof CraftingPattern && ((CraftingPattern) pattern).getAllowedTagList() != null) { addAllowedTags(tooltip, (CraftingPattern) pattern); } if (isExact(stack)) { tooltip.add(new TranslatableComponent(""misc.refinedstorage.pattern.exact"").setStyle(Styles.BLUE)); } if (isProcessing(stack)) { tooltip.add(new TranslatableComponent(""misc.refinedstorage.processing"").setStyle(Styles.BLUE)); } } else { tooltip.add(new TranslatableComponent(""misc.refinedstorage.pattern.invalid"").setStyle(Styles.RED)); tooltip.add(pattern.getErrorMessage().plainCopy().setStyle(Styles.GRAY)); } }","Fixed potential Pattern crash when loading Minecraft. Fixes #3176 Fixes a NPE when using ""level"" later on in the pattern factory Normally, this shouldn't be an issue because there is a hasTag() guard (and MC preloads tooltips of items where tag = null) But for some reason, there is an environment where MC loads the Pattern tooltip (at startup) with a NBT tag",https://github.com/refinedmods/refinedstorage/commit/48873ab12b0b7da6a3410b5f15e7d027fd6c804b,,,src/main/java/com/refinedmods/refinedstorage/item/PatternItem.java,3,java,False,2021-12-16T01:30:48Z "@Override public DatatableData retrieveDatatable(final String datatable) { // PERMITTED datatables SQLInjectionValidator.validateSQLInput(datatable); final String sql = ""select application_table_name, registered_table_name, entity_subtype"" + "" from x_registered_table "" + "" where exists"" + "" (select 'f'"" + "" from m_appuser_role ur "" + "" join m_role r on r.id = ur.role_id"" + "" left join m_role_permission rp on rp.role_id = r.id"" + "" left join m_permission p on p.id = rp.permission_id"" + "" where ur.appuser_id = "" + this.context.authenticatedUser().getId() + "" and registered_table_name='"" + datatable + ""'"" + "" and (p.code in ('ALL_FUNCTIONS', 'ALL_FUNCTIONS_READ') or p.code = concat('READ_', registered_table_name))) "" + "" order by application_table_name, registered_table_name""; final SqlRowSet rs = this.jdbcTemplate.queryForRowSet(sql); DatatableData datatableData = null; while (rs.next()) { final String appTableName = rs.getString(""application_table_name""); final String registeredDatatableName = rs.getString(""registered_table_name""); final String entitySubType = rs.getString(""entity_subtype""); final List columnHeaderData = this.genericDataService .fillResultsetColumnHeaders(registeredDatatableName); datatableData = DatatableData.create(appTableName, registeredDatatableName, entitySubType, columnHeaderData); } return datatableData; }","@Override public DatatableData retrieveDatatable(final String datatable) { // PERMITTED datatables SQLInjectionValidator.validateSQLInput(datatable); final String sql = ""select application_table_name, registered_table_name, entity_subtype"" + "" from x_registered_table "" + "" where exists"" + "" (select 'f'"" + "" from m_appuser_role ur "" + "" join m_role r on r.id = ur.role_id"" + "" left join m_role_permission rp on rp.role_id = r.id"" + "" left join m_permission p on p.id = rp.permission_id"" + "" where ur.appuser_id = ? and registered_table_name=? and (p.code in ('ALL_FUNCTIONS', "" + ""'ALL_FUNCTIONS_READ') or p.code = concat('READ_', registered_table_name))) "" + "" order by application_table_name, registered_table_name""; DatatableData datatableData = null; final SqlRowSet rowSet = jdbcTemplate.queryForRowSet(sql, new Object[] { this.context.authenticatedUser().getId(), datatable }); // NOSONAR if (rowSet.next()) { final String appTableName = rowSet.getString(""application_table_name""); final String registeredDatatableName = rowSet.getString(""registered_table_name""); final String entitySubType = rowSet.getString(""entity_subtype""); final List columnHeaderData = this.genericDataService .fillResultsetColumnHeaders(registeredDatatableName); datatableData = DatatableData.create(appTableName, registeredDatatableName, entitySubType, columnHeaderData); } return datatableData; }",FINERACT-1562: Excluding persistence.xml from being picked up by Spring,https://github.com/apache/fineract/commit/f22807b9442dafa0ca07d0fad4e24c2de84e8e33,,,fineract-provider/src/main/java/org/apache/fineract/infrastructure/dataqueries/service/ReadWriteNonCoreDataServiceImpl.java,3,java,False,2022-03-17T13:12:10Z "int xml_init(modsec_rec *msr, char **error_msg) { if (error_msg == NULL) return -1; *error_msg = NULL; msr->xml = apr_pcalloc(msr->mp, sizeof(xml_data)); if (msr->xml == NULL) return -1; return 1; }","int xml_init(modsec_rec *msr, char **error_msg) { xmlParserInputBufferCreateFilenameFunc entity; if (error_msg == NULL) return -1; *error_msg = NULL; msr->xml = apr_pcalloc(msr->mp, sizeof(xml_data)); if (msr->xml == NULL) return -1; if(msr->txcfg->xml_external_entity == 0) { entity = xmlParserInputBufferCreateFilenameDefault(xml_unload_external_entity); } return 1; }",Added SecXmlExternalEntity,https://github.com/SpiderLabs/ModSecurity/commit/d4d80b38aa85eccb26e3c61b04d16e8ca5de76fe,,,apache2/msc_xml.c,3,c,False,2013-03-04T20:54:20Z "BOOL transport_connect_nla(rdpTransport* transport) { freerdp* instance; rdpSettings* settings; if (transport->layer == TRANSPORT_LAYER_TSG) return TRUE; if (!transport_connect_tls(transport)) return FALSE; /* Network Level Authentication */ if (transport->settings->Authentication != TRUE) return TRUE; settings = transport->settings; instance = (freerdp*) settings->instance; if (transport->credssp == NULL) transport->credssp = credssp_new(instance, transport, settings); if (credssp_authenticate(transport->credssp) < 0) { if (!connectErrorCode) connectErrorCode = AUTHENTICATIONERROR; fprintf(stderr, ""Authentication failure, check credentials.\n"" ""If credentials are valid, the NTLMSSP implementation may be to blame.\n""); credssp_free(transport->credssp); return FALSE; } credssp_free(transport->credssp); return TRUE; }","BOOL transport_connect_nla(rdpTransport* transport) { freerdp* instance; rdpSettings* settings; if (transport->layer == TRANSPORT_LAYER_TSG) return TRUE; if (!transport_connect_tls(transport)) return FALSE; /* Network Level Authentication */ if (transport->settings->Authentication != TRUE) return TRUE; settings = transport->settings; instance = (freerdp*) settings->instance; if (transport->credssp == NULL) transport->credssp = credssp_new(instance, transport, settings); if (credssp_authenticate(transport->credssp) < 0) { if (!connectErrorCode) connectErrorCode = AUTHENTICATIONERROR; fprintf(stderr, ""Authentication failure, check credentials.\n"" ""If credentials are valid, the NTLMSSP implementation may be to blame.\n""); credssp_free(transport->credssp); transport->credssp = NULL; return FALSE; } credssp_free(transport->credssp); return TRUE; }","nla: invalidate sec handle after creation If sec pointer isn't invalidated after creation it is not possible to check if the upper and lower pointers are valid. This fixes a segfault in the server part if the client disconnects before the authentication was finished.",https://github.com/FreeRDP/FreeRDP/commit/0773bb9303d24473fe1185d85a424dfe159aff53,,,libfreerdp/core/transport.c,3,c,False,2013-07-01T17:24:19Z "private static Proxy buildProxy(Environment environment, String type) { final String proxyHost = environment.getProperty(""httpClient.proxy."" + type + "".host"", String.class, environment.getProperty(""http.proxyHost"")); final Integer proxyPort = environment.getProperty(""httpClient.proxy."" + type + "".port"", Integer.class, environment.getProperty(""http.proxyPort"", Integer.class, 3124)); Proxy.Type pType = Proxy.Type.HTTP; if (useSockProxy(environment, type)) { pType = Proxy.Type.SOCKS; } if (proxyHost != null) { return new Proxy(pType, new InetSocketAddress(proxyHost, proxyPort)); } return null; }","private static Proxy buildProxy(Environment environment, String type) { final String proxyHost = environment.getProperty(""httpClient.proxy."" + type + "".host"", String.class); final Integer proxyPort = environment.getProperty(""httpClient.proxy."" + type + "".port"", Integer.class, 3124); if (proxyHost != null) { Proxy.Type pType = Proxy.Type.HTTP; if (useSockProxy(environment, type)) { pType = Proxy.Type.SOCKS; } return new Proxy(pType, new InetSocketAddress(proxyHost, proxyPort)); } return null; }","fix: Do not use system proxy by default for OAuth authentication Closes gravitee-io/issues#5281",https://github.com/gravitee-io/gravitee-api-management/commit/e49bc8e6b75fd0be423e7ea79d45e18eba2d9456,,,gravitee-rest-api-service/src/main/java/io/gravitee/rest/api/service/builder/JerseyClientBuilder.java,3,java,False,2021-03-24T13:34:49Z "@SuppressWarnings(""deprecation"") @EventHandler public void onInventoryClick(InventoryClickEvent event) { if (event.isCancelled()) return; if (!(event.getWhoClicked() instanceof Player)) return; Player player = (Player)event.getWhoClicked(); final Mage mage = controller.getMage(player); InventoryType.SlotType slotType = event.getSlotType(); Integer slot = event.getSlot(); if (mage.getDebugLevel() >= DEBUG_LEVEL) { mage.sendDebugMessage(""CLICK: "" + event.getAction() + "", "" + event.getClick() + "" on "" + slotType + "" in "" + event.getInventory().getType() + "" slots: "" + slot + "":"" + event.getRawSlot()); } GUIAction gui = mage.getActiveGUI(); if (gui != null) { gui.clicked(event); return; } // Check for temporary items and skill items InventoryAction action = event.getAction(); InventoryType inventoryType = event.getInventory().getType(); boolean isPlayerInventory = inventoryType == InventoryType.CRAFTING || inventoryType == InventoryType.PLAYER; ItemStack clickedItem = event.getCurrentItem(); boolean isDrop = event.getClick() == ClickType.DROP || event.getClick() == ClickType.CONTROL_DROP; boolean isSkill = clickedItem != null && Wand.isSkill(clickedItem); // Check for right-click-to-use boolean isRightClick = action == InventoryAction.PICKUP_HALF; if (isSkill && isRightClick) { mage.useSkill(clickedItem); player.closeInventory(); event.setCancelled(true); return; } if (clickedItem != null && NMSUtils.isTemporary(clickedItem)) { String message = NMSUtils.getTemporaryMessage(clickedItem); if (message != null && message.length() > 1) { mage.sendMessage(message); } ItemStack replacement = NMSUtils.getReplacement(clickedItem); event.setCurrentItem(replacement); event.setCancelled(true); mage.armorUpdated(); return; } if (InventoryUtils.getMetaBoolean(clickedItem, ""unmoveable"", false)) { event.setCancelled(true); return; } // Look at the wand in hand ItemStack heldItem = event.getCursor(); boolean heldWand = Wand.isWand(heldItem); // Check for putting wands in a grindstone since they will re-apply their enchantments if (inventoryType.name().equals(""GRINDSTONE"") && heldWand && (slot == 1 || slot == 0)) { event.setCancelled(true); return; } // Check for wearing spells or wands boolean heldSpell = Wand.isSpell(heldItem); boolean clickedWand = Wand.isWand(clickedItem); if (slotType == InventoryType.SlotType.ARMOR) { if (heldSpell) { event.setCancelled(true); return; } if (heldWand) { Wand wand = controller.getWand(heldItem); if (wand.hasWearable()) { if (wand.isWearableInSlot(slot)) { ItemStack existing = player.getInventory().getItem(slot); player.getInventory().setItem(slot, heldItem); event.setCursor(existing); event.setCancelled(true); controller.onArmorUpdated(mage); return; } else { event.setCancelled(true); return; } } } // Notify mage that armor was updated, but wait one tick to do it controller.onArmorUpdated(mage); } boolean tryingToWear = action == InventoryAction.MOVE_TO_OTHER_INVENTORY && (inventoryType == InventoryType.PLAYER || inventoryType == InventoryType.CRAFTING); if (clickedWand && tryingToWear) { Wand wand = null; if (slot == player.getInventory().getHeldItemSlot()) { wand = mage.getActiveWand(); } if (wand == null) { wand = controller.getWand(clickedItem); } if (wand.tryToWear(mage)) { player.getInventory().setItem(slot, null); event.setCancelled(true); mage.checkWand(); return; } } // Another check for wearing spells boolean clickedSpell = Wand.isSpell(clickedItem); boolean clickedWearable = controller.isWearable(clickedItem); if (tryingToWear && clickedSpell && clickedWearable) { event.setCancelled(true); return; } boolean isHotbar = event.getAction() == InventoryAction.HOTBAR_SWAP || event.getAction() == InventoryAction.HOTBAR_MOVE_AND_READD; // I'm not sure why or how this happens, but sometimes we can get a hotbar event without a slot number? if (isHotbar && event.getHotbarButton() < 0) return; if (isHotbar && slotType == InventoryType.SlotType.ARMOR) { int hotbarButton = event.getHotbarButton(); ItemStack item = mage.getPlayer().getInventory().getItem(hotbarButton); if (item != null && Wand.isSpell(item)) { event.setCancelled(true); return; } controller.onArmorUpdated(mage); } Wand activeWand = mage.getActiveWand(); boolean isWandInventoryOpen = activeWand != null && activeWand.isInventoryOpen(); // Preventing putting skills in containers if (isSkill && !isPlayerInventory && !isWandInventoryOpen) { if (!isDrop) { event.setCancelled(true); } return; } boolean isFurnace = inventoryType == InventoryType.FURNACE; boolean isChest = inventoryType == InventoryType.CHEST || inventoryType == InventoryType.HOPPER || inventoryType == InventoryType.DISPENSER || inventoryType == InventoryType.DROPPER; // TODO: use enum when dropping backwards compat if (!isChest) isChest = inventoryType.name().equals(""SHULKER_BOX""); if (!isChest) isChest = inventoryType.name().equals(""BARREL""); boolean isContainerSlot = event.getSlot() == event.getRawSlot(); if (isWandInventoryOpen) { if (clickedSpell && clickedItem.getAmount() != 1) { clickedItem.setAmount(1); } // Check for page/hotbar cycling by clicking the active wand if (activeWand.getMode() == WandMode.INVENTORY) { // Don't allow the offhand slot to be messed with while the spell inventory is open if (event.getRawSlot() == 45) { event.setCancelled(true); return; } // Don't allow putting spells in a crafting slot if (slotType == InventoryType.SlotType.CRAFTING && heldSpell) { event.setCancelled(true); return; } if (clickedWand) { event.setCancelled(true); if ((dropChangesPages && isDrop) || isRightClick) { activeWand.cycleInventory(); } else { activeWand.cycleHotbar(1); // There doesn't seem to be any other way to allow cycling in creative if (player.getGameMode() == GameMode.CREATIVE) { activeWand.cycleInventory(); } } return; } // So many ways to try and move the wand around, that we have to watch for! if (isHotbar && Wand.isWand(player.getInventory().getItem(event.getHotbarButton()))) { event.setCancelled(true); return; } // Safety check for something that ought not to be possible // but perhaps happens with lag? if (Wand.isWand(event.getCursor())) { activeWand.closeInventory(); event.setCursor(null); event.setCancelled(true); return; } } else { // Prevent moving items into the skill inventory via the hotbar buttons if (isHotbar && isContainerSlot && !CompatibilityUtils.isEmpty(player.getInventory().getItem(event.getHotbarButton()))) { event.setCancelled(true); return; } } } else if (activeWand != null) { // Check for changes that could have been made to the active wand int activeSlot = player.getInventory().getHeldItemSlot(); if (event.getSlot() == activeSlot || (isHotbar && event.getHotbarButton() == activeSlot)) { mage.checkWand(); activeWand = mage.getActiveWand(); } } // Don't allow smelting wands if (isFurnace && clickedWand) { event.setCancelled(true); return; } if (isFurnace && isHotbar) { ItemStack destinationItem = player.getInventory().getItem(event.getHotbarButton()); if (Wand.isWand(destinationItem)) { event.setCancelled(true); return; } } if (isHotbar) { ItemStack destinationItem = player.getInventory().getItem(event.getHotbarButton()); if (InventoryUtils.getMetaBoolean(destinationItem, ""unmoveable"", false)) { event.setCancelled(true); return; } if (isChest && InventoryUtils.getMetaBoolean(destinationItem, ""unstashable"", false) && !player.hasPermission(""Magic.wand.override_stash"")) { event.setCancelled(true); return; } } // Check for unstashable wands if (isChest && !isContainerSlot && !player.hasPermission(""Magic.wand.override_stash"")) { if (InventoryUtils.getMetaBoolean(clickedItem, ""unstashable"", false)) { event.setCancelled(true); return; } } // Check for taking bound wands out of chests if (isChest && isContainerSlot && Wand.isBound(clickedItem)) { Wand testWand = controller.getWand(clickedItem); if (!testWand.canUse(player)) { event.setCancelled(true); return; } } // Check for armor changing if (tryingToWear && clickedItem != null) { if (clickedWearable) { controller.onArmorUpdated(mage); } } // Check for dropping items out of a wand's inventory // or dropping undroppable wands if (isDrop) { if (InventoryUtils.getMetaBoolean(clickedItem, ""undroppable"", false)) { event.setCancelled(true); if (activeWand != null) { if (activeWand.getHotbarCount() > 1) { activeWand.cycleHotbar(1); } else { activeWand.closeInventory(); } } return; } if (isWandInventoryOpen) { ItemStack droppedItem = clickedItem; if (!Wand.isSpell(droppedItem)) { mage.giveItem(droppedItem); event.setCurrentItem(null); event.setCancelled(true); return; } // This is a hack to deal with spells on cooldown disappearing, // Since the event handler doesn't match the zero-count itemstacks int heldSlot = player.getInventory().getHeldItemSlot(); WandInventory hotbar = activeWand.getHotbar(); if (hotbar != null && slot >= 0 && slot <= hotbar.getSize() && slot != heldSlot && activeWand.getMode() == WandMode.INVENTORY) { if (slot > heldSlot) slot--; if (slot < hotbar.getSize()) { droppedItem = hotbar.getItem(slot); } else { slot = null; } } else { slot = null; } if (!controller.isSpellDroppingEnabled()) { player.closeInventory(); String spellName = Wand.getSpell(droppedItem); if (spellName != null && !activeWand.isManualQuickCastDisabled() && enableInventoryCasting) { final Spell spell = mage.getSpell(spellName); if (spell != null) { // Delay this one tick because cancelling this event is going to mean the spell icon // gets put back in the player inventory, and this can cause strange side effects with // spells levelling up, or spells with GUIs or other inventories. final Wand castWand = activeWand; // This will also fire an arm swing animation event which we want to ignore // Sadly this didn't work because the animation event arrives first mage.checkLastClick(0); controller.getPlugin().getServer().getScheduler().runTaskLater(controller.getPlugin(), new WandCastTask(castWand, spell), 1); } } event.setCancelled(true); // This is needed to avoid spells on cooldown disappearing from the hotbar if (hotbar != null && slot != null && mage.getActiveGUI() == null) { player.getInventory().setItem(event.getSlot(), droppedItem); DeprecatedUtils.updateInventory(player); } return; } ItemStack newDrop = controller.removeItemFromWand(activeWand, droppedItem); if (newDrop != null) { Location location = player.getLocation(); Item item = location.getWorld().dropItem(location, newDrop); SafetyUtils.setVelocity(item, location.getDirection().normalize()); } else { event.setCancelled(true); } } return; } // Check for wand cycling with active inventory if (activeWand != null) { WandMode wandMode = activeWand.getMode(); boolean isChestInventory = wandMode == WandMode.CHEST || wandMode == WandMode.SKILLS; if ((wandMode == WandMode.INVENTORY && isPlayerInventory) || (isChestInventory && inventoryType == InventoryType.CHEST)) { if (activeWand.isInventoryOpen()) { if (event.getAction() == InventoryAction.NOTHING) { int direction = event.getClick() == ClickType.LEFT ? 1 : -1; activeWand.cycleInventory(direction); event.setCancelled(true); return; } if (event.getSlotType() == InventoryType.SlotType.ARMOR) { event.setCancelled(true); return; } // Chest mode falls back to selection from here. boolean isInventoryQuickSelect = isRightClick && wandMode == WandMode.INVENTORY && enableInventorySelection; if (isInventoryQuickSelect || wandMode == WandMode.CHEST) { player.closeInventory(); mage.activateIcon(activeWand, clickedItem); event.setCancelled(true); } // Prevent putting any non-skill item back into a skill inventory if (wandMode == WandMode.SKILLS && isContainerSlot && !CompatibilityUtils.isEmpty(heldItem) && !Wand.isSkill(heldItem)) { event.setCancelled(true); } } } } // Check for dropping upgrades onto a wand if (!isWandInventoryOpen && clickedWand && (Wand.isUpgrade(heldItem) || Wand.isSpell(heldItem) || Wand.isSP(heldItem) || Wand.isBrush(heldItem))) { if (activeWand != null) { activeWand.deactivate(); } Wand wand = controller.createWand(clickedItem); wand.activate(mage); if (wand.addItem(heldItem)) { event.setCancelled(true); event.setCursor(null); player.getInventory().setItem(event.getSlot(), wand.getItem()); } if (activeWand != null) { mage.checkWand(); } } }","@SuppressWarnings(""deprecation"") @EventHandler public void onInventoryClick(InventoryClickEvent event) { if (event.isCancelled()) return; if (!(event.getWhoClicked() instanceof Player)) return; Player player = (Player)event.getWhoClicked(); final Mage mage = controller.getMage(player); InventoryType.SlotType slotType = event.getSlotType(); Integer slot = event.getSlot(); if (mage.getDebugLevel() >= DEBUG_LEVEL) { mage.sendDebugMessage(""CLICK: "" + event.getAction() + "", "" + event.getClick() + "" on "" + slotType + "" in "" + event.getInventory().getType() + "" slots: "" + slot + "":"" + event.getRawSlot()); } GUIAction gui = mage.getActiveGUI(); if (gui != null) { gui.clicked(event); return; } // Check for temporary items and skill items InventoryAction action = event.getAction(); InventoryType inventoryType = event.getInventory().getType(); boolean isPlayerInventory = inventoryType == InventoryType.CRAFTING || inventoryType == InventoryType.PLAYER; ItemStack clickedItem = event.getCurrentItem(); boolean isDrop = event.getClick() == ClickType.DROP || event.getClick() == ClickType.CONTROL_DROP; boolean isSkill = clickedItem != null && Wand.isSkill(clickedItem); // Check for right-click-to-use boolean isRightClick = action == InventoryAction.PICKUP_HALF; if (isSkill && isRightClick) { mage.useSkill(clickedItem); player.closeInventory(); event.setCancelled(true); return; } if (clickedItem != null && NMSUtils.isTemporary(clickedItem)) { String message = NMSUtils.getTemporaryMessage(clickedItem); if (message != null && message.length() > 1) { mage.sendMessage(message); } ItemStack replacement = NMSUtils.getReplacement(clickedItem); event.setCurrentItem(replacement); event.setCancelled(true); mage.armorUpdated(); return; } if (InventoryUtils.getMetaBoolean(clickedItem, ""unmoveable"", false)) { event.setCancelled(true); return; } // Look at the wand in hand ItemStack heldItem = event.getCursor(); boolean heldWand = Wand.isWand(heldItem); boolean clickedWand = Wand.isWand(clickedItem); boolean isHotbar = action == InventoryAction.HOTBAR_SWAP || action == InventoryAction.HOTBAR_MOVE_AND_READD; // I'm not sure why or how this happens, but sometimes we can get a hotbar event without a slot number? int hotbarButton = event.getHotbarButton(); if (isHotbar && hotbarButton < 0) return; // Check for putting wands in a grindstone since they will re-apply their enchantments boolean isGrindstone = inventoryType.name().equals(""GRINDSTONE""); if (isGrindstone && heldWand && (slot == 1 || slot == 0) && slotType == InventoryType.SlotType.CRAFTING) { event.setCancelled(true); return; } if (isGrindstone && clickedWand && action == InventoryAction.MOVE_TO_OTHER_INVENTORY && slotType != InventoryType.SlotType.CRAFTING) { event.setCancelled(true); return; } if (isGrindstone && isHotbar) { ItemStack item = mage.getPlayer().getInventory().getItem(hotbarButton); if (Wand.isWand(item)) { event.setCancelled(true); return; } } // Check for wearing spells or wands boolean heldSpell = Wand.isSpell(heldItem); if (slotType == InventoryType.SlotType.ARMOR) { if (heldSpell) { event.setCancelled(true); return; } if (heldWand) { Wand wand = controller.getWand(heldItem); if (wand.hasWearable()) { if (wand.isWearableInSlot(slot)) { ItemStack existing = player.getInventory().getItem(slot); player.getInventory().setItem(slot, heldItem); event.setCursor(existing); event.setCancelled(true); controller.onArmorUpdated(mage); return; } else { event.setCancelled(true); return; } } } // Notify mage that armor was updated, but wait one tick to do it controller.onArmorUpdated(mage); } boolean tryingToWear = action == InventoryAction.MOVE_TO_OTHER_INVENTORY && (inventoryType == InventoryType.PLAYER || inventoryType == InventoryType.CRAFTING); if (clickedWand && tryingToWear) { Wand wand = null; if (slot == player.getInventory().getHeldItemSlot()) { wand = mage.getActiveWand(); } if (wand == null) { wand = controller.getWand(clickedItem); } if (wand.tryToWear(mage)) { player.getInventory().setItem(slot, null); event.setCancelled(true); mage.checkWand(); return; } } // Another check for wearing spells boolean clickedSpell = Wand.isSpell(clickedItem); boolean clickedWearable = controller.isWearable(clickedItem); if (tryingToWear && clickedSpell && clickedWearable) { event.setCancelled(true); return; } if (isHotbar && slotType == InventoryType.SlotType.ARMOR) { ItemStack item = mage.getPlayer().getInventory().getItem(hotbarButton); if (item != null && Wand.isSpell(item)) { event.setCancelled(true); return; } controller.onArmorUpdated(mage); } Wand activeWand = mage.getActiveWand(); boolean isWandInventoryOpen = activeWand != null && activeWand.isInventoryOpen(); // Preventing putting skills in containers if (isSkill && !isPlayerInventory && !isWandInventoryOpen) { if (!isDrop) { event.setCancelled(true); } return; } boolean isFurnace = inventoryType == InventoryType.FURNACE; boolean isChest = inventoryType == InventoryType.CHEST || inventoryType == InventoryType.HOPPER || inventoryType == InventoryType.DISPENSER || inventoryType == InventoryType.DROPPER; // TODO: use enum when dropping backwards compat if (!isChest) isChest = inventoryType.name().equals(""SHULKER_BOX""); if (!isChest) isChest = inventoryType.name().equals(""BARREL""); boolean isContainerSlot = event.getSlot() == event.getRawSlot(); if (isWandInventoryOpen) { if (clickedSpell && clickedItem.getAmount() != 1) { clickedItem.setAmount(1); } // Check for page/hotbar cycling by clicking the active wand if (activeWand.getMode() == WandMode.INVENTORY) { // Don't allow the offhand slot to be messed with while the spell inventory is open if (event.getRawSlot() == 45) { event.setCancelled(true); return; } // Don't allow putting spells in a crafting slot if (slotType == InventoryType.SlotType.CRAFTING && heldSpell) { event.setCancelled(true); return; } if (clickedWand) { event.setCancelled(true); if ((dropChangesPages && isDrop) || isRightClick) { activeWand.cycleInventory(); } else { activeWand.cycleHotbar(1); // There doesn't seem to be any other way to allow cycling in creative if (player.getGameMode() == GameMode.CREATIVE) { activeWand.cycleInventory(); } } return; } // So many ways to try and move the wand around, that we have to watch for! if (isHotbar && Wand.isWand(player.getInventory().getItem(event.getHotbarButton()))) { event.setCancelled(true); return; } // Safety check for something that ought not to be possible // but perhaps happens with lag? if (Wand.isWand(event.getCursor())) { activeWand.closeInventory(); event.setCursor(null); event.setCancelled(true); return; } } else { // Prevent moving items into the skill inventory via the hotbar buttons if (isHotbar && isContainerSlot && !CompatibilityUtils.isEmpty(player.getInventory().getItem(event.getHotbarButton()))) { event.setCancelled(true); return; } } } else if (activeWand != null) { // Check for changes that could have been made to the active wand int activeSlot = player.getInventory().getHeldItemSlot(); if (event.getSlot() == activeSlot || (isHotbar && event.getHotbarButton() == activeSlot)) { mage.checkWand(); activeWand = mage.getActiveWand(); } } // Don't allow smelting wands if (isFurnace && clickedWand) { event.setCancelled(true); return; } if (isFurnace && isHotbar) { ItemStack destinationItem = player.getInventory().getItem(event.getHotbarButton()); if (Wand.isWand(destinationItem)) { event.setCancelled(true); return; } } if (isHotbar) { ItemStack destinationItem = player.getInventory().getItem(event.getHotbarButton()); if (InventoryUtils.getMetaBoolean(destinationItem, ""unmoveable"", false)) { event.setCancelled(true); return; } if (isChest && InventoryUtils.getMetaBoolean(destinationItem, ""unstashable"", false) && !player.hasPermission(""Magic.wand.override_stash"")) { event.setCancelled(true); return; } } // Check for unstashable wands if (isChest && !isContainerSlot && !player.hasPermission(""Magic.wand.override_stash"")) { if (InventoryUtils.getMetaBoolean(clickedItem, ""unstashable"", false)) { event.setCancelled(true); return; } } // Check for taking bound wands out of chests if (isChest && isContainerSlot && Wand.isBound(clickedItem)) { Wand testWand = controller.getWand(clickedItem); if (!testWand.canUse(player)) { event.setCancelled(true); return; } } // Check for armor changing if (tryingToWear && clickedItem != null) { if (clickedWearable) { controller.onArmorUpdated(mage); } } // Check for dropping items out of a wand's inventory // or dropping undroppable wands if (isDrop) { if (InventoryUtils.getMetaBoolean(clickedItem, ""undroppable"", false)) { event.setCancelled(true); if (activeWand != null) { if (activeWand.getHotbarCount() > 1) { activeWand.cycleHotbar(1); } else { activeWand.closeInventory(); } } return; } if (isWandInventoryOpen) { ItemStack droppedItem = clickedItem; if (!Wand.isSpell(droppedItem)) { mage.giveItem(droppedItem); event.setCurrentItem(null); event.setCancelled(true); return; } // This is a hack to deal with spells on cooldown disappearing, // Since the event handler doesn't match the zero-count itemstacks int heldSlot = player.getInventory().getHeldItemSlot(); WandInventory hotbar = activeWand.getHotbar(); if (hotbar != null && slot >= 0 && slot <= hotbar.getSize() && slot != heldSlot && activeWand.getMode() == WandMode.INVENTORY) { if (slot > heldSlot) slot--; if (slot < hotbar.getSize()) { droppedItem = hotbar.getItem(slot); } else { slot = null; } } else { slot = null; } if (!controller.isSpellDroppingEnabled()) { player.closeInventory(); String spellName = Wand.getSpell(droppedItem); if (spellName != null && !activeWand.isManualQuickCastDisabled() && enableInventoryCasting) { final Spell spell = mage.getSpell(spellName); if (spell != null) { // Delay this one tick because cancelling this event is going to mean the spell icon // gets put back in the player inventory, and this can cause strange side effects with // spells levelling up, or spells with GUIs or other inventories. final Wand castWand = activeWand; // This will also fire an arm swing animation event which we want to ignore // Sadly this didn't work because the animation event arrives first mage.checkLastClick(0); controller.getPlugin().getServer().getScheduler().runTaskLater(controller.getPlugin(), new WandCastTask(castWand, spell), 1); } } event.setCancelled(true); // This is needed to avoid spells on cooldown disappearing from the hotbar if (hotbar != null && slot != null && mage.getActiveGUI() == null) { player.getInventory().setItem(event.getSlot(), droppedItem); DeprecatedUtils.updateInventory(player); } return; } ItemStack newDrop = controller.removeItemFromWand(activeWand, droppedItem); if (newDrop != null) { Location location = player.getLocation(); Item item = location.getWorld().dropItem(location, newDrop); SafetyUtils.setVelocity(item, location.getDirection().normalize()); } else { event.setCancelled(true); } } return; } // Check for wand cycling with active inventory if (activeWand != null) { WandMode wandMode = activeWand.getMode(); boolean isChestInventory = wandMode == WandMode.CHEST || wandMode == WandMode.SKILLS; if ((wandMode == WandMode.INVENTORY && isPlayerInventory) || (isChestInventory && inventoryType == InventoryType.CHEST)) { if (activeWand.isInventoryOpen()) { if (event.getAction() == InventoryAction.NOTHING) { int direction = event.getClick() == ClickType.LEFT ? 1 : -1; activeWand.cycleInventory(direction); event.setCancelled(true); return; } if (event.getSlotType() == InventoryType.SlotType.ARMOR) { event.setCancelled(true); return; } // Chest mode falls back to selection from here. boolean isInventoryQuickSelect = isRightClick && wandMode == WandMode.INVENTORY && enableInventorySelection; if (isInventoryQuickSelect || wandMode == WandMode.CHEST) { player.closeInventory(); mage.activateIcon(activeWand, clickedItem); event.setCancelled(true); } // Prevent putting any non-skill item back into a skill inventory if (wandMode == WandMode.SKILLS && isContainerSlot && !CompatibilityUtils.isEmpty(heldItem) && !Wand.isSkill(heldItem)) { event.setCancelled(true); } } } } // Check for dropping upgrades onto a wand if (!isWandInventoryOpen && clickedWand && (Wand.isUpgrade(heldItem) || Wand.isSpell(heldItem) || Wand.isSP(heldItem) || Wand.isBrush(heldItem))) { if (activeWand != null) { activeWand.deactivate(); } Wand wand = controller.createWand(clickedItem); wand.activate(mage); if (wand.addItem(heldItem)) { event.setCancelled(true); event.setCursor(null); player.getInventory().setItem(event.getSlot(), wand.getItem()); } if (activeWand != null) { mage.checkWand(); } } }",Catch shift+click and hotbar buttons for grindstone exploits,https://github.com/elBukkit/MagicPlugin/commit/1f8c40bc891e0e1d0459e8b9dadcf74a1983e4a5,,,Magic/src/main/java/com/elmakers/mine/bukkit/magic/listener/InventoryController.java,3,java,False,2021-04-04T21:45:02Z "@Override public long acceptEnergyFromNetwork(EnumFacing side, long voltage, long amperage) { if (side == null) { if (facing == null) return 0; side = facing; } long amperesUsed = 0L; List paths = net.getNetData(cable.getPos()); outer: for (RoutePath path : paths) { if (path.getMaxLoss() >= voltage) continue; if (GTUtility.arePosEqual(cable.getPos(), path.getPipePos()) && side == path.getFaceToHandler()) { //Do not insert into source handler continue; } IEnergyContainer dest = path.getHandler(cable.getWorld()); EnumFacing facing = path.getFaceToHandler().getOpposite(); if (dest == null || !dest.inputsEnergy(facing) || dest.getEnergyCanBeInserted() <= 0) continue; long v = voltage - path.getMaxLoss(); if(v <= 0) continue; for (TileEntityCable cable : path.getPath()) { if (cable.getMaxVoltage() < voltage) { for (TileEntityCable cable1 : path.getPath()) { burnCable(cable1.getWorld(), cable1.getPos()); } break outer; } } long amps = dest.acceptEnergyFromNetwork(facing, v, amperage - amperesUsed); if(amps == 0) continue; amperesUsed += amps; long voltageTraveled = voltage; for (TileEntityCable cable : path.getPath()) { voltageTraveled -= cable.getNodeData().getLossPerBlock(); if(voltageTraveled <= 0) break; if(cable.incrementAmperage(amps, voltageTraveled)) { burnCable(cable.getWorld(), cable.getPos()); } } if (amperage == amperesUsed) break; } net.addEnergyFluxPerSec(amperesUsed * voltage); return amperesUsed; }","@Override public long acceptEnergyFromNetwork(EnumFacing side, long voltage, long amperage) { if (transfer) return 0; if (side == null) { if (facing == null) return 0; side = facing; } long amperesUsed = 0L; List paths = net.getNetData(cable.getPos()); outer: for (RoutePath path : paths) { if (path.getMaxLoss() >= voltage) continue; if (GTUtility.arePosEqual(cable.getPos(), path.getPipePos()) && side == path.getFaceToHandler()) { //Do not insert into source handler continue; } IEnergyContainer dest = path.getHandler(cable.getWorld()); EnumFacing facing = path.getFaceToHandler().getOpposite(); if (dest == null || !dest.inputsEnergy(facing) || dest.getEnergyCanBeInserted() <= 0) continue; long v = voltage - path.getMaxLoss(); if(v <= 0) continue; for (TileEntityCable cable : path.getPath()) { if (cable.getMaxVoltage() < voltage) { for (TileEntityCable cable1 : path.getPath()) { burnCable(cable1.getWorld(), cable1.getPos()); } break outer; } } transfer = true; long amps = dest.acceptEnergyFromNetwork(facing, v, amperage - amperesUsed); transfer = false; if(amps == 0) continue; amperesUsed += amps; long voltageTraveled = voltage; for (TileEntityCable cable : path.getPath()) { voltageTraveled -= cable.getNodeData().getLossPerBlock(); if(voltageTraveled <= 0) break; if(cable.incrementAmperage(amps, voltageTraveled)) { burnCable(cable.getWorld(), cable.getPos()); } } if (amperage == amperesUsed) break; } net.addEnergyFluxPerSec(amperesUsed * voltage); return amperesUsed; }",Prevent Stack Overflow in ENet (#593),https://github.com/GregTechCEu/GregTech/commit/3a5ecb0d4056c99f308cda1bfe1d3626c1915773,,,src/main/java/gregtech/common/pipelike/cable/net/EnergyNetHandler.java,3,java,False,2022-02-19T21:39:50Z "@Override public List get(URI uri) { final ArrayList returnList = new ArrayList<>(); for (URI entryUri : mCookieMap.keySet()){ // Check if the URI is valid if (checkDomainsMatch(entryUri.getHost(), uri.getHost()) && checkPathsMatch(entryUri.getPath(), uri.getPath())){ returnList.addAll(Objects.requireNonNull(mCookieMap.get(entryUri))); } } // Remove all expired cookies final Iterator iterator = returnList.iterator(); while (iterator.hasNext()){ if (iterator.next().hasExpired()) iterator.remove(); } return returnList; }","@Override public List get(URI uri) { final ArrayList returnList = new ArrayList<>(); for (URI entryUri : mCookieMap.keySet()){ // Check if the URI is valid if (checkDomainsMatch(entryUri.getHost(), uri.getHost()) && checkPathsMatch(entryUri.getPath(), uri.getPath())){ returnList.addAll(Objects.requireNonNull(mCookieMap.get(entryUri))); } } // Remove all expired cookies final Iterator iterator = returnList.iterator(); while (iterator.hasNext()){ final HttpCookie cookie = iterator.next(); if (cookie == null || cookie.hasExpired()) // Remove null or expired cookies iterator.remove(); } return returnList; }",Fixes a bug where a null cookie can crash the cookie store,https://github.com/genious7/FanFictionReader/commit/5622151bc7d060d426769b46c9d699ba8d85090f,,,fanfictionReader/src/main/java/com/spicymango/fanfictionreader/util/AndroidCookieStore.java,3,java,False,2021-04-27T04:28:23Z "@Override protected List> buildData() { Entity entity = MetadataHelper.getEntity(queryData.getString(""entity"")); TemplateExtractor templateExtractor = new TemplateExtractor(this.template, true); Map varsMap = templateExtractor.transformVars(entity); List validFields = new ArrayList<>(); for (Map.Entry e : varsMap.entrySet()) { String validField = e.getValue(); if (validField != null && e.getKey().startsWith(TemplateExtractor.NROW_PREFIX)) { validFields.add(validField); } else { log.warn(""Invalid field `{}` in template : {}"", e.getKey(), this.template); } } if (validFields.isEmpty()) { log.warn(""No valid fields in template : {}"", this.template); return Collections.emptyList(); } queryData.put(""fields"", validFields); // 使用模板字段 QueryParser queryParser = new QueryParser(queryData); int[] limits = queryParser.getSqlLimit(); List list = Application.createQuery(queryParser.toSql(), getUser()) .setLimit(limits[0], limits[1]) .list(); List> datas = new ArrayList<>(); for (Record c : list) { datas.add(buildData(c, varsMap)); count++; } return datas; }","@Override protected List> buildData() { Entity entity = MetadataHelper.getEntity(queryData.getString(""entity"")); TemplateExtractor templateExtractor = new TemplateExtractor(this.template, true, false); Map varsMap = templateExtractor.transformVars(entity); List validFields = new ArrayList<>(); for (Map.Entry e : varsMap.entrySet()) { String validField = e.getValue(); if (validField != null && e.getKey().startsWith(TemplateExtractor.NROW_PREFIX)) { validFields.add(validField); } else { log.warn(""Invalid field `{}` in template : {}"", e.getKey(), this.template); } } if (validFields.isEmpty()) { return Collections.emptyList(); } queryData.put(""fields"", validFields); // 使用模板字段 QueryParser queryParser = new QueryParser(queryData); int[] limits = queryParser.getSqlLimit(); List list = Application.createQuery(queryParser.toSql(), getUser()) .setLimit(limits[0], limits[1]) .list(); List> datas = new ArrayList<>(); for (Record c : list) { datas.add(buildData(c, varsMap)); count++; } return datas; }","Fix 2.9.1 (#470) * fix cve * fix: list report * fix date value",https://github.com/getrebuild/rebuild/commit/6a5495c51cbf1a53d469cfcaae6aa8081a84c9e3,,,src/main/java/com/rebuild/core/service/datareport/EasyExcelListGenerator.java,3,java,False,2022-06-01T06:35:52Z "protected void loadPropertiesFromFile(File file) throws ConfigurationException { try { validateAgainstXSD(new FileInputStream(file)); DocumentBuilderFactory dbFactory = DocumentBuilderFactory.newInstance(); DocumentBuilder dBuilder = dbFactory.newDocumentBuilder(); Document doc = dBuilder.parse(file); doc.getDocumentElement().normalize(); NodeList nodeList = doc.getElementsByTagName(""property""); for (int i = 0; i < nodeList.getLength(); i++) { Node node = nodeList.item(i); if (node.getNodeType() == Node.ELEMENT_NODE) { Element element = (Element) node; String propertyKey = element.getAttribute(""name""); String propertyValue = element.getTextContent(); properties.put(propertyKey, propertyValue); } } } catch (Exception e) { logSpecial(""XML config file "" + filename + "" has invalid schema"", e); throw new ConfigurationException(""Configuration file : "" + filename + "" has invalid schema."" + e.getMessage(), e); } }","protected void loadPropertiesFromFile(File file) throws ConfigurationException { try ( InputStream configFile = new FileInputStream(file); ) { validateAgainstXSD(configFile); DocumentBuilderFactory dbFactory = DocumentBuilderFactory.newInstance(""org.apache.xerces.jaxp.DocumentBuilderFactoryImpl"", null); dbFactory.setFeature(""http://apache.org/xml/features/disallow-doctype-decl"", true); DocumentBuilder dBuilder = dbFactory.newDocumentBuilder(); Document doc = dBuilder.parse(file); doc.getDocumentElement().normalize(); NodeList nodeList = doc.getElementsByTagName(""property""); for (int i = 0; i < nodeList.getLength(); i++) { Node node = nodeList.item(i); if (node.getNodeType() == Node.ELEMENT_NODE) { Element element = (Element) node; String propertyKey = element.getAttribute(""name""); String propertyValue = element.getTextContent(); properties.put(propertyKey, propertyValue); } } } catch (IOException | SAXException | ParserConfigurationException e) { logSpecial(""XML config file "" + filename + "" doesn't exist or has invalid schema"", e); throw new ConfigurationException(""Configuration file : "" + filename + "" has invalid schema."" + e.getMessage(), e); } }","Suggested pom.xml updates and XmlEsapiPropertyLoader.java improvements (#612) Close issue #614 Pom changes: * Upgrade a few libraries, add some used but undeclared libraries, and delete a bunch of declared/unused libraries. * Upgrade a bunch of the plugins. * Suggested updates to XmlEsapiPropertyLoader.java to eliminate insider XXE risk, and other minor suggested cleanup. * A few more tweaks to use autoclosables to ensure streams get closed. * Remove debug lines.",https://github.com/ESAPI/esapi-java-legacy/commit/c9c3cebe6a66e6d864df89bafc51845fdf0ce919,,,src/main/java/org/owasp/esapi/configuration/XmlEsapiPropertyLoader.java,3,java,False,2021-03-24T01:08:42Z "@Override public void cancelCommands() { this.comm.cancelSend(); }","@Override public void cancelCommands() { this.comm.cancelSend(); this.isStreaming = false; if (this.streamStopWatch.isStarted()) this.streamStopWatch.stop(); }","Stops the stream if the physical reset/abort input is pressed If the Grbl controller has a physical button connected to the reset/abort input, and it's pressed while UGS is streaming commands, UGS doesn't properly detect that Grbl has been reset and does not stop streaming, which could lead to a machine crash",https://github.com/winder/Universal-G-Code-Sender/commit/c65d351a0e85f50e569e5d4f2941be480ca5726f,,,ugs-core/src/com/willwinder/universalgcodesender/AbstractController.java,3,java,False,2021-11-19T06:27:35Z "public void onUserUnlocked(int userId) { syncChannelsBypassingDnd(userId); }","public void onUserUnlocked(int userId) { mCurrentUserId = userId; syncChannelsBypassingDnd(); }","[Notification] Fix Notification channel Dnd bypass for multiusers -Permission granted for a given package using shell cmd (user system) are not sufficient due to a check of notification uid vs packagepreference uid. -If the packagepreference is deleted then restored, the channel preference are not taken into account. Bug: 178032672 Test: CTS/AudioManagerTest Signed-off-by: Francois Gaffie Change-Id: Ia26467f27b31bc048bdb141beac7d764fcb27f51 Merged-in: Ia26467f27b31bc048bdb141beac7d764fcb27f51",https://github.com/omnirom/android_frameworks_base/commit/92a9f5fc1d07d5ab8b89b02d09b73f355595449c,,,services/core/java/com/android/server/notification/PreferencesHelper.java,3,java,False,2021-02-24T16:26:29Z "constructor() { this.handlers = new Map(); window.addEventListener('message', (e) => { if (e.data && (e.data.command === 'onmessage' || e.data.command === 'do-update-state')) { // Came from inner iframe this.postMessage(e.data.command, e.data.data); return; } const channel = e.data.channel; const handler = this.handlers.get(channel); if (handler) { handler(e, e.data.args); } else { console.error('no handler for ', e); } }); }","constructor() { this.handlers = new Map(); window.addEventListener('message', e => { let sourceIsChildFrame = false; for (let i = 0; i < window.frames.length; i++) { const frame = window.frames[i]; if (e.source === frame) { sourceIsChildFrame = true; break; } } if (!sourceIsChildFrame && e.source !== window && e.source !== window.parent) { // return; } if (e.data && (e.data.command === 'onmessage' || e.data.command === 'do-update-state')) { // Came from inner iframe this.postMessage(e.data.command, e.data.data); return; } const channel = e.data.channel; const handler = this.handlers.get(channel); if (handler) { handler(e, e.data.args); } else { console.error('no handler for ', e); } }); }","webview: check message source frame Fix https://bugs.eclipse.org/bugs/show_bug.cgi?id=575924",https://github.com/eclipse-theia/theia/commit/4e1619dc8ab84e8abd900cf7a21421b2b8ef7319,CVE-2021-41038,"['NVD-CWE-Other', 'CWE-940']",packages/plugin-ext/src/main/browser/webview/pre/host.js,3,js,False,2021-09-16T23:04:42Z "void send_packets(tcpreplay_t *ctx, pcap_t *pcap, int idx) { struct timeval print_delta, now, last_pkt_ts; tcpreplay_opt_t *options = ctx->options; tcpreplay_stats_t *stats = &ctx->stats; COUNTER packetnum = 0; COUNTER limit_send = options->limit_send; struct pcap_pkthdr pkthdr; u_char *pktdata = NULL; sendpacket_t *sp = ctx->intf1; COUNTER pktlen; packet_cache_t *cached_packet = NULL; packet_cache_t **prev_packet = NULL; #if defined TCPREPLAY && defined TCPREPLAY_EDIT struct pcap_pkthdr *pkthdr_ptr; #endif int datalink = options->file_cache[idx].dlt; COUNTER skip_length = 0; COUNTER end_us; bool preload = options->file_cache[idx].cached; bool top_speed = (options->speed.mode == speed_topspeed || (options->speed.mode == speed_mbpsrate && options->speed.speed == 0)); bool now_is_now = true; gettimeofday(&now, NULL); if (!timerisset(&stats->start_time)) { TIMEVAL_SET(&stats->start_time, &now); if (ctx->options->stats >= 0) { char buf[64]; if (format_date_time(&stats->start_time, buf, sizeof(buf)) > 0) printf(""Test start: %s ...\n"", buf); } } ctx->skip_packets = 0; timerclear(&last_pkt_ts); if (options->limit_time > 0) end_us = TIMEVAL_TO_MICROSEC(&stats->start_time) + SEC_TO_MICROSEC(options->limit_time); else end_us = 0; if (options->preload_pcap) { prev_packet = &cached_packet; } else { prev_packet = NULL; } /* MAIN LOOP * Keep sending while we have packets or until * we've sent enough packets */ while (!ctx->abort && (pktdata = get_next_packet(ctx, pcap, &pkthdr, idx, prev_packet)) != NULL) { now_is_now = false; packetnum++; #if defined TCPREPLAY || defined TCPREPLAY_EDIT /* do we use the snaplen (caplen) or the ""actual"" packet len? */ pktlen = options->use_pkthdr_len ? (COUNTER)pkthdr.len : (COUNTER)pkthdr.caplen; #elif TCPBRIDGE pktlen = (COUNTER)pkthdr.caplen; #else #error WTF??? We should not be here! #endif dbgx(2, ""packet "" COUNTER_SPEC "" caplen "" COUNTER_SPEC, packetnum, pktlen); /* Dual nic processing */ if (ctx->intf2 != NULL) { sp = (sendpacket_t *)cache_mode(ctx, options->cachedata, packetnum); /* sometimes we should not send the packet */ if (sp == TCPR_DIR_NOSEND) continue; } #if defined TCPREPLAY && defined TCPREPLAY_EDIT pkthdr_ptr = &pkthdr; if (tcpedit_packet(tcpedit, &pkthdr_ptr, &pktdata, sp->cache_dir) == -1) { errx(-1, ""Error editing packet #"" COUNTER_SPEC "": %s"", packetnum, tcpedit_geterr(tcpedit)); } pktlen = options->use_pkthdr_len ? (COUNTER)pkthdr_ptr->len : (COUNTER)pkthdr_ptr->caplen; #endif if (ctx->options->unique_ip && ctx->unique_iteration && ctx->unique_iteration > ctx->last_unique_iteration) { /* edit packet to ensure every pass has unique IP addresses */ fast_edit_packet(&pkthdr, &pktdata, ctx->unique_iteration - 1, preload, datalink); } /* update flow stats */ if (options->flow_stats && !preload) update_flow_stats(ctx, options->cache_packets ? sp : NULL, &pkthdr, pktdata, datalink); /* * this accelerator improves performance by avoiding expensive * time stamps during periods where we have fallen behind in our * sending */ if (skip_length && pktlen < skip_length) { skip_length -= pktlen; } else if (ctx->skip_packets) { --ctx->skip_packets; } else { /* * time stamping is expensive, but now is the * time to do it. */ dbgx(4, ""This packet time: "" TIMEVAL_FORMAT, pkthdr.ts.tv_sec, pkthdr.ts.tv_usec); skip_length = 0; ctx->skip_packets = 0; if (options->speed.mode == speed_multiplier) { if (!timerisset(&last_pkt_ts)) { TIMEVAL_SET(&last_pkt_ts, &pkthdr.ts); } else if (timercmp(&pkthdr.ts, &last_pkt_ts, >)) { struct timeval delta; timersub(&pkthdr.ts, &last_pkt_ts, &delta); timeradd(&stats->pkt_ts_delta, &delta, &stats->pkt_ts_delta); TIMEVAL_SET(&last_pkt_ts, &pkthdr.ts); } if (!timerisset(&stats->time_delta)) TIMEVAL_SET(&stats->pkt_ts_delta, &stats->pkt_ts_delta); } if (!top_speed) { now_is_now = true; gettimeofday(&now, NULL); } /* * Only if the current packet is not late. * * This also sets skip_length and skip_packets which will avoid * timestamping for a given number of packets. */ calc_sleep_time(ctx, &stats->pkt_ts_delta, &stats->time_delta, pktlen, sp, packetnum, &stats->end_time, TIMEVAL_TO_MICROSEC(&stats->start_time), &skip_length); /* * Track the time of the ""last packet sent"". * * A number of 3rd party tools generate bad timestamps which go backwards * in time. Hence, don't update the ""last"" unless pkthdr.ts > last */ if (timercmp(&stats->time_delta, &stats->pkt_ts_delta, <)) TIMEVAL_SET(&stats->time_delta, &stats->pkt_ts_delta); /* * we know how long to sleep between sends, now do it. */ if (!top_speed) tcpr_sleep(ctx, sp, &ctx->nap, &now); } #ifdef ENABLE_VERBOSE /* do we need to print the packet via tcpdump? */ if (options->verbose) tcpdump_print(options->tcpdump, &pkthdr, pktdata); #endif dbgx(2, ""Sending packet #"" COUNTER_SPEC, packetnum); /* write packet out on network */ if (sendpacket(sp, pktdata, pktlen, &pkthdr) < (int)pktlen) { warnx(""Unable to send packet: %s"", sendpacket_geterr(sp)); break; } /* * Mark the time when we sent the last packet */ TIMEVAL_SET(&stats->end_time, &now); #ifdef TIMESTAMP_TRACE add_timestamp_trace_entry(pktlen, &stats->end_time, skip_length); #endif stats->pkts_sent++; stats->bytes_sent += pktlen; /* print stats during the run? */ if (options->stats > 0) { if (! timerisset(&stats->last_print)) { TIMEVAL_SET(&stats->last_print, &now); } else { timersub(&now, &stats->last_print, &print_delta); if (print_delta.tv_sec >= options->stats) { TIMEVAL_SET(&stats->end_time, &now); packet_stats(stats); TIMEVAL_SET(&stats->last_print, &now); } } } #if defined HAVE_NETMAP if (sp->first_packet || timesisset(&ctx->nap)) { wake_send_queues(sp, options); sp->first_packet = false; } #endif /* stop sending based on the duration limit... */ if ((end_us > 0 && (COUNTER)TIMEVAL_TO_MICROSEC(&now) > end_us) || /* ... or stop sending based on the limit -L? */ (limit_send > 0 && stats->pkts_sent >= limit_send)) { ctx->abort = true; } } /* while */ #ifdef HAVE_NETMAP /* when completing test, wait until the last packet is sent */ if (options->netmap && (ctx->abort || options->loop == 1)) { while (ctx->intf1 && !netmap_tx_queues_empty(ctx->intf1)) { now_is_now = true; gettimeofday(&now, NULL); } while (ctx->intf2 && !netmap_tx_queues_empty(ctx->intf2)) { now_is_now = true; gettimeofday(&now, NULL); } } #endif /* HAVE_NETMAP */ if (!now_is_now) gettimeofday(&now, NULL); TIMEVAL_SET(&stats->end_time, &now); increment_iteration(ctx); }","void send_packets(tcpreplay_t *ctx, pcap_t *pcap, int idx) { struct timeval print_delta, now, last_pkt_ts; tcpreplay_opt_t *options = ctx->options; tcpreplay_stats_t *stats = &ctx->stats; COUNTER packetnum = 0; COUNTER limit_send = options->limit_send; struct pcap_pkthdr pkthdr; u_char *pktdata = NULL; sendpacket_t *sp = ctx->intf1; COUNTER pktlen; packet_cache_t *cached_packet = NULL; packet_cache_t **prev_packet = NULL; #if defined TCPREPLAY && defined TCPREPLAY_EDIT struct pcap_pkthdr *pkthdr_ptr; #endif int datalink = options->file_cache[idx].dlt; COUNTER skip_length = 0; COUNTER end_us; bool preload = options->file_cache[idx].cached; bool top_speed = (options->speed.mode == speed_topspeed || (options->speed.mode == speed_mbpsrate && options->speed.speed == 0)); bool now_is_now = true; gettimeofday(&now, NULL); if (!timerisset(&stats->start_time)) { TIMEVAL_SET(&stats->start_time, &now); if (ctx->options->stats >= 0) { char buf[64]; if (format_date_time(&stats->start_time, buf, sizeof(buf)) > 0) printf(""Test start: %s ...\n"", buf); } } ctx->skip_packets = 0; timerclear(&last_pkt_ts); if (options->limit_time > 0) end_us = TIMEVAL_TO_MICROSEC(&stats->start_time) + SEC_TO_MICROSEC(options->limit_time); else end_us = 0; if (options->preload_pcap) { prev_packet = &cached_packet; } else { prev_packet = NULL; } /* MAIN LOOP * Keep sending while we have packets or until * we've sent enough packets */ while (!ctx->abort && (pktdata = get_next_packet(ctx, pcap, &pkthdr, idx, prev_packet)) != NULL) { now_is_now = false; packetnum++; #if defined TCPREPLAY || defined TCPREPLAY_EDIT /* do we use the snaplen (caplen) or the ""actual"" packet len? */ pktlen = options->use_pkthdr_len ? (COUNTER)pkthdr.len : (COUNTER)pkthdr.caplen; #elif TCPBRIDGE pktlen = (COUNTER)pkthdr.caplen; #else #error WTF??? We should not be here! #endif dbgx(2, ""packet "" COUNTER_SPEC "" caplen "" COUNTER_SPEC, packetnum, pktlen); /* Dual nic processing */ if (ctx->intf2 != NULL) { sp = (sendpacket_t *)cache_mode(ctx, options->cachedata, packetnum); /* sometimes we should not send the packet */ if (sp == TCPR_DIR_NOSEND) continue; } #if defined TCPREPLAY && defined TCPREPLAY_EDIT pkthdr_ptr = &pkthdr; if (tcpedit_packet(tcpedit, &pkthdr_ptr, &pktdata, sp->cache_dir) == -1) { errx(-1, ""Error editing packet #"" COUNTER_SPEC "": %s"", packetnum, tcpedit_geterr(tcpedit)); } pktlen = options->use_pkthdr_len ? (COUNTER)pkthdr_ptr->len : (COUNTER)pkthdr_ptr->caplen; #endif if (ctx->options->unique_ip && ctx->unique_iteration && ctx->unique_iteration > ctx->last_unique_iteration) { /* edit packet to ensure every pass has unique IP addresses */ if (fast_edit_packet(&pkthdr, &pktdata, ctx->unique_iteration - 1, preload, datalink) == -1) { ++stats->failed; continue; } } /* update flow stats */ if (options->flow_stats && !preload) update_flow_stats(ctx, options->cache_packets ? sp : NULL, &pkthdr, pktdata, datalink); /* * this accelerator improves performance by avoiding expensive * time stamps during periods where we have fallen behind in our * sending */ if (skip_length && pktlen < skip_length) { skip_length -= pktlen; } else if (ctx->skip_packets) { --ctx->skip_packets; } else { /* * time stamping is expensive, but now is the * time to do it. */ dbgx(4, ""This packet time: "" TIMEVAL_FORMAT, pkthdr.ts.tv_sec, pkthdr.ts.tv_usec); skip_length = 0; ctx->skip_packets = 0; if (options->speed.mode == speed_multiplier) { if (!timerisset(&last_pkt_ts)) { TIMEVAL_SET(&last_pkt_ts, &pkthdr.ts); } else if (timercmp(&pkthdr.ts, &last_pkt_ts, >)) { struct timeval delta; timersub(&pkthdr.ts, &last_pkt_ts, &delta); timeradd(&stats->pkt_ts_delta, &delta, &stats->pkt_ts_delta); TIMEVAL_SET(&last_pkt_ts, &pkthdr.ts); } if (!timerisset(&stats->time_delta)) TIMEVAL_SET(&stats->pkt_ts_delta, &stats->pkt_ts_delta); } if (!top_speed) { now_is_now = true; gettimeofday(&now, NULL); } /* * Only if the current packet is not late. * * This also sets skip_length and skip_packets which will avoid * timestamping for a given number of packets. */ calc_sleep_time(ctx, &stats->pkt_ts_delta, &stats->time_delta, pktlen, sp, packetnum, &stats->end_time, TIMEVAL_TO_MICROSEC(&stats->start_time), &skip_length); /* * Track the time of the ""last packet sent"". * * A number of 3rd party tools generate bad timestamps which go backwards * in time. Hence, don't update the ""last"" unless pkthdr.ts > last */ if (timercmp(&stats->time_delta, &stats->pkt_ts_delta, <)) TIMEVAL_SET(&stats->time_delta, &stats->pkt_ts_delta); /* * we know how long to sleep between sends, now do it. */ if (!top_speed) tcpr_sleep(ctx, sp, &ctx->nap, &now); } #ifdef ENABLE_VERBOSE /* do we need to print the packet via tcpdump? */ if (options->verbose) tcpdump_print(options->tcpdump, &pkthdr, pktdata); #endif dbgx(2, ""Sending packet #"" COUNTER_SPEC, packetnum); /* write packet out on network */ if (sendpacket(sp, pktdata, pktlen, &pkthdr) < (int)pktlen) { warnx(""Unable to send packet: %s"", sendpacket_geterr(sp)); break; } /* * Mark the time when we sent the last packet */ TIMEVAL_SET(&stats->end_time, &now); #ifdef TIMESTAMP_TRACE add_timestamp_trace_entry(pktlen, &stats->end_time, skip_length); #endif stats->pkts_sent++; stats->bytes_sent += pktlen; /* print stats during the run? */ if (options->stats > 0) { if (! timerisset(&stats->last_print)) { TIMEVAL_SET(&stats->last_print, &now); } else { timersub(&now, &stats->last_print, &print_delta); if (print_delta.tv_sec >= options->stats) { TIMEVAL_SET(&stats->end_time, &now); packet_stats(stats); TIMEVAL_SET(&stats->last_print, &now); } } } #if defined HAVE_NETMAP if (sp->first_packet || timesisset(&ctx->nap)) { wake_send_queues(sp, options); sp->first_packet = false; } #endif /* stop sending based on the duration limit... */ if ((end_us > 0 && (COUNTER)TIMEVAL_TO_MICROSEC(&now) > end_us) || /* ... or stop sending based on the limit -L? */ (limit_send > 0 && stats->pkts_sent >= limit_send)) { ctx->abort = true; } } /* while */ #ifdef HAVE_NETMAP /* when completing test, wait until the last packet is sent */ if (options->netmap && (ctx->abort || options->loop == 1)) { while (ctx->intf1 && !netmap_tx_queues_empty(ctx->intf1)) { now_is_now = true; gettimeofday(&now, NULL); } while (ctx->intf2 && !netmap_tx_queues_empty(ctx->intf2)) { now_is_now = true; gettimeofday(&now, NULL); } } #endif /* HAVE_NETMAP */ if (!now_is_now) gettimeofday(&now, NULL); TIMEVAL_SET(&stats->end_time, &now); increment_iteration(ctx); }","Bug #620 apply get.c functions fixed in #617 Add safety and failure reporting for packet captures with caplen too small.",https://github.com/appneta/tcpreplay/commit/61db8adae55e246e0bc9442fbe977fff46154970,,,src/send_packets.c,3,c,False,2021-03-13T06:47:20Z "private PropertiesFile getCachedDataFile(ModuleRevisionId mRevId) { return new PropertiesFile(new File(getRepositoryCacheRoot(), IvyPatternHelper.substitute( getDataFilePattern(), mRevId)), ""ivy cached data file for "" + mRevId); }","private PropertiesFile getCachedDataFile(ModuleRevisionId mRevId) { File file = new File(getRepositoryCacheRoot(), IvyPatternHelper.substitute( getDataFilePattern(), mRevId)); assertInsideCache(file); return new PropertiesFile(file, ""ivy cached data file for "" + mRevId); }",CVE-2022-37865 ZipPacking allows overwriting arbitrary files,https://github.com/apache/ant-ivy/commit/3f374602d4d63691398951b9af692960d019f4d9,,,src/java/org/apache/ivy/core/cache/DefaultRepositoryCacheManager.java,3,java,False,2022-08-21T16:54:43Z "function buildQueryString(obj) { let str = """" if (obj) { for (let [key, value] of Object.entries(obj)) { if (!key || key === """") { continue } if (str !== """") { str += ""&"" } str += `${key}=${encodeURIComponent(value || """")}` } } return str }","function buildQueryString(obj) { let str = """" if (obj) { for (let [key, value] of Object.entries(obj)) { if (!key || key === """") { continue } if (str !== """") { str += ""&"" } const bindings = findHBSBlocks(value) let count = 0 const bindingMarkers = {} bindings.forEach(binding => { const marker = `BINDING...${count++}` value = value.replace(binding, marker) bindingMarkers[marker] = binding }) let encoded = encodeURIComponent(value || """") Object.entries(bindingMarkers).forEach(([marker, binding]) => { encoded = encoded.replace(marker, binding) }) str += `${key}=${encoded}` } } return str }","Fixing issue introduced by fix for #7683 - encoding the query string caused handlebars statements to break, this rectifies that.",https://github.com/budibase/budibase/commit/d35864be0854216693a01307f81ffcabf6d549df,CVE-2022-3225,['CWE-913'],packages/builder/src/helpers/data/utils.js,3,js,False,2022-09-15T18:35:55Z "@Override public void fireUpon(CombatStack source, CombatStack target, int count) { if (random() < tech().hitChance) makeUnsuccessfulAttack(source, target); else makeSuccessfulAttack(source, target); }","@Override public void fireUpon(CombatStack source, CombatStack target, int count) { if (random() < tech().hitChance) makeSuccessfulAttack(source, target); else makeUnsuccessfulAttack(source, target); }","Branch for beta 2.18 or 0.9 or whatever it will be (#48) * Replaced many isPlayer() by isPlayerControlled() This leads to a more fluent experience on AutoPlay. Note: the council-voting acts weird when you try that there, getting you stuck, and the News-Broadcasts also seem to use a differnt logic and are always shown. * Orion-guard-handling Avoid sending colonization-fleets, when guardian is still alive Increase guardian-power-estimate to 100,000 Don't send and count bombers towards guardian-defeat-force * Fixed Crash from a report on reddit Not sure how that could happen though. Never had this issue in games started on my computer. * Fixed crash after AI defeats orion-guard Tried to access an out-of-bounds-value because it couldn't find the System where the guardian was. So looking to find the Planet with the Orionartifact now, which does find it. * All the forgotten isPlayer()-calls Including the Base- and Modnar-AI-Diplomat * Personalities now play a role in my AI once again Instead of everyone having the same conditions for war, there's now different ones. Some are more aggressive, some are less. * Fixed issue where enemy-fleets weren's seen, when they actually were. Also added a way of guessing when enemy-fleets aren't seen so it shouldn't trickle in tiny fleets that all retreat anymore in the early-game, before they can see the enemy-fleets. And also not later because they now actually can see them. * Update AIDiplomat.java * Delete ShipCombatResults.java * Delete Empire.java * Delete TradeRoute.java * Revert ""Delete TradeRoute.java"" This reverts commit 6e5c5a8604e89bb11a9a6dc63acd5b3f27194c83. * Revert ""Delete Empire.java"" This reverts commit 1a020295e05ebc735dae761f426742eb7bdc8d35. * Revert ""Delete ShipCombatResults.java"" This reverts commit 5f9287289feb666adf1aa809524973c54fbf0cd5. * Update ShipCombatResults.java reverting pull-request... manually because I don't know of a better way 8[ * Update Empire.java * Update TradeRoute.java * Merge with Master * Update TradeRoute.java * Update TradeRoute.java github editor does not allow me to remove a newline oO * AI improvements Added parameter to make the colonizer-function return just the uncolonized planets without substracting the colony-ships. Impelemented a very differnt diplomatic behavior, that supposedly is more suitable to actually winning by waging less war, particularly when big enough to be voted for. Revoked that AI doesn't adjust to enemy-troops when it has a more defensive unit-composition. In lategame going by destructive-power of bombers hasn't much merit, when 1 bombers can pack 60ish neutronium-bombs. Fixed an issue that prevented designing extended-fuel-range-colonizers asap. This once again helps expansion-speed a lot. Security now is only spent against empires actually in range to spy, as it was intended. Contact via council should not increase paranoia. Also Xenophobic-extra-paranoia removed. * Update OrionGuardianShip.java * War-declaration behavior Electible faction will no longer declare war on someone who is at war with the other electible faction. * Fix zero-division on refreshing a trade-route that had been adjusted due to empire-shrinkage. * AI & Bugfix Leader-stuff is now overridden Should now retreat against repulsors, when no counter available Tech-nullifier hit and miss mixup fixed * AI improvements Fixed a rare crash in AutoPlay-Mode Massive overhaul of AI-ship-design Spy master now more catious about avoiding unwanted, dangerous wars due to spying on the wrong people Colony-ship-designs now will only get a weapon, if this doesn't prevent reserve-tanks or reducing their size to medium Fixed an issue where ai wouldn't retreat from ships with repulsor-beam that exploited their range-advantage Increased research-value of cloaking-tech and battle-suits Upon reaching tech-level 99 in every field, AI will produce ships non-stop even in peace-time AI will now retreat fleets from empires it doesn't want to go to war with in order to avoid trespassing-issues Fixed issue where the AI wanted to but couldn't colonize orion before it was cleared and then wouldn't colonize other systems in that time AI will no longer break non-aggression-pacts when it still has a war with someone else AI will only begin wars because of spying, if it actually feels comfortable dealing with the person who spied on them AI will now try and predict whether it will be attacked soon and enact preventive measures * Tackling some combat-issue Skipping specials when it comes to determining optimal-range. Otherwise ships with long-range-specials like warp-dissipator would never close in on their prey. Resetting the selectedWeaponIndex upon reload to consistency start with same weapons every turn. Writing new attack-method that allows to skip certain weapons like for example repulsor-beam at the beginning of the turn and fire them at the end instead. * Update NewShipTemplate.java Fixed incorrect operator ""-="" instead of ""=-"", that prevented weapons being used at all when no weapon that is strong enough for theorethical best enemy shield could be found. Also when range is required an not fitting beam can be found try missiles and when no fitting missile can be found either, try short-range weapon. Should still be better than nothing. * Diplomacy and Ship-Building Reduced suicidal tendencies. No more war-declarations against wastly superior enemies. At most they ought to be 25% stronger. Voting behavior is now deterministic. No more votes based on fear, only on who they actually like and only for those whom they have real-contact. Ship-construction is now based on relative-productivity rather than using a hard cut-off for anything lower than standard-resources. So when the empire only has poor-systems it will try to build at least a few ships still. * Orion prevented war Fixed an issue, where wanting to build a colonizer for Orion prevented wars. * Update AIGeneral.java Don't invade unless you have something in orbit. * Update AIFleetCommander.java No longer using hyperspace-communications... for now. (it produced unintentional results and error-messages) Co-authored-by: rayfowler <58891984+rayfowler@users.noreply.github.com>",https://github.com/rayfowler/rotp-public/commit/5de4de9f996eddaa73b90b341940561e62c18e49,,,src/rotp/model/ships/ShipSpecialShipNullifier.java,3,java,False,2021-04-02T21:15:47Z "protected static void applyCharacterStyles(List paragraphs, List charStyles) { int paraIdx = 0, runIdx = 0; HSLFTextRun trun; for (int csIdx = 0; csIdx < charStyles.size(); csIdx++) { TextPropCollection p = charStyles.get(csIdx); for (int ccRun = 0, ccStyle = p.getCharactersCovered(); ccRun < ccStyle;) { HSLFTextParagraph para = paragraphs.get(paraIdx); List runs = para.getTextRuns(); trun = runs.get(runIdx); final int len = trun.getLength(); if (ccRun + len <= ccStyle) { ccRun += len; } else { String text = trun.getRawText(); trun.setText(text.substring(0, ccStyle - ccRun)); HSLFTextRun nextRun = new HSLFTextRun(para); nextRun.setText(text.substring(ccStyle - ccRun)); runs.add(runIdx + 1, nextRun); ccRun += ccStyle - ccRun; } trun.setCharacterStyle(p); if (paraIdx == paragraphs.size()-1 && runIdx == runs.size()-1) { if (csIdx < charStyles.size() - 1) { // special case, empty trailing text run HSLFTextRun nextRun = new HSLFTextRun(para); nextRun.setText(""""); runs.add(nextRun); ccRun++; } else { // need to add +1 to the last run of the last paragraph trun.getCharacterStyle().updateTextSize(trun.getLength()+1); ccRun++; } } // need to compare it again, in case a run has been added after if (++runIdx == runs.size()) { paraIdx++; runIdx = 0; } } } }","protected static void applyCharacterStyles(List paragraphs, List charStyles) { int paraIdx = 0, runIdx = 0; HSLFTextRun trun; for (int csIdx = 0; csIdx < charStyles.size(); csIdx++) { TextPropCollection p = charStyles.get(csIdx); int ccStyle = p.getCharactersCovered(); if (ccStyle > MAX_NUMBER_OF_STYLES) { throw new IllegalStateException(""Cannot process more than "" + MAX_NUMBER_OF_STYLES + "" styles, but had paragraph with "" + ccStyle); } for (int ccRun = 0; ccRun < ccStyle;) { HSLFTextParagraph para = paragraphs.get(paraIdx); List runs = para.getTextRuns(); trun = runs.get(runIdx); final int len = trun.getLength(); if (ccRun + len <= ccStyle) { ccRun += len; } else { String text = trun.getRawText(); trun.setText(text.substring(0, ccStyle - ccRun)); HSLFTextRun nextRun = new HSLFTextRun(para); nextRun.setText(text.substring(ccStyle - ccRun)); runs.add(runIdx + 1, nextRun); ccRun += ccStyle - ccRun; } trun.setCharacterStyle(p); if (paraIdx == paragraphs.size()-1 && runIdx == runs.size()-1) { if (csIdx < charStyles.size() - 1) { // special case, empty trailing text run HSLFTextRun nextRun = new HSLFTextRun(para); nextRun.setText(""""); runs.add(nextRun); ccRun++; } else { // need to add +1 to the last run of the last paragraph trun.getCharacterStyle().updateTextSize(trun.getLength()+1); ccRun++; } } // need to compare it again, in case a run has been added after if (++runIdx == runs.size()) { paraIdx++; runIdx = 0; } } } }","Fix issues found when fuzzing Apache POI via Jazzer Add some additional allocation limits to avoid OOM in some more cases with some broken input files git-svn-id: https://svn.apache.org/repos/asf/poi/trunk@1895922 13f79535-47bb-0310-9956-ffa450edef68",https://github.com/apache/poi/commit/9fa33b2b7e2fafb98fc9f5c784dd21487a14816a,,,poi-scratchpad/src/main/java/org/apache/poi/hslf/usermodel/HSLFTextParagraph.java,3,java,False,2021-12-13T19:22:34Z "@Override public byte[] toBinary() { final byte[] typeNameBytes = StringUtils.stringToBinary(typeName); final byte[] fieldDescriptorBytes = PersistenceUtils.toBinary(fieldDescriptors); final byte[] dataIDFieldBytes = StringUtils.stringToBinary(dataIDField); final ByteBuffer buffer = ByteBuffer.allocate( VarintUtils.unsignedIntByteLength(typeNameBytes.length) + VarintUtils.unsignedIntByteLength(fieldDescriptorBytes.length) + VarintUtils.unsignedIntByteLength(dataIDFieldBytes.length) + typeNameBytes.length + fieldDescriptorBytes.length + dataIDFieldBytes.length); VarintUtils.writeUnsignedInt(typeNameBytes.length, buffer); buffer.put(typeNameBytes); VarintUtils.writeUnsignedInt(fieldDescriptorBytes.length, buffer); buffer.put(fieldDescriptorBytes); VarintUtils.writeUnsignedInt(dataIDFieldBytes.length, buffer); buffer.put(dataIDFieldBytes); return buffer.array(); }","@Override public byte[] toBinary() { final byte[] typeNameBytes = StringUtils.stringToBinary(typeName); final byte[] fieldDescriptorBytes = PersistenceUtils.toBinary(fieldDescriptors); final byte[] dataIDFieldDescriptorBytes = PersistenceUtils.toBinary(dataIDFieldDescriptor); final ByteBuffer buffer = ByteBuffer.allocate( VarintUtils.unsignedIntByteLength(typeNameBytes.length) + VarintUtils.unsignedIntByteLength(fieldDescriptorBytes.length) + VarintUtils.unsignedIntByteLength(dataIDFieldDescriptorBytes.length) + typeNameBytes.length + fieldDescriptorBytes.length + dataIDFieldDescriptorBytes.length); VarintUtils.writeUnsignedInt(typeNameBytes.length, buffer); buffer.put(typeNameBytes); VarintUtils.writeUnsignedInt(fieldDescriptorBytes.length, buffer); buffer.put(fieldDescriptorBytes); VarintUtils.writeUnsignedInt(dataIDFieldDescriptorBytes.length, buffer); buffer.put(dataIDFieldDescriptorBytes); return buffer.array(); }","Fix issues and add improvements to basic data type adapters (#1867) * Fix issues and add improvements to basic data type adapters - Fix issues with the use of primitive types - Allow the data ID field to be kept separate from the other fields so that they don't get serialized twice - Allow the naming of attribute indices - Allow no field descriptors to be supplied - Update data ID serialization to use the field writer for the class instead of toString - Fix stack overflow on SimpleAbstractDataAdapter Signed-off-by: Johnathan Garrett * formatting Co-authored-by: Rich Fecher ",https://github.com/locationtech/geowave/commit/7fa4584f31e490dc2500804c6fd209cd062226b6,,,core/store/src/main/java/org/locationtech/geowave/core/store/adapter/AbstractDataTypeAdapter.java,3,java,False,2022-02-23T13:21:00Z "function escapeArgPowerShell(arg, interpolation, quoted) { let result = arg .replace(/\u0000/g, """") .replace(/`/g, ""``"") .replace(/\$/g, ""`$""); if (interpolation) { result = result .replace(/^((?:\*|[1-6])?)(>)/g, ""$1`$2"") .replace(/^(<|@|#|-|\:|\])/g, ""`$1"") .replace(/(,|\;|\&|\|)/g, ""`$1"") .replace(/(\(|\)|\{|\})/g, ""`$1"") .replace(/('|’|‘|‛|‚)/g, ""`$1"") .replace(/(""|“|”|„)/g, ""`$1""); } else if (quoted) { result = result.replace(/(""|“|”|„)/g, ""$1$1""); } return result; }","function escapeArgPowerShell(arg, interpolation, quoted) { let result = arg .replace(/\u0000/g, """") .replace(/`/g, ""``"") .replace(/\$/g, ""`$""); if (interpolation) { result = result .replace(/(^|\s)((?:\*|[1-6])?)(>)/g, ""$1$2`$3"") .replace(/(^|\s)(<|@|#|-|\:|\])/g, ""$1`$2"") .replace(/(,|\;|\&|\|)/g, ""`$1"") .replace(/(\(|\)|\{|\})/g, ""`$1"") .replace(/('|’|‘|‛|‚)/g, ""`$1"") .replace(/(""|“|”|„)/g, ""`$1""); } else if (quoted) { result = result.replace(/(""|“|”|„)/g, ""$1$1""); } return result; }",Merge branch 'main' into bug-323/unix-escaping,https://github.com/ericcornelissen/shescape/commit/703f1301caa588bb111247473273d73ec9442bbd,CVE-2022-31180,"['CWE-74', 'NVD-CWE-Other']",src/win.js,3,js,False,2022-07-05T23:14:28Z "public Boolean allowTopicOperation(TopicName topicName, TopicOperation operation, String originalRole, String role, AuthenticationDataSource authData) { try { return allowTopicOperationAsync(topicName, operation, originalRole, role, authData).get(); } catch (InterruptedException e) { throw new RestException(e); } catch (ExecutionException e) { throw new RestException(e.getCause()); } }","public Boolean allowTopicOperation(TopicName topicName, TopicOperation operation, String originalRole, String role, AuthenticationDataSource authData) throws Exception { try { return allowTopicOperationAsync(topicName, operation, originalRole, role, authData).get( conf.getZooKeeperOperationTimeoutSeconds(), SECONDS); } catch (InterruptedException e) { throw new RestException(e); } catch (ExecutionException e) { throw new RestException(e.getCause()); } }",[branch-2.9][fix][security] Add timeout of sync methods and avoid call sync method for AuthoriationService (#16083),https://github.com/apache/pulsar/commit/1fa9c2e17977cb451c0379581c35c70920a393f3,,,pulsar-broker-common/src/main/java/org/apache/pulsar/broker/authorization/AuthorizationService.java,3,java,False,2022-06-17T05:27:36Z "@Override public void fetchAuthSession( @NonNull Consumer onSuccess, @NonNull Consumer onException ) { try { awsMobileClient.currentUserState(new Callback() { @Override public void onResult(UserStateDetails result) { switch (result.getUserState()) { case SIGNED_OUT: case GUEST: MobileClientSessionAdapter.fetchSignedOutSession(awsMobileClient, onSuccess); break; case SIGNED_OUT_FEDERATED_TOKENS_INVALID: case SIGNED_OUT_USER_POOLS_TOKENS_INVALID: onSuccess.accept(expiredSession()); break; default: MobileClientSessionAdapter.fetchSignedInSession(awsMobileClient, onSuccess); } } @Override public void onError(Exception exception) { onException.accept(new AuthException( ""An error occurred while attempting to retrieve your user details"", exception, ""See attached exception for more details"" )); } }); } catch (Throwable exception) { onException.accept(new AuthException( ""An error occurred fetching authorization details for the current user"", exception, ""See attached exception for more details"" )); } }","@Override public void fetchAuthSession( @NonNull Consumer onSuccess, @NonNull Consumer onException ) { try { awsMobileClient.currentUserState(new Callback() { @Override public void onResult(UserStateDetails result) { switch (result.getUserState()) { case SIGNED_OUT: case GUEST: MobileClientSessionAdapter.fetchSignedOutSession(awsMobileClient, onSuccess); break; case SIGNED_OUT_FEDERATED_TOKENS_INVALID: case SIGNED_OUT_USER_POOLS_TOKENS_INVALID: onSuccess.accept(expiredSession()); break; default: MobileClientSessionAdapter.fetchSignedInSession(awsMobileClient, onSuccess); } } @Override public void onError(Exception exception) { onException.accept(CognitoAuthExceptionConverter.lookup( exception, ""Fetching authorization session failed."")); } }); } catch (Throwable exception) { onException.accept(new AuthException( ""An error occurred fetching authorization details for the current user"", exception, ""See attached exception for more details"" )); } }","fix(auth): throw correct auth exception for code mismatch (#1370) * fix(auth): #1102 throw correct auth exception for code mismatch * Add multifactor not found auth exception with detailed messaging * Update aws-auth-cognito/src/main/java/com/amplifyframework/auth/cognito/util/CognitoAuthExceptionConverter.java Co-authored-by: Chang Xu <42978935+changxu0306@users.noreply.github.com> * move to fit import rule * float all generic errors to exception mapper * add software token mfa exception * add more missing exceptions * reorder imports as per checkstyle * Update core/src/main/java/com/amplifyframework/auth/AuthException.java Co-authored-by: Chang Xu <42978935+changxu0306@users.noreply.github.com> * Update core/src/main/java/com/amplifyframework/auth/AuthException.java Co-authored-by: Chang Xu <42978935+changxu0306@users.noreply.github.com> * fix documentation description * fix checkstyle errors Co-authored-by: Chang Xu <42978935+changxu0306@users.noreply.github.com>",https://github.com/aws-amplify/amplify-android/commit/4cd7cfee41bac3635974149b4ca6dd269e0cc19b,,,aws-auth-cognito/src/main/java/com/amplifyframework/auth/cognito/AWSCognitoAuthPlugin.java,3,java,False,2021-06-11T21:51:07Z "@Override public boolean actPrimary( Platform server, LocalConfiguration config, Player player, LocalSession session, Location clicked, @Nullable Direction face ) { World world = (World) clicked.getExtent(); BlockVector3 blockPoint = clicked.toBlockPoint(); final BlockType blockType = world.getBlock(blockPoint).getBlockType(); if (blockType == BlockTypes.BEDROCK && !player.canDestroyBedrock()) { return false; } try (EditSession editSession = session.createEditSession(player)) { editSession.getSurvivalExtent().setToolUse(config.superPickaxeDrop); editSession.setBlock(blockPoint, BlockTypes.AIR.getDefaultState()); session.remember(editSession); } catch (MaxChangedBlocksException e) { player.print(Caption.of(""worldedit.tool.max-block-changes"")); } return true; }","@Override public boolean actPrimary( Platform server, LocalConfiguration config, Player player, LocalSession session, Location clicked, @Nullable Direction face ) { World world = (World) clicked.getExtent(); BlockVector3 blockPoint = clicked.toBlockPoint(); final BlockType blockType = world.getBlock(blockPoint).getBlockType(); if (blockType == BlockTypes.BEDROCK && !player.canDestroyBedrock()) { return false; } try (EditSession editSession = session.createEditSession(player)) { try { editSession.getSurvivalExtent().setToolUse(config.superPickaxeDrop); editSession.setBlock(blockPoint, BlockTypes.AIR.getDefaultState()); } catch (MaxChangedBlocksException e) { player.print(Caption.of(""worldedit.tool.max-block-changes"")); } finally { session.remember(editSession); } } return true; }","Fix major security bugs (3 brushes + superpickaxe)! (#1213) * Fix major security bugs (3 brushes + superpickaxe)! - Due to some recent changes, FAWE could edit everything in the world, no matter other plugin protections such as PS or WG. - Fix superpickaxe allow to bypass protections => Fix SurvivalModeExtent not taking into account protections plugins due to breaking blocks naturally to get drops. * Adress requests - Revert some unsuitabe changes - Add FAWE diff comments * Clean imports * Adress requests Co-authored-by: NotMyFault ",https://github.com/IntellectualSites/FastAsyncWorldEdit/commit/abaa347ad4856b209c741a8b29884d14a54c4b3d,,,worldedit-core/src/main/java/com/sk89q/worldedit/command/tool/SinglePickaxe.java,3,java,False,2021-08-07T09:09:33Z "public void invalidate(X11GraphicsDevice device) { screen = device.screen; if (X11GraphicsEnvironment.useBoundsCache()) resetBoundsCache(); }","public void invalidate(X11GraphicsDevice device) { screen = device.screen; // Only done while holding the AWT lock if (X11GraphicsEnvironment.useBoundsCache()) resetBoundsCache(); }","JBR-3623 SIGSEGV at [libawt_xawt] Java_sun_awt_X11GraphicsDevice_getConfigColormap This fix addresses two possible causes of crashes: 1. makeDefaultConfig() returning NULL. The fix is to die gracefully instead of crashing in an attempt to de-reference the NULL pointer. 2. A race condition when the number of screens change (this is only an issue with the number of xinerama screens; the number of X11 screens is static for the duration of the X session). The race scenario: X11GraphisDevice.makeDefaultConfiguration() is called on EDT so the call can race with X11GraphisDevice.invalidate() that re-sets the screen number of the device; the latter is invoked on the ""AWT-XAWT"" thread from X11GraphicsEnvironment.rebuildDevices(). So by the time makeDefaultConfiguration() makes a native call with the device's current screen number, the x11Screens array maintained by the native code could have become shorter. And the native methods like Java_sun_awt_X11GraphicsDevice_getConfigColormap() assume that the screen number passed to them is always current and valid. The AWT lock only protects against the changes during the native methods invocation, but does not protect against them being called with an outdated screen number. The fix is to eliminate the race by protecting X11GraphisDevice.screen with the AWT lock. (cherry picked from commit 0b53cd291fac8c031f84ea1bdac23693e68f259e) (cherry picked from commit 3a15dfad37e57c124733a6360f008cfe61dd95ec)",https://github.com/JetBrains/JetBrainsRuntime/commit/aed4d3e0ff96d026391f4598f4e10952fa425ae4,,,src/java.desktop/unix/classes/sun/awt/X11GraphicsDevice.java,3,java,False,2021-10-26T13:33:48Z "public static ShortcutPackage loadFromXml(ShortcutService s, ShortcutUser shortcutUser, XmlPullParser parser, boolean fromBackup) throws IOException, XmlPullParserException { final String packageName = ShortcutService.parseStringAttribute(parser, ATTR_NAME); final ShortcutPackage ret = new ShortcutPackage(shortcutUser, shortcutUser.getUserId(), packageName); ret.mApiCallCount = ShortcutService.parseIntAttribute(parser, ATTR_CALL_COUNT); ret.mLastResetTime = ShortcutService.parseLongAttribute(parser, ATTR_LAST_RESET); final int outerDepth = parser.getDepth(); int type; while ((type = parser.next()) != XmlPullParser.END_DOCUMENT && (type != XmlPullParser.END_TAG || parser.getDepth() > outerDepth)) { if (type != XmlPullParser.START_TAG) { continue; } final int depth = parser.getDepth(); final String tag = parser.getName(); if (depth == outerDepth + 1) { switch (tag) { case ShortcutPackageInfo.TAG_ROOT: ret.getPackageInfo().loadFromXml(parser, fromBackup); continue; case TAG_SHORTCUT: final ShortcutInfo si = parseShortcut(parser, packageName, shortcutUser.getUserId(), fromBackup); // Don't use addShortcut(), we don't need to save the icon. ret.mShortcuts.put(si.getId(), si); continue; case TAG_SHARE_TARGET: ret.mShareTargets.add(ShareTargetInfo.loadFromXml(parser)); continue; } } ShortcutService.warnForInvalidTag(depth, tag); } return ret; }","public static ShortcutPackage loadFromXml(ShortcutService s, ShortcutUser shortcutUser, XmlPullParser parser, boolean fromBackup) throws IOException, XmlPullParserException { final String packageName = ShortcutService.parseStringAttribute(parser, ATTR_NAME); final ShortcutPackage ret = new ShortcutPackage(shortcutUser, shortcutUser.getUserId(), packageName); ret.mApiCallCount = ShortcutService.parseIntAttribute(parser, ATTR_CALL_COUNT); ret.mLastResetTime = ShortcutService.parseLongAttribute(parser, ATTR_LAST_RESET); final int outerDepth = parser.getDepth(); int type; while ((type = parser.next()) != XmlPullParser.END_DOCUMENT && (type != XmlPullParser.END_TAG || parser.getDepth() > outerDepth)) { if (type != XmlPullParser.START_TAG) { continue; } final int depth = parser.getDepth(); final String tag = parser.getName(); if (depth == outerDepth + 1) { switch (tag) { case ShortcutPackageInfo.TAG_ROOT: ret.getPackageInfo().loadFromXml(parser, fromBackup); continue; case TAG_SHORTCUT: try { final ShortcutInfo si = parseShortcut(parser, packageName, shortcutUser.getUserId(), fromBackup); // Don't use addShortcut(), we don't need to save the icon. ret.mShortcuts.put(si.getId(), si); } catch (Exception e) { // b/246540168 malformed shortcuts should be ignored Slog.e(TAG, ""Failed parsing shortcut."", e); } continue; case TAG_SHARE_TARGET: ret.mShareTargets.add(ShareTargetInfo.loadFromXml(parser)); continue; } } ShortcutService.warnForInvalidTag(depth, tag); } return ret; }","[Do Not Merge] Ignore malformed shortcuts After an app publishes a shortcut that contains malformed intent, the system can be stuck in boot-loop due to uncaught exception caused by parsing the malformed intent. This CL ignores that particular malformed entry. Since shortcuts are constantly writes back into the xml from system memory, the malformed entry will be removed from the xml the next time system persists shortcuts from memory to file system. Bug: 246540168 Change-Id: Ie1e39005a5f9d8038bd703a5bc845779c2f46e94 Test: manual",https://github.com/LineageOS/android_frameworks_base/commit/9b0dd514d29bbf986f1d1a3c6cebc2ef2bcf782e,,,services/core/java/com/android/server/pm/ShortcutPackage.java,3,java,False,2022-09-21T23:03:11Z "function isExec(command){ try{ exec(command, { stdio: 'ignore' }) return true } catch (_e){ return false } }","function isExec(command){ try{ exec(quote(command.split("" "")), { stdio: 'ignore' }) return true } catch (_e){ return false } }",Start using shell quote,https://github.com/shime/find-exec/commit/74fb108097c229b03d6dba4cce81e36aa364b51c,CVE-2023-40582,['CWE-78'],index.js,3,js,False,2023-08-24T06:58:36Z "public static void getKeyPair() throws Exception { //KeyPairGenerator类用于生成公钥和密钥对,基于RSA算法生成对象 KeyPairGenerator keyPairGen = KeyPairGenerator.getInstance(""RSA""); //初始化密钥对生成器,密钥大小为96-1024位 keyPairGen.initialize(1024, new SecureRandom()); //生成一个密钥对,保存在keyPair中 KeyPair keyPair = keyPairGen.generateKeyPair(); PrivateKey privateKey = keyPair.getPrivate();//得到私钥 PublicKey publicKey = keyPair.getPublic();//得到公钥 //得到公钥字符串 String publicKeyString = new String(Base64.encodeBase64(publicKey.getEncoded())); //得到私钥字符串 String privateKeyString = new String(Base64.encodeBase64(privateKey.getEncoded())); //将公钥和私钥保存到Map keyMap.put(0, publicKeyString);//0表示公钥 keyMap.put(1, privateKeyString);//1表示私钥 }","public static void getKeyPair() throws Exception { //KeyPairGenerator类用于生成公钥和密钥对,基于RSA算法生成对象 KeyPairGenerator keyPairGen = KeyPairGenerator.getInstance(""RSA""); keyPairGen.initialize(2048, new SecureRandom()); //生成一个密钥对,保存在keyPair中 KeyPair keyPair = keyPairGen.generateKeyPair(); PrivateKey privateKey = keyPair.getPrivate();//得到私钥 PublicKey publicKey = keyPair.getPublic();//得到公钥 //得到公钥字符串 String publicKeyString = new String(Base64.encodeBase64(publicKey.getEncoded())); //得到私钥字符串 String privateKeyString = new String(Base64.encodeBase64(privateKey.getEncoded())); //将公钥和私钥保存到Map keyMap.put(0, publicKeyString);//0表示公钥 keyMap.put(1, privateKeyString);//1表示私钥 }","security fix Signed-off-by: zhichengpi ",https://github.com/FederatedAI/FATE-Board/commit/7eca097656c780ef1f8602bb6807927baefdd789,,,src/main/java/com/webank/ai/fate/board/utils/StandardRSAUtils.java,3,java,False,2022-12-14T07:06:22Z "private void performSmartAttackTarget(CombatStack stack) { //ail: skip repulsor and stasis-field in first round for (int i=0;i",https://github.com/rayfowler/rotp-public/commit/dd4fde13156daa4e16f84e196d58e4c415bfd012,,,src/rotp/model/ai/xilmi/AIShipCaptain.java,3,java,False,2021-04-20T16:42:22Z "size_t ieee802154_get_frame_hdr_len(const uint8_t *mhr) { /* TODO: include security header implications */ uint8_t tmp; size_t len = 3; /* 2 byte FCF, 1 byte sequence number */ /* figure out address sizes */ tmp = (mhr[1] & IEEE802154_FCF_DST_ADDR_MASK); if (tmp == IEEE802154_FCF_DST_ADDR_SHORT) { len += 4; /* 2 byte dst PAN + 2 byte dst short address */ } else if (tmp == IEEE802154_FCF_DST_ADDR_LONG) { len += 10; /* 2 byte dst PAN + 2 byte dst long address */ } else if (tmp != IEEE802154_FCF_DST_ADDR_VOID) { return 0; } else if (mhr[0] & IEEE802154_FCF_PAN_COMP) { /* PAN compression, but no destination address => illegal state */ return 0; } tmp = (mhr[1] & IEEE802154_FCF_SRC_ADDR_MASK); if (tmp == IEEE802154_FCF_SRC_ADDR_VOID) { return len; } else { if (!(mhr[0] & IEEE802154_FCF_PAN_COMP)) { len += 2; } if (tmp == IEEE802154_FCF_SRC_ADDR_SHORT) { return len + 2; } else if (tmp == IEEE802154_FCF_SRC_ADDR_LONG) { return len + 8; } } return 0; }","size_t ieee802154_get_frame_hdr_len(const uint8_t *mhr) { /* TODO: include security header implications */ uint8_t tmp, has_dst = 0; size_t len = 3; /* 2 byte FCF, 1 byte sequence number */ tmp = (mhr[0] & IEEE802154_FCF_TYPE_MASK); if (tmp == IEEE802154_FCF_TYPE_ACK) { /* ACK contains no other fields */ return len; } else if (tmp != IEEE802154_FCF_TYPE_BEACON) { /* Beacon contains no dst address */ tmp = (mhr[1] & IEEE802154_FCF_DST_ADDR_MASK); if (tmp == IEEE802154_FCF_DST_ADDR_SHORT) { len += 4; /* 2 byte dst PAN + 2 byte dst short address */ has_dst = 1; } else if (tmp == IEEE802154_FCF_DST_ADDR_LONG) { len += 10; /* 2 byte dst PAN + 8 byte dst long address */ has_dst = 1; } else if (tmp != IEEE802154_FCF_DST_ADDR_VOID) { return 0; } else if (mhr[0] & IEEE802154_FCF_PAN_COMP) { /* PAN compression, but no destination address => illegal state */ return 0; } } else if (mhr[0] & IEEE802154_FCF_PAN_COMP) { /* Beacon can't use PAN compression */ return 0; } tmp = (mhr[1] & IEEE802154_FCF_SRC_ADDR_MASK); if (tmp == IEEE802154_FCF_SRC_ADDR_VOID) { /* One of dst or src address must be present */ return has_dst ? len : 0; } else { if (!(mhr[0] & IEEE802154_FCF_PAN_COMP)) { len += 2; } if (tmp == IEEE802154_FCF_SRC_ADDR_SHORT) { return len + 2; } else if (tmp == IEEE802154_FCF_SRC_ADDR_LONG) { return len + 8; } } return 0; }","ieee802154: Adjust parsing of IEEE 802.15.4 frame header (cherry picked from commit 0bec3e245ed3815ad6c8cae54673f0021777768b)",https://github.com/RIOT-OS/RIOT/commit/f4df5b4c4f841ccb460930894cf68ab10b55b971,,,sys/net/link_layer/ieee802154/ieee802154.c,3,c,False,2022-10-07T09:38:06Z "@Override public boolean preProcess(Packet packet, XMPPResourceConnection session, NonAuthUserRepository repo, Queue results, Map settings) { boolean stop = false; if ((session == null) || session.isServerSession()) { return stop; } VHostItem vhost = session.getDomain(); if (log.isLoggable(Level.FINEST)) { log.log(Level.FINEST, ""VHost: {0}"", new Object[]{vhost}); } // Check whether the TLS has been completed // and the packet is allowed to be processed. if ((vhost != null) && session.isTlsRequired() && (session.getSessionData(ID) == null) && !packet.isElement(EL_NAME, XMLNS)) { stop = true; } return stop; }","@Override public boolean preProcess(Packet packet, XMPPResourceConnection session, NonAuthUserRepository repo, Queue results, Map settings) { boolean stop = false; if ((session == null) || session.isServerSession()) { return stop; } VHostItem vhost = session.getDomain(); if (log.isLoggable(Level.FINEST)) { log.log(Level.FINEST, ""VHost: {0}"", new Object[]{vhost}); } // Check whether the TLS has been completed // and the packet is allowed to be processed. if ((vhost != null) && (session.isTlsRequired() && !session.isEncrypted()) && !packet.isElement(EL_NAME, XMLNS)) { stop = true; } return stop; }",Fixed advertisement stream features for unauthorized stream #server-1334,https://github.com/tigase/tigase-server/commit/b9bc6f1db3891f1b4c80d28281cf7678f284892f,,,src/main/java/tigase/xmpp/impl/StartTLS.java,3,java,False,2022-10-07T14:16:48Z "@Override public byte[] transform(String name, String transformedName, byte[] basicClass) { if (!name.equals(""cofh.lib.util.ComparableItem"") && !name.equals(""cofh.lib.util.ItemWrapper"")) return basicClass; ClassNode classNode = new ClassNode(); ClassReader classReader = new ClassReader(basicClass); classReader.accept(classNode, 0); // Screw that improperly coded Hashcode Function that violates Java Standards and crashes the Game. // I'm gonna return 0 for it no matter what. It was broken before anyways, so I don't hurt anything. // Also here have some comedy right from the Javadocs of the Class I am fixing with this ASM. // Description of the cofh.lib.util.ComparableItem Class: // ""Wrapper for an Item/Metadata combination post 1.7. Quick and dirty, allows for Integer-based Hashes without collisions."" // What actually is inside the hashcode Function: // ""todo: this hash conflicts a lot"" // return (metadata & 65535) | getId() << 16; // And yes the getId() part violates the Hash Rule of Java since Item IDs constantly change when you load Worlds or join Servers. for (MethodNode m: classNode.methods) if (m.name.equals(""hashcode"")) { GT_ASM.logger.info(""Transforming "" + transformedName + "".hashcode""); // TODO: Put an Identity Hash for the Item instance, but DO NOT combine it with the metadata due to Wildcard Issues! // TODO: Maybe just hash the name of it and be done with it... m.instructions.clear(); m.instructions.insert(new InsnNode(Opcodes.ICONST_0)); m.instructions.insert(new InsnNode(Opcodes.IRETURN)); break; } ClassWriter writer = new ClassWriter(ClassWriter.COMPUTE_MAXS | ClassWriter.COMPUTE_FRAMES); classNode.accept(writer); return writer.toByteArray(); }","@Override public byte[] transform(String name, String transformedName, byte[] basicClass) { if (!name.equals(""cofh.lib.util.ComparableItem"") && !name.equals(""cofh.lib.util.ItemWrapper"")) return basicClass; ClassNode classNode = new ClassNode(); ClassReader classReader = new ClassReader(basicClass); classReader.accept(classNode, 0); // Screw that improperly coded Hashcode Function that violates Java Standards and crashes the Game. // Here have some comedy right from the Javadocs of the Class I am fixing with this ASM. // Description of the cofh.lib.util.ComparableItem Class: // ""Wrapper for an Item/Metadata combination post 1.7. Quick and dirty, allows for Integer-based Hashes without collisions."" // What actually is inside the hashcode Function: // ""todo: this hash conflicts a lot"" // return (metadata & 65535) | getId() << 16; // And yes the getId() part violates the Hash Rule of Java since Item IDs constantly change when you load Worlds or join Servers. for (MethodNode m: classNode.methods) if (m.name.equals(""hashcode"")) { GT_ASM.logger.info(""Transforming "" + transformedName + "".hashcode""); // Just use the system identityHashCode, but DO NOT combine it with the metadata due to Wildcard Issues! m.instructions.clear(); m.instructions.add(new VarInsnNode(Opcodes.ALOAD, 1)); // Load world m.instructions.add(new MethodInsnNode(Opcodes.INVOKESTATIC, ""java/lang/System"", ""identityHashCode"", ""(Ljava/lang/Object;)I"", false)); m.instructions.add(new InsnNode(Opcodes.IRETURN)); break; } ClassWriter writer = new ClassWriter(ClassWriter.COMPUTE_MAXS | ClassWriter.COMPUTE_FRAMES); classNode.accept(writer); return writer.toByteArray(); }","Update the CoFHLib_HashFix from just crashing to actually being operational and not crashing, even though it doesn't really matter, still better to do things so they work even if not used usefully.",https://github.com/GregTech6/gregtech6/commit/b29c41e1fc555b4cf15228014f7eee84b0c93f5f,,,src/main/java/gregtech/asm/transformers/CoFHLib_HashFix.java,3,java,False,2021-04-05T14:51:17Z "public static void main(String[] args) throws IOException { ReplicatePrimitiveCode.intToLongAndFloatingPoints( ""extensions/parquet/base/src/main/java/io/deephaven/parquet/base/PlainIntChunkedWriter.java"", ""int pageSize"", ""IntBuffer.allocate\\(4\\)"", ""int originalLimit"", ""int writeBulk"", ""int valueCount"", ""int rowCount"", ""int nullCount"", ""writeInt\\("", ""IntBuffer repeatCount"", ""length != QueryConstants\\.NULL_INT"", ""int length"", ""int i = 0;"", ""int targetCapacity"", ""IntBuffer nullOffsets"", ""// Duplicate for Replication\nimport java.nio.IntBuffer;"", ""int newSize"", ""final int currentCapacity"", ""final int currentPosition"", ""final int targetPageSize"", ""int requiredCapacity"", ""int newCapacity"", ""int MAXIMUM_TOTAL_CAPACITY = Integer.MAX_VALUE"") .forEach(ReplicateParquetChunkedWriters::injectIntBuffer); }","public static void main(String[] args) throws IOException { ReplicatePrimitiveCode.intToLongAndFloatingPoints( ""extensions/parquet/base/src/main/java/io/deephaven/parquet/base/PlainIntChunkedWriter.java"", ""int pageSize"", ""IntBuffer.allocate\\(4\\)"", ""int originalLimit"", ""int writeBulk"", ""int valueCount"", ""int rowCount"", ""int nullCount"", ""writeInt\\("", ""IntBuffer repeatCount"", ""length != QueryConstants\\.NULL_INT"", ""int length"", ""int i = 0;"", ""int targetCapacity"", ""IntBuffer nullOffsets"", ""// Duplicate for Replication\nimport java.nio.IntBuffer;"", ""int newSize"", ""final int currentCapacity"", ""final int currentPosition"", ""final int targetPageSize"", ""int newCapacity"", ""MAXIMUM_TOTAL_CAPACITY <= Integer.MAX_VALUE / 2"", ""int MAXIMUM_TOTAL_CAPACITY = Integer.MAX_VALUE"") .forEach(ReplicateParquetChunkedWriters::injectIntBuffer); }","Fix infinite loop caused by integer overflow in ParquetTools.writeTable() (#3332) * Handle integer overflow while ensuring capacity. * Introduce a MAX_ARRAY_SIZE constant",https://github.com/deephaven/deephaven-core/commit/5c8095dbcbee623f84f8132b5e51d5f0929ddaf0,,,replication/static/src/main/java/io/deephaven/replicators/ReplicateParquetChunkedWriters.java,3,java,False,2023-01-20T23:29:16Z "@Override public void onBackPressed() { if (Common.isBusy()) return; if (Common.getSearchWord() != null) { if (Common.getAPKsSearchWord().getVisibility() == View.VISIBLE) { Common.getAPKsSearchWord().setVisibility(View.GONE); Common.getAPKsTitle().setVisibility(View.VISIBLE); Common.getAPKsSearchWord().setText(null); } else if (Common.getAppsSearchWord().getVisibility() == View.VISIBLE) { Common.getAppsSearchWord().setVisibility(View.GONE); Common.getAppsTitle().setVisibility(View.VISIBLE); Common.getAppsSearchWord().setText(null); } else if (Common.getProjectsSearchWord().getVisibility() == View.VISIBLE) { Common.getProjectsSearchWord().setVisibility(View.GONE); Common.getProjectsTitle().setVisibility(View.VISIBLE); Common.getProjectsSearchWord().setText(null); } Common.setSearchWord(null); return; } if (mExit) { mExit = false; finish(); } else { sUtils.snackBar(findViewById(android.R.id.content), getString(R.string.press_back)).show(); mExit = true; mHandler.postDelayed(() -> mExit = false, 2000); } }","@Override public void onBackPressed() { if (Common.isBusy()) return; if (Common.getSearchWord() != null) { if (Common.getAPKsSearchWord() != null && Common.getAPKsSearchWord().getVisibility() == View.VISIBLE) { Common.getAPKsSearchWord().setVisibility(View.GONE); Common.getAPKsTitle().setVisibility(View.VISIBLE); Common.getAPKsSearchWord().setText(null); } else if (Common.getAppsSearchWord() != null && Common.getAppsSearchWord().getVisibility() == View.VISIBLE) { Common.getAppsSearchWord().setVisibility(View.GONE); Common.getAppsTitle().setVisibility(View.VISIBLE); Common.getAppsSearchWord().setText(null); } else if (Common.getProjectsSearchWord() != null && Common.getProjectsSearchWord().getVisibility() == View.VISIBLE) { Common.getProjectsSearchWord().setVisibility(View.GONE); Common.getProjectsTitle().setVisibility(View.VISIBLE); Common.getProjectsSearchWord().setText(null); } Common.setSearchWord(null); return; } if (mExit) { mExit = false; finish(); } else { sUtils.snackBar(findViewById(android.R.id.content), getString(R.string.press_back)).show(); mExit = true; mHandler.postDelayed(() -> mExit = false, 2000); } }","Fixed possible crashes due to NullPointerException Signed-off-by: apk-editor ",https://github.com/apk-editor/APK-Explorer-Editor/commit/1d8ecb32a427e61783537468542c07cbb5eaafcb,,,app/src/main/java/com/apk/editor/MainActivity.java,3,java,False,2023-01-19T22:53:33Z "@SuppressWarnings(""squid:S3776"") // Suppress high Cognitive Complexity warning public void flushOneMemTable() { IMemTable memTableToFlush = flushingMemTables.getFirst(); // signal memtable only may appear when calling asyncClose() if (!memTableToFlush.isSignalMemTable()) { try { writer.mark(); MemTableFlushTask flushTask = new MemTableFlushTask(memTableToFlush, writer, storageGroupName); flushTask.syncFlushMemTable(); } catch (Exception e) { if (writer == null) { logger.info( ""{}: {} is closed during flush, abandon flush task"", storageGroupName, tsFileResource.getTsFile().getName()); synchronized (flushingMemTables) { flushingMemTables.notifyAll(); } } else { logger.error( ""{}: {} meet error when flushing a memtable, change system mode to read-only"", storageGroupName, tsFileResource.getTsFile().getName(), e); IoTDBDescriptor.getInstance().getConfig().setReadOnly(true); try { logger.error( ""{}: {} IOTask meets error, truncate the corrupted data"", storageGroupName, tsFileResource.getTsFile().getName(), e); writer.reset(); } catch (IOException e1) { logger.error( ""{}: {} Truncate corrupted data meets error"", storageGroupName, tsFileResource.getTsFile().getName(), e1); } Thread.currentThread().interrupt(); } } } for (FlushListener flushListener : flushListeners) { flushListener.onFlushEnd(memTableToFlush); } try { flushQueryLock.writeLock().lock(); Iterator> iterator = modsToMemtable.iterator(); while (iterator.hasNext()) { Pair entry = iterator.next(); if (entry.right.equals(memTableToFlush)) { entry.left.setFileOffset(tsFileResource.getTsFileSize()); this.tsFileResource.getModFile().write(entry.left); tsFileResource.getModFile().close(); iterator.remove(); logger.info( ""[Deletion] Deletion with path: {}, time:{}-{} written when flush memtable"", entry.left.getPath(), ((Deletion) (entry.left)).getStartTime(), ((Deletion) (entry.left)).getEndTime()); } } } catch (IOException e) { logger.error( ""Meet error when writing into ModificationFile file of {} "", tsFileResource.getTsFile().getName(), e); } finally { flushQueryLock.writeLock().unlock(); } if (logger.isDebugEnabled()) { logger.debug( ""{}: {} try get lock to release a memtable (signal={})"", storageGroupName, tsFileResource.getTsFile().getName(), memTableToFlush.isSignalMemTable()); } // for sync flush synchronized (memTableToFlush) { releaseFlushedMemTable(memTableToFlush); memTableToFlush.notifyAll(); if (logger.isDebugEnabled()) { logger.debug( ""{}: {} released a memtable (signal={}), flushingMemtables size ={}"", storageGroupName, tsFileResource.getTsFile().getName(), memTableToFlush.isSignalMemTable(), flushingMemTables.size()); } } if (shouldClose && flushingMemTables.isEmpty() && writer != null) { try { writer.mark(); updateCompressionRatio(memTableToFlush); if (logger.isDebugEnabled()) { logger.debug( ""{}: {} flushingMemtables is empty and will close the file"", storageGroupName, tsFileResource.getTsFile().getName()); } endFile(); if (logger.isDebugEnabled()) { logger.debug(""{} flushingMemtables is clear"", storageGroupName); } } catch (Exception e) { logger.error( ""{} meet error when flush FileMetadata to {}, change system mode to read-only"", storageGroupName, tsFileResource.getTsFile().getAbsolutePath(), e); IoTDBDescriptor.getInstance().getConfig().setReadOnly(true); try { writer.reset(); } catch (IOException e1) { logger.error( ""{}: {} truncate corrupted data meets error"", storageGroupName, tsFileResource.getTsFile().getName(), e1); } logger.error( ""{}: {} marking or ending file meet error"", storageGroupName, tsFileResource.getTsFile().getName(), e); } // for sync close if (logger.isDebugEnabled()) { logger.debug( ""{}: {} try to get flushingMemtables lock."", storageGroupName, tsFileResource.getTsFile().getName()); } synchronized (flushingMemTables) { flushingMemTables.notifyAll(); } } }","@SuppressWarnings(""squid:S3776"") // Suppress high Cognitive Complexity warning public void flushOneMemTable() { IMemTable memTableToFlush = flushingMemTables.getFirst(); // signal memtable only may appear when calling asyncClose() if (!memTableToFlush.isSignalMemTable()) { try { writer.mark(); MemTableFlushTask flushTask = new MemTableFlushTask(memTableToFlush, writer, storageGroupName); flushTask.syncFlushMemTable(); } catch (Exception e) { if (writer == null) { logger.info( ""{}: {} is closed during flush, abandon flush task"", storageGroupName, tsFileResource.getTsFile().getName()); synchronized (flushingMemTables) { flushingMemTables.notifyAll(); } } else { logger.error( ""{}: {} meet error when flushing a memtable, change system mode to read-only"", storageGroupName, tsFileResource.getTsFile().getName(), e); IoTDBDescriptor.getInstance().getConfig().setReadOnly(true); try { logger.error( ""{}: {} IOTask meets error, truncate the corrupted data"", storageGroupName, tsFileResource.getTsFile().getName(), e); writer.reset(); } catch (IOException e1) { logger.error( ""{}: {} Truncate corrupted data meets error"", storageGroupName, tsFileResource.getTsFile().getName(), e1); } // release resource try { syncReleaseFlushedMemTable(memTableToFlush); // close wal node MultiFileLogNodeManager.getInstance() .closeNode(storageGroupName + ""-"" + tsFileResource.getTsFile().getName()); // make sure no query will search this file tsFileResource.setTimeIndex(config.getTimeIndexLevel().getTimeIndex()); // this callback method will register this empty tsfile into TsFileManager for (CloseFileListener closeFileListener : closeFileListeners) { closeFileListener.onClosed(this); } // close writer writer.close(); writer = null; synchronized (flushingMemTables) { flushingMemTables.notifyAll(); } } catch (Exception e1) { logger.error( ""{}: {} Release resource meets error"", storageGroupName, tsFileResource.getTsFile().getName(), e1); } return; } } } for (FlushListener flushListener : flushListeners) { flushListener.onFlushEnd(memTableToFlush); } try { flushQueryLock.writeLock().lock(); Iterator> iterator = modsToMemtable.iterator(); while (iterator.hasNext()) { Pair entry = iterator.next(); if (entry.right.equals(memTableToFlush)) { entry.left.setFileOffset(tsFileResource.getTsFileSize()); this.tsFileResource.getModFile().write(entry.left); tsFileResource.getModFile().close(); iterator.remove(); logger.info( ""[Deletion] Deletion with path: {}, time:{}-{} written when flush memtable"", entry.left.getPath(), ((Deletion) (entry.left)).getStartTime(), ((Deletion) (entry.left)).getEndTime()); } } } catch (IOException e) { logger.error( ""Meet error when writing into ModificationFile file of {} "", tsFileResource.getTsFile().getName(), e); } finally { flushQueryLock.writeLock().unlock(); } if (logger.isDebugEnabled()) { logger.debug( ""{}: {} try get lock to release a memtable (signal={})"", storageGroupName, tsFileResource.getTsFile().getName(), memTableToFlush.isSignalMemTable()); } // for sync flush syncReleaseFlushedMemTable(memTableToFlush); if (shouldClose && flushingMemTables.isEmpty() && writer != null) { try { writer.mark(); updateCompressionRatio(memTableToFlush); if (logger.isDebugEnabled()) { logger.debug( ""{}: {} flushingMemtables is empty and will close the file"", storageGroupName, tsFileResource.getTsFile().getName()); } endFile(); if (logger.isDebugEnabled()) { logger.debug(""{} flushingMemtables is clear"", storageGroupName); } } catch (Exception e) { logger.error( ""{} meet error when flush FileMetadata to {}, change system mode to read-only"", storageGroupName, tsFileResource.getTsFile().getAbsolutePath(), e); IoTDBDescriptor.getInstance().getConfig().setReadOnly(true); try { writer.reset(); } catch (IOException e1) { logger.error( ""{}: {} truncate corrupted data meets error"", storageGroupName, tsFileResource.getTsFile().getName(), e1); } logger.error( ""{}: {} marking or ending file meet error"", storageGroupName, tsFileResource.getTsFile().getName(), e); } // for sync close if (logger.isDebugEnabled()) { logger.debug( ""{}: {} try to get flushingMemtables lock."", storageGroupName, tsFileResource.getTsFile().getName()); } synchronized (flushingMemTables) { flushingMemTables.notifyAll(); } } }",[IOTDB-3160] TsFile will be corrupted when flushing memtable appears OOM (#5926),https://github.com/apache/iotdb/commit/0762e1e897f1894d2d51f7ca10d8a4d57d6335a9,,,server/src/main/java/org/apache/iotdb/db/engine/storagegroup/TsFileProcessor.java,3,java,False,2022-05-17T07:19:53Z "@Override protected void setContent(int content) { if(this.isMultiBlockOrigin()) { float before = this.getLevel(); super.setContent(content); this.updateMultiBlockFluidStates(before, this.getLevel()); } else { this.getMultiBlockOrigin().setContent(content); } }","@Override protected void setContent(int content) { if(this.isMultiBlockOrigin()) { float before = this.getLevel(); super.setContent(content); this.updateMultiBlockFluidStates(before, this.getLevel()); } else { TileEntityIrrigationTank origin = this.getMultiBlockOrigin(); if(origin != null) { // origin can be null if the origin chunk is not loaded origin.setContent(content); } } }",Fix Irrigation tank crash (#1392),https://github.com/AgriCraft/AgriCraft/commit/32944e66e27d2b8acc4602a22eedc100ce3535b6,,,src/main/java/com/infinityraider/agricraft/content/irrigation/TileEntityIrrigationTank.java,3,java,False,2021-08-25T17:10:03Z "private CompletableFuture isNamespaceOperationAllowed(NamespaceName namespaceName, NamespaceOperation operation) { CompletableFuture isProxyAuthorizedFuture; CompletableFuture isAuthorizedFuture; if (service.isAuthorizationEnabled()) { if (originalPrincipal != null) { isProxyAuthorizedFuture = service.getAuthorizationService().allowNamespaceOperationAsync( namespaceName, operation, originalPrincipal, getAuthenticationData()); } else { isProxyAuthorizedFuture = CompletableFuture.completedFuture(true); } isAuthorizedFuture = service.getAuthorizationService().allowNamespaceOperationAsync( namespaceName, operation, authRole, authenticationData); } else { isProxyAuthorizedFuture = CompletableFuture.completedFuture(true); isAuthorizedFuture = CompletableFuture.completedFuture(true); } return isProxyAuthorizedFuture.thenCombine(isAuthorizedFuture, (isProxyAuthorized, isAuthorized) -> { if (!isProxyAuthorized) { log.warn(""OriginalRole {} is not authorized to perform operation {} on namespace {}"", originalPrincipal, operation, namespaceName); } if (!isAuthorized) { log.warn(""Role {} is not authorized to perform operation {} on namespace {}"", authRole, operation, namespaceName); } return isProxyAuthorized && isAuthorized; }); }","private CompletableFuture isNamespaceOperationAllowed(NamespaceName namespaceName, NamespaceOperation operation) { if (!service.isAuthorizationEnabled()) { return CompletableFuture.completedFuture(true); } CompletableFuture isProxyAuthorizedFuture; if (originalPrincipal != null) { isProxyAuthorizedFuture = service.getAuthorizationService().allowNamespaceOperationAsync( namespaceName, operation, originalPrincipal, originalAuthData); } else { isProxyAuthorizedFuture = CompletableFuture.completedFuture(true); } CompletableFuture isAuthorizedFuture = service.getAuthorizationService().allowNamespaceOperationAsync( namespaceName, operation, authRole, authenticationData); return isProxyAuthorizedFuture.thenCombine(isAuthorizedFuture, (isProxyAuthorized, isAuthorized) -> { if (!isProxyAuthorized) { log.warn(""OriginalRole {} is not authorized to perform operation {} on namespace {}"", originalPrincipal, operation, namespaceName); } if (!isAuthorized) { log.warn(""Role {} is not authorized to perform operation {} on namespace {}"", authRole, operation, namespaceName); } return isProxyAuthorized && isAuthorized; }); }","[fix][broker] Fix passing incorrect authentication data (#16201) (#16840) ### Motivation #16065 fixes the race condition issue, but introduces a new issue. This issue is triggered when the Proxy and Broker work together, when we use the proxy to request the broker to do lookup/subscribe/produce operation, the broker always uses the original authentication data for authorization, not proxy authentication data, which causes this issue. ### Modification - Fix passing authentication data, differentiate between original auth data and connected auth data by avoid to use the `getAuthenticationData()`, this method name is easy to cause confusion and can not correctly get the authentication data (cherry picked from commit 936bbbcc6a4e8cf61547aeedf92e84fb3a089502) Signed-off-by: Zixuan Liu ",https://github.com/apache/pulsar/commit/bc67e203316721d91a3271134279b8c6fd62edcb,,,pulsar-broker/src/main/java/org/apache/pulsar/broker/service/ServerCnx.java,3,java,False,2022-08-02T07:06:50Z "@Override protected HttpProblem toProblem(UnauthorizedException exception) { return HttpProblem.valueOf(UNAUTHORIZED, exception.getMessage()); }","@Override protected HttpProblem toProblem(UnauthorizedException exception) { return HttpUnauthorizedUtils.toProblem(currentVertxRequest().getCurrent(), exception) .await().indefinitely(); }","[#237] Fix for: HttpAuthenticator is ignored when authentication fails (#238) * [#237] Fix for: HttpAuthenticator is ignored when authentication fails Closes #237 Closes #108",https://github.com/TietoEVRY/quarkus-resteasy-problem/commit/409a8dbee9e962ef1c9d788e3e96d19e8cab9e6a,,,runtime/src/main/java/com/tietoevry/quarkus/resteasy/problem/security/UnauthorizedExceptionMapper.java,3,java,False,2022-10-20T15:19:07Z "@Override public void initEntityValues() { if (!getEntity().isPresent()) { return; } final AbstractEntityCitizen citizen = getEntity().get(); citizen.setCitizenId(getId()); citizen.getCitizenColonyHandler().setColonyId(getColony().getID()); citizen.setIsChild(isChild()); citizen.setCustomName(Component.literal(getName())); citizen.getAttribute(Attributes.MAX_HEALTH).setBaseValue(BASE_MAX_HEALTH); citizen.setFemale(isFemale()); citizen.setTextureId(getTextureId()); citizen.getEntityData().set(DATA_COLONY_ID, colony.getID()); citizen.getEntityData().set(DATA_CITIZEN_ID, citizen.getCivilianID()); citizen.getEntityData().set(DATA_IS_FEMALE, citizen.isFemale() ? 1 : 0); citizen.getEntityData().set(DATA_TEXTURE, citizen.getTextureId()); citizen.getEntityData().set(DATA_TEXTURE_SUFFIX, getTextureSuffix()); citizen.getEntityData().set(DATA_IS_ASLEEP, isAsleep()); citizen.getEntityData().set(DATA_IS_CHILD, isChild()); citizen.getEntityData().set(DATA_BED_POS, getBedPos()); citizen.getEntityData().set(DATA_JOB, getJob() == null ? """" : getJob().getJobRegistryEntry().getKey().toString()); citizen.getEntityData().set(DATA_STYLE, colony.getTextureStyleId()); citizen.getCitizenExperienceHandler().updateLevel(); setLastPosition(citizen.blockPosition()); citizen.getCitizenJobHandler().onJobChanged(citizen.getCitizenJobHandler().getColonyJob()); applyResearchEffects(); applyItemModifiers(citizen); markDirty(); }","@Override public void initEntityValues() { if (!getEntity().isPresent()) { return; } final AbstractEntityCitizen citizen = getEntity().get(); citizen.setCitizenId(getId()); citizen.getCitizenColonyHandler().setColonyId(getColony().getID()); citizen.setIsChild(isChild()); citizen.setCustomName(Component.literal(getName())); citizen.getAttribute(Attributes.MAX_HEALTH).setBaseValue(BASE_MAX_HEALTH); citizen.setFemale(isFemale()); citizen.setTextureId(getTextureId()); citizen.getEntityData().set(DATA_COLONY_ID, colony.getID()); citizen.getEntityData().set(DATA_CITIZEN_ID, citizen.getCivilianID()); citizen.getEntityData().set(DATA_IS_FEMALE, citizen.isFemale() ? 1 : 0); citizen.getEntityData().set(DATA_TEXTURE, citizen.getTextureId()); citizen.getEntityData().set(DATA_TEXTURE_SUFFIX, getTextureSuffix()); citizen.getEntityData().set(DATA_IS_ASLEEP, isAsleep()); citizen.getEntityData().set(DATA_IS_CHILD, isChild()); citizen.getEntityData().set(DATA_BED_POS, getBedPos()); citizen.getEntityData().set(DATA_JOB, getJob() == null ? """" : getJob().getJobRegistryEntry().getKey().toString()); citizen.getEntityData().set(DATA_STYLE, colony.getTextureStyleId()); // Safety check that ensure the citizen its job matches the work building job if (getJob() != null && workBuilding != null) { boolean hasCorrectJob = false; for (WorkerBuildingModule module : workBuilding.getModules(WorkerBuildingModule.class)) { if (module.getJobEntry().equals(getJob().getJobRegistryEntry())) { hasCorrectJob = true; break; } } if (!hasCorrectJob) { MessageUtils.format(DEBUG_WARNING_CITIZEN_LOAD_FAILURE, citizen.getName()).sendTo(colony).forAllPlayers(); Log.getLogger().log(Level.ERROR, String.format(""Worker %s has been unassigned from his job, a problem was found during load. Worker job: %s; Building: %s"", citizen.getName().getString(), getJob().getJobRegistryEntry().getKey().toString(), workBuilding.getBuildingType().getRegistryName().toString())); // Remove the citizen from the building to prevent failures in the future. for (WorkerBuildingModule module : workBuilding.getModules(WorkerBuildingModule.class)) { module.removeCitizen(this); } } } citizen.getCitizenExperienceHandler().updateLevel(); setLastPosition(citizen.blockPosition()); citizen.getCitizenJobHandler().onJobChanged(citizen.getCitizenJobHandler().getColonyJob()); applyResearchEffects(); applyItemModifiers(citizen); markDirty(); }","Fix NBT assignment corruption (#8905) In some cases it's possible that NBT data gets corrupted and causes citizens their jobs to no longer match the expected job in the building they are assigned to. This fix will prevent any loading issues by unassigning the worker when an improper link between the citizen it's job and building is found, to prevent any crashes.",https://github.com/ldtteam/minecolonies/commit/78567c2636f8c9437a207afa17f22176d5fdaab4,,,src/main/java/com/minecolonies/coremod/colony/CitizenData.java,3,java,False,2023-01-22T12:20:02Z "private boolean userAuthenticationService() { if (externalAuthenticationService.isEnabled(AuthenticationScriptUsageType.SERVICE)) { CustomScriptConfiguration customScriptConfiguration = externalAuthenticationService .determineCustomScriptConfiguration(AuthenticationScriptUsageType.SERVICE, 1, this.authAcr); if (customScriptConfiguration == null) { logger.error(""Failed to get CustomScriptConfiguration. auth_step: '{}', acr: '{}'"", this.authStep, this.authAcr); } else { this.authAcr = customScriptConfiguration.getName(); boolean result = externalAuthenticationService.executeExternalAuthenticate(customScriptConfiguration, null, 1); logger.info(""Authentication result for '{}'. auth_step: '{}', result: '{}'"", credentials.getUsername(), this.authStep, result); if (result) { authenticationService.configureEventUser(); logger.info(""Authentication success for User: '{}'"", credentials.getUsername()); return true; } logger.info(""Authentication failed for User: '{}'"", credentials.getUsername()); } } if (StringHelper.isNotEmpty(credentials.getUsername())) { boolean authenticated = authenticationService.authenticate(credentials.getUsername(), credentials.getPassword()); if (authenticated) { authenticationService.configureEventUser(); logger.info(""Authentication success for User: '{}'"", credentials.getUsername()); return true; } logger.info(""Authentication failed for User: '{}'"", credentials.getUsername()); } return false; }","private boolean userAuthenticationService() { if (externalAuthenticationService.isEnabled(AuthenticationScriptUsageType.SERVICE)) { CustomScriptConfiguration customScriptConfiguration = externalAuthenticationService .determineCustomScriptConfiguration(AuthenticationScriptUsageType.SERVICE, 1, this.authAcr); if (customScriptConfiguration == null) { logger.error(""Failed to get CustomScriptConfiguration. auth_step: '{}', acr: '{}'"", this.authStep, this.authAcr); } else { this.authAcr = customScriptConfiguration.getName(); boolean result = externalAuthenticationService.executeExternalAuthenticate(customScriptConfiguration, null, 1); logger.info(""Authentication result for '{}'. auth_step: '{}', result: '{}'"", credentials.getUsername(), this.authStep, result); if (result) { authenticationService.configureEventUser(); logger.info(AUTHENTICATION_SUCCESS_FOR_USER, credentials.getUsername()); return true; } logger.info(""Authentication failed for User: '{}'"", credentials.getUsername()); } } if (StringHelper.isNotEmpty(credentials.getUsername())) { boolean authenticated = authenticationService.authenticate(credentials.getUsername(), credentials.getPassword()); if (authenticated) { authenticationService.configureEventUser(); logger.info(AUTHENTICATION_SUCCESS_FOR_USER, credentials.getUsername()); return true; } logger.info(""Authentication failed for User: '{}'"", credentials.getUsername()); } return false; }",fix: corrected issues in Authenticator (sonar),https://github.com/JanssenProject/jans/commit/27c687c1b3be2032fa3f0a95f7046d4fc3f2992f,,,server/src/main/java/io/jans/as/server/auth/Authenticator.java,3,java,False,2021-10-18T19:59:02Z "private void sendPendingStreaming(@Nullable String cause) { final IntentSender statusReceiver; synchronized (mLock) { statusReceiver = mRemoteStatusReceiver; } if (statusReceiver == null) { Slog.e(TAG, ""Missing receiver for pending streaming status.""); return; } final Intent intent = new Intent(); intent.putExtra(PackageInstaller.EXTRA_SESSION_ID, sessionId); intent.putExtra(PackageInstaller.EXTRA_STATUS, PackageInstaller.STATUS_PENDING_STREAMING); if (!TextUtils.isEmpty(cause)) { intent.putExtra(PackageInstaller.EXTRA_STATUS_MESSAGE, ""Staging Image Not Ready ["" + cause + ""]""); } else { intent.putExtra(PackageInstaller.EXTRA_STATUS_MESSAGE, ""Staging Image Not Ready""); } try { statusReceiver.sendIntent(mContext, 0, intent, null, null); } catch (IntentSender.SendIntentException ignored) { } }","private void sendPendingStreaming(@Nullable String cause) { final IntentSender statusReceiver; synchronized (mLock) { statusReceiver = mRemoteStatusReceiver; } if (statusReceiver == null) { Slog.e(TAG, ""Missing receiver for pending streaming status.""); return; } final Intent intent = new Intent(); intent.putExtra(PackageInstaller.EXTRA_SESSION_ID, sessionId); intent.putExtra(PackageInstaller.EXTRA_STATUS, PackageInstaller.STATUS_PENDING_STREAMING); if (!TextUtils.isEmpty(cause)) { intent.putExtra(PackageInstaller.EXTRA_STATUS_MESSAGE, ""Staging Image Not Ready ["" + cause + ""]""); } else { intent.putExtra(PackageInstaller.EXTRA_STATUS_MESSAGE, ""Staging Image Not Ready""); } try { final BroadcastOptions options = BroadcastOptions.makeBasic(); options.setPendingIntentBackgroundActivityLaunchAllowed(false); statusReceiver.sendIntent(mContext, 0, intent, null /* onFinished*/, null /* handler */, null /* requiredPermission */, options.toBundle()); } catch (IntentSender.SendIntentException ignored) { } }","[RESTRICT AUTOMERGE] Fix bypass BG-FGS and BAL via package manager APIs Opt-in for BAL of PendingIntent for following APIs: * PackageInstaller.uninstall() * PackageInstaller.installExistingPackage() * PackageInstaller.uninstallExistingPackage() * PackageInstaller.Session.commit() * PackageInstaller.Session.commitTransferred() * PackageManager.freeStorage() Bug: 230492955 Bug: 243377226 Test: atest android.security.cts.PackageInstallerTest Test: atest CtsStagedInstallHostTestCases Change-Id: I9b6f801d69ea6d2244a38dbe689e81afa4e798bf",https://github.com/PixelExperience/frameworks_base/commit/b0b1ddb4b4ba5db27f5616b02ae2cdca8b63496f,,,services/core/java/com/android/server/pm/PackageInstallerSession.java,3,java,False,2023-01-11T08:02:27Z "function push () { let value switch (token.type) { case 'punctuator': switch (token.value) { case '{': value = {} break case '[': value = [] break } break case 'null': case 'boolean': case 'numeric': case 'string': value = token.value break // This code is unreachable. // default: // throw invalidToken() } if (root === undefined) { root = value } else { const parent = stack[stack.length - 1] if (Array.isArray(parent)) { parent.push(value) } else { parent[key] = value } } if (value !== null && typeof value === 'object') { stack.push(value) if (Array.isArray(value)) { parseState = 'beforeArrayValue' } else { parseState = 'beforePropertyName' } } else { const current = stack[stack.length - 1] if (current == null) { parseState = 'end' } else if (Array.isArray(current)) { parseState = 'afterArrayValue' } else { parseState = 'afterPropertyValue' } } }","function push () { let value switch (token.type) { case 'punctuator': switch (token.value) { case '{': value = {} break case '[': value = [] break } break case 'null': case 'boolean': case 'numeric': case 'string': value = token.value break // This code is unreachable. // default: // throw invalidToken() } if (root === undefined) { root = value } else { const parent = stack[stack.length - 1] if (Array.isArray(parent)) { parent.push(value) } else { Object.defineProperty(parent, key, { value, writable: true, enumerable: true, configurable: true, }) } } if (value !== null && typeof value === 'object') { stack.push(value) if (Array.isArray(value)) { parseState = 'beforeArrayValue' } else { parseState = 'beforePropertyName' } } else { const current = stack[stack.length - 1] if (current == null) { parseState = 'end' } else if (Array.isArray(current)) { parseState = 'afterArrayValue' } else { parseState = 'afterPropertyValue' } } }","fix: add __proto__ to objects and arrays backport 7774c1097993bc3ce9f0ac4b722a32bf7d6871c8 to v1.",https://github.com/json5/json5/commit/b7c04ea36b953e1af75ea4ef89339f2d0256dab1,CVE-2022-46175,['CWE-1321'],src/parse.js,3,js,False,2022-12-16T03:16:27Z "private String refreshStatus() { return Optional.ofNullable(this.app.refresh().activeDeployment()) .map(d -> d.entity().getStatus()) .orElse(SpringCloudDeploymentStatus.UNKNOWN).getLabel(); }","private String refreshStatus() { return Optional.ofNullable(this.app.refresh().activeDeployment()) .map(d -> d.refresh()) .map(d -> d.entity().getStatus()) .orElse(SpringCloudDeploymentStatus.UNKNOWN).getLabel(); }",fix stack overflow when create new spring cloud app,https://github.com/microsoft/azure-tools-for-java/commit/b8f96fb1d4ccad6b87b4a85e7c3bdec0642e5ed6,,,Utils/azure-explorer-common/src/com/microsoft/tooling/msservices/serviceexplorer/azure/springcloud/SpringCloudAppNode.java,3,java,False,2021-06-24T03:27:30Z "@VisibleForTesting protected void runDispatcher() { boolean exceptionOccurred = false; _isStopped = false; if (logger.isDebugEnabled()) { logger.debug(""{}: Beginning to process events"", this); } long reAuthenticateWaitTime = getSystemProperty(RE_AUTHENTICATE_WAIT_TIME, DEFAULT_RE_AUTHENTICATE_WAIT_TIME); ClientMessage clientMessage = null; long wait_for_re_auth_start_time = -1; while (!isStopped()) { // SystemFailure.checkFailure(); DM's stopper does this if (getCache().getCancelCriterion().isCancelInProgress()) { break; } try { // If paused, wait to be told to resume (or interrupted if stopped) if (getProxy().isPaused()) { // ARB: Before waiting for resumption, process acks from client. // This will reduce the number of duplicates that a client receives after // reconnecting. synchronized (_pausedLock) { try { logger.info(""available ids = "" + _messageQueue.size() + "" , isEmptyAckList ="" + _messageQueue.isEmptyAckList() + "", peekInitialized = "" + _messageQueue.isPeekInitialized()); while (!_messageQueue.isEmptyAckList() && _messageQueue.isPeekInitialized()) { _messageQueue.remove(); } } catch (InterruptedException ex) { logger.warn(""{}: sleep interrupted."", this); } } waitForResumption(); } // if message is not delivered due to authentication expiation, continue to try to // deliver the same message. Always retrieve a new message from the queue if we are not // waiting for the re-auth to happen. if (wait_for_re_auth_start_time == -1) { try { clientMessage = (ClientMessage) _messageQueue.peek(); } catch (RegionDestroyedException skipped) { break; } } getStatistics().setQueueSize(_messageQueue.size()); if (isStopped()) { break; } if (clientMessage == null) { _messageQueue.remove(); continue; } // Process the message long start = getStatistics().startTime(); try { if (dispatchMessage(clientMessage)) { getStatistics().endMessage(start); _messageQueue.remove(); if (clientMessage instanceof ClientMarkerMessageImpl) { getProxy().setMarkerEnqueued(false); } } clientMessage = null; wait_for_re_auth_start_time = -1; } catch (NotAuthorizedException notAuthorized) { // behave as if the message is dispatched, remove from the queue logger.warn(""skip delivering message: "" + clientMessage, notAuthorized); _messageQueue.remove(); clientMessage = null; } catch (AuthenticationExpiredException expired) { if (wait_for_re_auth_start_time == -1) { wait_for_re_auth_start_time = System.currentTimeMillis(); // only send the message to clients who can handle the message if (getProxy().getVersion().isNewerThanOrEqualTo(RE_AUTHENTICATION_START_VERSION)) { EventID eventId = createEventId(); sendMessageDirectly(new ClientReAuthenticateMessage(eventId)); } // We wait for all versions of clients to re-authenticate. For older clients we still // wait, just in case client will perform some operations to // trigger credential refresh on its own. Thread.sleep(200); } else { long elapsedTime = System.currentTimeMillis() - wait_for_re_auth_start_time; if (elapsedTime > reAuthenticateWaitTime) { synchronized (_stopDispatchingLock) { logger.warn(""Client did not re-authenticate back successfully in "" + elapsedTime + ""ms. Unregister this client proxy.""); pauseOrUnregisterProxy(expired); } exceptionOccurred = true; } else { Thread.sleep(200); } } } } catch (MessageTooLargeException e) { logger.warn(""Message too large to send to client: {}, {}"", clientMessage, e.getMessage()); } catch (IOException e) { // Added the synchronization below to ensure that exception handling // does not occur while stopping the dispatcher and vice versa. synchronized (_stopDispatchingLock) { // An IOException occurred while sending a message to the // client. If the processor is not already stopped, assume // the client is dead and stop processing. if (!isStopped() && !getProxy().isPaused()) { if (""Broken pipe"".equals(e.getMessage())) { logger.warn(""{}: Proxy closing due to unexpected broken pipe on socket connection."", this); } else if (""Connection reset"".equals(e.getMessage())) { logger.warn(""{}: Proxy closing due to unexpected reset on socket connection."", this); } else if (""Connection reset by peer"".equals(e.getMessage())) { logger.warn( ""{}: Proxy closing due to unexpected reset by peer on socket connection."", this); } else if (""Socket is closed"".equals(e.getMessage()) || ""Socket Closed"".equals(e.getMessage())) { logger.info(""{}: Proxy closing due to socket being closed locally."", this); } else { logger.warn(String.format( ""%s: An unexpected IOException occurred so the proxy will be closed."", this), e); } // Let the CacheClientNotifier discover the proxy is not alive. // See isAlive(). // getProxy().close(false); pauseOrUnregisterProxy(e); } // _isStopped } // synchronized exceptionOccurred = true; } // IOException catch (InterruptedException e) { // If the thread is paused, ignore the InterruptedException and // continue. The proxy is null if stopDispatching has been called. if (getProxy().isPaused()) { if (logger.isDebugEnabled()) { logger.debug( ""{}: interrupted because it is being paused. It will continue and wait for resumption."", this); } Thread.interrupted(); continue; } // no need to reset the bit; we're exiting if (logger.isDebugEnabled()) { logger.debug(""{}: interrupted"", this); } break; } catch (CancelException e) { if (logger.isDebugEnabled()) { logger.debug(""{}: shutting down due to cancellation"", this); } exceptionOccurred = true; // message queue is defunct, don't try to read it. break; } catch (RegionDestroyedException e) { if (logger.isDebugEnabled()) { logger.debug(""{}: shutting down due to loss of message queue"", this); } exceptionOccurred = true; // message queue is defunct, don't try to read it. break; } catch (Exception e) { // An exception occurred while processing a message. Since it // is not an IOException, the client may still be alive, so // continue processing. if (!isStopped()) { logger.fatal(String.format(""%s : An unexpected Exception occurred"", this), e); } } } // Processing gets here if isStopped=true. What is this code below doing? if (!exceptionOccurred) { dispatchResidualMessages(); } if (logger.isTraceEnabled()) { logger.trace(""{}: Dispatcher thread is ending"", this); } }","@VisibleForTesting protected void runDispatcher() { boolean exceptionOccurred = false; _isStopped = false; if (logger.isDebugEnabled()) { logger.debug(""{}: Beginning to process events"", this); } long reAuthenticateWaitTime = getSystemProperty(RE_AUTHENTICATE_WAIT_TIME, DEFAULT_RE_AUTHENTICATE_WAIT_TIME); ClientMessage clientMessage = null; while (!isStopped()) { // SystemFailure.checkFailure(); DM's stopper does this if (getCache().getCancelCriterion().isCancelInProgress()) { break; } try { // If paused, wait to be told to resume (or interrupted if stopped) if (getProxy().isPaused()) { // ARB: Before waiting for resumption, process acks from client. // This will reduce the number of duplicates that a client receives after // reconnecting. synchronized (_pausedLock) { try { logger.info(""available ids = "" + _messageQueue.size() + "" , isEmptyAckList ="" + _messageQueue.isEmptyAckList() + "", peekInitialized = "" + _messageQueue.isPeekInitialized()); while (!_messageQueue.isEmptyAckList() && _messageQueue.isPeekInitialized()) { _messageQueue.remove(); } } catch (InterruptedException ex) { logger.warn(""{}: sleep interrupted."", this); } } waitForResumption(); } // if message is not delivered due to authentication expiation, continue to try to // deliver the same message. Always retrieve a new message from the queue if we are not // waiting for the re-auth to happen. if (waitForReAuthenticationStartTime == -1) { try { clientMessage = (ClientMessage) _messageQueue.peek(); } catch (RegionDestroyedException skipped) { break; } } getStatistics().setQueueSize(_messageQueue.size()); if (isStopped()) { break; } if (clientMessage == null) { _messageQueue.remove(); continue; } // Process the message long start = getStatistics().startTime(); try { if (dispatchMessage(clientMessage)) { getStatistics().endMessage(start); _messageQueue.remove(); if (clientMessage instanceof ClientMarkerMessageImpl) { getProxy().setMarkerEnqueued(false); } } clientMessage = null; waitForReAuthenticationStartTime = -1; } catch (NotAuthorizedException notAuthorized) { // behave as if the message is dispatched, remove from the queue logger.warn(""skip delivering message: "" + clientMessage, notAuthorized); _messageQueue.remove(); clientMessage = null; } catch (AuthenticationExpiredException expired) { if (waitForReAuthenticationStartTime == -1) { waitForReAuthenticationStartTime = System.currentTimeMillis(); // only send the message to clients who can handle the message if (getProxy().getVersion().isNewerThanOrEqualTo(RE_AUTHENTICATION_START_VERSION)) { EventID eventId = createEventId(); sendMessageDirectly(new ClientReAuthenticateMessage(eventId)); } // We wait for all versions of clients to re-authenticate. For older clients we still // wait, just in case client will perform some operations to // trigger credential refresh on its own. Thread.sleep(200); } else { long elapsedTime = System.currentTimeMillis() - waitForReAuthenticationStartTime; if (elapsedTime > reAuthenticateWaitTime) { // reset the timer here since we are no longer waiting for re-auth to happen anymore waitForReAuthenticationStartTime = -1; synchronized (_stopDispatchingLock) { logger.warn(""Client did not re-authenticate back successfully in "" + elapsedTime + ""ms. Unregister this client proxy.""); pauseOrUnregisterProxy(expired); } exceptionOccurred = true; } else { Thread.sleep(200); } } } } catch (MessageTooLargeException e) { logger.warn(""Message too large to send to client: {}, {}"", clientMessage, e.getMessage()); } catch (IOException e) { // Added the synchronization below to ensure that exception handling // does not occur while stopping the dispatcher and vice versa. synchronized (_stopDispatchingLock) { // An IOException occurred while sending a message to the // client. If the processor is not already stopped, assume // the client is dead and stop processing. if (!isStopped() && !getProxy().isPaused()) { if (""Broken pipe"".equals(e.getMessage())) { logger.warn(""{}: Proxy closing due to unexpected broken pipe on socket connection."", this); } else if (""Connection reset"".equals(e.getMessage())) { logger.warn(""{}: Proxy closing due to unexpected reset on socket connection."", this); } else if (""Connection reset by peer"".equals(e.getMessage())) { logger.warn( ""{}: Proxy closing due to unexpected reset by peer on socket connection."", this); } else if (""Socket is closed"".equals(e.getMessage()) || ""Socket Closed"".equals(e.getMessage())) { logger.info(""{}: Proxy closing due to socket being closed locally."", this); } else { logger.warn(String.format( ""%s: An unexpected IOException occurred so the proxy will be closed."", this), e); } // Let the CacheClientNotifier discover the proxy is not alive. // See isAlive(). // getProxy().close(false); pauseOrUnregisterProxy(e); } // _isStopped } // synchronized exceptionOccurred = true; } // IOException catch (InterruptedException e) { // If the thread is paused, ignore the InterruptedException and // continue. The proxy is null if stopDispatching has been called. if (getProxy().isPaused()) { if (logger.isDebugEnabled()) { logger.debug( ""{}: interrupted because it is being paused. It will continue and wait for resumption."", this); } Thread.interrupted(); continue; } // no need to reset the bit; we're exiting if (logger.isDebugEnabled()) { logger.debug(""{}: interrupted"", this); } break; } catch (CancelException e) { if (logger.isDebugEnabled()) { logger.debug(""{}: shutting down due to cancellation"", this); } exceptionOccurred = true; // message queue is defunct, don't try to read it. break; } catch (RegionDestroyedException e) { if (logger.isDebugEnabled()) { logger.debug(""{}: shutting down due to loss of message queue"", this); } exceptionOccurred = true; // message queue is defunct, don't try to read it. break; } catch (Exception e) { // An exception occurred while processing a message. Since it // is not an IOException, the client may still be alive, so // continue processing. if (!isStopped()) { logger.fatal(String.format(""%s : An unexpected Exception occurred"", this), e); } } } // Processing gets here if isStopped=true. What is this code below doing? if (!exceptionOccurred) { dispatchResidualMessages(); } if (logger.isTraceEnabled()) { logger.trace(""{}: Dispatcher thread is ending"", this); } }","GEODE-9803: Fix the flaky ""Failed To find authenticated user"" problem (#7149) * GEODE-9803: Fix the flaky ""Failed To find authenticated user"" problem * Only to update subject on the ClientCacheProxy if it's waiting for re-auth * logout the subject in one place when we close the dispatcher * reset the timer when we stopped waiting",https://github.com/apache/geode/commit/7179a7c74aef8315d22ec813a5dfdd08cd555c2b,,,geode-core/src/main/java/org/apache/geode/internal/cache/tier/sockets/MessageDispatcher.java,3,java,False,2021-12-06T17:44:16Z "public float getFloat(int col) throws SQLException { DB db = getDatabase(); if (db.column_type(stmt.pointer, markCol(col)) == SQLITE_NULL) { return 0; } return (float) db.column_double(stmt.pointer, markCol(col)); }","public float getFloat(int col) throws SQLException { DB db = getDatabase(); if (safeGetColumnType(markCol(col)) == SQLITE_NULL) { return 0; } return (float) safeGetDoubleCol(col); }",Wrap Statement Pointers to prevent use after free race,https://github.com/xerial/sqlite-jdbc/commit/e1d282cb2887ef427c7ad93d4fe7dd05a6c11473,,,src/main/java/org/sqlite/jdbc3/JDBC3ResultSet.java,3,java,False,2022-07-29T03:54:01Z "public Remote lookup(String boundName) { Remote remoteObject = remoteObjectCache.get(boundName); if( remoteObject == null ) { try { remoteObject = rmiRegistry.lookup(boundName); remoteObjectCache.put(boundName, remoteObject); } catch( RemoteException e ) { Throwable cause = ExceptionHandler.getCause(e); if( cause instanceof ClassNotFoundException ) { ExceptionHandler.lookupClassNotFoundException(cause.getMessage()); } else { ExceptionHandler.unexpectedException(e, ""lookup"", ""call"", false); } } catch( NotBoundException e) { Logger.eprintMixedYellow(""Caught"", ""NotBoundException"", ""on bound name ""); Logger.printlnPlainBlue(boundName + "".""); Logger.eprintln(""The specified bound name is not bound to the registry.""); RMGUtils.exit(); } } return remoteObject; }","public Remote lookup(String boundName) { Remote remoteObject = remoteObjectCache.get(boundName); if( remoteObject == null ) { try { remoteObject = rmiRegistry.lookup(boundName); remoteObjectCache.put(boundName, remoteObject); } catch( java.rmi.ConnectIOException e ) { ExceptionHandler.connectIOException(e, ""lookup""); } catch( java.rmi.ConnectException e ) { ExceptionHandler.connectException(e, ""lookup""); } catch( java.rmi.NoSuchObjectException e ) { ExceptionHandler.noSuchObjectException(e, ""registry"", true); } catch( java.rmi.NotBoundException e ) { ExceptionHandler.notBoundException(boundName); } catch( Exception e ) { Throwable cause = ExceptionHandler.getCause(e); if( cause instanceof ClassNotFoundException ) ExceptionHandler.lookupClassNotFoundException(cause.getMessage()); else if( cause instanceof SSRFException ) SSRFSocket.printContent(host, port); else ExceptionHandler.unexpectedException(e, ""lookup"", ""call"", true); } } return remoteObject; }","Fix several bugs The latest refactoring introcued some bugs: * Error handling for RMI connections was not fully working anymore * SSRF action caused exceptions in certain cases * SSRF-Response action was not working as intended All these bugs were addressed within this commit.",https://github.com/qtc-de/remote-method-guesser/commit/41607911a2b5d56e5398273bcf70dd006a4f166b,,,src/de/qtc/rmg/networking/RMIRegistryEndpoint.java,3,java,False,2021-08-06T05:44:52Z "private void addToolTipTextForVertex(StringBuilder buf, AttributedVertex vertex) { String vertexType = vertex.getVertexType(); buf.append(""

""); buf.append(vertex.getName()); if (vertexType != null) { buf.append(""
""); buf.append(""Type:  "" + vertexType); } buf.append(""

""); addAttributes(buf, AttributedVertex.NAME_KEY, AttributedVertex.VERTEX_TYPE_KEY); }","private void addToolTipTextForVertex(StringBuilder buf, AttributedVertex vertex) { String vertexType = vertex.getVertexType(); buf.append(""

""); String escapedText = HTMLUtilities.toLiteralHTML(vertex.getName(), 80); buf.append(escapedText); if (vertexType != null) { buf.append(""
""); buf.append(""Type:  "" + vertexType); } buf.append(""

""); addAttributes(buf, AttributedVertex.NAME_KEY, AttributedVertex.VERTEX_TYPE_KEY); }",Merge remote-tracking branch 'origin/GP-2707_dev747368_string_translation_toggle_on_char_arrays' into Ghidra_10.2,https://github.com/NationalSecurityAgency/ghidra/commit/ad6afeaaeb0d47eeb2a81b7925b0686ef186fe12,,,Ghidra/Features/GraphServices/src/main/java/ghidra/graph/visualization/AttributedToolTipInfo.java,3,java,False,2022-10-18T17:47:55Z "@Nullable @Override public Class getType(String name, boolean allowFactoryBeanInit) throws NoSuchBeanDefinitionException { String beanName = transformedBeanName(name); // Check manually registered singletons. Object beanInstance = getSingleton(beanName, false); if (beanInstance != null && beanInstance != NullValue.INSTANCE) { if (beanInstance instanceof FactoryBean && !BeanFactoryUtils.isFactoryDereference(name)) { // If it's a FactoryBean, we want to look at what it creates, not at the factory class. return getTypeForFactoryBean((FactoryBean) beanInstance); } else { return beanInstance.getClass(); } } // No singleton instance found -> check bean definition. BeanFactory parentBeanFactory = getParentBeanFactory(); if (parentBeanFactory != null && !containsBeanDefinition(beanName)) { // No bean definition found in this factory -> delegate to parent. return parentBeanFactory.getType(originalBeanName(name), allowFactoryBeanInit); } RootBeanDefinition mergedDef = getMergedLocalBeanDefinition(beanName); // Check decorated bean definition, if any: We assume it'll be easier // to determine the decorated bean's type than the proxy's type. BeanDefinitionHolder decorated = mergedDef.getDecoratedDefinition(); if (decorated != null && !BeanFactoryUtils.isFactoryDereference(name)) { RootBeanDefinition tbd = getMergedBeanDefinition(decorated.getBeanName(), decorated.getBeanDefinition(), mergedDef); Class targetClass = predictBeanType(decorated.getBeanName(), tbd); if (targetClass != null && !FactoryBean.class.isAssignableFrom(targetClass)) { return targetClass; } } Class beanClass = predictBeanType(beanName, mergedDef); // Check bean class whether we're dealing with a FactoryBean. if (beanClass != null && FactoryBean.class.isAssignableFrom(beanClass)) { if (!BeanFactoryUtils.isFactoryDereference(name)) { // If it's a FactoryBean, we want to look at what it creates, not at the factory class. return getTypeForFactoryBean(beanName, mergedDef, allowFactoryBeanInit).resolve(); } else { return beanClass; } } else { return (!BeanFactoryUtils.isFactoryDereference(name) ? beanClass : null); } }","@Nullable @Override public Class getType(String name, boolean allowFactoryBeanInit) throws NoSuchBeanDefinitionException { String beanName = transformedBeanName(name); // Check manually registered singletons. Object beanInstance = getSingleton(beanName, false); if (beanInstance != null && beanInstance != NullValue.INSTANCE) { if (beanInstance instanceof FactoryBean && !BeanFactoryUtils.isFactoryDereference(name)) { // If it's a FactoryBean, we want to look at what it creates, not at the factory class. return getTypeForFactoryBean((FactoryBean) beanInstance); } else { return beanInstance.getClass(); } } // No singleton instance found -> check bean definition. BeanFactory parentBeanFactory = getParentBeanFactory(); if (parentBeanFactory != null && !containsBeanDefinition(beanName)) { // No bean definition found in this factory -> delegate to parent. return parentBeanFactory.getType(originalBeanName(name), allowFactoryBeanInit); } RootBeanDefinition mergedDef = getMergedLocalBeanDefinition(beanName); Class beanClass = predictBeanType(beanName, mergedDef); if (beanClass != null) { // Check bean class whether we're dealing with a FactoryBean. if (FactoryBean.class.isAssignableFrom(beanClass)) { if (!BeanFactoryUtils.isFactoryDereference(name)) { // If it's a FactoryBean, we want to look at what it creates, not at the factory class. beanClass = getTypeForFactoryBean(beanName, mergedDef, allowFactoryBeanInit).resolve(); } } else if (BeanFactoryUtils.isFactoryDereference(name)) { return null; } } if (beanClass == null) { // Check decorated bean definition, if any: We assume it'll be easier // to determine the decorated bean's type than the proxy's type. BeanDefinitionHolder decorated = mergedDef.getDecoratedDefinition(); if (decorated != null && !BeanFactoryUtils.isFactoryDereference(name)) { RootBeanDefinition tbd = getMergedBeanDefinition( decorated.getBeanName(), decorated.getBeanDefinition(), mergedDef); Class targetClass = predictBeanType(decorated.getBeanName(), tbd); if (targetClass != null && !FactoryBean.class.isAssignableFrom(targetClass)) { return targetClass; } } } return beanClass; }",:zap: Avoid decorated definition bypass for scoped proxy determination,https://github.com/TAKETODAY/today-infrastructure/commit/5be2a9737503f028268b48d822ec5dde57a71aad,,,today-beans/src/main/java/cn/taketoday/beans/factory/support/AbstractBeanFactory.java,3,java,False,2022-10-20T14:03:26Z "@Override public RegistryTenant getTenant(String tenantId) { HttpRequest req = HttpRequest.newBuilder() .uri(URI.create(endpoint + TENANTS_API_BASE_PATH + ""/"" + tenantId)) .GET() .build(); try { HttpResponse res = client.send(req, BodyHandlers.ofInputStream()); if (res.statusCode() == 200) { return this.mapper.readValue(res.body(), RegistryTenant.class); } else if (res.statusCode() == 404) { throw new RegistryTenantNotFoundException(res.toString()); } throw new TenantManagerClientException(res.toString()); } catch ( IOException | InterruptedException e ) { throw new TenantManagerClientException(e); } }","@Override public RegistryTenant getTenant(String tenantId) { final Map headers = prepareRequestHeaders(); HttpRequest.Builder req = HttpRequest.newBuilder() .uri(URI.create(endpoint + TENANTS_API_BASE_PATH + ""/"" + tenantId)) .GET(); headers.forEach(req::header); try { HttpResponse res = client.send(req.build(), BodyHandlers.ofInputStream()); if (res.statusCode() == 200) { return this.mapper.readValue(res.body(), RegistryTenant.class); } else if (res.statusCode() == 404) { throw new RegistryTenantNotFoundException(res.toString()); } throw new TenantManagerClientException(res.toString()); } catch ( IOException | InterruptedException e ) { throw new TenantManagerClientException(e); } }","Initial security support in tenant manager (#1594) * Initial security support in tenant manager * Add auth tests for tenant manager client and fix configuration * Add mechanism to enable/disable auth at runtime in tenant manager * Remove unnecessary property * Fix property value * Configure surefire plugin and add no docker profile",https://github.com/Apicurio/apicurio-registry/commit/966c2e3bac6c4365d2ce6d0252a066ad17c94b3c,,,multitenancy/tenant-manager-client/src/main/java/io/apicurio/multitenant/client/TenantManagerClientImpl.java,3,java,False,2021-06-22T10:43:36Z "public void render(Screen screen, int x, int y, boolean isSelected, String contain, int containColor) { if (!visible) { return; } render(screen, x, y, isSelected); if (contain == null || contain.isEmpty()) { return; } String string = toString().toLowerCase(Locale.ENGLISH); contain = contain.toLowerCase(Locale.ENGLISH); Font.drawColor(string.replaceAll(contain, Color.toStringCode(containColor) + contain + Color.WHITE_CODE), screen, x, y); }","public void render(Screen screen, int x, int y, boolean isSelected, String contain, int containColor) { if (!visible) { return; } render(screen, x, y, isSelected); if (contain == null || contain.isEmpty()) { return; } String string = toString().toLowerCase(Locale.ENGLISH); contain = contain.toLowerCase(Locale.ENGLISH); Font.drawColor(string.replace(contain, Color.toStringCode(containColor) + contain + Color.WHITE_CODE), screen, x, y); }","Fix that certain characters crash Inventory Search This is because of String#replaceAll uses regex, which it is asking some regex pattern thereby now it's changed it to String#replace because it doesn't use regex, avoiding this crash when typing characters like ""{"", ""["" or ""(""",https://github.com/MinicraftPlus/minicraft-plus-revived/commit/8654f688243cd6fc33bbf10b9fb48c287feccfab,,,src/main/java/minicraft/screen/entry/ListEntry.java,3,java,False,2021-11-28T22:17:54Z "@EventHandler(priority = EventPriority.HIGHEST) public void onForge(InventoryClickEvent event) { if (OptionL.isEnabled(Skills.FORGING)) { //Check cancelled if (OptionL.getBoolean(Option.FORGING_CHECK_CANCELLED)) { if (event.isCancelled()) { return; } } Inventory inventory = event.getClickedInventory(); if (inventory != null) { if (inventory.getType().equals(InventoryType.ANVIL)) { if (event.getSlot() == 2) { if (event.getAction().equals(InventoryAction.PICKUP_ALL) || event.getAction().equals(InventoryAction.MOVE_TO_OTHER_INVENTORY)) { if (event.getWhoClicked() instanceof Player) { ItemStack addedItem = inventory.getItem(1); ItemStack baseItem = inventory.getItem(0); Player p = (Player) event.getWhoClicked(); if (inventory.getLocation() != null) { if (blockXpGainLocation(inventory.getLocation(), p)) return; } else { if (blockXpGainLocation(event.getWhoClicked().getLocation(), p)) return; } if (blockXpGainPlayer(p)) return; Skill s = Skills.FORGING; AnvilInventory anvil = (AnvilInventory) inventory; if (addedItem != null && baseItem != null) { if (addedItem.getType().equals(Material.ENCHANTED_BOOK)) { if (ItemUtils.isArmor(baseItem.getType())) { plugin.getLeveler().addXp(p, s, anvil.getRepairCost() * getXp(Source.COMBINE_ARMOR_PER_LEVEL)); } else if (ItemUtils.isWeapon(baseItem.getType())) { plugin.getLeveler().addXp(p, s, anvil.getRepairCost() * getXp(Source.COMBINE_WEAPON_PER_LEVEL)); } else if (baseItem.getType().equals(Material.ENCHANTED_BOOK)) { plugin.getLeveler().addXp(p, s, anvil.getRepairCost() * getXp(Source.COMBINE_BOOKS_PER_LEVEL)); } else { plugin.getLeveler().addXp(p, s, anvil.getRepairCost() * getXp(Source.COMBINE_TOOL_PER_LEVEL)); } } } } } } } else if (inventory.getType().toString().equals(""GRINDSTONE"")) { if (event.getSlotType() != InventoryType.SlotType.RESULT) return; if (!(event.getWhoClicked() instanceof Player)) return; Player player = (Player) event.getWhoClicked(); if (inventory.getLocation() != null) { if (blockXpGainLocation(inventory.getLocation(), player)) return; } else { if (blockXpGainLocation(event.getWhoClicked().getLocation(), player)) return; } if (blockXpGainPlayer(player)) return; // Calculate total level int totalLevel = 0; ItemStack topItem = inventory.getItem(0); // Get item in top slot if (topItem != null) { for (Map.Entry entry : topItem.getEnchantments().entrySet()) { if (!entry.getKey().equals(Enchantment.BINDING_CURSE) && !entry.getKey().equals(Enchantment.VANISHING_CURSE)) { totalLevel += entry.getValue(); } } } ItemStack bottomItem = inventory.getItem(1); // Get item in bottom slot if (bottomItem != null) { for (Map.Entry entry : bottomItem.getEnchantments().entrySet()) { if (!entry.getKey().equals(Enchantment.BINDING_CURSE) && !entry.getKey().equals(Enchantment.VANISHING_CURSE)) { totalLevel += entry.getValue(); } } } plugin.getLeveler().addXp(player, Skills.FORGING, totalLevel * getXp(Source.GRINDSTONE_PER_LEVEL)); } } } }","@EventHandler(priority = EventPriority.HIGHEST) public void onForge(InventoryClickEvent event) { if (OptionL.isEnabled(Skills.FORGING)) { //Check cancelled if (OptionL.getBoolean(Option.FORGING_CHECK_CANCELLED)) { if (event.isCancelled()) { return; } } Inventory inventory = event.getClickedInventory(); if (inventory != null) { if (!(event.getWhoClicked() instanceof Player)) return; Player player = (Player) event.getWhoClicked(); ClickType click = event.getClick(); // Only allow right and left clicks if inventory full if (click != ClickType.LEFT && click != ClickType.RIGHT && isInventoryFull(player)) return; if (event.getResult() != Event.Result.ALLOW) return; // Make sure the click was successful if (inventory.getType().equals(InventoryType.ANVIL)) { if (event.getSlot() == 2) { InventoryAction action = event.getAction(); if (action == InventoryAction.PICKUP_ALL || action == InventoryAction.MOVE_TO_OTHER_INVENTORY || action == InventoryAction.PICKUP_HALF) { ItemStack addedItem = inventory.getItem(1); ItemStack baseItem = inventory.getItem(0); if (inventory.getLocation() != null) { if (blockXpGainLocation(inventory.getLocation(), player)) return; } else { if (blockXpGainLocation(event.getWhoClicked().getLocation(), player)) return; } if (blockXpGainPlayer(player)) return; Skill s = Skills.FORGING; AnvilInventory anvil = (AnvilInventory) inventory; if (addedItem != null && baseItem != null) { if (addedItem.getType().equals(Material.ENCHANTED_BOOK)) { if (ItemUtils.isArmor(baseItem.getType())) { plugin.getLeveler().addXp(player, s, anvil.getRepairCost() * getXp(Source.COMBINE_ARMOR_PER_LEVEL)); } else if (ItemUtils.isWeapon(baseItem.getType())) { plugin.getLeveler().addXp(player, s, anvil.getRepairCost() * getXp(Source.COMBINE_WEAPON_PER_LEVEL)); } else if (baseItem.getType().equals(Material.ENCHANTED_BOOK)) { plugin.getLeveler().addXp(player, s, anvil.getRepairCost() * getXp(Source.COMBINE_BOOKS_PER_LEVEL)); } else { plugin.getLeveler().addXp(player, s, anvil.getRepairCost() * getXp(Source.COMBINE_TOOL_PER_LEVEL)); } } } } } } else if (inventory.getType().toString().equals(""GRINDSTONE"")) { if (event.getSlotType() != InventoryType.SlotType.RESULT) return; if (inventory.getLocation() != null) { if (blockXpGainLocation(inventory.getLocation(), player)) return; } else { if (blockXpGainLocation(event.getWhoClicked().getLocation(), player)) return; } if (blockXpGainPlayer(player)) return; // Calculate total level int totalLevel = 0; ItemStack topItem = inventory.getItem(0); // Get item in top slot if (topItem != null) { for (Map.Entry entry : topItem.getEnchantments().entrySet()) { if (!entry.getKey().equals(Enchantment.BINDING_CURSE) && !entry.getKey().equals(Enchantment.VANISHING_CURSE)) { totalLevel += entry.getValue(); } } } ItemStack bottomItem = inventory.getItem(1); // Get item in bottom slot if (bottomItem != null) { for (Map.Entry entry : bottomItem.getEnchantments().entrySet()) { if (!entry.getKey().equals(Enchantment.BINDING_CURSE) && !entry.getKey().equals(Enchantment.VANISHING_CURSE)) { totalLevel += entry.getValue(); } } } plugin.getLeveler().addXp(player, Skills.FORGING, totalLevel * getXp(Source.GRINDSTONE_PER_LEVEL)); } } } }",Fix another Forging XP exploit,https://github.com/Archy-X/AuraSkills/commit/c467c5ea8914f4ce490da300d90153cbe670ea53,,,src/main/java/com/archyx/aureliumskills/skills/levelers/ForgingLeveler.java,3,java,False,2021-06-06T03:08:40Z "public void initializeElementSize() { if (!type.isContainer()) { throw new IllegalStateException(""Can not initialize element size because node is not container.""); } else if (type.isOptional()) { setContainerSizeConstraint(new ContainerSizeConstraint(0, 1)); return; } if (getContainerSizeConstraint() != null) { return; } Integer min = null; Integer max = null; Size size = type.getAnnotation(Size.class); if (size != null) { min = size.min(); max = size.max(); } NotEmpty notEmpty = type.getAnnotation(NotEmpty.class); if (notEmpty != null) { if (min != null) { min = Math.max(1, min); } else { min = 1; } } setContainerSizeConstraint(new ContainerSizeConstraint(min, max)); }","public void initializeElementSize() { if (!type.isContainer()) { throw new IllegalStateException(""Can not initialize element size because node is not container.""); } else if (type.isOptional()) { setContainerSizeConstraint(new ContainerSizeConstraint(0, 1)); return; } if (getContainerSizeConstraint() != null) { return; } Integer min = null; Integer max = null; Size size = type.getAnnotation(Size.class); if (size != null) { min = size.min(); if (size.max() != Integer.MAX_VALUE) { // not initialized for preventing OOM max = size.max(); } else { max = min + DEFAULT_ELEMENT_MAX_SIZE; } } NotEmpty notEmpty = type.getAnnotation(NotEmpty.class); if (notEmpty != null) { if (min != null) { min = Math.max(1, min); } else { min = 1; } } setContainerSizeConstraint(new ContainerSizeConstraint(min, max)); }",Fix OOM when annotated size without max,https://github.com/naver/fixture-monkey/commit/21d53719030bc5eb3e7de7b695cb566a1441ea73,,,fixture-monkey/src/main/java/com/navercorp/fixturemonkey/arbitrary/ArbitraryNode.java,3,java,False,2022-03-18T06:36:04Z "public static String generateNewCookie(User user) { String cookie = DigestUtils.sha256Hex(user.getUsername() + UUID.randomUUID() + System.currentTimeMillis()); USERS_BY_COOKIE.put(cookie, user); return cookie; }","public String generateNewCookie(User user) { String cookie = DigestUtils.sha256Hex(user.getUsername() + UUID.randomUUID() + System.currentTimeMillis()); USERS_BY_COOKIE.put(cookie, user); saveNewCookie(user, cookie, System.currentTimeMillis()); return cookie; }","Implemented persistent cookies Fixed security vulnerability with cookies not being invalidated properly Request headers were not properly set for the Request object, leading to the Cookie header missing when logging out, which then left the cookie in memory. Rogue actor who gained access to the cookie could then use the cookie to access the panel. Made cookie expiry configurable with 'Webserver.Security.Cookie_expires_after' Due to cookie persistence there is no way to log everyone out of the panel. This will be addressed in a future commit with addition of a command. Affects issues: - Close #1740",https://github.com/plan-player-analytics/Plan/commit/fb4b272844263d33f5a6e85af29ac7e6e25ff80a,,,Plan/common/src/main/java/com/djrapitops/plan/delivery/webserver/auth/ActiveCookieStore.java,3,java,False,2021-03-20T10:02:02Z "@Override public CoreEvent process(CoreEvent event) throws MuleException { Optional exceptionSeen = empty(); String messageId = null; try { messageId = getIdForEvent(event); } catch (ExpressionRuntimeException e) { if (LOGGER.isDebugEnabled()) { // Logs the details of the error. LOGGER.warn(EXPRESSION_RUNTIME_EXCEPTION_ERROR_MSG, e); } // The current transaction needs to be committed, so it's not rolled back, what would cause an infinite loop. TransactionCoordination.getInstance().commitCurrentTransaction(); throw new ExpressionRuntimeException(createStaticMessage(EXPRESSION_RUNTIME_EXCEPTION_ERROR_MSG), e); } catch (Exception ex) { exceptionSeen = of(ex); } Lock lock = lockFactory.createLock(idrId + ""-"" + messageId); lock.lock(); try { RedeliveryCounter counter = findCounter(messageId); if (exceptionSeen.isPresent()) { throw new MessageRedeliveredException(messageId, counter.counter.get(), maxRedeliveryCount, exceptionSeen.get()); } else if (counter != null && counter.counter.get() > maxRedeliveryCount) { throw new MessageRedeliveredException(messageId, counter.errors, counter.counter.get(), maxRedeliveryCount); } try { CoreEvent returnEvent = processToApply(event, nestedChain, false, Mono.from(((BaseEventContext) event.getContext()).getResponsePublisher())); counter = findCounter(messageId); if (counter != null) { resetCounter(messageId); } return returnEvent; } catch (MessagingException ex) { incrementCounter(messageId, ex); throw ex; } catch (Exception ex) { incrementCounter(messageId, createMessagingException(event, ex)); throw ex; } } finally { lock.unlock(); } }","@Override public CoreEvent process(CoreEvent event) throws MuleException { Optional exceptionSeen = empty(); String messageId = null; try { messageId = getIdForEvent(event); } catch (ExpressionRuntimeException e) { if (LOGGER.isDebugEnabled()) { // Logs the details of the error. LOGGER.warn(EXPRESSION_RUNTIME_EXCEPTION_ERROR_MSG, e); } // The current transaction needs to be committed, so it's not rolled back, what would cause an infinite loop. TransactionCoordination.getInstance().commitCurrentTransaction(); throw new ExpressionRuntimeException(createStaticMessage(EXPRESSION_RUNTIME_EXCEPTION_ERROR_MSG), e); } catch (Exception ex) { exceptionSeen = of(ex); } if (messageId == null && !exceptionSeen.isPresent()) { // The current transaction needs to be committed, so it's not rolled back, what would cause an infinite loop. TransactionCoordination.getInstance().commitCurrentTransaction(); throw new ExpressionRuntimeException(createStaticMessage(BLANK_MESSAGE_ID_ERROR_MSG)); } Lock lock = lockFactory.createLock(idrId + ""-"" + messageId); lock.lock(); try { RedeliveryCounter counter = findCounter(messageId); if (exceptionSeen.isPresent()) { throw new MessageRedeliveredException(messageId, counter.counter.get(), maxRedeliveryCount, exceptionSeen.get()); } else if (counter != null && counter.counter.get() > maxRedeliveryCount) { throw new MessageRedeliveredException(messageId, counter.errors, counter.counter.get(), maxRedeliveryCount); } try { CoreEvent returnEvent = processToApply(event, nestedChain, false, Mono.from(((BaseEventContext) event.getContext()).getResponsePublisher())); counter = findCounter(messageId); if (counter != null) { resetCounter(messageId); } return returnEvent; } catch (MessagingException ex) { incrementCounter(messageId, ex); throw ex; } catch (Exception ex) { incrementCounter(messageId, createMessagingException(event, ex)); throw ex; } } finally { lock.unlock(); } }",MULE-19921: Redelivery Policy: infinite loop with blank message ID in a source configured with transactions (#10985),https://github.com/mulesoft/mule/commit/0aaea34e81a8339690cdf0aa15a694ddbe712860,,,modules/core-components/src/main/java/org/mule/runtime/core/internal/processor/IdempotentRedeliveryPolicy.java,3,java,False,2021-11-17T01:48:08Z "@GET @Produces(MediaType.APPLICATION_JSON) @ApiOperation( value = ""List all the applications accessible to authenticated user"", notes = ""User must have MANAGEMENT_APPLICATION[READ] and PORTAL_APPLICATION[READ] permission to list applications."" ) @ApiResponses( { @ApiResponse(code = 200, message = ""User's applications"", response = ApplicationEntity.class, responseContainer = ""List""), @ApiResponse(code = 500, message = ""Internal server error""), } ) @Permissions({ @Permission(value = RolePermission.ENVIRONMENT_APPLICATION, acls = RolePermissionAction.READ) }) public List getApplications(@QueryParam(""group"") final String group, @QueryParam(""query"") final String query) { Set applications; if (query != null && !query.trim().isEmpty()) { applications = applicationService.findByName(query); } else if (isAdmin()) { applications = group != null ? applicationService.findByGroups(Collections.singletonList(group)) : applicationService.findAll(); } else { applications = applicationService.findByUser(getAuthenticatedUser()); if (group != null && !group.isEmpty()) { applications = applications .stream() .filter(app -> app.getGroups() != null && app.getGroups().contains(group)) .collect(Collectors.toSet()); } } applications.forEach(application -> this.addPictureUrl(application)); return applications .stream() .sorted((o1, o2) -> String.CASE_INSENSITIVE_ORDER.compare(o1.getName(), o2.getName())) .collect(Collectors.toList()); }","@GET @Produces(MediaType.APPLICATION_JSON) @ApiOperation( value = ""List all the applications accessible to authenticated user"", notes = ""User must have MANAGEMENT_APPLICATION[READ] and PORTAL_APPLICATION[READ] permission to list applications."" ) @ApiResponses( { @ApiResponse(code = 200, message = ""User's applications"", response = ApplicationEntity.class, responseContainer = ""List""), @ApiResponse(code = 500, message = ""Internal server error""), } ) @Permissions({ @Permission(value = RolePermission.ENVIRONMENT_APPLICATION, acls = RolePermissionAction.READ) }) public List getApplications(@QueryParam(""group"") final String group, @QueryParam(""query"") final String query) { Set applications; if (query != null && !query.trim().isEmpty()) { applications = applicationService.findByName(isAdmin() ? null : getAuthenticatedUser(), query); } else if (isAdmin()) { applications = group != null ? applicationService.findByGroups(Collections.singletonList(group)) : applicationService.findAll(); } else { applications = applicationService.findByUser(getAuthenticatedUser()); if (group != null && !group.isEmpty()) { applications = applications .stream() .filter(app -> app.getGroups() != null && app.getGroups().contains(group)) .collect(Collectors.toSet()); } } applications.forEach(application -> this.addPictureUrl(application)); return applications .stream() .sorted((o1, o2) -> String.CASE_INSENSITIVE_ORDER.compare(o1.getName(), o2.getName())) .collect(Collectors.toList()); }",fix: search only user authorized applications by name,https://github.com/gravitee-io/gravitee-api-management/commit/5aa1e0627a189cc21acd5a59ff1297cce433337d,,,gravitee-rest-api-management/gravitee-rest-api-management-rest/src/main/java/io/gravitee/rest/api/management/rest/resource/ApplicationsResource.java,3,java,False,2021-05-05T13:34:46Z "long getBlobSize(final long blobHandle) throws IOException { final LongHashMap blobStreams = this.blobStreams; if (blobStreams != null) { final InputStream stream = blobStreams.get(blobHandle); if (stream != null) { stream.reset(); return stream.skip(Long.MAX_VALUE); // warning, this may return inaccurate results } } final LongHashMap blobFiles = this.blobFiles; if (blobFiles != null) { final File file = blobFiles.get(blobHandle); if (file != null) { return file.length(); } } return -1; }","long getBlobSize(final long blobHandle) throws IOException { final LongHashMap blobStreams = this.blobStreams; if (blobStreams != null) { final InputStream stream = blobStreams.get(blobHandle); if (stream != null) { if (stream instanceof ByteArraySizedInputStream) { return ((ByteArraySizedInputStream) stream).size(); } try { assert stream.markSupported(); stream.reset(); stream.mark(Integer.MAX_VALUE); return stream.skip(Long.MAX_VALUE); // warning, this may return inaccurate results } finally { stream.reset(); stream.mark(Integer.MAX_VALUE); } } } final LongHashMap blobFiles = this.blobFiles; if (blobFiles != null) { final File file = blobFiles.get(blobHandle); if (file != null) { return file.length(); } } return -1; }","Issue XD-908 was fixed. (#44) Issue XD-908 was fixed. 1. Callback which allows executing version post-validation actions before data flush was added. 2. BufferedInputStreams are used instead of ByteArray streams to fall back to the stored position during the processing of stream inside EntityStore. Which should decrease the risk of OOM. 3. All streams are stored in the temporary directory before transaction flush (after validation of the transaction version) and then moved to the BlobVault location after a successful commit. That is done gracefully handling situations when streams generate errors while storing the data. 4. Passed-in streams are automatically closed during commit/flush and abort/revert of transaction.",https://github.com/JetBrains/xodus/commit/9b7d0e6387d80b3e30abb48cad5a064f12cf8b38,,,entity-store/src/main/java/jetbrains/exodus/entitystore/PersistentStoreTransaction.java,3,java,False,2023-01-24T09:44:19Z "public static Document convertServerConfiguration(String serverConfiguration) throws Exception { serverConfiguration = convertPackageNames(serverConfiguration); DocumentBuilderFactory factory = getSecureDocumentBuilderFactory(); Document document; DocumentBuilder builder; builder = factory.newDocumentBuilder(); document = builder.parse(new InputSource(new StringReader(serverConfiguration))); // Remove users from the server configuration file if they were there. Element documentElement = document.getDocumentElement(); NodeList users = documentElement.getElementsByTagName(""users""); if (users != null && users.getLength() > 0) { documentElement.removeChild(users.item(0)); } Element channelsRoot = (Element) document.getElementsByTagName(""channels"").item(0); NodeList channels = getElements(document, ""channel"", ""com.mirth.connect.model.Channel""); List channelList = new ArrayList(); int length = channels.getLength(); for (int i = 0; i < length; i++) { // Must get node 0 because the first channel is removed each // iteration Element channel = (Element) channels.item(0); TransformerFactory tf = TransformerFactory.newInstance(); Transformer trans = tf.newTransformer(); trans.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION, ""yes""); StringWriter sw = new StringWriter(); trans.transform(new DOMSource(channel), new StreamResult(sw)); String channelDocXML = sw.toString(); channelList.add(new DonkeyElement(convertChannelString(channelDocXML)).getElement()); channelsRoot.removeChild(channel); } for (Element channel : channelList) { channelsRoot.appendChild(document.importNode(channel, true)); } NodeList codeTemplates = documentElement.getElementsByTagName(""codeTemplates""); int codeTemplateCount = codeTemplates.getLength(); for (int i = 0; i < codeTemplateCount; i++) { Element codeTemplate = (Element) codeTemplates.item(i); Element convertedCodeTemplate = convertCodeTemplates(new DonkeyElement(codeTemplate).toXml()).getDocumentElement(); documentElement.replaceChild(document.importNode(convertedCodeTemplate, true), codeTemplate); } return document; }","public static Document convertServerConfiguration(String serverConfiguration) throws Exception { serverConfiguration = convertPackageNames(serverConfiguration); DocumentBuilderFactory factory = getSecureDocumentBuilderFactory(); Document document; DocumentBuilder builder; builder = factory.newDocumentBuilder(); document = builder.parse(new InputSource(new StringReader(serverConfiguration))); // Remove users from the server configuration file if they were there. Element documentElement = document.getDocumentElement(); NodeList users = documentElement.getElementsByTagName(""users""); if (users != null && users.getLength() > 0) { documentElement.removeChild(users.item(0)); } Element channelsRoot = (Element) document.getElementsByTagName(""channels"").item(0); NodeList channels = getElements(document, ""channel"", ""com.mirth.connect.model.Channel""); List channelList = new ArrayList(); int length = channels.getLength(); for (int i = 0; i < length; i++) { // Must get node 0 because the first channel is removed each // iteration Element channel = (Element) channels.item(0); TransformerFactory tf = TransformerFactory.newInstance(); tf.setAttribute(XMLConstants.ACCESS_EXTERNAL_DTD, """"); tf.setAttribute(XMLConstants.ACCESS_EXTERNAL_STYLESHEET, """"); Transformer trans = tf.newTransformer(); trans.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION, ""yes""); StringWriter sw = new StringWriter(); trans.transform(new DOMSource(channel), new StreamResult(sw)); String channelDocXML = sw.toString(); channelList.add(new DonkeyElement(convertChannelString(channelDocXML)).getElement()); channelsRoot.removeChild(channel); } for (Element channel : channelList) { channelsRoot.appendChild(document.importNode(channel, true)); } NodeList codeTemplates = documentElement.getElementsByTagName(""codeTemplates""); int codeTemplateCount = codeTemplates.getLength(); for (int i = 0; i < codeTemplateCount; i++) { Element codeTemplate = (Element) codeTemplates.item(i); Element convertedCodeTemplate = convertCodeTemplates(new DonkeyElement(codeTemplate).toXml()).getDocumentElement(); documentElement.replaceChild(document.importNode(convertedCodeTemplate, true), codeTemplate); } return document; }","ROCKSOLID-6533 Added additional vulnerability MOB: Julian, Peter",https://github.com/nextgenhealthcare/connect/commit/9b180e28490405a4ca2c4518d1edb3d6f945f492,,,server/src/com/mirth/connect/model/util/ImportConverter.java,3,java,False,2021-07-29T23:44:30Z "@Override public void run() { mView.removeCallbacks(this); mView.show(false /* show */, true /* animate */, () -> { mWindowManager.removeView(mView); }); }","@Override public void run() { mView.removeCallbacks(this); mView.show(false /* show */, true /* animate */, () -> { if (mView.isAttachedToWindow()) { mWindowManager.removeView(mView); } }); }","Fixes AssistOrbController crash AssistOrbController caused a crash by trying to remove a view that was not attached. This change adds a check if the view is attached before removal. Test: Tested locally BUG: 195902117 FIX: 195902117 Change-Id: Ibc65a9b1789c7ee629c28de31392fffc0536ed70",https://github.com/omnirom/android_frameworks_base/commit/3f3563c3ae329b5e31c815f91138a2a61c0aa71d,,,packages/SystemUI/src/com/android/systemui/assist/AssistOrbController.java,3,java,False,2021-08-11T03:10:00Z "public void copy(Collection items, Connection connection) { if (items == null || items.isEmpty()) { return; } try { var reader = buildCsv(items); Stopwatch stopwatch = Stopwatch.createStarted(); CopyManager copyManager = connection.unwrap(PGConnection.class).getCopyAPI(); long rowsCount = copyManager.copyIn(sql, reader, properties.getBufferSize()); insertDurationMetric.record(stopwatch.elapsed()); log.info(""Copied {} rows to {} table in {}"", rowsCount, tableName, stopwatch); } catch (Exception e) { throw new ParserException(String.format(""Error copying %d items to table %s"", items.size(), tableName), e); } }","public void copy(Collection items, Connection connection) { if (items == null || items.isEmpty()) { return; } try { Stopwatch stopwatch = Stopwatch.createStarted(); PGConnection pgConnection = connection.unwrap(PGConnection.class); try (var pgCopyOutputStream = new PGCopyOutputStream(pgConnection, sql, properties.getBufferSize())) { writer.writeValue(pgCopyOutputStream, items); } insertDurationMetric.record(stopwatch.elapsed()); log.info(""Copied {} rows to {} table in {}"", items.size(), tableName, stopwatch); } catch (Exception e) { throw new ParserException(String.format(""Error copying %d items to table %s"", items.size(), tableName), e); } }","Optimize resources for kubernetes deployment (#1853) - Adjust importer resources limit to reach 10k tps ingestion - Add jvmFlag MaxRAMPercentage to jib container configuration - Fix OOM in PgCopy and adjust default buffer size for PGCopyOutputStream - Reduce default parser queueCapacity to 10 Signed-off-by: Xin Li ",https://github.com/hashgraph/hedera-mirror-node/commit/c4602280476dcd812c7d0fc2567ce22393643fdb,,,hedera-mirror-importer/src/main/java/com/hedera/mirror/importer/parser/PgCopy.java,3,java,False,2021-04-20T19:52:00Z "private Face Face_request(int i, int j) {//Find the surface by following the bar on the right side for the first time from the i-th point and the j-th point. Face tempFace = new Face(); tempFace.addPointId(i); tempFace.addPointId(j); int nextT; nextT = getRPoint(tempFace.getPointId(1), tempFace.getPointId(2)); while (nextT != tempFace.getPointId(1)) { if (nextT == 0) { tempFace.reset(); return tempFace; }//エラー時の対応 tempFace.addPointId(nextT); nextT = getRPoint(tempFace.getPointId(tempFace.getNumPoints() - 1), tempFace.getPointId(tempFace.getNumPoints())); } tempFace.align(); return tempFace; }","private Face Face_request(int i, int j) {//Find the surface by following the bar on the right side for the first time from the i-th point and the j-th point. Face tempFace = new Face(); tempFace.addPointId(i); tempFace.addPointId(j); int nextT; nextT = getRPoint(tempFace.getPointId(1), tempFace.getPointId(2)); do { if (nextT == 0) { tempFace.reset(); return tempFace; }//エラー時の対応 tempFace.addPointId(nextT); nextT = getRPoint(tempFace.getPointId(tempFace.getNumPoints() - 1), tempFace.getPointId(tempFace.getNumPoints())); } while (!tempFace.containsPointId(nextT)); tempFace.align(); return tempFace; }",Fix infinite loop in folding_estimated_03,https://github.com/oriedita/oriedita/commit/b4ad3b12d1b52b9f014a867ec2d15e2ee02beb16,,,src/main/java/origami/crease_pattern/PointSet.java,3,java,False,2021-10-03T14:08:26Z "private StarSystem smartPath(ShipFleet fleet, StarSystem target) { if(target != null && !empire.tech().hyperspaceCommunications()) { Galaxy gal = galaxy(); float ourEffectiveBC = bcValue(fleet, false, true, true, false); float civTech = empire.tech().avgTechLevel(); float targetTech = civTech; //We smart-path towards the gather-point to be more flexible //for that we seek the closest system from where we currently are, that is closer to the gather-point, if none is found, we go to the gather-point StarSystem pathNode = null; float smallestDistance = Float.MAX_VALUE; for (int id=0;id= fleet.distanceTo(target)) continue; if(current.distanceTo(target) + fleet.distanceTo(current) > 1.5 * fleet.distanceTo(target)) continue; float enemyBc = 0.0f; if(systemInfoBuffer.containsKey(id)) { enemyBc = systemInfoBuffer.get(id).enemyBc; if(empire.aggressiveWith(current.empId())) enemyBc += empire.sv.bases(current.id)*current.empire().tech().newMissileBaseCost(); } if(current.empire() != null) targetTech = current.empire().tech().avgTechLevel(); if(enemyBc * (targetTech+10.0f) * 2 > ourEffectiveBC * (civTech+10.0f)) continue; if(fleet.distanceTo(current) < smallestDistance) { pathNode = current; smallestDistance = fleet.distanceTo(current); } } if(pathNode != null) target = pathNode; } return target; }","private StarSystem smartPath(ShipFleet fleet, StarSystem target) { if(target != null && !empire.tech().hyperspaceCommunications()) { Galaxy gal = galaxy(); float ourFightingBC = bcValue(fleet, false, true, false, false); float ourBombingBC = bcValue(fleet, false, false, true, false); float civTech = empire.tech().avgTechLevel(); float targetTech = civTech; //We smart-path towards the gather-point to be more flexible //for that we seek the closest system from where we currently are, that is closer to the gather-point, if none is found, we go to the gather-point StarSystem pathNode = null; float smallestDistance = Float.MAX_VALUE; for (int id=0;id= fleet.distanceTo(target)) continue; if(current.distanceTo(target) + fleet.distanceTo(current) > 1.5 * fleet.distanceTo(target)) continue; float enemyFightingBc = 0.0f; float enemyMissileBc = 0.0f; if(systemInfoBuffer.containsKey(id)) { enemyFightingBc = systemInfoBuffer.get(id).enemyFightingBc; if(empire.aggressiveWith(current.empId())) enemyMissileBc += empire.sv.bases(current.id)*current.empire().tech().newMissileBaseCost(); } if(current.empire() != null) targetTech = current.empire().tech().avgTechLevel(); if(enemyFightingBc * (targetTech+10.0f) * 2 > ourFightingBC * (civTech+10.0f)) continue; if(enemyMissileBc * (targetTech+10.0f) * 2 > ourBombingBC * (civTech+10.0f)) continue; if(fleet.distanceTo(current) < smallestDistance) { pathNode = current; smallestDistance = fleet.distanceTo(current); } } if(pathNode != null) target = pathNode; } return target; }","New algorithm to determine whom to go to war with (#71) * Update AIScientist.java Adjusted values of a bunch of techs. * Update AIShipCaptain.java Fixed accidental removal of range-adjustment in new target-selection-formula and removed unused code. * Update NewShipTemplate.java Allowing missiles to be used again under certain circumstances, taking ECM into account and basing weapon-decision on actual shield-levels rather than best possible. * Update TechMissileWeapon.java Fixed that 2-rack-missiles didn't have +1 speed as they should have according to official strategy-guide. * Update AIScientist.java Tech-Slider-Allocations now depend on racial-bonuses, not leader-personality. * Immersive Xilmi-AI When set to AI: Selectable, the Xilmi AI now goes in immersive-mode, once again making numerous uses of leader-traits. * Update CombatStackColony.java Fixed a bug, that planets without missile-bases always absorbed damage as if they already had a shield-built, even if they had none and even if they were in a nebula. * Tactical combat improvements Can now detect when someone protects another stack with repulsor-beams and retreats, when it cannot counter it with long-range-weapons. Optimal range for firing missiles increased by repulsor-radius so missile-ships won't be affected by the can't counter repulsors-detection. Missiles will now be held back until getting closer to prevent target from dodging them easily. Unused specials like Repulsor will no longer prevent ships from kiting. * Update AIShipCaptain.java Only kite when there's either repulsor-beam or missile-weapons installed on the ship. * Update AIFleetCommander.java Defending is only half as desirable as attacking now. * Immersive Xilmi-AI Lot's of changes for the personality-mode of Xilmi-AI. * Update DiplomaticEmbassy.java Fix for one empire still holding a grudge against the other when signing a peace-treaty. * Update AIShipCaptain.java Somehow the Xilmi-AI must have had conquered a system with a missile-base on it against another type of AI and then crashed at this place, I didn't even think it would get to for a colony. * Update AISpyMaster.java No longer consider computer-advantage for how much to spend into counter-espionage. * Race-fitting-playstyles implemented and leader-specfic-self-restrictions removed. * Update AIGeneral.java Invader-AI back to normal victim-selection. * Update AIGovernor.java Turns out espionage didn't work like I thought it would. So Darlok just building ships and relying on stealing techs was a bad idea. (You can only steal techs below your highest level in any given tree!) * Update AIDiplomat.java Fixed issue where AI wouldn't allow the player to ask for tech-trades and where they would take deals that are horrible for themselves when trading with other AIs. Trades are now usually all done within a 66%-150% tech-cost-range. * Update AIGeneral.java Giving themselves a personality/objective-combination that fits their behavior. * Update AIDiplomat.java Tech exchange only will work within same tier now. * Update AIGeneral.java Removed setting of personalities as this causes issue with missing texts. * Update AIScientist.java Fixed issue for Silicoids trading for Eco-restoration-techs. * Update ColonyDefense.java * Update ColonyDefense.java Shield will now only be built automatically under the following circumstances: There's missile-bases existing There's missile-bases needing to be upgraded There's missile-bases to be built * Update AIDiplomat.java Avoid false positives in war-declaration for incoming fleets when the system in question was only recently colonized. * Update AIShipCaptain.java Fixed a rare but not impossible crash. * Update AIDiplomat.java No longer accept joint-war-proposals from empires we like less than who they propose as victim. * Update AIGovernor.java Now building missile-bases... under very specific and rare circumstances. * Update AIShipCaptain.java Fixed crash when handling missile-bases. Individual stacks that can't find a target to attack no longer automatically retreat and instead let their behavior be governed by whether the whole fleet would want to retreat. * Update ColonyDefense.java Reverted previous changes which also happened to prevent AI from building shields. * Update CombatStackShip.java Fixed issue where multi-shot-weapons weren't reported as used when they were used. * Update AIFleetCommander.java Fleets now are split depending on their warp-speed unless they are on the way to their final-attack-target. * Update AIDiplomat.java Knowing about uncolonized systems no longer prevents wars. * Update CombatStackShip.java Revert change to shipComponentIsUsed * Update AIShipCaptain.java Moved logic that detects if a weapon has been used to this file. * Update AIScientist.java Try to avoid researching techs we know our neighbors already have since we can trade for it or steal it. * Update AIFleetCommander.java Colony ships now only ignore distance if they are huge as otherwise ignoring distance was horrible in late-game with hyperspace-communications. Keeping scout-designs around for longer. * Fixed a very annoying issue that caused eco-spending to become... insufficient and thus people to die when adjusting espionage- or security-spending. * Reserve-management-improvements Rich and Ultra-Rich planets now put their production into reserve when they would otherwise conduct research. Reserve will now try to keep an emergency-reserve for dealing with events like Supernova. Exceeding twice the amount of that reserve will always be spent so the money doesn't just lie around unused, when there's no new colonies that still need industry. * Update AIShipCaptain.java Removed an unneccessary white line 8[ * Update AIFleetCommander.java Reversed keeping scouts for longer * Update AIGovernor.java no industry, when under siege * Update AIGovernor.java Small fixed to sieged colonies building industry when they shouldn't. * Update Rotp.java Versioning 0.93a * Update RacesUI.java Race-selector no longer jumps after selecting a race. Race-selector scroll-speed when dragging is no longer amplified like the scroll-bar but instead moves 1:1 the distance dragged. * Update AIFleetCommander.java Smart-Path will no longer path over systems further away than the target-system. Fleets will now always be split by speed if more than 2/3rd of the fleet have the fastest speed possible. * Update AIGovernor.java Build more fleet when fighting someone who has no or extremely little fleet. * Update AIShipCaptain.java Kiting no longer uses path-finding during auto-resolve. Ships with repulsor and long-range will no longer get closer than 2 tiles before firing against ships that don't have long range. Will only retreat to system with enemy fleets when there's no system without enemy fleets to retreat to. * Update CombatStackColony.java Added override for optimal firing-range for missile-bases. It is 9. * Update CombatStackShip.java Optimal firing-range for ship-stacks with missiles will now be at least two when they have repulsors. * Update NewShipTemplate.java The willingness of the AI to use repulsor-beam now scales with how many opponent ships have long range. It will be higher if there's only a few but drop down to 0 if all opponent ships use them. * Update AI.java Improved logic for shuttling around population within the empire. * Update ShipBattleUI.java Fixed a bug where remaining commands were transferred from one stack to another, which could also cause a crash when missile-bases were involved. * Update Colony.java currentProductionCapacity now correctly takes into consideration how many factories are actually operated. * Update NewShipTemplate.java Fixes and improvements to special-selection. Mainly bigger emphasis on using cloaking-device and stasis-field. * Update AIShipDesigner.java Consider getting an important special like cloaking, stasis or black-hole-generator as reason to immediately make a new design. * Update SystemView.java Systems with enemy-fleets will now flash the Alert. Especially usefull when under siege by cloaked enemy fleets. * Update AIShipCaptain.java Added check whether retreat was possible when retreating for the reason that nothing can be done. * Update AIGovernor.java Taking natural pop-growth and the cost of terraforming into account when deciding to build factories or population. This usually results to prefering factories almost always when they can be operated. * War- and Peace-making changes. Prevent war-declaration when there's barely any fleet to attack with. Smarter selection of preferred victim. In particular taking their diplomatic status with others into account. Toned down overall aggressiveness. Several personalities now are taken into account for determining behavior. * Update General.java Don't attack too early. * Update AIFleetCommander.java Colony ships will now always prefer undefended targets instead of waiting for help if they want to colonize a defended system. * Update Rotp.java Version 0.93b * Update NewShipTemplate.java Not needing ranged weapon, when we have cloaking-device. * Improved behavior when using missiles to act according to expectations of /u/bot39lvl * Showing pop-growth at clean-eco. * New Version with u/bot39lvl recommended changes to missile-boat-handling * Fixed issue that caused ships being scrapped after loading a game, no longer taking incoming enemy fleets into consideration that are more than one turn away from reaching their target. * Stacks that want to retreat will now also try and damage their target if it is more than one space away as long as they don't use up all movement-points. Planets with no missile-bases will not become a target unless all non-bomb-weapons were used. * Fixed an issue where a new design would override a similar existing one. * When defending or when having better movement-speed now shall always try to get the 1st strike. * Not keeping a defensive fleet on duty when the incoming opponent attack will overwhelm them anyways. * Using more unique ship-names * Avoid ship-information being cut off by drawing ship-button-overlay into the upper direction as soon as a stack is below the middle of the screen. * Fixed exploit that allowed player to ignore enemy repulsor-beams via auto-resolve. * Fixed issue that caused missile-ships to sometimes retreat when they shouldn't. * Calling beam/missileDefense() method instead of looking at the member since the function also takes stealth into account which we want to do for better decision-making. * Ships with limited shot-weapons no longer think they can land all hits at once. * Best tech of each type no longer gets it's research-value reduced. * Halfed inertial-value again as it otherwise may suppress vital range-tech. * Prevent overbuilding colony-ships in lategame by taking into consideration when systems can build more than one per turn. * Design-names now use name of a system that is actually owned and add a number to make sure they are unique. * Fixed some issues with no longer firing before retreating after rework and now ignoring stacks in stasis for whether to retreat or not. * Evenly distributing population across the empire led to an increase of almost 30% productivity at a reference turn in tests and thus turned out to be a much better population-distribution-strategy when compared to the ""bring new colonies to 25%""-rule-of-thumb as suggested in the official-strategy-guide. * Last defending stacks in stasis are now also made to autoretreat as otherwise this would result in 100 turns of ""you can't do anything but watch"". * Avoid having more than two designs with Stasis-Field as it doesn't stack. * Should fix an issue that caused usage of Hyper-Space-Communications to be inefficient. * Futher optimization on population-shuttling. * Fixed possible crash from trying to make peace while being involved in a final war. * Fixed infinite loop when trying to scrap the last existing design. * Making much better use of natural growth. * Some further slight adjustments to economy-handling that lead to an even better result in my test. * Fix for ""Hyperspace Communications: can't reroute back to the starting planet - bug"" by setting system to null, when leaving the orbit. In this vein no longer check for a stargate-connection when a fleet isn't at a system anymore. * Only the victor and the owner of the colony fought over get a scan on the system. Not all participants. Especially not someone who fled from the orion-guardian and wanted to exploit this bug to get free high-end-techs! * Prepare next version number since Ray hasn't commited anything yet since the beginning of June. :( * Presumably a better fix to the issue of carrying over button-presses to the next stack. But I don't have a good save to test it. * Fixed that for certain techs the inherited baseValue method either had no override or the override did not reference to the corresponding AI-method. * Reverted fix for redirecting ships with hyperspace-communications to their source-system because it could crash the game when trying to redirect ships using rally-points. * Using same ship-design-naming-pattern for all types of ships so player can't idintify colony-ships by looking at the name. * Added missing override for baseValue from AI. * Made separate method for upgradeCost so it can be used from outside, like AI for example. * Fixed an issue where ships wouldn't retreat when they couldn't path to their preferred target. * Changed how much the AI values certain technologies. Most notably will it like warp-speed-improvements more. * Introduced an algorithm that guesses how long it will take to kill another empire and how long it would take the other empire to kill ourselves. This is used in target-selection and also in order to decide on whether we should go all in with our military. If we think the other empire can kill us more quickly than what it takes to benefit from investments into economy, we go all-in with building military. * Fixed an issue that prevented ships being sent back to where they came from while in space via using hyperspace-communications. Note: The intention of that code is already handled by the ""CanSendTo""-check just above of it. At this place the differientiation between beeing in transit is made, so that code was redundant for it's intended use-case. * Production- and reseach-modifier now considered in decision to build ships non-stop or not. Fixed bug that caused AI-colonies to not build ships when they should. Consider incoming transports in decision whether to build population or not. * Big revamp of dimplomatic AI-behavior. AI should now make much more sophisticated decisions about when to go to war. * No longer bolstering population of low-pop-systems during war as this is pretty exploitable and detracts from producting military. * Version * Fixed a weird issue that prevented AIs from bombarding each other unless the player had knowledge about who the owner of the system to be bombarded is. * Less willing to go to war, when there's other ways to expand. * Fixed issue with colonizers and hyper-space-communications, that I thought I had fixed before. When there's other possible targets to attack, a fleet waiting for invasion-forces, that can glass the system it is orbiting will split up and continue its attack. * Only building excess colonizers, when someone we know (including ourselves) is at war and there's potential to colonize systems that are freed up by that war. * At 72% and higher population a system wanting to build a colonizer will go all-in on it. This mostly affects Sakkra and Meklar, so they expand quicker and make more use of fast pop-growth. * Fixed extremely rare crash. * 0.93g * Guessing travel-time and impact of nebulae instead of actually calculating the correct travel-times including nebulae to improve turn-times. * No longer using bestVictim in ship-Design-Code. * Lower limit from transport-size removed. * Yet another big revamp about when to go to war. It's much more simple now. * Transports sent towards someone who we don't want to have a war with now will be set to surrender on arrival. Travel-distance-calculation simplified in favor of turn-processing. Fixed dysfunctional defense-code that was recently broken. * Pop-growth now plays a role in invasion-decisionmaking. Invasions now can occur without a fleet in orbit. Code for estimating kill-time now takes invasions into account. Drastically simplified victim-selection. * Due to the changes in how the AI handles it's fleets during the wait time for invasions the amount of bombers built was increased. * Changed how it is determined whether to retreat against fleets with repulsors. Fixed issue with not firing missiles under certain circumstances. Stacks of smaller ships fighting against stacks of bigger ships are now more likely to retreat, when they can't kill at least one of the bigger ships per turn. * Moved accidental-stargate-building-prevention-workaround to where it actually is effective. * Fixed an issue where a combat would end prematurely when missiles were fired but still on their way to their target. * Removed commented-out code * Removed actual war-weariness from the reasons to make peace as there's now other and better reasons to make peace. * Bombers are now more specialized as in better at bombing and worse at actual combat. * Bomb-Percentage now considers all opponents, not just the current enemy. * The usage of designs is now recognized by their loadout and not by what role it was assigned to it during design. * No longer super-heavy commitment to ship-production in war. Support of hybrid-playstyle. * Fixed issue that sometimes prevented shooting missiles. * Lowered counter-espionage by no longer looking at average tech-level of opponents but instead at tech-level of highest opponent. * Support for hybrid ship-designs and many tweaks- and fixes in scrapping-logic. * Setting eco-slider with a popup that promts for a percentage now uses the percentage of the amount that isn't required to keep clean. * Fixed previously integrated potential dead-lock. * Indentation * Fix for becoming enemy of others before they are in range in the always-war-mode. * Version-number for next inofficial build. * No security-spending when no contact. But luckily that actually makes no difference between it only actually gets detracted from income when there's contacts. * Revert ""Setting eco-slider with a popup that promts for a percentage now uses the percentage of the amount that isn't required to keep clean."" This reverts commit a2fe5dce3c1be344b6c96b6bfa1b5d16b321fafa. * Taught AI to use divert-reserve to research-checkbox * I don't know how it can happen but I've seen rare cases of colonies with negative-population. This is a workaround that changes them back to 1 pop. * Skip AI turn when corresponing empire is dead. * Fixed possible endless-loop from scrapping last existing ship-design. * Fixed issue where AI would build colonizers as bombers after having scrapped their last existing bomber-design. * Removed useless code. * Removed useless code. * Xilmi AI now capable of deciding when to use bio-weapons. * Bioweapon-support * New voting behavior: Xilmi Ai now votes for whoever they are most scared of but aren't at war with. * Fixed for undecisive behavior of launching an assault but retreating until transports arrive because developmentPct is no longer maxxed after sending transports. (War would still get triggered by the invasion but the fleet sent to accompany the invasion would retreat) * No longer escorting colony-ships on their way to presumably undefended systems. Reason: This oftentimes used a good portion of the fleet for no good reason, when they could be better used for attacking/defending. * Requiring closer range to fire missiles. * Lower score for using bio-weapons depending on how many missile-bases are seen. * No longer altering tech-allocations based on war-state. * New, more diverse and supposedly more interesting diplomatic behavior for AI. * Pick weapon to counter best enemy shield in use rather than average to avoid situations where lasers or scatterpack-V are countered too hard. Also: Make sure that there is a design with the most current bomb before considering bio-weapons. * Weapons that allow heavy-mounts don't get their value decreased so AI doesn't end up without decent repulsor-counter. * Moved negative-population workaround to a place where it is actually called. * Smarter decision-making about when to bomb or not to bomb during on-going invasions. * Incoming invasions of oneself should be slightly better covered but without tying too much of the fleet to it. * Choose target by distance from fleet. * Giving more cover to incoming invasions. * Made rank-check-functions available outside of diplomat too. * Always abstain if not both candidates are known. Superpowers should avoid wars. * Fixed an issue where defenders wouldn't always stay back when they should. * Don't hold back full power when in war anymore. * Quality of ships now more important for scrapping than before. * Reversed prior change in retreat-logic for smaller ships: Yes, the enemy could retreat but control over the system is probably more important than preserving some ships. * Fixed issue where AI would retreat from repulsors when they had missiles. * Minimum speed-requirement for missiles now takes repulsor-beams and diagonals into account. * AI will prepare their wars a little better and also take having to prepare into account before invadion. * No longer voting until both candidates are met. AI now knows much better to capitalize on an advantage and actually win the game instead of throwing it in a risky way. * Moved a debug-output to another place. * 0.93l * Better preparations before going to war. Removed alliances again. * Pick war-target by population-center rather than potential population center. * Fixed a bunch of issued leading to bad colony-ship-management in the lategame. * The better an AI is doing, the more careful they are about how to pick their enemies. * Increased minimum ship-maintenance-threshold for the early-game. * New version * Forgot to remove a debug-message. * Fixed issue reported by u/Individual_Act289: Transports launched before final war disappear on arrival. * Fixed logical error in maxFiringRange-method which could cause unwanted retreats. * When at war, AI will not make so many colony-ships, fixed issue where invasions wouldn't happen against partially built missile-bases, build more bombers when there's a high military-superiority * Willingness to defend now scales with defense-ratio. * Holding back before going to war as long as techs can still be easily researched. * AI will get a bit more tech when it's opportune instead of going for war. * Smart path will avoid paths where the detour would be longer than 50%, fleets that would otherwise go to a staging-point while they are orbiting an enemy will instead stay in orbit of the enemy. * Yet unused methor determining the required count of fighters to shoo scouts away. * Techs that are more than 5 levels behind the average will now be researched even if they are low priority. * Handling for enemy missile-frigates. * No longer scrap ships while at war. * Shields are seen as more useful, new way of determining what size ships should be. * enemyTransportsInTransit now also returns transports of neutral/cold-war-opponents * Created separate method unfriendlyTransportsInTransit * Improved algorithm to determine ship-design-size, reduction in score for hybrids without bombs * Run from missile code should no longer try to outrun missiles that are too close already * New method for unfriendlyTransportsInTransit used * Taught AI to protect their systems against scouting * Taught AI to protect their systems against scouting * Fixed issue that prevented scouts from being sent to long-range-targets when they were part of a fleet with other ships. * Xilmi-AI now declaring war at any poploss, not just at 30+ * Sanity check for fleeing from missiles: Only do it when something could actually be lost. * Prepare better for potential attacks. * Some code cleanup * Fixed issue where other ships than destroyers could be built as scout-repellers. * Avoid downsizing of weapons in non-destroyer-ships. * Distances need to be recalculated immediately after obtaining new system as otherwise AI would act on outdated information. In this case it led to the AI offering peace due to losing range on an opponent whos colony it just conquered despite that act bringing lots of new systems into range. * Fixed an issue where AI would consider an opponents contacts instead of their own when determining the opponents relative standing. Also no longer looking at empires outside of ship-range for potential wars. * Priority for my purpose needs to be above 1000 and below 1400. Below 1000 it gets into conflict with scouts and above 1400 it will rush out the ships under all circumstances. * The widespread usage of scout-repellers makes adding a weapon to a colony-ship much more important. * Added missing override for maxFiringRange * Fixed that after capturing a colony the default for max-bases was not used from the settings of the new owner. * Default for bases on new systems and whether excess-spending goes to research can now be changed in Remnants.cfg * Fixed issue that allowed ship-designs without weapons to be considered the best design. * Fixed a rare crash I had never seen before and can't really explain. * Now taking into account if a weapon would cause a lot of overkill and reduce it's score if it is the case. Most likely will only affect Death-Ray and maybe Mauler-Device. * Fixed an issue with negative-fleets and error-messages. Fixed an issue where systems of empires without income wouldn't be attacked when they had stealth-ships or were out of sensor-range. * Improved detection on whether scout-repellers are needed. Also forbid scout-repellers when unlimited range is available. * Removed code that would consistently scrap unused designs, which sometimes had unintended side-effects when building bigger ships. Replaced what it was meant for by something vastly better: A design-rotation that happens based on how much the design contributes to the maintenance-cost. When there's 4 available slots for combat-designs and one design takes up more than 1/3rd of the maintenance, a new design is enforced, even if it is the same as before. * Fixed issue where ships wouldn't shoot at nearby targets when they couldn't reach their preferred target. Rewrote combat-outcome-expectation to much better guess the expected outcome, which now also consideres auto-repair. * New algorithm to determine who is the best target for a war. * New algorithm to determine the ratio of bombers vs. fighters respectively bombs vs. anti-ship-weapons on a hybrid. * Fixed issue where huge colonizers wouldn't be built when Orion was reachable. * The slots for scouts and scout-repellers are no longer used during wars. * Improved strategic target-selection to better take ship-roles into account. * Fixed issue in bcValue not recognizing scouts of non-AI-player * Fixed several issues with design-scoring. (possible zero-division and using size instead of space) * Much more dedicated and better adapted defending-techniques. * Improved estimate on how many troops need to stay back in order to shoot down transports.",https://github.com/rayfowler/rotp-public/commit/2ec066ab66098db56a37be9f35ccf980ce38866b,,,src/rotp/model/ai/xilmi/AIFleetCommander.java,3,java,False,2021-10-12T17:22:38Z "private void addClickableFile(SpannableStringBuilder sb, final DiagnosticWrapper diagnostic) { ClickableSpan span = new ClickableSpan() { @Override public void onClick(@NonNull View view) { // MainFragment -> BottomEditorFragment -> AppLogFragment Fragment parent = getParentFragment(); if (parent != null) { Fragment main = parent.getParentFragment(); if (main instanceof MainFragment) { ((MainFragment) main).openFile(diagnostic.getSource(), (int) diagnostic.getLineNumber() - 1, 0); } } } }; String label = diagnostic.getSource().getName(); label = label + "":"" + diagnostic.getLineNumber(); sb.append(""["" + label + ""]"", span, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE); }","private void addClickableFile(SpannableStringBuilder sb, final DiagnosticWrapper diagnostic) { if (diagnostic.getSource() == null || !diagnostic.getSource().exists()) { return; } ClickableSpan span = new ClickableSpan() { @Override public void onClick(@NonNull View view) { // MainFragment -> BottomEditorFragment -> AppLogFragment Fragment parent = getParentFragment(); if (parent != null) { Fragment main = parent.getParentFragment(); if (main instanceof MainFragment) { ((MainFragment) main).openFile(diagnostic.getSource(), (int) diagnostic.getLineNumber() - 1, 0); } } } }; String label = diagnostic.getSource().getName(); label = label + "":"" + diagnostic.getLineNumber(); sb.append(""["" + label + ""]"", span, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE); }",fix: crash when attempting to log on an unknown source,https://github.com/tyron12233/CodeAssist/commit/639c7fa2f7cabcf0f3e8e2df7b49490d53e8b6e3,,,app/src/main/java/com/tyron/code/ui/editor/log/AppLogFragment.java,3,java,False,2021-09-18T10:50:38Z "private Response updateLifetime(String appName, Service updateAppData, final UserGroupInformation ugi) throws IOException, InterruptedException { String newLifeTime = ugi.doAs(new PrivilegedExceptionAction() { @Override public String run() throws YarnException, IOException { ServiceClient sc = getServiceClient(); sc.init(YARN_CONFIG); sc.start(); String newLifeTime = sc.updateLifetime(appName, updateAppData.getLifetime()); sc.close(); return newLifeTime; } }); ServiceStatus status = new ServiceStatus(); status.setDiagnostics( ""Service ("" + appName + "")'s lifeTime is updated to "" + newLifeTime + "", "" + updateAppData.getLifetime() + "" seconds remaining""); return formatResponse(Status.OK, status); }","private Response updateLifetime(String appName, Service updateAppData, final UserGroupInformation ugi) throws IOException, InterruptedException { String newLifeTime = ugi.doAs(new PrivilegedExceptionAction() { @Override public String run() throws YarnException, IOException { ServiceClient sc = getServiceClient(); try { sc.init(YARN_CONFIG); sc.start(); String newLifeTime = sc.updateLifetime(appName, updateAppData.getLifetime()); return newLifeTime; } finally { sc.close(); } } }); ServiceStatus status = new ServiceStatus(); status.setDiagnostics( ""Service ("" + appName + "")'s lifeTime is updated to "" + newLifeTime + "", "" + updateAppData.getLifetime() + "" seconds remaining""); return formatResponse(Status.OK, status); }","[CLOUD-196] YARN-9067. YARN Resource Manager is running OOM because of leak of Configuration Object. Contributed by Eric Yang. Co-authored-by: Weiwei Yang ",https://github.com/hopshadoop/hops/commit/19fbf220b0a550fdb244151a4e69f99e5bb55019,,,hadoop-yarn-project/hadoop-yarn/hadoop-yarn-applications/hadoop-yarn-services/hadoop-yarn-services-api/src/main/java/org/apache/hadoop/yarn/service/webapp/ApiServer.java,3,java,False,2022-12-01T13:01:27Z "public void scoreViewClicked(View view) { if (field.getGameState().isGameInProgress()) { if (field.getGameState().isPaused()) { unpauseGame(); } else { pauseGame(); showPausedButtons(); } } else { doStartGame(null); } }","public void scoreViewClicked(View view) { if (field.getGameState().isGameInProgress()) { if (field.getGameState().isPaused()) { unpauseGame(); } else { pauseGame(); showPausedButtons(); } } else { // https://github.com/dozingcat/Vector-Pinball/issues/91 // doStartGame() needs to be synchronized so that we don't try to // start the game while the FieldDriver thread is updating the // Box2d world. But pauseGame() above should not be synchronized // because that can deadlock the FieldDriver thread. Yes, all of // this concurrency is badly in need of refactoring. synchronized (field) { doStartGame(null); } } }",Fix possible crash when starting game by touching ScoreView (#106),https://github.com/dozingcat/Vector-Pinball/commit/e8f6a0887d2ff6e3372b3d09eb360e818d1ec075,,,app/src/main/java/com/dozingcatsoftware/bouncy/BouncyActivity.java,3,java,False,2022-03-12T18:59:58Z "private void drawGui() { GridBagLayout gridBagLayout = new GridBagLayout(); gridBagLayout.columnWidths = new int[] {0, 100, 250, 0, 0}; gridBagLayout.rowHeights = new int[]{10, 0, 0, 0, 0, 0, 0, 30, 0, 0, 0, 0, 0, 0, 0}; gridBagLayout.columnWeights = new double[]{0.0, 1.0, 0.0, 0.0, Double.MIN_VALUE}; gridBagLayout.rowWeights = new double[]{0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 1.0, Double.MIN_VALUE}; setLayout(gridBagLayout); JTextComponent.removeKeymap(""RTextAreaKeymap""); jwtArea = new RSyntaxTextArea(20,60); UIManager.put(""RSyntaxTextAreaUI.actionMap"", null); UIManager.put(""RSyntaxTextAreaUI.inputMap"", null); UIManager.put(""RTextAreaUI.actionMap"", null); UIManager.put(""RTextAreaUI.inputMap"", null); jwtArea.setMarginLinePosition(70); jwtArea.setWhitespaceVisible(true); jwtArea.setMinimumSize(new Dimension(300, 300)); SyntaxScheme scheme = jwtArea.getSyntaxScheme(); Style style = new Style(); style.foreground = new Color(222,133,10); scheme.setStyle(Token.LITERAL_STRING_DOUBLE_QUOTE, style); jwtArea.revalidate(); jwtArea.setHighlightCurrentLine(false); jwtArea.setCurrentLineHighlightColor(Color.WHITE); jwtArea.setSyntaxEditingStyle(SyntaxConstants.SYNTAX_STYLE_JAVASCRIPT); jwtArea.setEditable(true); jwtArea.setPopupMenu(new JPopupMenu()); RTextScrollPane sp = new RTextScrollPane(jwtArea); sp.setVerticalScrollBarPolicy(ScrollPaneConstants.VERTICAL_SCROLLBAR_AS_NEEDED); sp.setLineNumbersEnabled(false); GridBagConstraints gbc_jwtArea = new GridBagConstraints(); gbc_jwtArea.gridheight = 12; gbc_jwtArea.gridwidth = 1; gbc_jwtArea.insets = new Insets(0, 0, 5, 5); gbc_jwtArea.fill = GridBagConstraints.BOTH; gbc_jwtArea.gridx = 1; gbc_jwtArea.gridy = 1; add(sp, gbc_jwtArea); rdbtnDontModifySignature = new JRadioButton(Strings.dontModify); rdbtnDontModifySignature.setToolTipText(Strings.dontModifyToolTip); rdbtnDontModifySignature.setSelected(true); rdbtnDontModifySignature.setHorizontalAlignment(SwingConstants.LEFT); GridBagConstraints gbc_rdbtnDontModifySignature = new GridBagConstraints(); gbc_rdbtnDontModifySignature.anchor = GridBagConstraints.WEST; gbc_rdbtnDontModifySignature.insets = new Insets(0, 0, 5, 5); gbc_rdbtnDontModifySignature.gridx = 2; gbc_rdbtnDontModifySignature.gridy = 1; add(rdbtnDontModifySignature, gbc_rdbtnDontModifySignature); rdbtnRecalculateSignature = new JRadioButton(Strings.recalculateSignature); rdbtnRecalculateSignature.setToolTipText(Strings.recalculateSignatureToolTip); rdbtnRecalculateSignature.setHorizontalAlignment(SwingConstants.LEFT); GridBagConstraints gbc_rdbtnRecalculateSignature = new GridBagConstraints(); gbc_rdbtnRecalculateSignature.anchor = GridBagConstraints.WEST; gbc_rdbtnRecalculateSignature.insets = new Insets(0, 0, 5, 5); gbc_rdbtnRecalculateSignature.gridx = 2; gbc_rdbtnRecalculateSignature.gridy = 2; add(rdbtnRecalculateSignature, gbc_rdbtnRecalculateSignature); rdbtnOriginalSignature = new JRadioButton(Strings.keepOriginalSignature); rdbtnOriginalSignature.setToolTipText(Strings.keepOriginalSignatureToolTip); rdbtnOriginalSignature.setHorizontalAlignment(SwingConstants.LEFT); GridBagConstraints gbc_rdbtnNewRadioButton_1 = new GridBagConstraints(); gbc_rdbtnNewRadioButton_1.insets = new Insets(0, 0, 5, 5); gbc_rdbtnNewRadioButton_1.anchor = GridBagConstraints.WEST; gbc_rdbtnNewRadioButton_1.gridx = 2; gbc_rdbtnNewRadioButton_1.gridy = 3; add(rdbtnOriginalSignature, gbc_rdbtnNewRadioButton_1); rdbtnRandomKey = new JRadioButton(Strings.randomKey); rdbtnRandomKey.setToolTipText(Strings.randomKeyToolTip); rdbtnRandomKey.setHorizontalAlignment(SwingConstants.LEFT); GridBagConstraints gbc_rdbtnNewRadioButton = new GridBagConstraints(); gbc_rdbtnNewRadioButton.anchor = GridBagConstraints.WEST; gbc_rdbtnNewRadioButton.insets = new Insets(0, 0, 5, 5); gbc_rdbtnNewRadioButton.gridx = 2; gbc_rdbtnNewRadioButton.gridy = 4; add(rdbtnRandomKey, gbc_rdbtnNewRadioButton); rdbtnChooseSignature = new JRadioButton(Strings.chooseSignature); rdbtnChooseSignature.setToolTipText(Strings.chooseSignatureToolTip); rdbtnChooseSignature.setHorizontalAlignment(SwingConstants.LEFT); GridBagConstraints gbc_rdbtnNewRadioButton1 = new GridBagConstraints(); gbc_rdbtnNewRadioButton1.anchor = GridBagConstraints.WEST; gbc_rdbtnNewRadioButton1.insets = new Insets(0, 0, 5, 5); gbc_rdbtnNewRadioButton1.gridx = 2; gbc_rdbtnNewRadioButton1.gridy = 5; add(rdbtnChooseSignature, gbc_rdbtnNewRadioButton1); ButtonGroup btgrp = new ButtonGroup(); btgrp.add(rdbtnDontModifySignature); btgrp.add(rdbtnOriginalSignature); btgrp.add(rdbtnRandomKey); btgrp.add(rdbtnRecalculateSignature); btgrp.add(rdbtnChooseSignature); separator = new JSeparator(); GridBagConstraints gbc_separator = new GridBagConstraints(); gbc_separator.insets = new Insets(0, 0, 5, 5); gbc_separator.gridx = 2; gbc_separator.gridy = 5; add(separator, gbc_separator); lblSecretKey = new JLabel(Strings.interceptRecalculationKey); GridBagConstraints gbc_lblSecretKey = new GridBagConstraints(); gbc_lblSecretKey.insets = new Insets(0, 0, 5, 5); gbc_lblSecretKey.anchor = GridBagConstraints.SOUTHWEST; gbc_lblSecretKey.gridx = 2; gbc_lblSecretKey.gridy = 6; add(lblSecretKey, gbc_lblSecretKey); jwtKeyArea = new JTextArea(""""); jwtKeyArea.setRows(2); jwtKeyArea.setLineWrap(false); jwtArea.setWhitespaceVisible(true); jwtKeyArea.setEnabled(false); GridBagConstraints gbc_keyField = new GridBagConstraints(); gbc_keyField.insets = new Insets(0, 0, 5, 5); gbc_keyField.fill = GridBagConstraints.HORIZONTAL; gbc_keyField.gridx = 2; gbc_keyField.gridy = 7; JScrollPane jp = new JScrollPane(jwtKeyArea); jp.setMinimumSize(new Dimension(100, 70)); add(jp, gbc_keyField); lblProblem = new JLabel(""""); GridBagConstraints gbc_lblProblem = new GridBagConstraints(); gbc_lblProblem.insets = new Insets(0, 0, 5, 5); gbc_lblProblem.gridx = 1; gbc_lblProblem.gridy = 8; add(lblProblem, gbc_lblProblem); lblNewLabel = new JLabel(""Alg None Attack:""); GridBagConstraints gbc_lblNewLabel = new GridBagConstraints(); gbc_lblNewLabel.anchor = GridBagConstraints.WEST; gbc_lblNewLabel.insets = new Insets(0, 0, 5, 5); gbc_lblNewLabel.gridx = 2; gbc_lblNewLabel.gridy = 9; add(lblNewLabel, gbc_lblNewLabel); lblCookieFlags = new JLabel(""""); GridBagConstraints gbc_lblCookieFlag = new GridBagConstraints(); gbc_lblCookieFlag.insets = new Insets(0, 0, 5, 5); gbc_lblCookieFlag.anchor = GridBagConstraints.WEST; gbc_lblCookieFlag.gridx = 1; gbc_lblCookieFlag.gridy = 10; add(lblCookieFlags, gbc_lblCookieFlag); noneAttackComboBox = new JComboBox(); GridBagConstraints gbc_noneAttackComboBox = new GridBagConstraints(); gbc_noneAttackComboBox.anchor = GridBagConstraints.WEST; gbc_noneAttackComboBox.insets = new Insets(0, 0, 5, 5); gbc_noneAttackComboBox.gridx = 2; gbc_noneAttackComboBox.gridy = 10; add(noneAttackComboBox, gbc_noneAttackComboBox); chkbxCVEAttack = new JCheckBox(""CVE-2018-0114 Attack""); chkbxCVEAttack.setToolTipText(""The public and private key used can be found in src/app/helpers/Strings.java""); chkbxCVEAttack.setHorizontalAlignment(SwingConstants.LEFT); GridBagConstraints gbc_chkbxCVEAttack = new GridBagConstraints(); gbc_chkbxCVEAttack.anchor = GridBagConstraints.WEST; gbc_chkbxCVEAttack.insets = new Insets(0, 0, 5, 5); gbc_chkbxCVEAttack.gridx = 2; gbc_chkbxCVEAttack.gridy = 11; add(chkbxCVEAttack, gbc_chkbxCVEAttack); lbRegisteredClaims = new JLabel(); lbRegisteredClaims.setBackground(SystemColor.controlHighlight); GridBagConstraints gbc_lbRegisteredClaims = new GridBagConstraints(); gbc_lbRegisteredClaims.insets = new Insets(0, 0, 5, 5); gbc_lbRegisteredClaims.fill = GridBagConstraints.BOTH; gbc_lbRegisteredClaims.gridx = 2; gbc_lbRegisteredClaims.gridy = 12; add(lbRegisteredClaims, gbc_lbRegisteredClaims); btnCopyPubPrivKeyCVEAttack = new JButton(""Copy used public &private key to clipboard used in CVE attack""); btnCopyPubPrivKeyCVEAttack.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent arg0) { Toolkit.getDefaultToolkit() .getSystemClipboard() .setContents( new StringSelection(""Public Key:\r\n""+Config.cveAttackModePublicKey+""\r\n\r\nPrivate Key:\r\n""+Config.cveAttackModePrivateKey), null ); } }); btnCopyPubPrivKeyCVEAttack.setVisible(false); GridBagConstraints gbc_button = new GridBagConstraints(); gbc_button.insets = new Insets(0, 0, 0, 5); gbc_button.gridx = 2; gbc_button.gridy = 13; add(btnCopyPubPrivKeyCVEAttack, gbc_button); noneAttackComboBox.addItem("" -""); noneAttackComboBox.addItem(""Alg: none""); noneAttackComboBox.addItem(""Alg: None""); noneAttackComboBox.addItem(""Alg: nOnE""); noneAttackComboBox.addItem(""Alg: NONE""); }","private void drawGui() { GridBagLayout gridBagLayout = new GridBagLayout(); gridBagLayout.columnWidths = new int[] {0, 100, 250, 0, 0}; gridBagLayout.rowHeights = new int[]{10, 0, 0, 0, 0, 0, 0, 30, 0, 0, 0, 0, 0, 0, 0}; gridBagLayout.columnWeights = new double[]{0.0, 1.0, 0.0, 0.0, Double.MIN_VALUE}; gridBagLayout.rowWeights = new double[]{0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 1.0, Double.MIN_VALUE}; setLayout(gridBagLayout); JTextComponent.removeKeymap(""RTextAreaKeymap""); jwtArea = new RSyntaxTextArea(20,60); UIManager.put(""RSyntaxTextAreaUI.actionMap"", null); UIManager.put(""RSyntaxTextAreaUI.inputMap"", null); UIManager.put(""RTextAreaUI.actionMap"", null); UIManager.put(""RTextAreaUI.inputMap"", null); jwtArea.setMarginLinePosition(70); jwtArea.setWhitespaceVisible(true); jwtArea.setMinimumSize(new Dimension(300, 300)); SyntaxScheme scheme = jwtArea.getSyntaxScheme(); Style style = new Style(); style.foreground = new Color(222,133,10); scheme.setStyle(Token.LITERAL_STRING_DOUBLE_QUOTE, style); jwtArea.revalidate(); jwtArea.setHighlightCurrentLine(false); jwtArea.setCurrentLineHighlightColor(Color.WHITE); jwtArea.setSyntaxEditingStyle(SyntaxConstants.SYNTAX_STYLE_JAVASCRIPT); jwtArea.setEditable(true); jwtArea.setPopupMenu(new JPopupMenu()); RTextScrollPane sp = new RTextScrollPane(jwtArea); sp.setVerticalScrollBarPolicy(ScrollPaneConstants.VERTICAL_SCROLLBAR_AS_NEEDED); sp.setLineNumbersEnabled(false); GridBagConstraints gbc_jwtArea = new GridBagConstraints(); gbc_jwtArea.gridheight = 12; gbc_jwtArea.gridwidth = 1; gbc_jwtArea.insets = new Insets(0, 0, 5, 5); gbc_jwtArea.fill = GridBagConstraints.BOTH; gbc_jwtArea.gridx = 1; gbc_jwtArea.gridy = 1; add(sp, gbc_jwtArea); rdbtnDontModifySignature = new JRadioButton(Strings.dontModify); rdbtnDontModifySignature.setToolTipText(Strings.dontModifyToolTip); rdbtnDontModifySignature.setSelected(true); rdbtnDontModifySignature.setHorizontalAlignment(SwingConstants.LEFT); GridBagConstraints gbc_rdbtnDontModifySignature = new GridBagConstraints(); gbc_rdbtnDontModifySignature.anchor = GridBagConstraints.WEST; gbc_rdbtnDontModifySignature.insets = new Insets(0, 0, 5, 5); gbc_rdbtnDontModifySignature.gridx = 2; gbc_rdbtnDontModifySignature.gridy = 1; add(rdbtnDontModifySignature, gbc_rdbtnDontModifySignature); rdbtnRecalculateSignature = new JRadioButton(Strings.recalculateSignature); rdbtnRecalculateSignature.setToolTipText(Strings.recalculateSignatureToolTip); rdbtnRecalculateSignature.setHorizontalAlignment(SwingConstants.LEFT); GridBagConstraints gbc_rdbtnRecalculateSignature = new GridBagConstraints(); gbc_rdbtnRecalculateSignature.anchor = GridBagConstraints.WEST; gbc_rdbtnRecalculateSignature.insets = new Insets(0, 0, 5, 5); gbc_rdbtnRecalculateSignature.gridx = 2; gbc_rdbtnRecalculateSignature.gridy = 2; add(rdbtnRecalculateSignature, gbc_rdbtnRecalculateSignature); rdbtnOriginalSignature = new JRadioButton(Strings.keepOriginalSignature); rdbtnOriginalSignature.setToolTipText(Strings.keepOriginalSignatureToolTip); rdbtnOriginalSignature.setHorizontalAlignment(SwingConstants.LEFT); GridBagConstraints gbc_rdbtnNewRadioButton_1 = new GridBagConstraints(); gbc_rdbtnNewRadioButton_1.insets = new Insets(0, 0, 5, 5); gbc_rdbtnNewRadioButton_1.anchor = GridBagConstraints.WEST; gbc_rdbtnNewRadioButton_1.gridx = 2; gbc_rdbtnNewRadioButton_1.gridy = 3; add(rdbtnOriginalSignature, gbc_rdbtnNewRadioButton_1); rdbtnRandomKey = new JRadioButton(Strings.randomKey); rdbtnRandomKey.setToolTipText(Strings.randomKeyToolTip); rdbtnRandomKey.setHorizontalAlignment(SwingConstants.LEFT); GridBagConstraints gbc_rdbtnNewRadioButton = new GridBagConstraints(); gbc_rdbtnNewRadioButton.anchor = GridBagConstraints.WEST; gbc_rdbtnNewRadioButton.insets = new Insets(0, 0, 5, 5); gbc_rdbtnNewRadioButton.gridx = 2; gbc_rdbtnNewRadioButton.gridy = 4; add(rdbtnRandomKey, gbc_rdbtnNewRadioButton); rdbtnChooseSignature = new JRadioButton(Strings.chooseSignature); rdbtnChooseSignature.setToolTipText(Strings.chooseSignatureToolTip); rdbtnChooseSignature.setHorizontalAlignment(SwingConstants.LEFT); GridBagConstraints gbc_rdbtnNewRadioButton1 = new GridBagConstraints(); gbc_rdbtnNewRadioButton1.anchor = GridBagConstraints.WEST; gbc_rdbtnNewRadioButton1.insets = new Insets(0, 0, 5, 5); gbc_rdbtnNewRadioButton1.gridx = 2; gbc_rdbtnNewRadioButton1.gridy = 5; add(rdbtnChooseSignature, gbc_rdbtnNewRadioButton1); ButtonGroup btgrp = new ButtonGroup(); btgrp.add(rdbtnDontModifySignature); btgrp.add(rdbtnOriginalSignature); btgrp.add(rdbtnRandomKey); btgrp.add(rdbtnRecalculateSignature); btgrp.add(rdbtnChooseSignature); separator = new JSeparator(); GridBagConstraints gbc_separator = new GridBagConstraints(); gbc_separator.insets = new Insets(0, 0, 5, 5); gbc_separator.gridx = 2; gbc_separator.gridy = 5; add(separator, gbc_separator); lblSecretKey = new JLabel(Strings.interceptRecalculationKey); GridBagConstraints gbc_lblSecretKey = new GridBagConstraints(); gbc_lblSecretKey.insets = new Insets(0, 0, 5, 5); gbc_lblSecretKey.anchor = GridBagConstraints.SOUTHWEST; gbc_lblSecretKey.gridx = 2; gbc_lblSecretKey.gridy = 6; add(lblSecretKey, gbc_lblSecretKey); jwtKeyArea = new JTextArea(""""); jwtKeyArea.setRows(2); jwtKeyArea.setLineWrap(false); jwtArea.setWhitespaceVisible(true); jwtKeyArea.setEnabled(false); GridBagConstraints gbc_keyField = new GridBagConstraints(); gbc_keyField.insets = new Insets(0, 0, 5, 5); gbc_keyField.fill = GridBagConstraints.HORIZONTAL; gbc_keyField.gridx = 2; gbc_keyField.gridy = 7; JScrollPane jp = new JScrollPane(jwtKeyArea); jp.setMinimumSize(new Dimension(100, 70)); add(jp, gbc_keyField); lblProblem = new JLabel(""""); GridBagConstraints gbc_lblProblem = new GridBagConstraints(); gbc_lblProblem.insets = new Insets(0, 0, 5, 5); gbc_lblProblem.gridx = 1; gbc_lblProblem.gridy = 8; add(lblProblem, gbc_lblProblem); lblNewLabel = new JLabel(""Alg None Attack:""); GridBagConstraints gbc_lblNewLabel = new GridBagConstraints(); gbc_lblNewLabel.anchor = GridBagConstraints.WEST; gbc_lblNewLabel.insets = new Insets(0, 0, 5, 5); gbc_lblNewLabel.gridx = 2; gbc_lblNewLabel.gridy = 9; add(lblNewLabel, gbc_lblNewLabel); lblCookieFlags = new JLabel(""""); GridBagConstraints gbc_lblCookieFlag = new GridBagConstraints(); gbc_lblCookieFlag.insets = new Insets(0, 0, 5, 5); gbc_lblCookieFlag.anchor = GridBagConstraints.WEST; gbc_lblCookieFlag.gridx = 1; gbc_lblCookieFlag.gridy = 10; add(lblCookieFlags, gbc_lblCookieFlag); noneAttackComboBox = new JComboBox(); GridBagConstraints gbc_noneAttackComboBox = new GridBagConstraints(); gbc_noneAttackComboBox.anchor = GridBagConstraints.WEST; gbc_noneAttackComboBox.insets = new Insets(0, 0, 5, 5); gbc_noneAttackComboBox.gridx = 2; gbc_noneAttackComboBox.gridy = 10; add(noneAttackComboBox, gbc_noneAttackComboBox); chkbxCVEAttack = new JCheckBox(""CVE-2018-0114 Attack""); chkbxCVEAttack.setToolTipText(""The public and private key used can be found in src/app/helpers/Strings.java""); chkbxCVEAttack.setHorizontalAlignment(SwingConstants.LEFT); GridBagConstraints gbc_chkbxCVEAttack = new GridBagConstraints(); gbc_chkbxCVEAttack.anchor = GridBagConstraints.WEST; gbc_chkbxCVEAttack.insets = new Insets(0, 0, 5, 5); gbc_chkbxCVEAttack.gridx = 2; gbc_chkbxCVEAttack.gridy = 11; add(chkbxCVEAttack, gbc_chkbxCVEAttack); lbRegisteredClaims = new JLabel(); lbRegisteredClaims.setBackground(SystemColor.controlHighlight); GridBagConstraints gbc_lbRegisteredClaims = new GridBagConstraints(); gbc_lbRegisteredClaims.insets = new Insets(0, 0, 5, 5); gbc_lbRegisteredClaims.fill = GridBagConstraints.BOTH; gbc_lbRegisteredClaims.gridx = 2; gbc_lbRegisteredClaims.gridy = 12; add(lbRegisteredClaims, gbc_lbRegisteredClaims); btnCopyPubPrivKeyCVEAttack = new JButton(""Copy used public & private\r\nkey to clipboard used in CVE attack""); btnCopyPubPrivKeyCVEAttack.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent arg0) { Toolkit.getDefaultToolkit() .getSystemClipboard() .setContents( new StringSelection(""Public Key:\r\n""+Config.cveAttackModePublicKey+""\r\n\r\nPrivate Key:\r\n""+Config.cveAttackModePrivateKey), null ); } }); btnCopyPubPrivKeyCVEAttack.setVisible(false); GridBagConstraints gbc_button = new GridBagConstraints(); gbc_button.insets = new Insets(0, 0, 0, 5); gbc_button.gridx = 2; gbc_button.gridy = 13; add(btnCopyPubPrivKeyCVEAttack, gbc_button); noneAttackComboBox.addItem("" -""); noneAttackComboBox.addItem(""Alg: none""); noneAttackComboBox.addItem(""Alg: None""); noneAttackComboBox.addItem(""Alg: nOnE""); noneAttackComboBox.addItem(""Alg: NONE""); }",WIP - CVE attack realtime,https://github.com/ozzi-/JWT4B/commit/75021e5c5dba0f09cac0e82d153116b7e2249d58,,,src/gui/JWTInterceptTab.java,3,java,False,2021-11-23T16:43:26Z "int getAvailRing(final int i) throws MemoryAccessException { final long address = driver + VIRTQ_AVAIL_RING + (long) toWrappedRingIndex(i) * VIRTQ_AVAILABLE_RING_STRIDE; return (int) memoryMap.load(address, Sizes.SIZE_16_LOG2) & 0xFFFF; }","short getAvailRing(final int i) throws MemoryAccessException { final long address = driver + VIRTQ_AVAIL_RING + (long) toWrappedRingIndex(i) * VIRTQ_AVAILABLE_RING_STRIDE; return (short) (memoryMap.load(address, Sizes.SIZE_16_LOG2) & 0xFFFFL); }","Use shorts where we actually have shorts, fixes potential infinite loop when next available index is exactly the wrap point (0x8000, which as int will never equal a short value).",https://github.com/fnuecke/sedna/commit/ae93820014397840d62f2572e720b710ac368276,,,src/main/java/li/cil/sedna/device/virtio/AbstractVirtIODevice.java,3,java,False,2022-07-19T21:31:56Z "public void wallfilter(String name, String[] values,AttackContext attackContext) { String[] wallfilterrules = this.getWallfilterrules(); if (wallfilterrules == null || wallfilterrules.length == 0 || values == null || values.length == 0 || iswhilename(name)) return; int j = 0; for (String value : values) { if (value == null || value.equals("""")) { j++; continue; } for (int i = 0; i < wallfilterrules.length; i++) { if (value.indexOf(wallfilterrules[i]) >= 0) { attackContext.setParamName(name); attackContext.setValues(values); attackContext.setPosition(j); attackContext.setAttackRule(wallfilterrules[i]); attackFielterPolicy.attackHandle(attackContext); break; } } j++; } }","public void wallfilter(String name, String[] values,AttackContext attackContext) { if(attackFielterPolicy.isDisable()){ return; } String[] wallfilterrules = this.getWallfilterrules(); if (wallfilterrules == null || wallfilterrules.length == 0 || values == null || values.length == 0 || iswhilename(name)) return; int j = 0; for (String value : values) { if (value == null || value.equals("""")) { j++; continue; } for (int i = 0; i < wallfilterrules.length; i++) { if (value.indexOf(wallfilterrules[i]) >= 0) { attackContext.setParamName(name); attackContext.setValues(values); attackContext.setPosition(j); attackContext.setAttackRule(wallfilterrules[i]); attackContext.setAttackType(AttackContext.XSS_ATTACK); attackFielterPolicy.attackHandle(attackContext); break; } } j++; } }","xss和敏感词攻击过滤功能添加 作业启停功能完善",https://github.com/bbossgroups/bboss/commit/c581475ddcb4548aeb168ac05711c911d80042cb,,,bboss-util/src/org/frameworkset/util/ReferHelper.java,3,java,False,2021-12-02T06:13:40Z "@Override protected void dumpLocked(String prefix, PrintWriter pw) { super.dumpLocked(prefix, pw); final String prefix2 = prefix + "" ""; pw.print(prefix); pw.print(""Service Info: ""); if (mInfo == null) { pw.println(""N/A""); } else { pw.println(); mInfo.dump(prefix2, pw); } pw.print(prefix); pw.print(""Zombie: ""); pw.println(mZombie); if (mRemoteService != null) { pw.print(prefix); pw.println(""remote service:""); mRemoteService.dump(prefix2, pw); } if (mSessions.size() == 0) { pw.print(prefix); pw.println(""no sessions""); } else { final int sessionsSize = mSessions.size(); pw.print(prefix); pw.print(""number sessions: ""); pw.println(sessionsSize); for (int i = 0; i < sessionsSize; i++) { pw.print(prefix); pw.print(""#""); pw.println(i); final ContentCaptureServerSession session = mSessions.valueAt(i); session.dumpLocked(prefix2, pw); pw.println(); } } }","@Override protected void dumpLocked(String prefix, PrintWriter pw) { super.dumpLocked(prefix, pw); final String prefix2 = prefix + "" ""; pw.print(prefix); pw.print(""Service Info: ""); if (mInfo == null) { pw.println(""N/A""); } else { pw.println(); mInfo.dump(prefix2, pw); } pw.print(prefix); pw.print(""Zombie: ""); pw.println(mZombie); pw.print(prefix); pw.print(""Rebind count: ""); pw.println(mRebindCount); pw.print(prefix); pw.print(""Last rebind: ""); pw.println(mLastRebindTime); if (mRemoteService != null) { pw.print(prefix); pw.println(""remote service:""); mRemoteService.dump(prefix2, pw); } if (mSessions.size() == 0) { pw.print(prefix); pw.println(""no sessions""); } else { final int sessionsSize = mSessions.size(); pw.print(prefix); pw.print(""number sessions: ""); pw.println(sessionsSize); for (int i = 0; i < sessionsSize; i++) { pw.print(prefix); pw.print(""#""); pw.println(i); final ContentCaptureServerSession session = mSessions.valueAt(i); session.dumpLocked(prefix2, pw); pw.println(); } } }","Rebind ContentCaptureService when the binderDied. If the ContentCaptureService has package dependency with other package, if the package is updating, ContentCaptureService will also be killed. In the normal case, if the service will be reconnected but in this case the binding is cleared without any notification to the ContentCaptureManagerService. The bug is in the core platform infra. In the Content Capture code, we only see the binderDied. This change is a short term solution in S, we will rebind the service when the binderDied. To avoid crash loop, we only bind the service with limit rebind counts. Bug: 199609306 Test: manual. Add addPackageDependency to package and update the package. Make sure the state is not zombie. Change-Id: I09a4cf6281a5a259a9a759ca640d6f075726e562",https://github.com/omnirom/android_frameworks_base/commit/4fc5c86bb9945be49cd77140facf62ba70b5b7e4,,,services/contentcapture/java/com/android/server/contentcapture/ContentCapturePerUserService.java,3,java,False,2021-09-23T13:48:31Z "public Response revokeCert(CertId id, CertRevokeRequest request, boolean caCert) { if (id == null) { logger.warn(""Unable to revoke cert: Missing certificate ID""); throw new BadRequestException(""Unable to revoke cert: Missing certificate ID""); } if (request == null) { logger.warn(""revokeCert: request is null""); throw new BadRequestException(""Unable to revoke cert: invalid request""); } // check cert actually exists. This will throw a CertNotFoundException // if the cert does not exist @SuppressWarnings(""unused"") CertData data = getCertData(id); RevocationReason revReason = request.getReason(); if (revReason == RevocationReason.REMOVE_FROM_CRL) { return unrevokeCert(id); } String caIssuerDN = null; X500Name caX500DN = null; RevocationProcessor processor; try { processor = new RevocationProcessor(""caDoRevoke-agent"", getLocale(headers)); processor.setStartTime(new Date().getTime()); // TODO: set initiative based on auth info processor.setInitiative(AuditFormat.FROMAGENT); processor.setSerialNumber(id); processor.setRevocationReason(revReason); processor.setRequestType(revReason == RevocationReason.CERTIFICATE_HOLD ? RevocationProcessor.ON_HOLD : RevocationProcessor.REVOKE); processor.setInvalidityDate(request.getInvalidityDate()); processor.setComments(request.getComments()); processor.setAuthority(authority); caX500DN = (X500Name) authority.getCACert().getIssuerDN(); } catch (EBaseException e) { logger.error(""Unable to revoke certificate: "" + e.getMessage(), e); throw new PKIException(""Unable to revoke certificate: "" + e.getMessage(), e); } try { X509Certificate clientCert = null; try { clientCert = CAProcessor.getSSLClientCertificate(servletRequest); } catch (EBaseException e) { // No client certificate, ignore. } CertRecord clientRecord = null; BigInteger clientSerialNumber = null; String clientSubjectDN = null; if (clientCert != null) { clientSerialNumber = clientCert.getSerialNumber(); clientSubjectDN = clientCert.getSubjectDN().toString(); X500Name x500issuerDN = (X500Name) clientCert.getIssuerDN(); /* * internal revocation check only to be conducted for certs * issued by this CA * For client certs issued by external CAs, TLS mutual auth * would have completed the authenticaton/verification if * OCSP was enabled; * Furthermore, prior to the actual revocation, client cert * is mapped against the agent group database for proper * privilege regardless of the issuer. */ if (x500issuerDN.equals(caX500DN)) { logger.info(""CertService.revokeCert: client cert issued by this CA""); clientRecord = processor.getCertificateRecord(clientSerialNumber); // Verify client cert is not revoked. // TODO: This should be checked during authentication. if (clientRecord.getStatus().equals(CertRecord.STATUS_REVOKED)) { throw new UnauthorizedException(CMS.getLogMessage(""CMSGW_UNAUTHORIZED"")); } } else { logger.info(""CertService.revokeCert: client cert not issued by this CA""); if (!authority.allowExtCASignedAgentCerts()) { logger.error(""CertService.revokeCert: allowExtCASignedAgentCerts false;""); throw new UnauthorizedException(CMS.getLogMessage(""CMSGW_UNAUTHORIZED"")); } else { logger.info(""CertService.revokeCert: allowExtCASignedAgentCerts true;""); } } } if (authority.noncesEnabled() && !processor.isMemberOfSubsystemGroup(clientCert)) { processor.validateNonce(servletRequest, ""cert-revoke"", id.toBigInteger(), request.getNonce()); } // Find target cert record if different from client cert. CertRecord targetRecord = id.equals(clientSerialNumber) ? clientRecord : processor.getCertificateRecord(id); X509CertImpl targetCert = targetRecord.getCertificate(); processor.createCRLExtension(); // TODO remove hardcoded role names and consult authzmgr // (so that we can handle externally-authenticated principals) GenericPrincipal principal = (GenericPrincipal) servletRequest.getUserPrincipal(); String subjectDN = principal.hasRole(""Certificate Manager Agents"") ? null : clientSubjectDN; processor.validateCertificateToRevoke(subjectDN, targetRecord, caCert); processor.addCertificateToRevoke(targetCert); processor.createRevocationRequest(); processor.auditChangeRequest(ILogger.SUCCESS); } catch (PKIException e) { logger.warn(""Unable to pre-process revocation request: "" + e.getMessage()); processor.auditChangeRequest(ILogger.FAILURE); throw e; } catch (EBaseException e) { logger.error(""Unable to pre-process revocation request: "" + e.getMessage(), e); processor.auditChangeRequest(ILogger.FAILURE); throw new PKIException(""Unable to revoke cert: "" + e.getMessage(), e); } catch (IOException e) { logger.error(""Unable to pre-process revocation request: "" + e.getMessage(), e); processor.auditChangeRequest(ILogger.FAILURE); throw new PKIException(""Unable to revoke cert: "" + e.getMessage(), e); } // change audit processing from ""REQUEST"" to ""REQUEST_PROCESSED"" // to distinguish which type of signed audit log message to save // as a failure outcome in case an exception occurs try { processor.processRevocationRequest(); processor.auditChangeRequestProcessed(ILogger.SUCCESS); } catch (EBaseException e) { logger.error(""Unable to process revocation request: "" + e.getMessage(), e); processor.auditChangeRequestProcessed(ILogger.FAILURE); throw new PKIException(""Unable to revoke certificate: "" + e.getMessage(), e); } try { IRequest certRequest = processor.getRequest(); CertRequestDAO dao = new CertRequestDAO(); CertRequestInfo requestInfo = dao.getRequest(certRequest.getRequestId(), uriInfo); return createOKResponse(requestInfo); } catch (EBaseException e) { logger.error(""Unable to create revocation response: "" + e.getMessage(), e); throw new PKIException(""Unable to create revocation response: "" + e.getMessage(), e); } }","public Response revokeCert(CertId id, CertRevokeRequest request, boolean caCert) { if (id == null) { logger.warn(""Unable to revoke cert: Missing certificate ID""); throw new BadRequestException(""Unable to revoke cert: Missing certificate ID""); } if (request == null) { logger.warn(""revokeCert: request is null""); throw new BadRequestException(""Unable to revoke cert: invalid request""); } // check cert actually exists. This will throw a CertNotFoundException // if the cert does not exist @SuppressWarnings(""unused"") CertData data = getCertData(id); RevocationReason revReason = request.getReason(); if (revReason == RevocationReason.REMOVE_FROM_CRL) { return unrevokeCert(id); } String caIssuerDN = null; X500Name caX500DN = null; RevocationProcessor processor; try { processor = new RevocationProcessor(""caDoRevoke-agent"", getLocale(headers)); processor.setStartTime(new Date().getTime()); // TODO: set initiative based on auth info processor.setInitiative(AuditFormat.FROMAGENT); processor.setSerialNumber(id); processor.setRevocationReason(revReason); processor.setRequestType(revReason == RevocationReason.CERTIFICATE_HOLD ? RevocationProcessor.ON_HOLD : RevocationProcessor.REVOKE); processor.setInvalidityDate(request.getInvalidityDate()); processor.setComments(request.getComments()); processor.setAuthority(authority); caX500DN = (X500Name) authority.getCACert().getSubjectDN(); } catch (EBaseException e) { logger.error(""Unable to revoke certificate: "" + e.getMessage(), e); throw new PKIException(""Unable to revoke certificate: "" + e.getMessage(), e); } try { X509Certificate clientCert = null; try { clientCert = CAProcessor.getSSLClientCertificate(servletRequest); } catch (EBaseException e) { // No client certificate, ignore. } CertRecord clientRecord = null; BigInteger clientSerialNumber = null; String clientSubjectDN = null; if (clientCert != null) { clientSerialNumber = clientCert.getSerialNumber(); clientSubjectDN = clientCert.getSubjectDN().toString(); X500Name x500issuerDN = (X500Name) clientCert.getIssuerDN(); /* * internal revocation check only to be conducted for certs * issued by this CA * For client certs issued by external CAs, TLS mutual auth * would have completed the authenticaton/verification if * OCSP was enabled; * Furthermore, prior to the actual revocation, client cert * is mapped against the agent group database for proper * privilege regardless of the issuer. */ if (x500issuerDN.equals(caX500DN)) { logger.info(""CertService.revokeCert: client cert issued by this CA""); clientRecord = processor.getCertificateRecord(clientSerialNumber); // Verify client cert is not revoked. // TODO: This should be checked during authentication. if (clientRecord.getStatus().equals(CertRecord.STATUS_REVOKED)) { throw new UnauthorizedException(CMS.getLogMessage(""CMSGW_UNAUTHORIZED"")); } } else { logger.info(""CertService.revokeCert: client cert not issued by this CA""); if (!authority.allowExtCASignedAgentCerts()) { logger.error(""CertService.revokeCert: allowExtCASignedAgentCerts false;""); throw new UnauthorizedException(CMS.getLogMessage(""CMSGW_UNAUTHORIZED"")); } else { logger.info(""CertService.revokeCert: allowExtCASignedAgentCerts true;""); } } } if (authority.noncesEnabled() && !processor.isMemberOfSubsystemGroup(clientCert)) { processor.validateNonce(servletRequest, ""cert-revoke"", id.toBigInteger(), request.getNonce()); } // Find target cert record if different from client cert. CertRecord targetRecord = id.equals(clientSerialNumber) ? clientRecord : processor.getCertificateRecord(id); X509CertImpl targetCert = targetRecord.getCertificate(); processor.createCRLExtension(); // TODO remove hardcoded role names and consult authzmgr // (so that we can handle externally-authenticated principals) GenericPrincipal principal = (GenericPrincipal) servletRequest.getUserPrincipal(); String subjectDN = principal.hasRole(""Certificate Manager Agents"") ? null : clientSubjectDN; processor.validateCertificateToRevoke(subjectDN, targetRecord, caCert); processor.addCertificateToRevoke(targetCert); processor.createRevocationRequest(); processor.auditChangeRequest(ILogger.SUCCESS); } catch (PKIException e) { logger.warn(""Unable to pre-process revocation request: "" + e.getMessage()); processor.auditChangeRequest(ILogger.FAILURE); throw e; } catch (EBaseException e) { logger.error(""Unable to pre-process revocation request: "" + e.getMessage(), e); processor.auditChangeRequest(ILogger.FAILURE); throw new PKIException(""Unable to revoke cert: "" + e.getMessage(), e); } catch (IOException e) { logger.error(""Unable to pre-process revocation request: "" + e.getMessage(), e); processor.auditChangeRequest(ILogger.FAILURE); throw new PKIException(""Unable to revoke cert: "" + e.getMessage(), e); } // change audit processing from ""REQUEST"" to ""REQUEST_PROCESSED"" // to distinguish which type of signed audit log message to save // as a failure outcome in case an exception occurs try { processor.processRevocationRequest(); processor.auditChangeRequestProcessed(ILogger.SUCCESS); } catch (EBaseException e) { logger.error(""Unable to process revocation request: "" + e.getMessage(), e); processor.auditChangeRequestProcessed(ILogger.FAILURE); throw new PKIException(""Unable to revoke certificate: "" + e.getMessage(), e); } try { IRequest certRequest = processor.getRequest(); CertRequestDAO dao = new CertRequestDAO(); CertRequestInfo requestInfo = dao.getRequest(certRequest.getRequestId(), uriInfo); return createOKResponse(requestInfo); } catch (EBaseException e) { logger.error(""Unable to create revocation response: "" + e.getMessage(), e); throw new PKIException(""Unable to create revocation response: "" + e.getMessage(), e); } }","Bug1990105- TPS Not properly enforcing Token Profile Separation This patch addresses the issue that TPS agent operations on tokens, activities, and profiles are not limited by the types (profiles) permmtted to the agent (as described in the documentation). This is a regression from 8.x. The affected operations are: - findProfiles - getProfiles - updateProfile - changeStatus (of a profile) - retrieveTokens - getToken - modifyToken - changeTokenStatus - retrieveActivities - getActivity Note that some operations that seem like should be affected are not due to the fact that they are TPS admin operations and are shielded from entering the TPS service at the activity level. For example, deleting a token would be such a case. The authorization enforcement added in this patch should affect both access from the web UI as well as access from PKI CLI. Reference: https://github.com/dogtagpki/pki/wiki/PKI-TPS-CLI Another note: the VLV complicates the resulting page. If the returned entries on the page are all restricted then nothing would be shown. To add a bit more clarity, an entry is added to reflect such effect so that it would be less confusing to the role user. The entries are left with the epoch date. This would affect both WEB UI and PKI CLI. Also, a list minute addition to address an issue with 1911472 in CertService.java where the subject DN of the CA signing cert should be used instead of the issuer. fixes https://bugzilla.redhat.com/show_bug.cgi?id=1990105",https://github.com/dogtagpki/pki/commit/b9db71b98480f6ba47e66dd6cde1d9dfec80eb66,,,base/ca/src/main/java/org/dogtagpki/server/ca/rest/CertService.java,3,java,False,2021-08-11T16:15:48Z "@Override public Publisher> doFilter(HttpRequest request, ServerFilterChain chain) { String origin = request.getHeaders().getOrigin().orElse(null); if (origin == null) { LOG.trace(""Http Header "" + HttpHeaders.ORIGIN + "" not present. Proceeding with the request.""); return chain.proceed(request); } CorsOriginConfiguration corsOriginConfiguration = getConfiguration(origin).orElse(null); if (corsOriginConfiguration != null) { if (CorsUtil.isPreflightRequest(request)) { return handlePreflightRequest(request, chain, corsOriginConfiguration); } if (!validateMethodToMatch(request, corsOriginConfiguration).isPresent()) { return forbidden(); } return Publishers.then(chain.proceed(request), resp -> decorateResponseWithHeaders(request, resp, corsOriginConfiguration)); } LOG.trace(""CORS configuration not found for {} origin"", origin); return chain.proceed(request); }","@Override public Publisher> doFilter(HttpRequest request, ServerFilterChain chain) { String origin = request.getHeaders().getOrigin().orElse(null); if (origin == null) { LOG.trace(""Http Header "" + HttpHeaders.ORIGIN + "" not present. Proceeding with the request.""); return chain.proceed(request); } CorsOriginConfiguration corsOriginConfiguration = getConfiguration(origin).orElse(null); if (corsOriginConfiguration != null) { if (CorsUtil.isPreflightRequest(request)) { return handlePreflightRequest(request, chain, corsOriginConfiguration); } if (!validateMethodToMatch(request, corsOriginConfiguration).isPresent()) { return forbidden(); } if (shouldDenyToPreventDriveByLocalhostAttack(corsOriginConfiguration, request)) { LOG.trace(""The resolved configuration allows any origin. To prevent drive-by-localhost attacks the request is forbidden""); return forbidden(); } return Publishers.then(chain.proceed(request), resp -> decorateResponseWithHeaders(request, resp, corsOriginConfiguration)); } LOG.trace(""CORS configuration not found for {} origin"", origin); return chain.proceed(request); }",Merge branch '3.7.x' into 3.8.x,https://github.com/micronaut-projects/micronaut-core/commit/d8490106c759cfe93adfd161e46ac9433bde955f,,,http-server/src/main/java/io/micronaut/http/server/cors/CorsFilter.java,3,java,False,2022-12-22T20:00:32Z "public String getCurrentUserName() { Authentication auth = SecurityContextHolder.getContext().getAuthentication(); if (!(auth instanceof AnonymousAuthenticationToken)) { return auth.getName(); } return ""anonymous""; }","public String getCurrentUserName() { Authentication auth = SecurityContextHolder.getContext().getAuthentication(); if (null == auth || auth instanceof AnonymousAuthenticationToken) { return ""anonymous""; } return auth.getName(); }",Add NPE prevention on null authentication,https://github.com/ff4j/ff4j/commit/f68aeee75ef6aca45058c9c903068c54ab81ad76,,,ff4j-security-spring/src/main/java/org/ff4j/security/SpringSecurityAuthorisationManager.java,3,java,False,2022-04-24T03:54:17Z "private static void clean() { boolean running = true; try { while (running) { Reference ref = GLOBAL_QUEUE.remove(); if (ref instanceof ListenableWeakReference) { ((ListenableWeakReference) ref).onDereference(); } } } catch (InterruptedException e) { running = false; BugReport.intercept(e).warn(); Thread.currentThread().interrupt(); } }","private static void clean() { boolean running = true; while (running) { try { Reference ref = GLOBAL_QUEUE.remove(); if (ref instanceof ListenableWeakReference) { ((ListenableWeakReference) ref).onDereference(); } } catch (InterruptedException e) { running = false; BugReport.intercept(e).warn(); Thread.currentThread().interrupt(); } } }","fix coverity 1437552 (infinite loop) git-svn-id: https://josm.openstreetmap.de/svn/trunk@18212 0c6e7542-c601-0410-84e7-c038aed88b3b",https://github.com/JOSM/josm/commit/c969849e4d43846cc7d91625e2bdd2316c44b812,,,src/org/openstreetmap/josm/tools/ListenableWeakReference.java,3,java,False,2021-09-12T00:15:34Z "public boolean startInstrumentation(ComponentName className, String profileFile, int flags, Bundle arguments, IInstrumentationWatcher watcher, IUiAutomationConnection uiAutomationConnection, int userId, String abiOverride) { enforceNotIsolatedCaller(""startInstrumentation""); final int callingUid = Binder.getCallingUid(); final int callingPid = Binder.getCallingPid(); userId = mUserController.handleIncomingUser(callingPid, callingUid, userId, false, ALLOW_FULL_ONLY, ""startInstrumentation"", null); // Refuse possible leaked file descriptors if (arguments != null && arguments.hasFileDescriptors()) { throw new IllegalArgumentException(""File descriptors passed in Bundle""); } synchronized(this) { InstrumentationInfo ii = null; ApplicationInfo ai = null; boolean noRestart = (flags & INSTR_FLAG_NO_RESTART) != 0; try { ii = mContext.getPackageManager().getInstrumentationInfo( className, STOCK_PM_FLAGS); ai = AppGlobals.getPackageManager().getApplicationInfo( ii.targetPackage, STOCK_PM_FLAGS, userId); } catch (PackageManager.NameNotFoundException e) { } catch (RemoteException e) { } if (ii == null) { reportStartInstrumentationFailureLocked(watcher, className, ""Unable to find instrumentation info for: "" + className); return false; } if (ai == null) { reportStartInstrumentationFailureLocked(watcher, className, ""Unable to find instrumentation target package: "" + ii.targetPackage); return false; } if (ii.targetPackage.equals(""android"")) { if (!noRestart) { reportStartInstrumentationFailureLocked(watcher, className, ""Cannot instrument system server without 'no-restart'""); return false; } } else if (!ai.hasCode()) { reportStartInstrumentationFailureLocked(watcher, className, ""Instrumentation target has no code: "" + ii.targetPackage); return false; } int match = mContext.getPackageManager().checkSignatures( ii.targetPackage, ii.packageName); if (match < 0 && match != PackageManager.SIGNATURE_FIRST_NOT_SIGNED) { if (Build.IS_DEBUGGABLE && (callingUid == Process.ROOT_UID) && (flags & INSTR_FLAG_ALWAYS_CHECK_SIGNATURE) == 0) { Slog.w(TAG, ""Instrumentation test "" + ii.packageName + "" doesn't have a signature matching the target "" + ii.targetPackage + "", which would not be allowed on the production Android builds""); } else { String msg = ""Permission Denial: starting instrumentation "" + className + "" from pid="" + Binder.getCallingPid() + "", uid="" + Binder.getCallingUid() + "" not allowed because package "" + ii.packageName + "" does not have a signature matching the target "" + ii.targetPackage; reportStartInstrumentationFailureLocked(watcher, className, msg); throw new SecurityException(msg); } } boolean disableHiddenApiChecks = ai.usesNonSdkApi() || (flags & INSTR_FLAG_DISABLE_HIDDEN_API_CHECKS) != 0; boolean disableTestApiChecks = disableHiddenApiChecks || (flags & INSTR_FLAG_DISABLE_TEST_API_CHECKS) != 0; if (disableHiddenApiChecks || disableTestApiChecks) { enforceCallingPermission(android.Manifest.permission.DISABLE_HIDDEN_API_CHECKS, ""disable hidden API checks""); } if ((flags & ActivityManager.INSTR_FLAG_INSTRUMENT_SDK_SANDBOX) != 0) { return startInstrumentationOfSdkSandbox( className, profileFile, arguments, watcher, uiAutomationConnection, userId, abiOverride, ii, ai, noRestart, disableHiddenApiChecks, disableTestApiChecks); } ActiveInstrumentation activeInstr = new ActiveInstrumentation(this); activeInstr.mClass = className; String defProcess = ai.processName;; if (ii.targetProcesses == null) { activeInstr.mTargetProcesses = new String[]{ai.processName}; } else if (ii.targetProcesses.equals(""*"")) { activeInstr.mTargetProcesses = new String[0]; } else { activeInstr.mTargetProcesses = ii.targetProcesses.split("",""); defProcess = activeInstr.mTargetProcesses[0]; } activeInstr.mTargetInfo = ai; activeInstr.mProfileFile = profileFile; activeInstr.mArguments = arguments; activeInstr.mWatcher = watcher; activeInstr.mUiAutomationConnection = uiAutomationConnection; activeInstr.mResultClass = className; activeInstr.mHasBackgroundActivityStartsPermission = checkPermission( START_ACTIVITIES_FROM_BACKGROUND, callingPid, callingUid) == PackageManager.PERMISSION_GRANTED; activeInstr.mHasBackgroundForegroundServiceStartsPermission = checkPermission( START_FOREGROUND_SERVICES_FROM_BACKGROUND, callingPid, callingUid) == PackageManager.PERMISSION_GRANTED; activeInstr.mNoRestart = noRestart; final long origId = Binder.clearCallingIdentity(); ProcessRecord app; synchronized (mProcLock) { if (noRestart) { app = getProcessRecordLocked(ai.processName, ai.uid); } else { // Instrumentation can kill and relaunch even persistent processes forceStopPackageLocked(ii.targetPackage, -1, true, false, true, true, false, userId, ""start instr""); // Inform usage stats to make the target package active if (mUsageStatsService != null) { mUsageStatsService.reportEvent(ii.targetPackage, userId, UsageEvents.Event.SYSTEM_INTERACTION); } app = addAppLocked(ai, defProcess, false, disableHiddenApiChecks, disableTestApiChecks, abiOverride, ZYGOTE_POLICY_FLAG_EMPTY); app.mProfile.addHostingComponentType(HOSTING_COMPONENT_TYPE_INSTRUMENTATION); } app.setActiveInstrumentation(activeInstr); activeInstr.mFinished = false; activeInstr.mSourceUid = callingUid; activeInstr.mRunningProcesses.add(app); if (!mActiveInstrumentation.contains(activeInstr)) { mActiveInstrumentation.add(activeInstr); } } if ((flags & INSTR_FLAG_DISABLE_ISOLATED_STORAGE) != 0) { // Allow OP_NO_ISOLATED_STORAGE app op for the package running instrumentation with // --no-isolated-storage flag. mAppOpsService.setMode(AppOpsManager.OP_NO_ISOLATED_STORAGE, ai.uid, ii.packageName, AppOpsManager.MODE_ALLOWED); } Binder.restoreCallingIdentity(origId); if (noRestart) { instrumentWithoutRestart(activeInstr, ai); } } return true; }","public boolean startInstrumentation(ComponentName className, String profileFile, int flags, Bundle arguments, IInstrumentationWatcher watcher, IUiAutomationConnection uiAutomationConnection, int userId, String abiOverride) { enforceNotIsolatedCaller(""startInstrumentation""); final int callingUid = Binder.getCallingUid(); final int callingPid = Binder.getCallingPid(); userId = mUserController.handleIncomingUser(callingPid, callingUid, userId, false, ALLOW_FULL_ONLY, ""startInstrumentation"", null); // Refuse possible leaked file descriptors if (arguments != null && arguments.hasFileDescriptors()) { throw new IllegalArgumentException(""File descriptors passed in Bundle""); } synchronized(this) { InstrumentationInfo ii = null; ApplicationInfo ai = null; boolean noRestart = (flags & INSTR_FLAG_NO_RESTART) != 0; try { ii = mContext.getPackageManager().getInstrumentationInfo( className, STOCK_PM_FLAGS); ai = AppGlobals.getPackageManager().getApplicationInfo( ii.targetPackage, STOCK_PM_FLAGS, userId); } catch (PackageManager.NameNotFoundException e) { } catch (RemoteException e) { } if (ii == null) { reportStartInstrumentationFailureLocked(watcher, className, ""Unable to find instrumentation info for: "" + className); return false; } if (ai == null) { reportStartInstrumentationFailureLocked(watcher, className, ""Unable to find instrumentation target package: "" + ii.targetPackage); return false; } if (ii.targetPackage.equals(""android"")) { if (!noRestart) { reportStartInstrumentationFailureLocked(watcher, className, ""Cannot instrument system server without 'no-restart'""); return false; } } else if (!ai.hasCode()) { reportStartInstrumentationFailureLocked(watcher, className, ""Instrumentation target has no code: "" + ii.targetPackage); return false; } int match = mContext.getPackageManager().checkSignatures( ii.targetPackage, ii.packageName); if (match < 0 && match != PackageManager.SIGNATURE_FIRST_NOT_SIGNED) { if (Build.IS_DEBUGGABLE && (callingUid == Process.ROOT_UID) && (flags & INSTR_FLAG_ALWAYS_CHECK_SIGNATURE) == 0) { Slog.w(TAG, ""Instrumentation test "" + ii.packageName + "" doesn't have a signature matching the target "" + ii.targetPackage + "", which would not be allowed on the production Android builds""); } else { String msg = ""Permission Denial: starting instrumentation "" + className + "" from pid="" + Binder.getCallingPid() + "", uid="" + Binder.getCallingUid() + "" not allowed because package "" + ii.packageName + "" does not have a signature matching the target "" + ii.targetPackage; reportStartInstrumentationFailureLocked(watcher, className, msg); throw new SecurityException(msg); } } if (!Build.IS_DEBUGGABLE && callingUid != ROOT_UID && callingUid != SHELL_UID && callingUid != SYSTEM_UID && !hasActiveInstrumentationLocked(callingPid)) { // If it's not debug build and not called from root/shell/system uid, reject it. final String msg = ""Permission Denial: instrumentation test "" + className + "" from pid="" + callingPid + "", uid="" + callingUid + "", pkgName="" + getPackageNameByPid(callingPid) + "" not allowed because it's not started from SHELL""; Slog.wtfQuiet(TAG, msg); reportStartInstrumentationFailureLocked(watcher, className, msg); throw new SecurityException(msg); } boolean disableHiddenApiChecks = ai.usesNonSdkApi() || (flags & INSTR_FLAG_DISABLE_HIDDEN_API_CHECKS) != 0; boolean disableTestApiChecks = disableHiddenApiChecks || (flags & INSTR_FLAG_DISABLE_TEST_API_CHECKS) != 0; if (disableHiddenApiChecks || disableTestApiChecks) { enforceCallingPermission(android.Manifest.permission.DISABLE_HIDDEN_API_CHECKS, ""disable hidden API checks""); } if ((flags & ActivityManager.INSTR_FLAG_INSTRUMENT_SDK_SANDBOX) != 0) { return startInstrumentationOfSdkSandbox( className, profileFile, arguments, watcher, uiAutomationConnection, userId, abiOverride, ii, ai, noRestart, disableHiddenApiChecks, disableTestApiChecks); } ActiveInstrumentation activeInstr = new ActiveInstrumentation(this); activeInstr.mClass = className; String defProcess = ai.processName;; if (ii.targetProcesses == null) { activeInstr.mTargetProcesses = new String[]{ai.processName}; } else if (ii.targetProcesses.equals(""*"")) { activeInstr.mTargetProcesses = new String[0]; } else { activeInstr.mTargetProcesses = ii.targetProcesses.split("",""); defProcess = activeInstr.mTargetProcesses[0]; } activeInstr.mTargetInfo = ai; activeInstr.mProfileFile = profileFile; activeInstr.mArguments = arguments; activeInstr.mWatcher = watcher; activeInstr.mUiAutomationConnection = uiAutomationConnection; activeInstr.mResultClass = className; activeInstr.mHasBackgroundActivityStartsPermission = checkPermission( START_ACTIVITIES_FROM_BACKGROUND, callingPid, callingUid) == PackageManager.PERMISSION_GRANTED; activeInstr.mHasBackgroundForegroundServiceStartsPermission = checkPermission( START_FOREGROUND_SERVICES_FROM_BACKGROUND, callingPid, callingUid) == PackageManager.PERMISSION_GRANTED; activeInstr.mNoRestart = noRestart; final long origId = Binder.clearCallingIdentity(); ProcessRecord app; synchronized (mProcLock) { if (noRestart) { app = getProcessRecordLocked(ai.processName, ai.uid); } else { // Instrumentation can kill and relaunch even persistent processes forceStopPackageLocked(ii.targetPackage, -1, true, false, true, true, false, userId, ""start instr""); // Inform usage stats to make the target package active if (mUsageStatsService != null) { mUsageStatsService.reportEvent(ii.targetPackage, userId, UsageEvents.Event.SYSTEM_INTERACTION); } app = addAppLocked(ai, defProcess, false, disableHiddenApiChecks, disableTestApiChecks, abiOverride, ZYGOTE_POLICY_FLAG_EMPTY); app.mProfile.addHostingComponentType(HOSTING_COMPONENT_TYPE_INSTRUMENTATION); } app.setActiveInstrumentation(activeInstr); activeInstr.mFinished = false; activeInstr.mSourceUid = callingUid; activeInstr.mRunningProcesses.add(app); if (!mActiveInstrumentation.contains(activeInstr)) { mActiveInstrumentation.add(activeInstr); } } if ((flags & INSTR_FLAG_DISABLE_ISOLATED_STORAGE) != 0) { // Allow OP_NO_ISOLATED_STORAGE app op for the package running instrumentation with // --no-isolated-storage flag. mAppOpsService.setMode(AppOpsManager.OP_NO_ISOLATED_STORAGE, ai.uid, ii.packageName, AppOpsManager.MODE_ALLOWED); } Binder.restoreCallingIdentity(origId); if (noRestart) { instrumentWithoutRestart(activeInstr, ai); } } return true; }","DO NOT MERGE: Context#startInstrumentation could be started from SHELL only now. Or, if an instrumentation starts another instrumentation and so on, and the original instrumentation is started from SHELL, allow all Context#startInstrumentation calls in this chain. Otherwise, it'll throw a SecurityException. Bug: 237766679 Test: atest CtsAppTestCases:InstrumentationTest Merged-In: Ia08f225c21a3933067d066a578ea4af9c23e7d4c Merged-In: I1b76f61c5fd6c9f7e738978592260945a606f40c Merged-In: I3ea7aa27bd776fec546908a37f667f680da9c892 Change-Id: I7ca7345b064e8e74f7037b8fa3ed45bb6423e406",https://github.com/aosp-mirror/platform_frameworks_base/commit/0bf31e3efc914b32817bfae8a602d8d5816bf70a,,,services/core/java/com/android/server/am/ActivityManagerService.java,3,java,False,2022-08-04T18:36:26Z "private List getAppIds(String logPath) { List logs = convertFile2List(logPath); List appIds = new ArrayList<>(); /* * analysis log?get submited yarn application id */ for (String log : logs) { String appId = findAppId(log); if (StringUtils.isNotEmpty(appId) && !appIds.contains(appId)) { logger.info(""find app id: {}"", appId); appIds.add(appId); } } return appIds; }","private List getAppIds(String logPath) { List appIds = new ArrayList<>(); File file = new File(logPath); if (!file.exists()) { return appIds; } /* * analysis log?get submited yarn application id */ try (BufferedReader br = new BufferedReader(new InputStreamReader(new FileInputStream(logPath), StandardCharsets.UTF_8))) { String line; while ((line = br.readLine()) != null) { String appId = findAppId(line); if (StringUtils.isNotEmpty(appId) && !appIds.contains(appId)) { logger.info(""find app id: {}"", appId); appIds.add(appId); } } } catch (Exception e) { logger.error(String.format(""read file: %s failed : "", logPath), e); } return appIds; }",fix work oom when task logs's size is very large (#11224),https://github.com/apache/dolphinscheduler/commit/9a53c6ac3430c9edb1ded218d5a0190214fadc80,,,dolphinscheduler-task-plugin/dolphinscheduler-task-api/src/main/java/org/apache/dolphinscheduler/plugin/task/api/AbstractCommandExecutor.java,3,java,False,2022-08-01T07:28:06Z "private boolean containsBacktrackableBranch(@Nullable RegexTree tree) { if (tree == null) { return false; } switch (tree.kind()) { case DISJUNCTION: return true; case REPETITION: RepetitionTree repetition = (RepetitionTree) tree; if (isPossessive(repetition)) { return false; } if (repetition.getQuantifier().isFixed()) { return containsBacktrackableBranch(repetition.getElement()); } return true; case CAPTURING_GROUP: case NON_CAPTURING_GROUP: return containsBacktrackableBranch(((GroupTree) tree).getElement()); case SEQUENCE: for (RegexTree child : ((SequenceTree) tree).getItems()) { if (containsBacktrackableBranch(child)) { return true; } } return false; default: return false; } }","private boolean containsBacktrackableBranch(@Nullable RegexTree tree) { if (tree == null) { return false; } switch (tree.kind()) { case DISJUNCTION: return true; case REPETITION: RepetitionTree repetition = (RepetitionTree) tree; return !repetition.getQuantifier().isFixed() || containsBacktrackableBranch(repetition.getElement()); case CAPTURING_GROUP: case NON_CAPTURING_GROUP: return containsBacktrackableBranch(((GroupTree) tree).getElement()); case SEQUENCE: for (RegexTree child : ((SequenceTree) tree).getItems()) { if (containsBacktrackableBranch(child)) { return true; } } return false; default: return false; } }",SONARJAVA-3841 FN in S5998 (regex stackoverflow) for possessive quantifiers,https://github.com/SonarSource/sonar-java/commit/d0e483ace26059c57d026b11f64dd7b3b32aa92c,,,java-checks/src/main/java/org/sonar/java/checks/regex/RegexStackOverflowCheck.java,3,java,False,2021-05-20T13:48:48Z "public boolean allowTenantOperation(String tenantName, TenantOperation operation, String originalRole, String role, AuthenticationDataSource authData) { try { return allowTenantOperationAsync( tenantName, operation, originalRole, role, authData).get(); } catch (InterruptedException e) { throw new RestException(e); } catch (ExecutionException e) { throw new RestException(e.getCause()); } }","public boolean allowTenantOperation(String tenantName, TenantOperation operation, String originalRole, String role, AuthenticationDataSource authData) { try { return allowTenantOperationAsync( tenantName, operation, originalRole, role, authData).get( conf.getZooKeeperOperationTimeoutSeconds(), SECONDS); } catch (InterruptedException e) { Thread.currentThread().interrupt(); throw new RestException(e); } catch (ExecutionException e) { throw new RestException(e.getCause()); } catch (TimeoutException e) { throw new RestException(e); } }",[branch-2.9][fix][security] Add timeout of sync methods and avoid call sync method for AuthoriationService (#16083),https://github.com/apache/pulsar/commit/1fa9c2e17977cb451c0379581c35c70920a393f3,,,pulsar-broker-common/src/main/java/org/apache/pulsar/broker/authorization/AuthorizationService.java,3,java,False,2022-06-17T05:27:36Z "public String getPath() { if (WINDOWS && !""hdfs"".equals(getFsType())) { return uri.getAuthority() + uri.getPath(); } return uri.getPath(); }","public String getPath() { if (WINDOWS && !""hdfs"".equals(getFsType())) { return StringUtils.isNotBlank(uri.getAuthority()) ? uri.getAuthority() + uri.getPath() : uri.getPath(); } return uri.getPath(); }","[ISSUE-3306] Fix FsPath null String (#3307) * Fix the possible NPE problems in get auth path",https://github.com/apache/linkis/commit/14974151270ef9f9dd9338fcb23e3b2c4fde0579,,,linkis-commons/linkis-common/src/main/java/org/apache/linkis/common/io/FsPath.java,3,java,False,2022-09-13T16:24:53Z "private int readIdentifier(String sql, int end, int tokenStart, int i, int cp, ArrayList tokens) { if (cp >= Character.MIN_SUPPLEMENTARY_CODE_POINT) { i++; } int endIndex = findIdentifierEnd(sql, end, i + Character.charCount(cp) - 1); tokens.add(new Token.IdentifierToken(tokenStart, extractIdentifier(sql, tokenStart, endIndex), false, false)); return endIndex; }","private int readIdentifier(String sql, int end, int tokenStart, int i, int cp, ArrayList tokens) { int endIndex = findIdentifierEnd(sql, end, i); tokens.add(new Token.IdentifierToken(tokenStart, extractIdentifier(sql, tokenStart, endIndex), false, false)); return endIndex; }",Fix infinite loop in Tokenizer when special whitespace character is used,https://github.com/h2database/h2database/commit/5032cbf23d6c4343bdb58b0fc10ac6387bd9223c,,,h2/src/main/org/h2/command/Tokenizer.java,3,java,False,2022-09-01T04:11:32Z "@Override public boolean execute(CommandSender sender, String[] args) { Player player = (Player) sender; User user = IridiumSkyblock.getInstance().getUserManager().getUser(player); Optional island = user.getIsland(); if (!island.isPresent()) { player.sendMessage(StringUtils.color(IridiumSkyblock.getInstance().getMessages().noIsland.replace(""%prefix%"", IridiumSkyblock.getInstance().getConfiguration().prefix))); return false; } island.get().setVisitable(false); int visitorCount = 0; for (User visitor : IridiumSkyblock.getInstance().getIslandManager().getPlayersOnIsland(island.get())) { if (visitor.getIsland().map(Island::getId).orElse(0) == island.get().getId() || IridiumSkyblock.getInstance().getIslandManager().getIslandTrusted(island.get(), visitor).isPresent()) { continue; } PlayerUtils.teleportSpawn(visitor.toPlayer()); visitor.toPlayer().sendMessage(StringUtils.color(IridiumSkyblock.getInstance().getMessages().expelledIslandLocked.replace(""%player%"", user.getName()).replace(""%prefix%"", IridiumSkyblock.getInstance().getConfiguration().prefix))); visitorCount++; } player.sendMessage(StringUtils.color(IridiumSkyblock.getInstance().getMessages().islandNowPrivate .replace(""%prefix%"", IridiumSkyblock.getInstance().getConfiguration().prefix) .replace(""%amount%"", String.valueOf(visitorCount))) ); return true; }","@Override public boolean execute(CommandSender sender, String[] args) { Player player = (Player) sender; User user = IridiumSkyblock.getInstance().getUserManager().getUser(player); Optional island = user.getIsland(); if (!island.isPresent()) { player.sendMessage(StringUtils.color(IridiumSkyblock.getInstance().getMessages().noIsland.replace(""%prefix%"", IridiumSkyblock.getInstance().getConfiguration().prefix))); return false; } island.get().setVisitable(false); int visitorCount = 0; for (User visitor : IridiumSkyblock.getInstance().getIslandManager().getPlayersOnIsland(island.get())) { if (visitor.isBypassing() || visitor.getIsland().map(Island::getId).orElse(0) == island.get().getId() || IridiumSkyblock.getInstance().getIslandManager().getIslandTrusted(island.get(), visitor).isPresent()) { continue; } PlayerUtils.teleportSpawn(visitor.toPlayer()); visitor.toPlayer().sendMessage(StringUtils.color(IridiumSkyblock.getInstance().getMessages().expelledIslandLocked.replace(""%player%"", user.getName()).replace(""%prefix%"", IridiumSkyblock.getInstance().getConfiguration().prefix))); visitorCount++; } player.sendMessage(StringUtils.color(IridiumSkyblock.getInstance().getMessages().islandNowPrivate .replace(""%prefix%"", IridiumSkyblock.getInstance().getConfiguration().prefix) .replace(""%amount%"", String.valueOf(visitorCount))) ); return true; }","Prevent bypassing players being kicked by private command (#414) * Prevent bypassing players being kicked by private command * Rename bypass field to bypassing",https://github.com/Iridium-Development/IridiumSkyblock/commit/43f9f0c2f99a59c6eaa5e790e72cf6df016ad23e,,,src/main/java/com/iridium/iridiumskyblock/commands/PrivateCommand.java,3,java,False,2021-10-02T10:24:36Z "public synchronized void addAuthentication(ClientAuthenticator authenticator) throws IOException, SshException { checkReady(); if(Log.isDebugEnabled()) { Log.debug(""Adding {} authentication"", authenticator.getName()); } boolean start = authenticators.isEmpty(); if(authenticator instanceof PasswordAuthenticator) { if(supportedAuths.contains(""keyboard-interactive"") && context.getPreferKeyboardInteractiveOverPassword()) { if(Log.isDebugEnabled()) { Log.debug(""We prefer keyboard-interactive over password so injecting keyboard-interactive authenticator""); } authenticators.addLast(new KeyboardInteractiveAuthenticator( new PasswordOverKeyboardInteractiveCallback( (PasswordAuthenticator) authenticator))); if(supportedAuths.contains(""password"")) { authenticators.addLast(authenticator); } } } else { authenticators.addLast(authenticator); } if(start) { doNextAuthentication(); } }","public void addAuthentication(ClientAuthenticator authenticator) throws IOException, SshException { checkReady(); synchronized(this) { if(Log.isDebugEnabled()) { Log.debug(""Adding {} authentication"", authenticator.getName()); } boolean start = authenticators.isEmpty(); if(authenticator instanceof PasswordAuthenticator) { if(supportedAuths.contains(""keyboard-interactive"") && context.getPreferKeyboardInteractiveOverPassword()) { if(Log.isDebugEnabled()) { Log.debug(""We prefer keyboard-interactive over password so injecting keyboard-interactive authenticator""); } authenticators.addLast(new KeyboardInteractiveAuthenticator( new PasswordOverKeyboardInteractiveCallback( (PasswordAuthenticator) authenticator))); if(supportedAuths.contains(""password"")) { authenticators.addLast(authenticator); } } } else { authenticators.addLast(authenticator); } if(start) { doNextAuthentication(); } } }",Fix authentication in callbacks,https://github.com/sshtools/maverick-synergy/commit/12e4896fef42a72c32fd20be860dee4666d1fd57,,,maverick-synergy-client/src/main/java/com/sshtools/client/AuthenticationProtocolClient.java,3,java,False,2021-03-07T17:16:32Z "public ResultSet executeQuery() throws SQLException { checkOpen(); if (columnCount == 0) { throw new SQLException(""Query does not return results""); } rs.close(); conn.getDatabase().reset(pointer); boolean success = false; try { resultsWaiting = conn.getDatabase().execute(this, batch); success = true; } finally { if (!success && pointer != 0) conn.getDatabase().reset(pointer); } return getResultSet(); }","public ResultSet executeQuery() throws SQLException { checkOpen(); if (columnCount == 0) { throw new SQLException(""Query does not return results""); } rs.close(); pointer.safeRunConsume(DB::reset); boolean success = false; try { resultsWaiting = conn.getDatabase().execute(this, batch); success = true; } finally { if (!success && !pointer.isClosed()) { pointer.safeRunInt(DB::reset); } } return getResultSet(); }",Wrap Statement Pointers to prevent use after free race,https://github.com/xerial/sqlite-jdbc/commit/e1d282cb2887ef427c7ad93d4fe7dd05a6c11473,,,src/main/java/org/sqlite/jdbc3/JDBC3PreparedStatement.java,3,java,False,2022-07-29T03:54:01Z "@Inject(method = ""clickSlot"", at = @At(value = ""INVOKE"", target = ""Lnet/minecraft/screen/ScreenHandler;onSlotClick(IILnet/minecraft/screen/slot/SlotActionType;Lnet/minecraft/entity/player/PlayerEntity;)V"")) private void onClickSlot(int syncId, int slotId, int button, SlotActionType actionType, PlayerEntity player, CallbackInfo ci) { if (MultiConnectAPI.instance().getProtocolVersion() <= 754 && actionType == SlotActionType.THROW) { this.cachedList.set(slotId, ItemStack.EMPTY); } }","@Inject(method = ""clickSlot"", at = @At(value = ""INVOKE"", target = ""Lnet/minecraft/screen/ScreenHandler;onSlotClick(IILnet/minecraft/screen/slot/SlotActionType;Lnet/minecraft/entity/player/PlayerEntity;)V"")) private void onClickSlot(int syncId, int slotId, int button, SlotActionType actionType, PlayerEntity player, CallbackInfo ci) { if (MultiConnectAPI.instance().getProtocolVersion() <= 754 && actionType == SlotActionType.THROW && slotId >= 0) { this.cachedList.set(slotId, ItemStack.EMPTY); } }",Fix keybind overflow,https://github.com/senseiwells/EssentialClient/commit/0a000dae7ccf95ccd5a608f42e676d3d564e0341,,,src/main/java/me/senseiwells/essentialclient/mixins/compat/ClientPlayerInteractionManagerMixin.java,3,java,False,2022-06-24T21:38:56Z "@Override public void onCreateOptionsMenu(@NonNull final Menu menu, @NonNull final MenuInflater inflater) { super.onCreateOptionsMenu(menu, inflater); final ActionBar supportActionBar = activity.getSupportActionBar(); if (supportActionBar != null) { supportActionBar.setDisplayShowTitleEnabled(false); supportActionBar.setDisplayHomeAsUpEnabled(true); } menuItemToFilterName = new HashMap<>(); int itemId = 0; boolean isFirstItem = true; final Context c = getContext(); for (final String filter : service.getSearchQHFactory().getAvailableContentFilter()) { if (filter.equals(YoutubeSearchQueryHandlerFactory.MUSIC_SONGS)) { final MenuItem musicItem = menu.add(2, itemId++, 0, ""YouTube Music""); musicItem.setEnabled(false); } else if (filter.equals(PeertubeSearchQueryHandlerFactory.SEPIA_VIDEOS)) { final MenuItem sepiaItem = menu.add(2, itemId++, 0, ""Sepia Search""); sepiaItem.setEnabled(false); } menuItemToFilterName.put(itemId, filter); final MenuItem item = menu.add(1, itemId++, 0, ServiceHelper.getTranslatedFilterString(filter, c)); if (isFirstItem) { item.setChecked(true); isFirstItem = false; } } menu.setGroupCheckable(1, true, true); restoreFilterChecked(menu, filterItemCheckedId); }","@Override public void onCreateOptionsMenu(@NonNull final Menu menu, @NonNull final MenuInflater inflater) { super.onCreateOptionsMenu(menu, inflater); final ActionBar supportActionBar = activity.getSupportActionBar(); if (supportActionBar != null) { supportActionBar.setDisplayShowTitleEnabled(false); supportActionBar.setDisplayHomeAsUpEnabled(true); } menuItemToFilterName = new HashMap<>(); int itemId = 0; boolean isFirstItem = true; final Context c = getContext(); if (service == null) { Log.w(TAG, ""onCreateOptionsMenu() called with null service""); updateService(); } for (final String filter : service.getSearchQHFactory().getAvailableContentFilter()) { if (filter.equals(YoutubeSearchQueryHandlerFactory.MUSIC_SONGS)) { final MenuItem musicItem = menu.add(2, itemId++, 0, ""YouTube Music""); musicItem.setEnabled(false); } else if (filter.equals(PeertubeSearchQueryHandlerFactory.SEPIA_VIDEOS)) { final MenuItem sepiaItem = menu.add(2, itemId++, 0, ""Sepia Search""); sepiaItem.setEnabled(false); } menuItemToFilterName.put(itemId, filter); final MenuItem item = menu.add(1, itemId++, 0, ServiceHelper.getTranslatedFilterString(filter, c)); if (isFirstItem) { item.setChecked(true); isFirstItem = false; } } menu.setGroupCheckable(1, true, true); restoreFilterChecked(menu, filterItemCheckedId); }","#6522: Fix null pointer exception when displaying SearchFragment It seems due to #6394 updating the FragmentX library there was a change to the order of lifecycle calls, as such onResume() was no longer before onCreateOptionsMenu() creating a null pointer exception when using service in onCreateOptionsMenu() as it is only set in onResume(). By moving the initialization of service to onStart() which still happens before onCreateOptionsMenu() this crash can be avoided. This commit also adds a check for a null service to prevent future crashes for similar issues.",https://github.com/polymorphicshade/Tubular/commit/384ca6620542caee1ec787f93fa13c8d70aeacb7,,,app/src/main/java/org/schabi/newpipe/fragments/list/search/SearchFragment.java,3,java,False,2021-06-22T15:52:02Z "public Key parseKeyWithLegacyFallback( ProtoKeySerialization protoKeySerialization, SecretKeyAccess access) { if (access == null) { throw new NullPointerException(""access cannot be null""); } try { return parseKey(protoKeySerialization, access); } catch (GeneralSecurityException e) { try { return new LegacyProtoKey(protoKeySerialization, access); } catch (GeneralSecurityException e2) { // Cannot happen -- this only throws if we have no access. throw new TinkBugException(""Creating a LegacyProtoKey failed"", e2); } } }","public Key parseKeyWithLegacyFallback( ProtoKeySerialization protoKeySerialization, SecretKeyAccess access) throws GeneralSecurityException { if (access == null) { throw new NullPointerException(""access cannot be null""); } if (!hasParserForKey(protoKeySerialization)) { try { return new LegacyProtoKey(protoKeySerialization, access); } catch (GeneralSecurityException e2) { // Cannot happen -- this only throws if we have no access. throw new TinkBugException(""Creating a LegacyProtoKey failed"", e2); } } return parseKey(protoKeySerialization, access); }","Let parseKeyWithLegacyFallback only fall back to LegacyProtoKey when no parser exists. When a parser exists and parsing fails, the function should raise a GeneralSecurityException. KeysetHandle currently contains unparsed keys that can be invalid and parses them when the user tries to access them using getAt(). Before this change, that function would return a LegacyProtoKey that contains the unparsed, invalid key. This behaviour is unexpected and should be changed. The only reasonable behavior is to raise an exception. But raising a checked exception is not possible, because it would break the API. So we have to convert the exception into an unchecked exception. Note that eventually we want this error to be raised earlier when the keyset handle is constructed, in which case we can raise this as a checked exception. This change may break users that currently have unparsable keys in their keyset and use getAt. But such keysets are unusable anyways, producing a primitive will always throw an exception. And Tink doesn't allow the user to generate such keysets. So I don't think there is a big risk in breaking anybody. PiperOrigin-RevId: 484271577",https://github.com/tink-crypto/tink/commit/cd76db8b7d2ae02ba59205f8367258aec7114c5a,,,java_src/src/main/java/com/google/crypto/tink/internal/MutableSerializationRegistry.java,3,java,False,2022-10-27T16:19:28Z "private Notification buildNotification(String msg) { Notification.Builder notification; if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) { final String CHANNELID = ""Foreground Service AIS-catcher""; NotificationChannel channel = new NotificationChannel(CHANNELID, CHANNELID, NotificationManager.IMPORTANCE_HIGH); getSystemService(NotificationManager.class).createNotificationChannel(channel); notification = new Notification.Builder(this, CHANNELID); } else { notification = new Notification.Builder(this); } Intent notificationIntent = new Intent(this.getApplicationContext(), MainActivity.class); PendingIntent contentIntent = PendingIntent.getActivity(this.getApplicationContext(), 0, notificationIntent, 0); notification.setContentIntent(contentIntent) .setContentText(msg) .setContentTitle(""AIS-catcher"") .setSmallIcon(R.drawable.ic_notif_launcher); return notification.build(); }","private Notification buildNotification(String msg) { Notification.Builder notification; if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) { final String CHANNELID = ""Foreground Service AIS-catcher""; NotificationChannel channel = new NotificationChannel(CHANNELID, CHANNELID, NotificationManager.IMPORTANCE_HIGH); getSystemService(NotificationManager.class).createNotificationChannel(channel); notification = new Notification.Builder(this, CHANNELID); } else { notification = new Notification.Builder(this); } Intent notificationIntent = new Intent(this.getApplicationContext(), MainActivity.class); PendingIntent contentIntent = PendingIntent.getActivity(this.getApplicationContext(), 0, notificationIntent, PendingIntent.FLAG_IMMUTABLE); notification.setContentIntent(contentIntent) .setContentText(msg) .setContentTitle(""AIS-catcher"") .setSmallIcon(R.drawable.ic_notif_launcher); return notification.build(); }",Fixing reported crash on Play Console (likely missing IMMUTABLE flag in creating PendingIntent for notification),https://github.com/jvde-github/AIS-catcher-for-Android/commit/5d97b2e9eb853da2e78ab7a42996423ffb495dd5,,,app/src/main/java/com/jvdegithub/aiscatcher/AisService.java,3,java,False,2022-09-03T07:05:53Z "@SuppressWarnings(""unchecked"") @Override public void authorized(Subject var) throws SurenessAuthorizationException { List ownRoles = (List)var.getOwnRoles(); List supportRoles = (List)var.getSupportRoles(); if (supportRoles != null && !supportRoles.isEmpty() && ownRoles != null && supportRoles.stream().anyMatch(ownRoles::contains)) { return; } throw new UnauthorizedException(""custom authorized: do not have the role to access resource""); }","@SuppressWarnings(""unchecked"") @Override public void authorized(Subject var) throws SurenessAuthorizationException { List ownRoles = (List) var.getOwnRoles(); List supportRoles = (List) var.getSupportRoles(); if (supportRoles == null || supportRoles.isEmpty() || (ownRoles != null && supportRoles.stream().anyMatch(ownRoles::contains))) { return; } throw new UnauthorizedException(""custom authorized: do not have the role to access resource""); }",fix api can be accessed by any role when accessRole not config (#83),https://github.com/dromara/sureness/commit/d22105da5ad8c027a136f302a4198d0d5bfd5aa5,,,sample-tom/src/main/java/com/usthe/sureness/sample/tom/sureness/processor/CustomTokenProcessor.java,3,java,False,2021-04-02T12:11:33Z "@Override protected final ByteBuf allocateBuffer(ChannelHandlerContext ctx, ByteBuf msg, boolean preferDirect) throws Exception { int sizeEstimate = (int) Math.ceil(msg.readableBytes() * 1.001) + 12; if (writeHeader) { switch (wrapper) { case GZIP: sizeEstimate += gzipHeader.length; break; case ZLIB: sizeEstimate += 2; // first two magic bytes break; default: // no op } } return ctx.alloc().heapBuffer(sizeEstimate); }","@Override protected final ByteBuf allocateBuffer(ChannelHandlerContext ctx, ByteBuf msg, boolean preferDirect) throws Exception { int sizeEstimate = (int) Math.ceil(msg.readableBytes() * 1.001) + 12; if (writeHeader) { switch (wrapper) { case GZIP: sizeEstimate += gzipHeader.length; break; case ZLIB: sizeEstimate += 2; // first two magic bytes break; default: // no op } } // sizeEstimate might overflow if close to 2G if (sizeEstimate < 0 || sizeEstimate > MAX_INITIAL_OUTPUT_BUFFER_SIZE) { // can always expand later return ctx.alloc().heapBuffer(MAX_INITIAL_OUTPUT_BUFFER_SIZE); } return ctx.alloc().heapBuffer(sizeEstimate); }","Avoid allocating large buffers in JdkZlibEncoder (#12641) Motivation: Before this patch, JdkZlibEncoder allocates two buffers of roughly the same size as the input buffer: one for copying data to heap, one for output. The former is always unnecessary, since inflate calls can take smaller buffers, and the latter is sometimes unnecessary, if the input data compresses well. This behavior can lead to large heap buffer allocation that bypass pooling and lead to unnecessary heap pressure. Modification: This patch introduces a limit to both allocations. The limit is arbitrarily set to 64K (should it be configurable?) to stay within standard pool thresholds. The copy-to-heap code is modified so that if the input is larger than this limit, it is gradually passed to the deflater with multiple setInput/deflate calls. The output buffer code was already capable of expanding a too small buffer. If the output is larger than the limit, we could instead write it incrementally as small chunks downstream, however I don't know if this is worthwhile, since we don't really have any way of handling backpressure. Additionally, this patch fixes three bugs I found during development: - It is possible for the deflater to return `needsInput` even when there is still data to write, because the output buffer is full. I changed the code to check whether output is full first. This could potentially lead to a pointless resize if we estimated the output size exactly right, but this seems unlikely. - the size estimate in `allocateBuffer` could overflow if the input buffer is almost 2G. The capacity limit fixes this issue. - The deflater kept a reference to the input array even after the encode call had completed. I set the input to `new byte[0]` to avoid this. Result: JdkZlibEncoder does not allocate unnecessarily large temporary arrays. However, it may have to resize the output array more often if data can't be compressed well.",https://github.com/netty/netty/commit/ef9a583ee91cece0516b27289795eadb559ae39b,,,codec/src/main/java/io/netty/handler/codec/compression/JdkZlibEncoder.java,3,java,False,2022-07-27T19:01:51Z "public static boolean compareXmls(InputStream xml1, InputStream xml2) throws ParserConfigurationException, SAXException, IOException { DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance(); dbf.setNamespaceAware(true); dbf.setCoalescing(true); dbf.setIgnoringElementContentWhitespace(true); dbf.setIgnoringComments(true); DocumentBuilder db = dbf.newDocumentBuilder(); db.setEntityResolver(new SafeEmptyEntityResolver()); Document doc1 = db.parse(xml1); doc1.normalizeDocument(); Document doc2 = db.parse(xml2); doc2.normalizeDocument(); return doc2.isEqualNode(doc1); }","public static boolean compareXmls(InputStream xml1, InputStream xml2) throws ParserConfigurationException, SAXException, IOException { DocumentBuilder db = XmlProcessorCreator.createSafeDocumentBuilder(true, true); Document doc1 = db.parse(xml1); doc1.normalizeDocument(); Document doc2 = db.parse(xml2); doc2.normalizeDocument(); return doc2.isEqualNode(doc1); }","Remove DTDs with non-existent reference from patterns in hyph module DEVSIX-3270",https://github.com/itext/itext-java/commit/0310e5e63df1cfa3584714fb57138a3484d8251d,,,kernel/src/main/java/com/itextpdf/kernel/utils/XmlUtils.java,3,java,False,2021-03-11T18:25:46Z "@GetMapping(value = ""/getSystemInfo"", produces = ""application/json"") public ResponseEntity getSystemInfo(HttpServletRequest request) { try { User user = Common.getUser(request); if (user != null && user.isAdmin()) { return new ResponseEntity<>(systemSettingsService.getSystemInfoSettings(), HttpStatus.OK); } else { return new ResponseEntity<>(HttpStatus.UNAUTHORIZED); } } catch (Exception e) { LOG.error(e); return new ResponseEntity<>(HttpStatus.INTERNAL_SERVER_ERROR); } }","@GetMapping(value = ""/getSystemInfo"", produces = ""application/json"") public ResponseEntity getSystemInfo(HttpServletRequest request) { try { User user = Common.getUser(request); if (user != null) { return new ResponseEntity<>(systemSettingsService.getSystemInfoSettings(), HttpStatus.OK); } else { return new ResponseEntity<>(HttpStatus.UNAUTHORIZED); } } catch (Exception e) { LOG.error(e); return new ResponseEntity<>(HttpStatus.INTERNAL_SERVER_ERROR); } }","#2047 Fix access to bussines object for non admin. Allow user to create a watchList based on the DataPoint permission settings. Fix the user not authorized exceptions.",https://github.com/SCADA-LTS/Scada-LTS/commit/4e8f667359b8e520d72085f4c35a6ff41fd42187,,,src/org/scada_lts/web/mvc/api/SystemSettingsAPI.java,3,java,False,2022-01-21T10:40:44Z "@Bean public SecurityWebFilterChain configure(ServerHttpSecurity http) { log.info(""Configuring LOGIN_FORM authentication.""); http.authorizeExchange() .pathMatchers(AUTH_WHITELIST) .permitAll() .anyExchange() .authenticated(); final RedirectServerAuthenticationSuccessHandler handler = new RedirectServerAuthenticationSuccessHandler(); handler.setRedirectStrategy(new EmptyRedirectStrategy()); http .httpBasic().and() .formLogin() .loginPage(""/auth"") .authenticationSuccessHandler(handler); return http.csrf().disable().build(); }","@Bean public SecurityWebFilterChain configure(ServerHttpSecurity http) { log.info(""Configuring LOGIN_FORM authentication.""); final var authHandler = new RedirectServerAuthenticationSuccessHandler(); authHandler.setRedirectStrategy(new EmptyRedirectStrategy()); final var logoutSuccessHandler = new RedirectServerLogoutSuccessHandler(); logoutSuccessHandler.setLogoutSuccessUrl(URI.create(LOGOUT_URL)); return http .addFilterAfter(new LogoutPageGeneratingWebFilter(), SecurityWebFiltersOrder.REACTOR_CONTEXT) .csrf().disable() .authorizeExchange() .pathMatchers(AUTH_WHITELIST).permitAll() .anyExchange().authenticated() .and().formLogin().loginPage(LOGIN_URL).authenticationSuccessHandler(authHandler) .and().logout().logoutSuccessHandler(logoutSuccessHandler) .and().build(); }",Fix basic auth logout page (#2106),https://github.com/provectus/kafka-ui/commit/c1bdbec2b2d9158c9c210f77748d330812e28e2a,,,kafka-ui-api/src/main/java/com/provectus/kafka/ui/config/auth/BasicAuthSecurityConfig.java,3,java,False,2022-06-03T12:36:06Z "public boolean validateEthSignature(AccountStore accountStore, DynamicPropertiesStore dynamicPropertiesStore, TriggerSmartContract contract) throws ValidateSignatureException { if (!isVerified) { if (dynamicPropertiesStore.getAllowEthereumCompatibleTransaction() == 0){ throw new ValidateSignatureException(""EthereumCompatibleTransaction is off, need to be opened by proposal""); } if (this.transaction.getSignatureCount() <= 0 || this.transaction.getRawData().getContractCount() <= 0) { throw new ValidateSignatureException(""miss sig or contract""); } if (this.transaction.getSignatureCount() > dynamicPropertiesStore .getTotalSignNum()) { throw new ValidateSignatureException(""too many signatures""); } if (contract.getType() != 1) { throw new ValidateSignatureException(""not eth contract""); } EthTrx t = new EthTrx(contract.getRlpData().toByteArray()); t.rlpParse(); try { TriggerSmartContract contractFromParse = t.rlpParseToTriggerSmartContract(); if(!contractFromParse.equals(contract)){ isVerified = false; throw new ValidateSignatureException(""eth sig error""); } if (!validateSignature(this.transaction, t.getRawHash(), accountStore, dynamicPropertiesStore)) { isVerified = false; throw new ValidateSignatureException(""sig error""); } } catch (SignatureException | PermissionException | SignatureFormatException e) { isVerified = false; throw new ValidateSignatureException(e.getMessage()); } isVerified = true; } return true; }","public boolean validateEthSignature(AccountStore accountStore, DynamicPropertiesStore dynamicPropertiesStore, TriggerSmartContract contract) throws ValidateSignatureException { if (!isVerified) { if (dynamicPropertiesStore.getAllowEthereumCompatibleTransaction() == 0){ throw new ValidateSignatureException(""EthereumCompatibleTransaction is off, need to be opened by proposal""); } if (this.transaction.getSignatureCount() <= 0 || this.transaction.getRawData().getContractCount() <= 0) { throw new ValidateSignatureException(""miss sig or contract""); } if (this.transaction.getSignatureCount() != 1) { throw new ValidateSignatureException(""eth contract only one signature""); } if (contract.getType() != 1) { throw new ValidateSignatureException(""not eth contract""); } EthTrx t = new EthTrx(contract.getRlpData().toByteArray()); t.rlpParse(); try { TriggerSmartContract contractFromParse = t.rlpParseToTriggerSmartContract(); if(!contractFromParse.equals(contract)){ isVerified = false; throw new ValidateSignatureException(""eth sig error, vision transaction have been changed,not equal rlp parsed transaction""); } if (!validateSignature(this.transaction, t.getRawHash(), accountStore, dynamicPropertiesStore)) { isVerified = false; throw new ValidateSignatureException(""eth sig error""); } } catch (SignatureException | PermissionException | SignatureFormatException e) { isVerified = false; throw new ValidateSignatureException(e.getMessage()); } isVerified = true; } return true; }","Bugfix/20220108/ethereum compatible replayattack (#113) * update version ultima_v1.0.3 * optimize validateEthSignature and rlpParseContract parameters * update version ultima_v1.0.4",https://github.com/vision-consensus/vision-core/commit/89c1e0742966adf99fb5fa855c6b6e37c63e861f,,,chainstorage/src/main/java/org/vision/core/capsule/TransactionCapsule.java,3,java,False,2022-01-21T13:15:55Z "private void performRequest(IUploadServer server, final String action, final boolean isAsync, final byte[] data, final Mapheader, final String method, final RequestShouldRetryHandler shouldRetryHandler, final RequestProgressHandler progressHandler, final RequestCompleteHandler completeHandler){ if (server == null || server.getHost() == null || server.getHost().length() == 0) { ResponseInfo responseInfo = ResponseInfo.sdkInteriorError(""server error""); completeAction(responseInfo, null, completeHandler); return; } currentServer = server; String serverHost = server.getHost(); String serverIP = server.getIp(); if (config.urlConverter != null){ serverIP = null; serverHost = config.urlConverter.convert(serverHost); } String scheme = config.useHttps ? ""https://"" : ""http://""; String urlString = scheme + serverHost + (action != null ? action : """"); final Request request = new Request(urlString, method, header, data, config.connectTimeout); request.host = serverHost; request.ip = serverIP; LogUtil.i(""key:"" + StringUtils.toNonnullString(requestInfo.key) + "" url:"" + StringUtils.toNonnullString(request.urlString)); LogUtil.i(""key:"" + StringUtils.toNonnullString(requestInfo.key) + "" headers:"" + StringUtils.toNonnullString(request.allHeaders)); singleRequest.request(request, server, isAsync, shouldRetryHandler, progressHandler, new HttpSingleRequest.RequestCompleteHandler() { @Override public void complete(ResponseInfo responseInfo, ArrayList requestMetricsList, JSONObject response) { requestMetrics.addMetricsList(requestMetricsList); if (shouldRetryHandler.shouldRetry(responseInfo, response) && config.allowBackupHost && responseInfo.couldRegionRetry()){ IUploadServer newServer = getNextServer(responseInfo); if (newServer != null){ performRequest(newServer, action, isAsync, request.httpBody, header, method, shouldRetryHandler, progressHandler, completeHandler); request.httpBody = null; } else { request.httpBody = null; completeAction(responseInfo, response, completeHandler); } } else { request.httpBody = null; completeAction(responseInfo, response, completeHandler); } } }); }","private void performRequest(final IUploadServer server, final String action, final boolean isAsync, final byte[] data, final Map header, final String method, final RequestShouldRetryHandler shouldRetryHandler, final RequestProgressHandler progressHandler, final RequestCompleteHandler completeHandler) { if (server == null || server.getHost() == null || server.getHost().length() == 0) { ResponseInfo responseInfo = ResponseInfo.sdkInteriorError(""server error""); completeAction(responseInfo, null, completeHandler); return; } currentServer = server; String serverHost = server.getHost(); String serverIP = server.getIp(); if (config.urlConverter != null) { serverIP = null; serverHost = config.urlConverter.convert(serverHost); } String scheme = config.useHttps ? ""https://"" : ""http://""; String urlString = scheme + serverHost + (action != null ? action : """"); final Request request = new Request(urlString, method, header, data, config.connectTimeout); request.host = serverHost; request.ip = serverIP; LogUtil.i(""key:"" + StringUtils.toNonnullString(requestInfo.key) + "" url:"" + StringUtils.toNonnullString(request.urlString)); LogUtil.i(""key:"" + StringUtils.toNonnullString(requestInfo.key) + "" headers:"" + StringUtils.toNonnullString(request.allHeaders)); singleRequest.request(request, server, isAsync, shouldRetryHandler, progressHandler, new HttpSingleRequest.RequestCompleteHandler() { @Override public void complete(ResponseInfo responseInfo, ArrayList requestMetricsList, JSONObject response) { requestMetrics.addMetricsList(requestMetricsList); boolean hijacked = false; if (requestMetricsList != null && requestMetricsList.size() > 0) { UploadSingleRequestMetrics metrics = requestMetricsList.get(requestMetricsList.size() - 1); if (metrics.isForsureHijacked() || metrics.isMaybeHijacked()) { hijacked = true; } } if (hijacked) { region.updateIpListFormHost(server.getHost()); } if ((shouldRetryHandler.shouldRetry(responseInfo, response) && config.allowBackupHost && responseInfo.couldRegionRetry()) || hijacked) { IUploadServer newServer = getNextServer(responseInfo); if (newServer != null) { performRequest(newServer, action, isAsync, request.httpBody, header, method, shouldRetryHandler, progressHandler, completeHandler); request.httpBody = null; } else { request.httpBody = null; completeAction(responseInfo, response, completeHandler); } } else { request.httpBody = null; completeAction(responseInfo, response, completeHandler); } } }); }",handle dns hijacked & dns prefetch add doh,https://github.com/qiniu/android-sdk/commit/ada3c8feb608ed37fe8d64ba2d10ac672a207525,,,library/src/main/java/com/qiniu/android/http/request/HttpRegionRequest.java,3,java,False,2021-08-27T10:02:18Z "private void fillPermissionList() { actionsList.setDataProvider(new ScrollingList.DataProvider() { @Override public int getElementCount() { return actions.size(); } @Override public void updateElement(final int index, @NotNull final Pane rowPane) { final Action action = actions.get(index); final String name = new TranslatableComponent(KEY_TO_PERMISSIONS + action.toString().toLowerCase(Locale.US)).getString(); if (name.contains(KEY_TO_PERMISSIONS)) { Log.getLogger().warn(""Didn't work for:"" + name); return; } rowPane.findPaneOfTypeByID(NAME_LABEL, Text.class).setText(name); final boolean isTriggered = building.getColony().getPermissions().hasPermission(actionsRank, action); rowPane.findPaneOfTypeByID(""trigger"", Button.class) .setText(isTriggered ? new TranslatableComponent(COM_MINECOLONIES_COREMOD_GUI_WORKERHUTS_RETRIEVE_ON) : new TranslatableComponent(COM_MINECOLONIES_COREMOD_GUI_WORKERHUTS_RETRIEVE_OFF)); rowPane.findPaneOfTypeByID(""index"", Text.class).setText(Integer.toString(index)); } }); }","private void fillPermissionList() { actionsList.setDataProvider(new ScrollingList.DataProvider() { @Override public int getElementCount() { return actions.size(); } @Override public void updateElement(final int index, @NotNull final Pane rowPane) { final Action action = actions.get(index); final String name = new TranslatableComponent(KEY_TO_PERMISSIONS + action.toString().toLowerCase(Locale.US)).getString(); if (name.contains(KEY_TO_PERMISSIONS)) { Log.getLogger().warn(""Didn't work for:"" + name); return; } rowPane.findPaneOfTypeByID(NAME_LABEL, Text.class).setText(name); final boolean isTriggered = building.getColony().getPermissions().hasPermission(actionsRank, action); final Button onOffButton = rowPane.findPaneOfTypeByID(""trigger"", Button.class); onOffButton.setText(isTriggered ? new TranslatableComponent(COM_MINECOLONIES_COREMOD_GUI_WORKERHUTS_RETRIEVE_ON) : new TranslatableComponent(COM_MINECOLONIES_COREMOD_GUI_WORKERHUTS_RETRIEVE_OFF)); rowPane.findPaneOfTypeByID(""index"", Text.class).setText(Integer.toString(index)); if (!building.getColony().getPermissions().canAlterPermission(building.getColony().getPermissions().getRank(Minecraft.getInstance().player), actionsRank, action)) { onOffButton.disable(); } else { onOffButton.enable(); } } }); }","Fix permission issues (#7972) Ranks are no longer a static map, which was used as a per-colony map thus causing crashes and desyncs. If the last colony loaded had a custom rank, all other colonies would crash out due to not matching permissions for that rank. Permission/Rank seperation is removed, permission flag is now part of the rank instead of an externally synced map, which also auto-corrects bad stored data to default permissions. UI now has non-changeable permission buttons disabled.",https://github.com/ldtteam/minecolonies/commit/b1b86dffe64dd4c0f9d3060769fc418fd5d2869a,,,src/main/java/com/minecolonies/coremod/client/gui/townhall/WindowPermissionsPage.java,3,java,False,2022-01-23T12:23:45Z "static RzList /**/ *__io_maps(RzDebug *dbg) { RzList *list = rz_list_new(); char *str = dbg->iob.system(dbg->iob.io, ""dm""); if (!str) { rz_list_free(list); return NULL; } char *ostr = str; ut64 map_start, map_end; char perm[32]; char name[512]; for (;;) { char *nl = strchr(str, '\n'); if (nl) { *nl = 0; *name = 0; *perm = 0; map_start = map_end = 0LL; if (!strncmp(str, ""sys "", 4)) { char *sp = strchr(str + 4, ' '); if (sp) { str = sp + 1; } else { str += 4; } } char *_s_ = strstr(str, "" s ""); if (_s_) { memmove(_s_, _s_ + 2, strlen(_s_)); } _s_ = strstr(str, "" ? ""); if (_s_) { memmove(_s_, _s_ + 2, strlen(_s_)); } sscanf(str, ""0x%"" PFMT64x "" - 0x%"" PFMT64x "" %s %s"", &map_start, &map_end, perm, name); if (map_end != 0LL) { RzDebugMap *map = rz_debug_map_new(name, map_start, map_end, rz_str_rwx(perm), 0); rz_list_append(list, map); } str = nl + 1; } else { break; } } free(ostr); rz_cons_reset(); return list; }","static RzList /**/ *__io_maps(RzDebug *dbg) { RzList *list = rz_list_new(); char *str = dbg->iob.system(dbg->iob.io, ""dm""); if (!str) { rz_list_free(list); return NULL; } char *ostr = str; ut64 map_start, map_end; char perm[IO_MAPS_PERM_SZ + 1]; char name[IO_MAPS_NAME_SZ + 1]; for (;;) { char *nl = strchr(str, '\n'); if (nl) { *nl = 0; *name = 0; *perm = 0; map_start = map_end = 0LL; if (!strncmp(str, ""sys "", 4)) { char *sp = strchr(str + 4, ' '); if (sp) { str = sp + 1; } else { str += 4; } } char *_s_ = strstr(str, "" s ""); if (_s_) { memmove(_s_, _s_ + 2, strlen(_s_)); } _s_ = strstr(str, "" ? ""); if (_s_) { memmove(_s_, _s_ + 2, strlen(_s_)); } sscanf(str, ""0x%"" PFMT64x "" - 0x%"" PFMT64x "" %"" RZ_STR_DEF(IO_MAPS_PERM_SZ) ""s %"" RZ_STR_DEF(IO_MAPS_NAME_SZ) ""s"", &map_start, &map_end, perm, name); if (map_end != 0LL) { RzDebugMap *map = rz_debug_map_new(name, map_start, map_end, rz_str_rwx(perm), 0); rz_list_append(list, map); } str = nl + 1; } else { break; } } free(ostr); rz_cons_reset(); return list; }",Fix conversion from GDB register profile to rizin profile,https://github.com/rizinorg/rizin/commit/504bf2a911b316c1431f634027fe7e31045a1a29,,,librz/debug/p/debug_io.c,3,c,False,2023-03-13T17:53:58Z "private V set(Object key, TxDecisionMaker decisionMaker) { TransactionStore store = transaction.store; Transaction blockingTransaction; long sequenceNumWhenStarted; VersionedValue result; String mapName = null; do { sequenceNumWhenStarted = store.openTransactions.get().getVersion(); assert transaction.getBlockerId() == 0; @SuppressWarnings(""unchecked"") K k = (K) key; // second parameter (value) is not really used, // since TxDecisionMaker has it embedded result = map.operate(k, null, decisionMaker); MVMap.Decision decision = decisionMaker.getDecision(); assert decision != null; assert decision != MVMap.Decision.REPEAT; blockingTransaction = decisionMaker.getBlockingTransaction(); if (decision != MVMap.Decision.ABORT || blockingTransaction == null) { hasChanges |= decision != MVMap.Decision.ABORT; V res = result == null ? null : result.getCurrentValue(); return res; } decisionMaker.reset(); if (mapName == null) { mapName = map.getName(); } } while (blockingTransaction.sequenceNum > sequenceNumWhenStarted || transaction.waitFor(blockingTransaction, mapName, key)); throw DataUtils.newMVStoreException(DataUtils.ERROR_TRANSACTION_LOCKED, ""Map entry <{0}> with key <{1}> and value {2} is locked by tx {3} and can not be updated by tx {4}"" + "" within allocated time interval {5} ms."", mapName, key, result, blockingTransaction.transactionId, transaction.transactionId, transaction.timeoutMillis); }","private V set(Object key, TxDecisionMaker decisionMaker) { TransactionStore store = transaction.store; Transaction blockingTransaction; // long sequenceNumWhenStarted; VersionedValue result; String mapName = null; do { // sequenceNumWhenStarted = store.openTransactions.get().getVersion(); assert transaction.getBlockerId() == 0; @SuppressWarnings(""unchecked"") K k = (K) key; // second parameter (value) is not really used, // since TxDecisionMaker has it embedded result = map.operate(k, null, decisionMaker); MVMap.Decision decision = decisionMaker.getDecision(); assert decision != null; assert decision != MVMap.Decision.REPEAT; blockingTransaction = decisionMaker.getBlockingTransaction(); if (decision != MVMap.Decision.ABORT || blockingTransaction == null) { hasChanges |= decision != MVMap.Decision.ABORT; V res = result == null ? null : result.getCurrentValue(); return res; } decisionMaker.reset(); if (mapName == null) { mapName = map.getName(); } } while (/*blockingTransaction.sequenceNum > sequenceNumWhenStarted ||*/ transaction.waitFor(blockingTransaction, mapName, key)); throw DataUtils.newMVStoreException(DataUtils.ERROR_TRANSACTION_LOCKED, ""Map entry <{0}> with key <{1}> and value {2} is locked by tx {3} and can not be updated by tx {4}"" + "" within allocated time interval {5} ms."", mapName, key, result, blockingTransaction.transactionId, transaction.transactionId, transaction.timeoutMillis); }",fix for infinite loop on deadlock #3115,https://github.com/h2database/h2database/commit/c408e313fc021351197bee8824779db8745cdfb7,,,h2/src/main/org/h2/mvstore/tx/TransactionMap.java,3,java,False,2021-05-16T18:39:48Z "@Override public Optional resolve(Request request) { String cookies = request.getHeader(""Cookie"").orElse(""""); String foundCookie = null; for (String cookie : cookies.split("";"")) { if (cookie.isEmpty()) continue; String[] split = cookie.split(""=""); String name = split[0]; String value = split[1]; if (""auth"".equals(name)) { foundCookie = value; ActiveCookieStore.removeCookie(value); } } if (foundCookie == null) { throw new WebUserAuthException(FailReason.NO_USER_PRESENT); } return Optional.of(getResponse(foundCookie)); }","@Override public Optional resolve(Request request) { String cookies = request.getHeader(""Cookie"").orElse(""""); String foundCookie = null; for (String cookie : cookies.split("";"")) { if (cookie.isEmpty()) continue; String[] split = cookie.split(""=""); String name = split[0]; String value = split[1]; if (""auth"".equals(name)) { foundCookie = value; activeCookieStore.removeCookie(value); } } if (foundCookie == null) { throw new WebUserAuthException(FailReason.EXPIRED_COOKIE); } return Optional.of(getResponse()); }","Implemented persistent cookies Fixed security vulnerability with cookies not being invalidated properly Request headers were not properly set for the Request object, leading to the Cookie header missing when logging out, which then left the cookie in memory. Rogue actor who gained access to the cookie could then use the cookie to access the panel. Made cookie expiry configurable with 'Webserver.Security.Cookie_expires_after' Due to cookie persistence there is no way to log everyone out of the panel. This will be addressed in a future commit with addition of a command. Affects issues: - Close #1740",https://github.com/plan-player-analytics/Plan/commit/fb4b272844263d33f5a6e85af29ac7e6e25ff80a,,,Plan/common/src/main/java/com/djrapitops/plan/delivery/webserver/resolver/auth/LogoutResolver.java,3,java,False,2021-03-20T10:02:02Z "private boolean handleArraySubscript( Address pArrayAddress, int pSubscript, CType pExpectedType, CArrayType pArrayType) { if (!pArrayAddress.isConcrete()) { return false; } BigInteger typeSize = machineModel.getSizeof(pExpectedType); BigInteger subscriptOffset = BigInteger.valueOf(pSubscript).multiply(typeSize); // Check if we are already out of array bound, if we have an array length. if (pArrayType.hasKnownConstantSize() && machineModel.getSizeof(pArrayType).compareTo(subscriptOffset) <= 0) { return false; } if (pArrayType.getLength() == null) { return false; } Address arrayAddressWithOffset = pArrayAddress.addOffset(subscriptOffset); BigInteger subscript = BigInteger.valueOf(pSubscript); CIntegerLiteralExpression litExp = new CIntegerLiteralExpression(FileLocation.DUMMY, CNumericTypes.INT, subscript); CArraySubscriptExpression arraySubscript = new CArraySubscriptExpression( subExpression.getFileLocation(), pExpectedType, subExpression, litExp); @Nullable Object concreteValue; if (isStructOrUnionType(pExpectedType) || pExpectedType instanceof CArrayType) { // Arrays and structs are represented as addresses concreteValue = arrayAddressWithOffset; } else { concreteValue = concreteState.getValueFromMemory(arraySubscript, arrayAddressWithOffset); } if (concreteValue == null) { return false; } ValueLiteral valueLiteral; Address valueAddress = Address.getUnknownAddress(); if (pExpectedType instanceof CSimpleType) { valueLiteral = getValueLiteral(((CSimpleType) pExpectedType), concreteValue); } else { valueAddress = Address.valueOf(concreteValue); if (valueAddress.isUnknown()) { return false; } valueLiteral = ExplicitValueLiteral.valueOf(valueAddress, machineModel); } if (!valueLiteral.isUnknown()) { SubExpressionValueLiteral subExpressionValueLiteral = new SubExpressionValueLiteral(valueLiteral, arraySubscript); valueLiterals.addSubExpressionValueLiteral(subExpressionValueLiteral); } if (!valueAddress.isUnknown()) { Pair visits = Pair.of(pExpectedType, valueAddress); if (visited.contains(visits)) { return false; } visited.add(visits); ValueLiteralVisitor v = new ValueLiteralVisitor(valueAddress, valueLiterals, arraySubscript, visited); pExpectedType.accept(v); } // the check if the array continued was performed at an earlier stage in this function return true; }","private boolean handleArraySubscript( Address pArrayAddress, int pSubscript, CType pExpectedType, CArrayType pArrayType) { if (!pArrayAddress.isConcrete()) { return false; } BigInteger typeSize = machineModel.getSizeof(pExpectedType); BigInteger subscriptOffset = BigInteger.valueOf(pSubscript).multiply(typeSize); // For the following bound check we need a statically known size, // otherwise we would loop infinitely. // TODO in principle we could extract the runtime size from the state? if (!pArrayType.hasKnownConstantSize()) { return false; } // Check if we are already out of array bound if (machineModel.getSizeof(pArrayType).compareTo(subscriptOffset) <= 0) { return false; } Address arrayAddressWithOffset = pArrayAddress.addOffset(subscriptOffset); BigInteger subscript = BigInteger.valueOf(pSubscript); CIntegerLiteralExpression litExp = new CIntegerLiteralExpression(FileLocation.DUMMY, CNumericTypes.INT, subscript); CArraySubscriptExpression arraySubscript = new CArraySubscriptExpression( subExpression.getFileLocation(), pExpectedType, subExpression, litExp); @Nullable Object concreteValue; if (isStructOrUnionType(pExpectedType) || pExpectedType instanceof CArrayType) { // Arrays and structs are represented as addresses concreteValue = arrayAddressWithOffset; } else { concreteValue = concreteState.getValueFromMemory(arraySubscript, arrayAddressWithOffset); } if (concreteValue == null) { return false; } ValueLiteral valueLiteral; Address valueAddress = Address.getUnknownAddress(); if (pExpectedType instanceof CSimpleType) { valueLiteral = getValueLiteral(((CSimpleType) pExpectedType), concreteValue); } else { valueAddress = Address.valueOf(concreteValue); if (valueAddress.isUnknown()) { return false; } valueLiteral = ExplicitValueLiteral.valueOf(valueAddress, machineModel); } if (!valueLiteral.isUnknown()) { SubExpressionValueLiteral subExpressionValueLiteral = new SubExpressionValueLiteral(valueLiteral, arraySubscript); valueLiterals.addSubExpressionValueLiteral(subExpressionValueLiteral); } if (!valueAddress.isUnknown()) { Pair visits = Pair.of(pExpectedType, valueAddress); if (visited.contains(visits)) { return false; } visited.add(visits); ValueLiteralVisitor v = new ValueLiteralVisitor(valueAddress, valueLiterals, arraySubscript, visited); pExpectedType.accept(v); } // the check if the array continued was performed at an earlier stage in this function return true; }","Fix infinite loop in AssumptionToEdgeAllocator for variable-length arrays AssumptionToEdgeAllocator relies on a statically known array size for its bounds check, and if this size is not known, it does no bounds check and loops infinitely. Before r42979 / b3feab3b this did not occur because for VLAs a wrong array size was used (cf. #1031) and only for incomplete array types the bounds check was skipped, but for incomplete array types we had a separate check anyway. Since that commit, we correctly avoid using the wrong array size, but this meant that now there was no bounds check at all for VLAs. Now we change that check that for all arrays without known size we just stop immediately and for other arrays we do the bounds check. This also covers incomplete array types because isIncomplete() implies !hasKnownConstantSize() for arrays. git-svn-id: https://svn.sosy-lab.org/software/cpachecker/trunk@42981 4712c6d2-40bb-43ae-aa4b-fec3f1bdfe4c",https://github.com/sosy-lab/cpachecker/commit/d4fc028b772fd6ff5fe871fe86c0876ac01a4257,,,src/org/sosy_lab/cpachecker/core/counterexample/AssumptionToEdgeAllocator.java,3,java,False,2023-02-03T11:02:54Z "default void startFromAction(SmartspaceAction action, View v, boolean showOnLockscreen) { if (action.getIntent() != null) { startIntent(v, action.getIntent(), showOnLockscreen); } else if (action.getPendingIntent() != null) { startPendingIntent(action.getPendingIntent(), showOnLockscreen); } }","default void startFromAction(SmartspaceAction action, View v, boolean showOnLockscreen) { try { if (action.getIntent() != null) { startIntent(v, action.getIntent(), showOnLockscreen); } else if (action.getPendingIntent() != null) { startPendingIntent(action.getPendingIntent(), showOnLockscreen); } } catch (ActivityNotFoundException e) { Log.w(TAG, ""Could not launch intent for action: "" + action, e); } }","Prevent bad intents from crashing sysui Smartspace could potentially send Intents that don't resolve, which will crash sysui. Log a warning. Also register an event notifier to let the SmartspaceSession know of a user action. Bug: 208350043 Test: atest LockscreenSmartspaceControllerTest + manual (use new smartspace flashlight off content) Change-Id: Ife517864c6933bc2d6ef01c28ec97363d9ebfbd7",https://github.com/omnirom/android_frameworks_base/commit/51f8e62e5442e4c01b4cfbf522a0f5223c8103be,,,packages/SystemUI/plugin/bcsmartspace/src/com/android/systemui/plugins/BcSmartspaceDataPlugin.java,3,java,False,2021-12-16T20:19:21Z "public void shutdown() { getExecutorService().shutdown(); try { getExecutorService().awaitTermination(30, TimeUnit.SECONDS); } catch (InterruptedException e) { } finally { executor = null; } }","public void shutdown() { if(executor != null) { executor.shutdown(); try { executor.awaitTermination(30, TimeUnit.SECONDS); } catch (InterruptedException e) { } finally { executor = null; } } }","Do not recreate the executor on shutdown If the ssh server is stopped or closed twice, the shutdown can end up in an infinite loop that overloads the heap. This is due to it recreating the executor service and adding a new shutdown hook after the first stop or close set the executor to null. This commit uses the executor static field value directly in shutdown instead of getExecutorService to avoid the infinitely recreated shutdown hooks.",https://github.com/sshtools/maverick-synergy/commit/c589230069429c1231b2842acdaebb4c5ee3136d,,,maverick-synergy-common/src/main/java/com/sshtools/synergy/ssh/SshContext.java,3,java,False,2021-05-25T17:39:50Z "public static boolean isSubtype(@Nonnull TypeMirror type, @Nonnull List superTypes, @Nonnull Types typeEnvironment) { List typeSuperTypes = getAllSuperTypes(typeEnvironment, type); typeSuperTypes.add(0, type); for (TypeMirror t : typeSuperTypes) { String oldi = toUniqueString(t); for (TypeMirror i : superTypes) { String newi = toUniqueString(i); if (oldi.equals(newi)) { return true; } } } return false; }","public static boolean isSubtype(@Nonnull TypeMirror type, @Nonnull List superTypes, @Nonnull Types typeEnvironment) { List typeSuperTypes = new ArrayList<>(getAllSuperTypes(typeEnvironment, type)); typeSuperTypes.add(0, type); for (TypeMirror t : typeSuperTypes) { String oldi = toUniqueString(t); for (TypeMirror i : superTypes) { String newi = toUniqueString(i); if (oldi.equals(newi)) { return true; } } } return false; }",Prevent stack overflow when getting all super types,https://github.com/revapi/revapi/commit/e559e6f68474e6481573b78336699cab1f8e1bca,,,revapi-java-spi/src/main/java/org/revapi/java/spi/Util.java,3,java,False,2022-07-21T19:17:01Z "private AuthenticationResponse authenticate(Authenticator authenticator, RequestContext requestContext) { try { AuthenticationContext authenticate = authenticator.authenticate(requestContext); requestContext.setAuthenticationContext(authenticate); if (authenticate.isAuthenticated()) { updateClusterHeaderAndCheckEnv(requestContext, authenticate); return new AuthenticationResponse(true, false, false); } } catch (APISecurityException e) { //TODO: (VirajSalaka) provide the error code properly based on exception (401, 403, 429 etc) FilterUtils.setErrorToContext(requestContext, e); } return new AuthenticationResponse(false, false, true); }","private AuthenticationResponse authenticate(Authenticator authenticator, RequestContext requestContext) { try { AuthenticationContext authenticate = authenticator.authenticate(requestContext); requestContext.setAuthenticationContext(authenticate); if (authenticate.isAuthenticated()) { updateClusterHeaderAndCheckEnv(requestContext, authenticate); // set backend security EndpointSecurityUtils.addEndpointSecurity(requestContext); return new AuthenticationResponse(true, false, false); } } catch (APISecurityException e) { //TODO: (VirajSalaka) provide the error code properly based on exception (401, 403, 429 etc) FilterUtils.setErrorToContext(requestContext, e); } return new AuthenticationResponse(false, false, true); }",fix no security basic auth backend,https://github.com/wso2/product-microgateway/commit/cbe70820b892fd72b53a625407c593b9d6b93dee,,,enforcer-parent/enforcer/src/main/java/org/wso2/choreo/connect/enforcer/security/AuthFilter.java,3,java,False,2021-11-22T06:20:07Z "@Override public void invoke() { IsolateThread vmThread = PlatformThreads.getIsolateThread(thread); Pointer rootSP = cont.sp; CodePointer rootIP = cont.ip; preemptStatus = StoredContinuationImpl.allocateFromForeignStack(cont, rootSP, vmThread); if (preemptStatus == 0) { VMThreads.ActionOnExitSafepointSupport.setSwitchStack(vmThread); VMThreads.ActionOnExitSafepointSupport.setSwitchStackTarget(vmThread, rootSP, rootIP); } }","@Override public void invoke() { IsolateThread vmThread = PlatformThreads.getIsolateThread(thread); Pointer bottomSP = cont.bottomSP; Pointer returnSP = cont.sp; CodePointer returnIP = cont.ip; preemptStatus = StoredContinuationImpl.allocateFromForeignStack(cont, bottomSP, vmThread); if (preemptStatus == 0) { cont.sp = WordFactory.nullPointer(); cont.bottomSP = WordFactory.nullPointer(); VMThreads.ActionOnExitSafepointSupport.setSwitchStack(vmThread); VMThreads.ActionOnExitSafepointSupport.setSwitchStackTarget(vmThread, returnSP, returnIP); } }","Fix Continuation.enter1 overwriting its own frame, check for stack overflow, and avoid extra heap buffer.",https://github.com/oracle/graal/commit/aadbff556c457e107f5f44706750b11cf569e404,,,substratevm/src/com.oracle.svm.core/src/com/oracle/svm/core/thread/Continuation.java,3,java,False,2022-03-02T18:51:14Z "private void loginWithCertificate(final HttpServletRequest request) { LOGGER.debug(""loginWithCertificate""); String dn = CertificateUtil.extractCertificateDN(request); LOGGER.debug(() -> ""DN = "" + dn); if (dn != null) { final String cn = CertificateUtil.extractCNFromDN(dn); LOGGER.debug(() -> ""CN = "" + cn); if (cn != null) { // Check for a certificate LOGGER.debug(() -> ""User has presented a certificate: "" + cn); Optional optionalSubject = getIdFromCertificate(cn); if (optionalSubject.isEmpty()) { throw new RuntimeException( ""User is presenting a certificate but this certificate cannot be processed!""); } else { final String subject = optionalSubject.get(); final Optional optionalAccount = accountDao.get(subject); if (optionalAccount.isEmpty()) { // There's no user so we can't let them have access. throw new BadRequestException( ""The user identified by the certificate does not exist in the auth database.""); } else { final Account account = optionalAccount.get(); if (!account.isLocked() && !account.isInactive() && account.isEnabled()) { LOGGER.info(""Logging user in using DN with subject {}"", subject); setAuthState(request.getSession(true), new AuthStateImpl(account, false, System.currentTimeMillis())); // Reset last access, login failures, etc... accountDao.recordSuccessfulLogin(subject); } } } } } }","private void loginWithCertificate(final HttpServletRequest request) { LOGGER.debug(""loginWithCertificate""); final Optional optionalCN = CertificateUtil.getCN(request); optionalCN.ifPresent(cn -> { // Check for a certificate LOGGER.debug(() -> ""Got CN: "" + cn); Optional optionalUserId = getIdFromCertificate(cn); if (optionalUserId.isEmpty()) { throw new RuntimeException( ""Found CN but the identity cannot be extracted (CN = "" + cn + "")""); } else { final String userId = optionalUserId.get(); final Optional optionalAccount = accountDao.get(userId); if (optionalAccount.isEmpty()) { // There's no user so we can't let them have access. throw new BadRequestException( ""An account for the userId does not exist (userId = "" + userId + "")""); } else { final Account account = optionalAccount.get(); if (!account.isLocked() && !account.isInactive() && account.isEnabled()) { LOGGER.info(() -> ""Logging user in: "" + userId); setAuthState(request.getSession(true), new AuthStateImpl(account, false, System.currentTimeMillis())); // Reset last access, login failures, etc... accountDao.recordSuccessfulLogin(userId); } } } }); }",#2142 Fix certificate authentication issues,https://github.com/gchq/stroom/commit/42762b4b0b8d85c858879374355747f5ce56a3d9,,,stroom-security/stroom-security-identity/src/main/java/stroom/security/identity/authenticate/AuthenticationServiceImpl.java,3,java,False,2021-03-26T12:27:16Z "@Override public void configure() throws Exception { String queueName = String.format(TWIN_QUEUE_NAME_FORMAT, SystemInfoUtils.getInstanceId(), ""Twin.Sink""); final JmsEndpoint endpoint = getContext().getEndpoint(String.format(""queuingservice:%s"", queueName), JmsEndpoint.class); from(endpoint).setExchangePattern(ExchangePattern.InOnly) .process(processor) .routeId(SystemInfoUtils.getInstanceId() + "".Twin.Sink""); }","@Override public void configure() throws Exception { String queueName = String.format(TWIN_QUEUE_NAME_FORMAT, SystemInfoUtils.getInstanceId(), ""Twin.Sink""); final JmsEndpoint endpoint = getContext().getEndpoint(String.format(""queuingservice:topic:%s"", queueName), JmsEndpoint.class); from(endpoint).setExchangePattern(ExchangePattern.InOnly) .process(processor) .routeId(SystemInfoUtils.getInstanceId() + "".Twin.Sink""); }","NMS-13726: Fix jms twin issues Use topic for Twin Sink Add authorization entries for Twin topics",https://github.com/OpenNMS/opennms/commit/4295b952130ad801a474f9371625fa1a4c457bb3,,,core/ipc/twin/jms/subscriber/src/main/java/org/opennms/core/ipc/twin/jms/subscriber/JmsTwinSubscriber.java,3,java,False,2021-11-09T22:07:03Z "@Override boolean sendMouseEvent(NSEvent nsEvent, int type, boolean send) { if (type == SWT.DragDetect) { dragDetected = true; } else if (type == SWT.MouseUp) { /* * This code path handles the case of an unmodified click on an already-selected row. * To keep the order of events correct, deselect the other selected items and send the * selection event before MouseUp is sent. Ignore the next selection event. */ if (selectedRowIndex != -1) { if (dragDetected) { selectedRowIndex = -1; } else { NSOutlineView widget = (NSOutlineView)view; NSIndexSet selectedRows = widget.selectedRowIndexes (); int count = (int)selectedRows.count(); long [] indexBuffer = new long [count]; selectedRows.getIndexes(indexBuffer, count, 0); for (int i = 0; i < count; i++) { if (indexBuffer[i] == selectedRowIndex) continue; ignoreSelect = true; widget.deselectRow (indexBuffer[i]); ignoreSelect = false; } Event event = new Event (); id itemID = widget.itemAtRow (selectedRowIndex); if (itemID != null) { Widget item = display.getWidget (itemID.id); if (item != null && item instanceof TreeItem) { event.item = display.getWidget (itemID.id); sendSelectionEvent (SWT.Selection, event, false); } } selectedRowIndex = -1; ignoreSelect = true; } } dragDetected = false; } return super.sendMouseEvent (nsEvent, type, send); }","@Override boolean sendMouseEvent(NSEvent nsEvent, int type, boolean send) { if (type == SWT.DragDetect) { dragDetected = true; } else if (type == SWT.MouseUp) { // See code comment in Table.handleClickSelected() if (selectedRowIndex != -1) { if (dragDetected) { selectedRowIndex = -1; } else { NSOutlineView widget = (NSOutlineView)view; NSIndexSet selectedRows = widget.selectedRowIndexes (); int count = (int)selectedRows.count(); long [] indexBuffer = new long [count]; selectedRows.getIndexes(indexBuffer, count, 0); for (int i = 0; i < count; i++) { if (indexBuffer[i] == selectedRowIndex) continue; ignoreSelect = true; widget.deselectRow (indexBuffer[i]); ignoreSelect = false; } Event event = new Event (); id itemID = widget.itemAtRow (selectedRowIndex); // (itemID = null) means that item was removed after // 'selectedRowIndex' was cached if (itemID != null) { Widget item = display.getWidget (itemID.id); if (item != null && item instanceof TreeItem) { event.item = display.getWidget (itemID.id); sendSelectionEvent (SWT.Selection, event, false); } } selectedRowIndex = -1; ignoreSelect = true; } } dragDetected = false; } return super.sendMouseEvent (nsEvent, type, send); }","Bug 456602 - [Cocoa] ArrayIndexOutOfBoundsException in Table._getItem The problem is that item for cached `selectedRowIndex` can be deleted between mouse down (where variable is set) and mouse up (where it's used). I tried to solve the original problem (where macOS sends SWT.Selection after `[NSEvent doubleClickInterval]` from mouse down) but didn't find a way to do that. It seems that there are no settings that could disable double click detection in `-[NSTableView mouseDown:]`. So the workaround has to stay, it seems. I also noticed that macOS cancels pending selection event in `-[NSTableView noteNumberOfRowsChanged]`. SWT already calls that whenever number of items changes (item is deleted or added). I was thinking to reset `selectedRowIndex` in it, but then I wasn't sure if it's the right thing to do if for example an item is added at the end - surely this doesn't prevent from proceeding with handling click on the old item? I the end, I decided to not overcomplicate things and just fix the crash without affecting anything else. Change-Id: I42cb381d408d105e4df6372a2d69967b9b274a9a Signed-off-by: Alexandr Miloslavskiy Reviewed-on: https://git.eclipse.org/r/c/platform/eclipse.platform.swt/+/192115 Tested-by: Platform Bot Tested-by: Lakshmi P Shanmugam Reviewed-by: Lakshmi P Shanmugam ",https://github.com/eclipse-platform/eclipse.platform.swt/commit/5fdce45fa7483a5e87270ace76e3796f0e1b8116,,,bundles/org.eclipse.swt/Eclipse SWT/cocoa/org/eclipse/swt/widgets/Tree.java,3,java,False,2022-03-22T02:01:05Z "@GuardedBy(""mLock"") private void updateRequirementsLocked() { long gpsInterval = mRequest.getQuality() < QUALITY_LOW_POWER ? mRequest.getIntervalMillis() : INTERVAL_DISABLED; long networkInterval = mRequest.getIntervalMillis(); mGpsListener.resetProviderRequest(gpsInterval); mNetworkListener.resetProviderRequest(networkInterval); }","@GuardedBy(""mLock"") private void updateRequirementsLocked() { // it's possible there might be race conditions on device start where a provider doesn't // appear to be present yet, but once a provider is present it shouldn't go away. if (!mGpsPresent) { mGpsPresent = mLocationManager.hasProvider(GPS_PROVIDER); } if (!mNlpPresent) { mNlpPresent = mLocationManager.hasProvider(NETWORK_PROVIDER); } long gpsInterval = mGpsPresent && (!mNlpPresent || mRequest.getQuality() < QUALITY_LOW_POWER) ? mRequest.getIntervalMillis() : INTERVAL_DISABLED; long networkInterval = mNlpPresent ? mRequest.getIntervalMillis() : INTERVAL_DISABLED; mGpsListener.resetProviderRequest(gpsInterval); mNetworkListener.resetProviderRequest(networkInterval); }","Fix newly discovered crashes in FusedLocationProvider We recently discovered the FusedLocationProvider doesn't function well when the gps or network provider is missing, but these errors were previously hidden. Now that the crashes are apparent, deal with cases where these providers may not be present. Bug: 214358333 Test: presubmits Change-Id: I660592bee4897fc335f5fe1d2f2499c047b62e66",https://github.com/omnirom/android_frameworks_base/commit/1679ed09011e7756e415be9086a9f0ca5dff816b,,,packages/FusedLocation/src/com/android/location/fused/FusedLocationProvider.java,3,java,False,2022-01-13T18:39:11Z "@Override public R run(Action action) throws TException, InterruptedException { return clientPool().run(action); }","@Override public R run(Action action) throws TException, InterruptedException { try { return tableMetaStore.doAs(() -> clientPool().run(action)); } catch (RuntimeException e) { throw throwTException(e); } }","[Hive] Fix kerberos authenticate (#474) add doAs in CachedHiveClientPool",https://github.com/apache/incubator-amoro/commit/9d786890506278e76a5e01d536eaf00c6e8edf3b,,,hive/src/main/java/com/netease/arctic/hive/CachedHiveClientPool.java,3,java,False,2022-10-17T02:51:56Z "private Map collectDefinedVariables(String contents) { Map vars = new HashMap<>(); final Matcher m = SET_VAR_REGEX.matcher(contents); int count = 0; while (m.find()) { count++; LOGGER.debug(""Found set variable command match with {} groups: {}"", m.groupCount(), m.group(0)); final String name = m.group(1); final String value = m.group(2); LOGGER.debug(""Group 1: {}"", name); LOGGER.debug(""Group 2: {}"", value); vars.put(name, value); } LOGGER.debug(""Found {} matches."", count); return vars; }","private Map collectDefinedVariables(String contents) { Map vars = new HashMap<>(); final Matcher m = SET_VAR_REGEX.matcher(contents); int count = 0; while (m.find()) { count++; LOGGER.debug(""Found set variable command match with {} groups: {}"", m.groupCount(), m.group(0)); final String name = m.group(1); final String value = m.group(2); LOGGER.debug(""Group 1: {}"", name); LOGGER.debug(""Group 2: {}"", value); vars.put(name, value); } LOGGER.debug(""Found {} matches."", count); return removeSelfReferences(vars); }",#4499 Prevent infinite loop,https://github.com/jeremylong/DependencyCheck/commit/842591b4f2e3649c3fe0972a43e0af8b974672a4,,,core/src/main/java/org/owasp/dependencycheck/analyzer/CMakeAnalyzer.java,3,java,False,2022-06-25T16:11:51Z "@SubscribeEvent public void onShiftClickPlayer(PacketEvent e) { if (!UtilitiesConfig.INSTANCE.preventTradesDuels) return; EntityPlayerSP player = ModCore.mc().player; Entity clicked = e.getPacket().getEntityFromWorld(player.world); if (!(clicked instanceof EntityPlayer)) return; EntityPlayer ep = (EntityPlayer) clicked; if (ep.getTeam() == null) return; // player model npc if (!player.isSneaking() || player.getHeldItemMainhand().isEmpty()) return; e.setCanceled(true); }","@SubscribeEvent public void onShiftClickPlayer(PacketEvent e) { if (!UtilitiesConfig.INSTANCE.preventTradesDuels) return; EntityPlayerSP player = ModCore.mc().player; if (!player.isSneaking()) return; Entity clicked = e.getPacket().getEntityFromWorld(player.world); if (!(clicked instanceof EntityPlayer)) return; EntityPlayer ep = (EntityPlayer) clicked; if (ep.getTeam() == null) return; // player model npc ItemType item = ItemUtils.getItemType(player.getHeldItemMainhand()); if (item == null) return; // not any type of gear if (item != ItemType.WAND && item != ItemType.DAGGER && item != ItemType.BOW && item != ItemType.SPEAR && item != ItemType.RELIK) return; // not a weapon e.setCanceled(true); }","Bugfixes & Various QoL (#309) * Fix skill point overlay crash * Update spell costs * Fix crash when handling missing major ids * Add new major ids * Improve how the waypoint menu handles groups & icons * Allow user to share location/pin to guild from map gui * Improve the prevent trades/duels in combat feature * Improve athena outage message * Improve mythic found sound and chest close prevention * Remove /class welcome messages like other info messages * Update item identification cost formulas",https://github.com/Wynntils/Wynntils/commit/31c1ca29d0a8345050d8075436c7673ee80e6f15,,,src/main/java/com/wynntils/modules/utilities/events/ClientEvents.java,3,java,False,2021-02-28T07:45:46Z "public String getFooter() { try { return URLDecoder.decode(footer, ""UTF-8""); // footer is url encoded } catch (UnsupportedEncodingException e) { return null; } }","public String getFooter() { try { return URLDecoder.decode(StringEscapeUtils.unescapeJava(footer.replace(""%u"", ""\\u"")), ""UTF-8""); // footer is url encoded } catch (UnsupportedEncodingException e) { return null; } }","Fix crash with %uXXXX encoded chars in RR fields Fixed this earlier for main RR text in #3197, but didn't fix it for header or footer fields, so this fixes that.",https://github.com/Haptic-Apps/Slide/commit/ab2b617d37eaabd8be6b2b59ca65f0de08c88dae,,,app/src/main/java/me/ccrama/redditslide/Toolbox/RemovalReasons.java,3,java,False,2021-04-30T19:27:39Z "@Override public void render(float partialTicks, ItemTransforms.TransformType transformType, ItemStack stack, ItemStack parent, LivingEntity entity, PoseStack poseStack, MultiBufferSource renderTypeBuffer, int light, int overlay) { if(OptifineHelper.isShadersEnabled()) { double transition = 1.0 - Math.pow(1.0 - AimingHandler.get().getNormalisedAdsProgress(), 2); double zScale = 0.05 + 0.95 * (1.0 - transition); poseStack.scale(1.0F, 1.0F, (float) zScale); } if(transformType.firstPerson() && entity.equals(Minecraft.getInstance().player)) { poseStack.pushPose(); { Matrix4f matrix = poseStack.last().pose(); Matrix3f normal = poseStack.last().normal(); float size = 1.4F / 16.0F; poseStack.translate(-size / 2, 0.85 * 0.0625, -0.3 * 0.0625); double invertProgress = (1.0 - AimingHandler.get().getNormalisedAdsProgress()); poseStack.translate(-0.04 * invertProgress, 0.01 * invertProgress, 0); double scale = 6.0; poseStack.translate(size / 2, size / 2, 0); poseStack.translate(-(size / scale) / 2, -(size / scale) / 2, 0); poseStack.translate(0, 0, 0.0001); int reticleGlowColor = RenderUtil.getItemStackColor(stack, parent, 0); CompoundTag tag = stack.getTag(); if(tag != null && tag.contains(""ReticleColor"", Tag.TAG_INT)) { reticleGlowColor = tag.getInt(""ReticleColor""); } float red = ((reticleGlowColor >> 16) & 0xFF) / 255F; float green = ((reticleGlowColor >> 8) & 0xFF) / 255F; float blue = ((reticleGlowColor >> 0) & 0xFF) / 255F; float alpha = (float) AimingHandler.get().getNormalisedAdsProgress(); VertexConsumer builder; if(!OptifineHelper.isShadersEnabled()) { builder = renderTypeBuffer.getBuffer(RenderType.entityTranslucent(RED_DOT_RETICLE_GLOW)); builder.vertex(matrix, 0, (float) (size / scale), 0).color(red, green, blue, alpha).uv(0.0F, 0.9375F).overlayCoords(overlay).uv2(15728880).normal(normal, 0.0F, 1.0F, 0.0F).endVertex(); builder.vertex(matrix, 0, 0, 0).color(red, green, blue, alpha).uv(0.0F, 0.0F).overlayCoords(overlay).uv2(15728880).normal(normal, 0.0F, 1.0F, 0.0F).endVertex(); builder.vertex(matrix, (float) (size / scale), 0, 0).color(red, green, blue, alpha).uv(0.9375F, 0.0F).overlayCoords(overlay).uv2(15728880).normal(normal, 0.0F, 1.0F, 0.0F).endVertex(); builder.vertex(matrix, (float) (size / scale), (float) (size / scale), 0).color(red, green, blue, alpha).uv(0.9375F, 0.9375F).overlayCoords(overlay).uv2(15728880).normal(normal, 0.0F, 1.0F, 0.0F).endVertex(); } alpha = (float) (0.75F * AimingHandler.get().getNormalisedAdsProgress()); builder = renderTypeBuffer.getBuffer(RenderType.entityTranslucent(RED_DOT_RETICLE)); builder.vertex(matrix, 0, (float) (size / scale), 0).color(1.0F, 1.0F, 1.0F, alpha).uv(0.0F, 0.9375F).overlayCoords(overlay).uv2(15728880).normal(normal, 0.0F, 1.0F, 0.0F).endVertex(); builder.vertex(matrix, 0, 0, 0).color(1.0F, 1.0F, 1.0F, alpha).uv(0.0F, 0.0F).overlayCoords(overlay).uv2(15728880).normal(normal, 0.0F, 1.0F, 0.0F).endVertex(); builder.vertex(matrix, (float) (size / scale), 0, 0).color(1.0F, 1.0F, 1.0F, alpha).uv(0.9375F, 0.0F).overlayCoords(overlay).uv2(15728880).normal(normal, 0.0F, 1.0F, 0.0F).endVertex(); builder.vertex(matrix, (float) (size / scale), (float) (size / scale), 0).color(1.0F, 1.0F, 1.0F, alpha).uv(0.9375F, 0.9375F).overlayCoords(overlay).uv2(15728880).normal(normal, 0.0F, 1.0F, 0.0F).endVertex(); } poseStack.popPose(); } BakedModel bakedModel = Minecraft.getInstance().getItemRenderer().getItemModelShaper().getItemModel(stack); Minecraft.getInstance().getItemRenderer().render(stack, ItemTransforms.TransformType.NONE, false, poseStack, renderTypeBuffer, light, overlay, GunModel.wrap(bakedModel)); }","@Override public void render(float partialTicks, ItemTransforms.TransformType transformType, ItemStack stack, ItemStack parent, @Nullable LivingEntity entity, PoseStack poseStack, MultiBufferSource renderTypeBuffer, int light, int overlay) { if(OptifineHelper.isShadersEnabled()) { double transition = 1.0 - Math.pow(1.0 - AimingHandler.get().getNormalisedAdsProgress(), 2); double zScale = 0.05 + 0.95 * (1.0 - transition); poseStack.scale(1.0F, 1.0F, (float) zScale); } if(transformType.firstPerson() && entity != null && entity.equals(Minecraft.getInstance().player)) { poseStack.pushPose(); { Matrix4f matrix = poseStack.last().pose(); Matrix3f normal = poseStack.last().normal(); float size = 1.4F / 16.0F; poseStack.translate(-size / 2, 0.85 * 0.0625, -0.3 * 0.0625); double invertProgress = (1.0 - AimingHandler.get().getNormalisedAdsProgress()); poseStack.translate(-0.04 * invertProgress, 0.01 * invertProgress, 0); double scale = 6.0; poseStack.translate(size / 2, size / 2, 0); poseStack.translate(-(size / scale) / 2, -(size / scale) / 2, 0); poseStack.translate(0, 0, 0.0001); int reticleGlowColor = RenderUtil.getItemStackColor(stack, parent, 0); CompoundTag tag = stack.getTag(); if(tag != null && tag.contains(""ReticleColor"", Tag.TAG_INT)) { reticleGlowColor = tag.getInt(""ReticleColor""); } float red = ((reticleGlowColor >> 16) & 0xFF) / 255F; float green = ((reticleGlowColor >> 8) & 0xFF) / 255F; float blue = ((reticleGlowColor >> 0) & 0xFF) / 255F; float alpha = (float) AimingHandler.get().getNormalisedAdsProgress(); VertexConsumer builder; if(!OptifineHelper.isShadersEnabled()) { builder = renderTypeBuffer.getBuffer(RenderType.entityTranslucent(RED_DOT_RETICLE_GLOW)); builder.vertex(matrix, 0, (float) (size / scale), 0).color(red, green, blue, alpha).uv(0.0F, 0.9375F).overlayCoords(overlay).uv2(15728880).normal(normal, 0.0F, 1.0F, 0.0F).endVertex(); builder.vertex(matrix, 0, 0, 0).color(red, green, blue, alpha).uv(0.0F, 0.0F).overlayCoords(overlay).uv2(15728880).normal(normal, 0.0F, 1.0F, 0.0F).endVertex(); builder.vertex(matrix, (float) (size / scale), 0, 0).color(red, green, blue, alpha).uv(0.9375F, 0.0F).overlayCoords(overlay).uv2(15728880).normal(normal, 0.0F, 1.0F, 0.0F).endVertex(); builder.vertex(matrix, (float) (size / scale), (float) (size / scale), 0).color(red, green, blue, alpha).uv(0.9375F, 0.9375F).overlayCoords(overlay).uv2(15728880).normal(normal, 0.0F, 1.0F, 0.0F).endVertex(); } alpha = (float) (0.75F * AimingHandler.get().getNormalisedAdsProgress()); builder = renderTypeBuffer.getBuffer(RenderType.entityTranslucent(RED_DOT_RETICLE)); builder.vertex(matrix, 0, (float) (size / scale), 0).color(1.0F, 1.0F, 1.0F, alpha).uv(0.0F, 0.9375F).overlayCoords(overlay).uv2(15728880).normal(normal, 0.0F, 1.0F, 0.0F).endVertex(); builder.vertex(matrix, 0, 0, 0).color(1.0F, 1.0F, 1.0F, alpha).uv(0.0F, 0.0F).overlayCoords(overlay).uv2(15728880).normal(normal, 0.0F, 1.0F, 0.0F).endVertex(); builder.vertex(matrix, (float) (size / scale), 0, 0).color(1.0F, 1.0F, 1.0F, alpha).uv(0.9375F, 0.0F).overlayCoords(overlay).uv2(15728880).normal(normal, 0.0F, 1.0F, 0.0F).endVertex(); builder.vertex(matrix, (float) (size / scale), (float) (size / scale), 0).color(1.0F, 1.0F, 1.0F, alpha).uv(0.9375F, 0.9375F).overlayCoords(overlay).uv2(15728880).normal(normal, 0.0F, 1.0F, 0.0F).endVertex(); } poseStack.popPose(); } BakedModel bakedModel = Minecraft.getInstance().getItemRenderer().getItemModelShaper().getItemModel(stack); Minecraft.getInstance().getItemRenderer().render(stack, ItemTransforms.TransformType.NONE, false, poseStack, renderTypeBuffer, light, overlay, GunModel.wrap(bakedModel)); }",🐛 Fixed potential crash when player is null,https://github.com/MrCrayfish/MrCrayfishGunMod/commit/0916fe277c5633f9d4062e4d0fa3f2b25f940c60,,,src/main/java/com/mrcrayfish/guns/client/render/gun/model/ShortScopeModel.java,3,java,False,2022-07-13T14:05:31Z "private void scanZip(Path zippedFile) { LOGGER.info(""Unzipping "" + zippedFile); File destination = new File(unzipDirectory, UUID.randomUUID().toString()); zippedFilePath = zippedFile; if (!destination.exists()) { destination.mkdirs(); } try { ZipFile zipFile = new ZipFile(zippedFile.toString()); zipFile.extractAll(destination.toString()); File file = new File(destination, "".info""); file.createNewFile(); try ( PrintWriter pw = new PrintWriter(file)) { pw.write(zippedFile.toString()); } for (File foundDir : destination.listFiles()) { if (foundDir.isDirectory()) { scanDirectory(foundDir.toPath()); continue; } scanFile(foundDir.toPath()); } } catch (IOException ex) { LOGGER.exception(ex); } }","private void scanZip(Path zippedFile) { LOGGER.info(""Unzipping "" + zippedFile); File destination = new File(unzipDirectory, UUID.randomUUID().toString()); zippedFilePath = zippedFile; if (!destination.exists()) { destination.mkdirs(); } try { Utils.unzip(new ZipFile(zippedFile.toFile()), destination); File file = new File(destination, "".info""); file.createNewFile(); try ( PrintWriter pw = new PrintWriter(file)) { pw.write(zippedFile.toString()); } for (File foundDir : destination.listFiles()) { if (foundDir.isDirectory()) { scanDirectory(foundDir.toPath()); continue; } scanFile(foundDir.toPath()); } } catch (IOException ex) { Logger.getLogger(Scanner.class.getName()).log(Level.SEVERE, null, ex); } }","Changes Fixed some issues in CrasherCheck Fixed some issues in DispatchCommandCheck Fixed an issue in NonVanillaEnchantCheck Fixed a security issue related to zips Now checks for JNIC usage",https://github.com/OpticFusion1/MCAntiMalware/commit/8b07511019fee60ea2c5bc29b26d68446eabf494,,,MCAntiMalware-Core/src/main/java/optic_fusion1/antimalware/scanner/Scanner.java,3,java,False,2021-08-18T09:50:22Z "private void loadSuite(AbstractSuite suite, Attribute attribute) { icon.setImageResource(suite.getIcon()); title.setText(suite.getTestList(preferenceManager)[0].getLabelResId()); desc.setText(getString(R.string.OONIRun_YouAreAboutToRun)); if (attribute != null && attribute.urls != null) { for (String url : attribute.urls) items.add(new TextItem(url)); adapter.notifyTypesChanged(); iconBig.setVisibility(View.GONE); } else { iconBig.setImageResource(suite.getIcon()); iconBig.setVisibility(View.VISIBLE); } run.setOnClickListener(v -> { Intent runIntent = RunningActivity.newIntent(OoniRunActivity.this, suite.asArray()); if (runIntent != null) { startActivity(runIntent); finish(); } }); }","private void loadSuite(AbstractSuite suite, Attribute attribute) { icon.setImageResource(suite.getIcon()); title.setText(suite.getTestList(preferenceManager)[0].getLabelResId()); desc.setText(getString(R.string.OONIRun_YouAreAboutToRun)); if (attribute != null && attribute.urls != null) { for (String url : attribute.urls) { if (URLUtil.isValidUrl(url)) items.add(new TextItem(url)); } adapter.notifyTypesChanged(); iconBig.setVisibility(View.GONE); } else { iconBig.setImageResource(suite.getIcon()); iconBig.setVisibility(View.VISIBLE); } run.setOnClickListener(v -> { Intent runIntent = RunningActivity.newIntent(OoniRunActivity.this, suite.asArray()); if (runIntent != null) { startActivity(runIntent); finish(); } }); }","validate URLs (#443) * validate URLs * Prevent the app from crashing",https://github.com/ooni/probe-android/commit/235ba6bd8243d741bbfb2cd6912aeff75996c8c1,,,app/src/main/java/org/openobservatory/ooniprobe/activity/OoniRunActivity.java,3,java,False,2021-07-20T10:57:23Z "boolean isOpen() throws SQLException { return (pointer != 0); }","boolean isOpen() throws SQLException { return !pointer.isClosed(); }",Wrap Statement Pointers to prevent use after free race,https://github.com/xerial/sqlite-jdbc/commit/e1d282cb2887ef427c7ad93d4fe7dd05a6c11473,,,src/main/java/org/sqlite/core/CoreStatement.java,3,java,False,2022-07-29T03:54:01Z "private boolean hasPermission(String sid, Permission permission, RoleType roleType, AccessControlled controlledItem) { final Set permissions = getImplyingPermissions(permission); final boolean[] hasPermission = { false }; // Walk through the roles, and only add the roles having the given permission, // or a permission implying the given permission new RoleWalker() { @Override public void perform(Role current) { if (current.hasAnyPermission(permissions)) { if (grantedRoles.get(current).contains(sid)) { // Handle roles macro if (Macro.isMacro(current)) { Macro macro = RoleMacroExtension.getMacro(current.getName()); if (macro != null) { RoleMacroExtension macroExtension = RoleMacroExtension.getMacroExtension(macro.getName()); if (macroExtension.IsApplicable(roleType) && macroExtension.hasPermission(sid, permission, roleType, controlledItem, macro)) { hasPermission[0] = true; abort(); } } } else { hasPermission[0] = true; abort(); } } else if (Settings.TREAT_USER_AUTHORITIES_AS_ROLES) { try { UserDetails userDetails = cache.getIfPresent(sid); if (userDetails == null) { userDetails = Jenkins.get().getSecurityRealm().loadUserByUsername(sid); cache.put(sid, userDetails); } for (GrantedAuthority grantedAuthority : userDetails.getAuthorities()) { if (grantedAuthority.getAuthority().equals(current.getName())) { hasPermission[0] = true; abort(); return; } } } catch (BadCredentialsException e) { LOGGER.log(Level.FINE, ""Bad credentials"", e); } catch (DataAccessException e) { LOGGER.log(Level.FINE, ""failed to access the data"", e); } catch (RuntimeException ex) { // There maybe issues in the logic, which lead to IllegalStateException in Acegi // Security (JENKINS-35652) // So we want to ensure this method does not fail horribly in such case LOGGER.log(Level.WARNING, ""Unhandled exception during user authorities processing"", ex); } } } } }; return hasPermission[0]; }","@Restricted(NoExternalUse.class) public boolean hasPermission(String sid, Permission permission, RoleType roleType, AccessControlled controlledItem) { final Set permissions = getImplyingPermissions(permission); final boolean[] hasPermission = { false }; // Walk through the roles, and only add the roles having the given permission, // or a permission implying the given permission new RoleWalker() { @Override public void perform(Role current) { if (current.hasAnyPermission(permissions)) { if (grantedRoles.get(current).contains(sid)) { // Handle roles macro if (Macro.isMacro(current)) { Macro macro = RoleMacroExtension.getMacro(current.getName()); if (controlledItem != null && macro != null) { RoleMacroExtension macroExtension = RoleMacroExtension.getMacroExtension(macro.getName()); if (macroExtension.IsApplicable(roleType) && macroExtension.hasPermission(sid, permission, roleType, controlledItem, macro)) { hasPermission[0] = true; abort(); } } } else { hasPermission[0] = true; abort(); } } else if (Settings.TREAT_USER_AUTHORITIES_AS_ROLES) { try { UserDetails userDetails = cache.getIfPresent(sid); if (userDetails == null) { userDetails = Jenkins.get().getSecurityRealm().loadUserByUsername2(sid); cache.put(sid, userDetails); } for (GrantedAuthority grantedAuthority : userDetails.getAuthorities()) { if (grantedAuthority.getAuthority().equals(current.getName())) { hasPermission[0] = true; abort(); return; } } } catch (RuntimeException ex) { // There maybe issues in the logic, which lead to IllegalStateException in Acegi // Security (JENKINS-35652) // So we want to ensure this method does not fail horribly in such case LOGGER.log(Level.WARNING, ""Unhandled exception during user authorities processing"", ex); } } } } }; return hasPermission[0]; }","[JENKINS-19934] fix project naming strategy (#179) * [JENKINS-19934] WIP fix project naming strategy The project naming strategy is currently not considering if the user has the permission to create a job with a given name at all. I just checks if the passed name matches any of the patterns. Also it doesn't consider the full name, e.g. when a project is created inside a folder. This can lead to the situtation that a user creates a job but is then unable to configure the job. This change will do the following: Prerequisites: - Rolebased project naming strategy is enabled. - for each role when create is enabled also configure and read should be enabled If a user has either globally or in any item role the create permission then he will see the ""New item"" link in the side panel. A user that has global create permissions can create jobs with any name. For a user that has create permission on one or more item roles the entered name is matched against the role and the users permissions. Current limitation is that it only works reliably via the UI. When trying to create a job via the CLI, there is no staplerrequest that can be used to find the parent item. So job creation via cli will fall back to the old behaviour and just check the item name itself. In case JENKINS-68602 gets resolved requests coming in via the CLI would also be properly checked. This also adds an admin monitor that warns when the role based project naming strategy is not enabled. * fix javadoc ref * add more tests * fix group resolution can't use the code path from authorities as roles that is wrong. Add tests that verify group permissions work properly * fix javadoc * code cleanup * optimize checking create permission * update documentation * remove unused method * fix formatting * exclude macro roles from naming check * add tests * adjust readme",https://github.com/jenkinsci/role-strategy-plugin/commit/b60076577ec7fed7ff9286966e2b56dad7a65c90,,,src/main/java/com/michelin/cio/hudson/plugins/rolestrategy/RoleMap.java,3,java,False,2022-07-28T12:06:01Z "private boolean isSymlink(File f) { try { String canonicalPath = f.getCanonicalPath(); return f.isDirectory() && !canonicalPath.contains(f.getAbsolutePath()); } catch (IOException e) { } return false; }","private boolean isSymlink(File f) { try { String canonicalPath = f.getCanonicalPath(); String absolutePath = f.getAbsolutePath(); if (isWindows) { canonicalPath = canonicalPath.toUpperCase(); absolutePath = absolutePath.toUpperCase(); } return f.isDirectory() && !canonicalPath.contains(absolutePath); } catch (IOException e) { } return false; }","fixed broken directory traversal on windows, v1.2.5",https://github.com/logpresso/CVE-2021-44228-Scanner/commit/6e97dbafaefac30413b81ecff2e0c6d445cf66dc,,,src/main/java/com/logpresso/scanner/Log4j2Scanner.java,3,java,False,2021-12-14T05:36:54Z "@EventHandler(ignoreCancelled = true) public void onPistonExtend(BlockPistonExtendEvent event) { boolean undone = false; // Immediately undo or commit any blocks involved for (Block block : event.getBlocks()) { BlockData undoData = controller.getModifiedBlock(block.getLocation()); if (undoData != null) { undone = true; UndoList undoList = undoData.getUndoList(); if (undoList.isScheduled()) { undoData.undo(false); } else { undoData.commit(); } } } // If we undid anything, cancel this event if (undone) { event.setCancelled(true); } }","@EventHandler(ignoreCancelled = true) public void onPistonExtend(BlockPistonExtendEvent event) { boolean undone = false; // Immediately undo or commit any blocks involved List blocks = new ArrayList<>(event.getBlocks()); // Look one past the line of moved blocks, in case it has been broken it will not be in this list // But it will in fact be modified by the exten, which seems like a flaw in this event and can cause // block dupe exploits if not handled. if (!blocks.isEmpty()) { blocks.add(blocks.get(blocks.size() - 1).getRelative(event.getDirection())); } for (Block block : blocks) { BlockData undoData = controller.getModifiedBlock(block.getLocation()); if (undoData != null) { undone = true; UndoList undoList = undoData.getUndoList(); if (undoList.isScheduled()) { undoData.undo(false); } else { undoData.commit(); } } } // If we undid anything, cancel this event if (undone) { event.setCancelled(true); } }",Fix yet another piston-related block dupe exploit,https://github.com/elBukkit/MagicPlugin/commit/ec640b5097a090e758bc162dcca1947836fdd93b,,,Magic/src/main/java/com/elmakers/mine/bukkit/magic/listener/BlockController.java,3,java,False,2022-05-02T19:54:55Z "@Override public Optional transform(ClassLoader classLoader, String className, ClassVisitor writer, TransformContext ctx) { if (""com.mojang.authlib.properties.Property"".equals(className)) { return Optional.of(new ClassVisitor(ASM9, writer) { @Override public MethodVisitor visitMethod(int access, String name, String desc, String signature, String[] exceptions) { if (""isSignatureValid"".equals(name) && ""(Ljava/security/PublicKey;)Z"".equals(desc)) { ctx.markModified(); MethodVisitor mv = super.visitMethod(access, name, desc, signature, exceptions); mv.visitCode(); mv.visitVarInsn(ALOAD, 0); mv.visitFieldInsn(GETFIELD, ""com/mojang/authlib/properties/Property"", ""value"", ""Ljava/lang/String;""); mv.visitVarInsn(ALOAD, 0); mv.visitFieldInsn(GETFIELD, ""com/mojang/authlib/properties/Property"", ""signature"", ""Ljava/lang/String;""); ctx.invokeCallback(mv, YggdrasilKeyTransformUnit.class, ""verifyPropertySignature""); mv.visitInsn(IRETURN); mv.visitMaxs(-1, -1); mv.visitEnd(); return null; } else { return super.visitMethod(access, name, desc, signature, exceptions); } } }); } else if (""com.mojang.authlib.yggdrasil.YggdrasilServicesKeyInfo"".equals(className)) { return Optional.of(new ClassVisitor(ASM9, writer) { @Override public MethodVisitor visitMethod(int access, String name, String desc, String signature, String[] exceptions) { if (""validateProperty"".equals(name) && ""(Lcom/mojang/authlib/properties/Property;)Z"".equals(desc)) { ctx.markModified(); MethodVisitor mv = super.visitMethod(access, name, desc, signature, exceptions); mv.visitCode(); mv.visitVarInsn(ALOAD, 1); mv.visitMethodInsn(INVOKEVIRTUAL, ""com/mojang/authlib/properties/Property"", ""getValue"", ""()Ljava/lang/String;"", false); mv.visitVarInsn(ALOAD, 1); mv.visitMethodInsn(INVOKEVIRTUAL, ""com/mojang/authlib/properties/Property"", ""getSignature"", ""()Ljava/lang/String;"", false); ctx.invokeCallback(mv, YggdrasilKeyTransformUnit.class, ""verifyPropertySignature""); mv.visitInsn(IRETURN); mv.visitMaxs(-1, -1); mv.visitEnd(); return null; } else { return super.visitMethod(access, name, desc, signature, exceptions); } } }); } else { return Optional.empty(); } }","@Override public Optional transform(ClassLoader classLoader, String className, ClassVisitor writer, TransformContext ctx) { if (""com.mojang.authlib.properties.Property"".equals(className)) { return Optional.of(new ClassVisitor(ASM9, writer) { @Override public MethodVisitor visitMethod(int access, String name, String desc, String signature, String[] exceptions) { if (""isSignatureValid"".equals(name) && ""(Ljava/security/PublicKey;)Z"".equals(desc)) { ctx.markModified(); MethodVisitor mv = super.visitMethod(access, name, desc, signature, exceptions); mv.visitCode(); mv.visitVarInsn(ALOAD, 0); mv.visitFieldInsn(GETFIELD, ""com/mojang/authlib/properties/Property"", ""value"", ""Ljava/lang/String;""); mv.visitVarInsn(ALOAD, 0); mv.visitFieldInsn(GETFIELD, ""com/mojang/authlib/properties/Property"", ""signature"", ""Ljava/lang/String;""); ctx.invokeCallback(mv, YggdrasilKeyTransformUnit.class, ""verifyPropertySignature""); mv.visitInsn(IRETURN); mv.visitMaxs(-1, -1); mv.visitEnd(); return null; } else { return super.visitMethod(access, name, desc, signature, exceptions); } } }); } else if (""com.mojang.authlib.yggdrasil.YggdrasilServicesKeyInfo"".equals(className)) { return Optional.of(new ClassVisitor(ASM9, writer) { @Override public MethodVisitor visitMethod(int access, String name, String desc, String signature, String[] exceptions) { if (""validateProperty"".equals(name) && ""(Lcom/mojang/authlib/properties/Property;)Z"".equals(desc)) { ctx.markModified(); MethodVisitor mv = super.visitMethod(access, name, desc, signature, exceptions); mv.visitCode(); mv.visitVarInsn(ALOAD, 1); mv.visitMethodInsn(INVOKEVIRTUAL, ""com/mojang/authlib/properties/Property"", ""getValue"", ""()Ljava/lang/String;"", false); mv.visitVarInsn(ALOAD, 1); mv.visitMethodInsn(INVOKEVIRTUAL, ""com/mojang/authlib/properties/Property"", ""getSignature"", ""()Ljava/lang/String;"", false); ctx.invokeCallback(mv, YggdrasilKeyTransformUnit.class, ""verifyPropertySignature""); mv.visitInsn(IRETURN); mv.visitMaxs(-1, -1); mv.visitEnd(); return null; } else if (""signature"".equals(name) && ""()Ljava/security/Signature;"".equals(desc)) { ctx.markModified(); MethodVisitor mv = super.visitMethod(access, name, desc, signature, exceptions); mv.visitCode(); ctx.invokeCallback(mv, YggdrasilKeyTransformUnit.class, ""createDummySignature""); mv.visitInsn(ARETURN); mv.visitMaxs(-1, -1); mv.visitEnd(); return null; } else { return super.visitMethod(access, name, desc, signature, exceptions); } } }); } else { return Optional.empty(); } }",Fix 1.19.1 insecure chat warning,https://github.com/yushijinhun/authlib-injector/commit/c8882173be0b34b67b4721b53ca1a05004da1fe8,,,src/main/java/moe/yushi/authlibinjector/transform/support/YggdrasilKeyTransformUnit.java,3,java,False,2022-08-04T16:21:00Z "@SuppressFBWarnings(value = ""NP_BOOLEAN_RETURN_NULL"", justification = ""As declared in Jenkins API"") @Override @CheckForNull protected Boolean hasPermission(Sid sid, Permission permission) { if (RoleMap.this.hasPermission(toString(sid), permission, roleType, item)) { if (item instanceof Item) { final ItemGroup parent = ((Item) item).getParent(); if (parent instanceof Item && (Item.DISCOVER.equals(permission) || Item.READ.equals(permission)) && shouldCheckParentPermissions()) { // For READ and DISCOVER permission checks, do the same permission check on the // parent Permission requiredPermissionOnParent = permission == Item.DISCOVER ? Item.DISCOVER : Item.READ; if (!((Item) parent).hasPermission(requiredPermissionOnParent)) { return null; } } } return true; } return null; }","@SuppressFBWarnings(value = ""NP_BOOLEAN_RETURN_NULL"", justification = ""As declared in Jenkins API"") @Override @CheckForNull protected Boolean hasPermission(Sid sid, Permission permission) { if (RoleMap.this.hasPermission(toString(sid), permission, roleType, item)) { if (item instanceof Item) { final ItemGroup parent = ((Item) item).getParent(); if (parent instanceof Item && (Item.DISCOVER.equals(permission) || Item.READ.equals(permission)) && shouldCheckParentPermissions()) { // For READ and DISCOVER permission checks, do the same permission check on the // parent Permission requiredPermissionOnParent = permission == Item.DISCOVER ? Item.DISCOVER : Item.READ; if (!((Item) parent).hasPermission(requiredPermissionOnParent)) { return null; } } } return true; } // For Item.CREATE // We need to find out if the given user has anywhere permission to create something // not just in the current roletype, this can only reliably work when the project naming // strategy is set to the role based naming strategy if (permission == Item.CREATE && item == null) { AuthorizationStrategy auth = Jenkins.get().getAuthorizationStrategy(); ProjectNamingStrategy pns = Jenkins.get().getProjectNamingStrategy(); if (auth instanceof RoleBasedAuthorizationStrategy && pns instanceof RoleBasedProjectNamingStrategy) { RoleBasedAuthorizationStrategy rbas = (RoleBasedAuthorizationStrategy) auth; RoleMap roleMapProject = rbas.getRoleMap(RoleType.Project); if (roleMapProject.hasPermission(toString(sid), permission, RoleType.Project, item)) { return true; } } } return null; }","[JENKINS-19934] fix project naming strategy (#179) * [JENKINS-19934] WIP fix project naming strategy The project naming strategy is currently not considering if the user has the permission to create a job with a given name at all. I just checks if the passed name matches any of the patterns. Also it doesn't consider the full name, e.g. when a project is created inside a folder. This can lead to the situtation that a user creates a job but is then unable to configure the job. This change will do the following: Prerequisites: - Rolebased project naming strategy is enabled. - for each role when create is enabled also configure and read should be enabled If a user has either globally or in any item role the create permission then he will see the ""New item"" link in the side panel. A user that has global create permissions can create jobs with any name. For a user that has create permission on one or more item roles the entered name is matched against the role and the users permissions. Current limitation is that it only works reliably via the UI. When trying to create a job via the CLI, there is no staplerrequest that can be used to find the parent item. So job creation via cli will fall back to the old behaviour and just check the item name itself. In case JENKINS-68602 gets resolved requests coming in via the CLI would also be properly checked. This also adds an admin monitor that warns when the role based project naming strategy is not enabled. * fix javadoc ref * add more tests * fix group resolution can't use the code path from authorities as roles that is wrong. Add tests that verify group permissions work properly * fix javadoc * code cleanup * optimize checking create permission * update documentation * remove unused method * fix formatting * exclude macro roles from naming check * add tests * adjust readme",https://github.com/jenkinsci/role-strategy-plugin/commit/b60076577ec7fed7ff9286966e2b56dad7a65c90,,,src/main/java/com/michelin/cio/hudson/plugins/rolestrategy/RoleMap.java,3,java,False,2022-07-28T12:06:01Z "private void startStream() { final StreamsBuilder builder = new StreamsBuilder(); builder.table(new ApplicationCommunicationWebhooks().name(), Materialized.as(webhooksStore)); // channel.updated builder.stream(new ApplicationCommunicationChannels().name()) .foreach((channelId, channel) -> onRecord(ChannelUpdated.fromChannel(channel))); final KTable metadataTable = builder.table(new ApplicationCommunicationMetadata().name()) .groupBy((metadataId, metadata) -> KeyValue.pair(getSubject(metadata).getIdentifier(), metadata)) .aggregate(MetadataMap::new, MetadataMap::adder, MetadataMap::subtractor); final KStream messageStream = builder.stream(new ApplicationCommunicationMessages().name()); // message.created messageStream.filter((messageId, message) -> message != null && isNewMessage(message)) .foreach((messageId, message) -> onRecord(MessageCreated.fromMessage(message))); final KTable messageTable = messageStream.toTable() .leftJoin(metadataTable, (message, metadataMap) -> MessageContainer.builder() .message(message) .metadataMap(Optional.ofNullable(metadataMap).orElse(new MetadataMap())) .build()); // message.updated messageTable.toStream() .foreach((messageId, messageContainer) -> onRecord(MessageUpdated.fromMessageContainer(messageContainer))); // conversation.updated messageTable.groupBy((messageId, messageContainer) -> KeyValue.pair(messageContainer.getMessage().getConversationId(), messageContainer)) .aggregate(Conversation::new, (conversationId, container, aggregate) -> { if (aggregate.getLastMessageContainer() == null) { aggregate = Conversation.builder() .lastMessageContainer(container) .createdAt(container.getMessage().getSentAt()) // Set this only once for the sent time of the first message .build(); } // equals because messages can be updated if (container.getMessage().getSentAt() >= aggregate.getLastMessageContainer().getMessage().getSentAt()) { aggregate.setLastMessageContainer(container); } return aggregate; }, (conversationId, container, aggregate) -> { // If the deleted message was the last message we have no way of replacing it // so we have no choice but to keep it return aggregate; }) .leftJoin(metadataTable, (conversation, metadataMap) -> { if (metadataMap != null) { return conversation.toBuilder() .metadataMap(metadataMap) .build(); } return conversation; }) .toStream() .foreach((conversationId, conversation) -> onRecord(ConversationUpdated.fromConversation(conversation))); streams.start(builder.build(), appId); }","private void startStream() { final StreamsBuilder builder = new StreamsBuilder(); builder.table(new ApplicationCommunicationWebhooks().name(), Materialized.as(webhooksStore)); // channel.updated builder.stream(new ApplicationCommunicationChannels().name()) .foreach((channelId, channel) -> onRecord(ChannelUpdated.fromChannel(channel))); final KTable metadataTable = builder.table(new ApplicationCommunicationMetadata().name()) .groupBy((metadataId, metadata) -> KeyValue.pair(getSubject(metadata).getIdentifier(), metadata)) .aggregate(MetadataMap::new, MetadataMap::adder, MetadataMap::subtractor); final KStream messageStream = builder.stream(new ApplicationCommunicationMessages().name()); // message.created messageStream.filter((messageId, message) -> message != null && isNewMessage(message)) .foreach((messageId, message) -> onRecord(MessageCreated.fromMessage(message))); final KTable messageTable = messageStream.toTable() .leftJoin(metadataTable, (message, metadataMap) -> MessageContainer.builder() .message(message) .metadataMap(Optional.ofNullable(metadataMap).orElse(new MetadataMap())) .build()); // message.updated messageTable.toStream() .foreach((messageId, messageContainer) -> { if (messageContainer != null) { onRecord(MessageUpdated.fromMessageContainer(messageContainer)); } }); // conversation.updated messageTable.groupBy((messageId, messageContainer) -> KeyValue.pair(messageContainer.getMessage().getConversationId(), messageContainer)) .aggregate(Conversation::new, (conversationId, container, aggregate) -> { if (aggregate.getLastMessageContainer() == null) { aggregate = Conversation.builder() .lastMessageContainer(container) .createdAt(container.getMessage().getSentAt()) // Set this only once for the sent time of the first message .build(); } // equals because messages can be updated if (container.getMessage().getSentAt() >= aggregate.getLastMessageContainer().getMessage().getSentAt()) { aggregate.setLastMessageContainer(container); } return aggregate; }, (conversationId, container, aggregate) -> { // If the deleted message was the last message we have no way of replacing it // so we have no choice but to keep it return aggregate; }) .leftJoin(metadataTable, (conversation, metadataMap) -> { if (metadataMap != null) { return conversation.toBuilder() .metadataMap(metadataMap) .build(); } return conversation; }) .toStream() .foreach((conversationId, conversation) -> onRecord(ConversationUpdated.fromConversation(conversation))); streams.start(builder.build(), appId); }",[#2337] Fix webhook publisher crash for deleted messages (#2340),https://github.com/airyhq/airy/commit/15d381951de9fc0f5def72c2ef0b9a36ff5e026b,,,backend/webhook/publisher/src/main/java/co/airy/core/webhook/publisher/Stores.java,3,java,False,2021-08-27T10:02:09Z "@SuppressWarnings(""removal"") @Nullable private static IRecipeTransferError transferRecipe( RecipeTransferManager recipeTransferManager, C container, IRecipeLayoutInternal recipeLayout, Player player, boolean maxTransfer, boolean doTransfer ) { if (Internal.getRuntime().isEmpty()) { return RecipeTransferErrorInternal.INSTANCE; } IRecipeCategory recipeCategory = recipeLayout.getRecipeCategory(); final IRecipeTransferHandler transferHandler = recipeTransferManager.getRecipeTransferHandler(container, recipeCategory); if (transferHandler == null) { if (doTransfer) { LOGGER.error(""No Recipe Transfer handler for container {}"", container.getClass()); } return RecipeTransferErrorInternal.INSTANCE; } RecipeSlots recipeSlots = recipeLayout.getRecipeSlots(); IRecipeSlotsView recipeSlotsView = recipeSlots.getView(); try { return transferHandler.transferRecipe(container, recipeLayout.getRecipe(), recipeSlotsView, player, maxTransfer, doTransfer); } catch (UnsupportedOperationException ignored) { // old handlers do not support calling the new transferRecipe method. // call the legacy method instead return transferHandler.transferRecipe(container, recipeLayout.getRecipe(), recipeLayout.getLegacyAdapter(), player, maxTransfer, doTransfer); } }","@SuppressWarnings(""removal"") @Nullable private static IRecipeTransferError transferRecipe( RecipeTransferManager recipeTransferManager, C container, IRecipeLayoutInternal recipeLayout, Player player, boolean maxTransfer, boolean doTransfer ) { if (Internal.getRuntime().isEmpty()) { return RecipeTransferErrorInternal.INSTANCE; } IRecipeCategory recipeCategory = recipeLayout.getRecipeCategory(); final IRecipeTransferHandler transferHandler = recipeTransferManager.getRecipeTransferHandler(container, recipeCategory); if (transferHandler == null) { if (doTransfer) { LOGGER.error(""No Recipe Transfer handler for container {}"", container.getClass()); } return RecipeTransferErrorInternal.INSTANCE; } RecipeSlots recipeSlots = recipeLayout.getRecipeSlots(); IRecipeSlotsView recipeSlotsView = recipeSlots.getView(); try { try { return transferHandler.transferRecipe(container, recipeLayout.getRecipe(), recipeSlotsView, player, maxTransfer, doTransfer); } catch (UnsupportedOperationException ignored) { // old handlers do not support calling the new transferRecipe method. // call the legacy method instead return transferHandler.transferRecipe(container, recipeLayout.getRecipe(), recipeLayout.getLegacyAdapter(), player, maxTransfer, doTransfer); } } catch (RuntimeException e) { LOGGER.error( ""Recipe transfer handler '{}' for container '{}' and recipe '{}' threw an error: "", transferHandler.getClass(), transferHandler.getContainerClass(), transferHandler.getRecipeClass(), e ); return RecipeTransferErrorInternal.INSTANCE; } }",Fix #2890 Protect against broken recipe transfer handlers crashing,https://github.com/mezz/JustEnoughItems/commit/96fe3cd675109e497c49f0674ffbee311d051267,,,Common/src/main/java/mezz/jei/common/transfer/RecipeTransferUtil.java,3,java,False,2022-07-14T00:42:01Z "private boolean isLauncherShowing(ActivityManager.RunningTaskInfo runningTaskInfo) { if (runningTaskInfo == null) { return false; } else { return runningTaskInfo.topActivity.equals(mDefaultHome); } }","private boolean isLauncherShowing(@Nullable ActivityManager.RunningTaskInfo runningTaskInfo) { if (runningTaskInfo == null || runningTaskInfo.topActivity == null) { return false; } else { return runningTaskInfo.topActivity.equals(mDefaultHome); } }","Fix PhoneStateMonitor crash Fixes an issue where PhoneStateMonitor could crash if the task stack changed and the new running task had a null top activity. Test: Tested locally BUG: 204516470 FIX: 204516470 Change-Id: I8880b6ed508d7985b709e43cd624aa0a20414d0c",https://github.com/omnirom/android_frameworks_base/commit/b9e01837ffc6b9b14d3d520fdb17af85a77e26e9,,,packages/SystemUI/src/com/android/systemui/assist/PhoneStateMonitor.java,3,java,False,2021-12-15T20:44:15Z "public List selectPeers(TunnelPoolSettings settings) { int length = getLength(settings); if (length < 0) return null; if ( (length == 0) && (settings.getLength()+settings.getLengthVariance() > 0) ) return null; List rv; boolean isInbound = settings.isInbound(); if (length > 0) { // special cases boolean v6Only = isIPv6Only(); boolean ntcpDisabled = isNTCPDisabled(); boolean ssuDisabled = isSSUDisabled(); boolean checkClosestHop = v6Only || ntcpDisabled || ssuDisabled; boolean hidden = ctx.router().isHidden() || ctx.router().getRouterInfo().getAddressCount() <= 0 || !ctx.commSystem().haveInboundCapacity(95); boolean hiddenInbound = hidden && isInbound; boolean hiddenOutbound = hidden && !isInbound; if (shouldSelectExplicit(settings)) return selectExplicit(settings, length); Set exclude = getExclude(isInbound, false); Set matches = new HashSet(length); if (length == 1) { // closest-hop restrictions if (checkClosestHop) { Set moreExclude = getClosestHopExclude(isInbound); if (moreExclude != null) exclude.addAll(moreExclude); } if (hiddenInbound) { // SANFP adds all not-connected to exclude, so make a copy Set SANFPExclude = new HashSet(exclude); ctx.profileOrganizer().selectActiveNotFailingPeers(1, SANFPExclude, matches); } if (matches.isEmpty()) { // ANFP does not fall back to non-connected ctx.profileOrganizer().selectFastPeers(length, exclude, matches, 0); } matches.remove(ctx.routerHash()); rv = new ArrayList(matches); } else { // build a tunnel using 4 subtiers. // For a 2-hop tunnel, the first hop comes from subtiers 0-1 and the last from subtiers 2-3. // For a longer tunnels, the first hop comes from subtier 0, the middle from subtiers 2-3, and the last from subtier 1. rv = new ArrayList(length + 1); SessionKey randomKey = settings.getRandomKey(); // OBEP or IB last hop // group 0 or 1 if two hops, otherwise group 0 Set lastHopExclude; if (isInbound) { // exclude existing OBEPs to get some diversity ? // closest-hop restrictions if (checkClosestHop) { Set moreExclude = getClosestHopExclude(false); if (moreExclude != null) { moreExclude.addAll(exclude); lastHopExclude = moreExclude; } else { lastHopExclude = exclude; } } else { lastHopExclude = exclude; } } else { lastHopExclude = exclude; } if (hiddenInbound) { // IB closest hop if (log.shouldInfo()) log.info(""CPS SANFP closest IB exclude "" + lastHopExclude.size()); // SANFP adds all not-connected to exclude, so make a copy Set SANFPExclude = new HashSet(lastHopExclude); ctx.profileOrganizer().selectActiveNotFailingPeers(1, SANFPExclude, matches); if (matches.isEmpty()) { if (log.shouldInfo()) log.info(""CPS SFP closest IB exclude "" + lastHopExclude.size()); // ANFP does not fall back to non-connected ctx.profileOrganizer().selectFastPeers(1, lastHopExclude, matches, randomKey, length == 2 ? SLICE_0_1 : SLICE_0); } } else if (hiddenOutbound) { // OBEP // check for hidden and outbound, and the paired (inbound) tunnel is zero-hop // if so, we need the OBEP to be connected to us, so we get the build reply back // This should be rare except at startup TunnelManagerFacade tmf = ctx.tunnelManager(); TunnelPool tp = tmf.getInboundPool(settings.getDestination()); boolean pickFurthest; if (tp != null) { pickFurthest = true; TunnelPoolSettings tps = tp.getSettings(); int len = tps.getLength(); if (len <= 0 || tps.getLengthOverride() == 0 || len + tps.getLengthVariance() <= 0) { // leave it true } else { List tunnels = tp.listTunnels(); if (!tunnels.isEmpty()) { for (TunnelInfo ti : tp.listTunnels()) { if (ti.getLength() > 1) { pickFurthest = false; break; } } } else { // no tunnels in the paired tunnel pool // BuildRequester will be using exploratory tp = tmf.getInboundExploratoryPool(); tps = tp.getSettings(); len = tps.getLength(); if (len <= 0 || tps.getLengthOverride() == 0 || len + tps.getLengthVariance() <= 0) { // leave it true } else { tunnels = tp.listTunnels(); if (!tunnels.isEmpty()) { for (TunnelInfo ti : tp.listTunnels()) { if (ti.getLength() > 1) { pickFurthest = false; break; } } } } } } } else { // shouldn't happen pickFurthest = false; } if (pickFurthest) { if (log.shouldInfo()) log.info(""CPS SANFP OBEP exclude "" + lastHopExclude.size()); // SANFP adds all not-connected to exclude, so make a copy Set SANFPExclude = new HashSet(lastHopExclude); ctx.profileOrganizer().selectActiveNotFailingPeers(1, SANFPExclude, matches); if (matches.isEmpty()) { // ANFP does not fall back to non-connected if (log.shouldInfo()) log.info(""CPS SFP OBEP exclude "" + lastHopExclude.size()); ctx.profileOrganizer().selectFastPeers(1, lastHopExclude, matches, randomKey, length == 2 ? SLICE_0_1 : SLICE_0); } } else { ctx.profileOrganizer().selectFastPeers(1, lastHopExclude, matches, randomKey, length == 2 ? SLICE_0_1 : SLICE_0); } } else { // TODO exclude IPv6-only at OBEP? Caught in checkTunnel() below ctx.profileOrganizer().selectFastPeers(1, lastHopExclude, matches, randomKey, length == 2 ? SLICE_0_1 : SLICE_0); } matches.remove(ctx.routerHash()); exclude.addAll(matches); rv.addAll(matches); matches.clear(); if (length > 2) { // middle hop(s) // group 2 or 3 ctx.profileOrganizer().selectFastPeers(length - 2, exclude, matches, randomKey, SLICE_2_3); matches.remove(ctx.routerHash()); if (matches.size() > 1) { // order the middle peers for tunnels >= 4 hops List ordered = new ArrayList(matches); orderPeers(ordered, randomKey); rv.addAll(ordered); } else { rv.addAll(matches); } exclude.addAll(matches); matches.clear(); } // IBGW or OB first hop // group 2 or 3 if two hops, otherwise group 1 if (!isInbound) { // exclude existing IBGWs to get some diversity ? // closest-hop restrictions if (checkClosestHop) { Set moreExclude = getClosestHopExclude(true); if (moreExclude != null) exclude.addAll(moreExclude); } } // TODO exclude IPv6-only at IBGW? Caught in checkTunnel() below ctx.profileOrganizer().selectFastPeers(1, exclude, matches, randomKey, length == 2 ? SLICE_2_3 : SLICE_1); matches.remove(ctx.routerHash()); rv.addAll(matches); } } else { rv = new ArrayList(1); } //if (length != rv.size() && log.shouldWarn()) // log.warn(""CPS requested "" + length + "" got "" + rv.size() + "": "" + DataHelper.toString(rv)); //else if (log.shouldDebug()) // log.debug(""EPS result: "" + DataHelper.toString(rv)); if (isInbound) rv.add(0, ctx.routerHash()); else rv.add(ctx.routerHash()); if (rv.size() > 1) { if (!checkTunnel(isInbound, rv)) rv = null; } return rv; }","public List selectPeers(TunnelPoolSettings settings) { int length = getLength(settings); if (length < 0) return null; if ( (length == 0) && (settings.getLength()+settings.getLengthVariance() > 0) ) return null; List rv; boolean isInbound = settings.isInbound(); if (length > 0) { // special cases boolean v6Only = isIPv6Only(); boolean ntcpDisabled = isNTCPDisabled(); boolean ssuDisabled = isSSUDisabled(); boolean checkClosestHop = v6Only || ntcpDisabled || ssuDisabled; boolean hidden = ctx.router().isHidden() || ctx.router().getRouterInfo().getAddressCount() <= 0 || !ctx.commSystem().haveInboundCapacity(95); boolean hiddenInbound = hidden && isInbound; boolean hiddenOutbound = hidden && !isInbound; int ipRestriction = (ctx.getBooleanProperty(""i2np.allowLocal"") || length <= 1) ? 0 : settings.getIPRestriction(); MaskedIPSet ipSet = ipRestriction > 0 ? new MaskedIPSet(16) : null; if (shouldSelectExplicit(settings)) return selectExplicit(settings, length); Set exclude = getExclude(isInbound, false); Set matches = new HashSet(length); if (length == 1) { // closest-hop restrictions if (checkClosestHop) { Set moreExclude = getClosestHopExclude(isInbound); if (moreExclude != null) exclude.addAll(moreExclude); } // 1-hop, IP restrictions not required here if (hiddenInbound) { // SANFP adds all not-connected to exclude, so make a copy Set SANFPExclude = new HashSet(exclude); ctx.profileOrganizer().selectActiveNotFailingPeers(1, SANFPExclude, matches); } if (matches.isEmpty()) { // ANFP does not fall back to non-connected ctx.profileOrganizer().selectFastPeers(length, exclude, matches); } matches.remove(ctx.routerHash()); rv = new ArrayList(matches); } else { // build a tunnel using 4 subtiers. // For a 2-hop tunnel, the first hop comes from subtiers 0-1 and the last from subtiers 2-3. // For a longer tunnels, the first hop comes from subtier 0, the middle from subtiers 2-3, and the last from subtier 1. rv = new ArrayList(length + 1); SessionKey randomKey = settings.getRandomKey(); // OBEP or IB last hop // group 0 or 1 if two hops, otherwise group 0 Set lastHopExclude; if (isInbound) { // exclude existing OBEPs to get some diversity ? // closest-hop restrictions if (checkClosestHop) { Set moreExclude = getClosestHopExclude(false); if (moreExclude != null) { moreExclude.addAll(exclude); lastHopExclude = moreExclude; } else { lastHopExclude = exclude; } } else { lastHopExclude = exclude; } } else { lastHopExclude = exclude; } if (hiddenInbound) { // IB closest hop if (log.shouldInfo()) log.info(""CPS SANFP closest IB exclude "" + lastHopExclude.size()); // SANFP adds all not-connected to exclude, so make a copy Set SANFPExclude = new HashSet(lastHopExclude); ctx.profileOrganizer().selectActiveNotFailingPeers(1, SANFPExclude, matches, ipRestriction, ipSet); if (matches.isEmpty()) { if (log.shouldInfo()) log.info(""CPS SFP closest IB exclude "" + lastHopExclude.size()); // ANFP does not fall back to non-connected ctx.profileOrganizer().selectFastPeers(1, lastHopExclude, matches, randomKey, length == 2 ? SLICE_0_1 : SLICE_0, ipRestriction, ipSet); } } else if (hiddenOutbound) { // OBEP // check for hidden and outbound, and the paired (inbound) tunnel is zero-hop // if so, we need the OBEP to be connected to us, so we get the build reply back // This should be rare except at startup TunnelManagerFacade tmf = ctx.tunnelManager(); TunnelPool tp = tmf.getInboundPool(settings.getDestination()); boolean pickFurthest; if (tp != null) { pickFurthest = true; TunnelPoolSettings tps = tp.getSettings(); int len = tps.getLength(); if (len <= 0 || tps.getLengthOverride() == 0 || len + tps.getLengthVariance() <= 0) { // leave it true } else { List tunnels = tp.listTunnels(); if (!tunnels.isEmpty()) { for (TunnelInfo ti : tp.listTunnels()) { if (ti.getLength() > 1) { pickFurthest = false; break; } } } else { // no tunnels in the paired tunnel pool // BuildRequester will be using exploratory tp = tmf.getInboundExploratoryPool(); tps = tp.getSettings(); len = tps.getLength(); if (len <= 0 || tps.getLengthOverride() == 0 || len + tps.getLengthVariance() <= 0) { // leave it true } else { tunnels = tp.listTunnels(); if (!tunnels.isEmpty()) { for (TunnelInfo ti : tp.listTunnels()) { if (ti.getLength() > 1) { pickFurthest = false; break; } } } } } } } else { // shouldn't happen pickFurthest = false; } if (pickFurthest) { if (log.shouldInfo()) log.info(""CPS SANFP OBEP exclude "" + lastHopExclude.size()); // SANFP adds all not-connected to exclude, so make a copy Set SANFPExclude = new HashSet(lastHopExclude); ctx.profileOrganizer().selectActiveNotFailingPeers(1, SANFPExclude, matches, ipRestriction, ipSet); if (matches.isEmpty()) { // ANFP does not fall back to non-connected if (log.shouldInfo()) log.info(""CPS SFP OBEP exclude "" + lastHopExclude.size()); ctx.profileOrganizer().selectFastPeers(1, lastHopExclude, matches, randomKey, length == 2 ? SLICE_0_1 : SLICE_0, ipRestriction, ipSet); } } else { ctx.profileOrganizer().selectFastPeers(1, lastHopExclude, matches, randomKey, length == 2 ? SLICE_0_1 : SLICE_0, ipRestriction, ipSet); } } else { // TODO exclude IPv6-only at OBEP? Caught in checkTunnel() below ctx.profileOrganizer().selectFastPeers(1, lastHopExclude, matches, randomKey, length == 2 ? SLICE_0_1 : SLICE_0, ipRestriction, ipSet); } matches.remove(ctx.routerHash()); exclude.addAll(matches); rv.addAll(matches); matches.clear(); if (length > 2) { // middle hop(s) // group 2 or 3 ctx.profileOrganizer().selectFastPeers(length - 2, exclude, matches, randomKey, SLICE_2_3, ipRestriction, ipSet); matches.remove(ctx.routerHash()); if (matches.size() > 1) { // order the middle peers for tunnels >= 4 hops List ordered = new ArrayList(matches); orderPeers(ordered, randomKey); rv.addAll(ordered); } else { rv.addAll(matches); } exclude.addAll(matches); matches.clear(); } // IBGW or OB first hop // group 2 or 3 if two hops, otherwise group 1 if (!isInbound) { // exclude existing IBGWs to get some diversity ? // closest-hop restrictions if (checkClosestHop) { Set moreExclude = getClosestHopExclude(true); if (moreExclude != null) exclude.addAll(moreExclude); } } // TODO exclude IPv6-only at IBGW? Caught in checkTunnel() below ctx.profileOrganizer().selectFastPeers(1, exclude, matches, randomKey, length == 2 ? SLICE_2_3 : SLICE_1, ipRestriction, ipSet); matches.remove(ctx.routerHash()); rv.addAll(matches); } } else { rv = new ArrayList(1); } //if (length != rv.size() && log.shouldWarn()) // log.warn(""CPS requested "" + length + "" got "" + rv.size() + "": "" + DataHelper.toString(rv)); //else if (log.shouldDebug()) // log.debug(""EPS result: "" + DataHelper.toString(rv)); if (isInbound) rv.add(0, ctx.routerHash()); else rv.add(ctx.routerHash()); if (rv.size() > 1) { if (!checkTunnel(isInbound, rv)) rv = null; } return rv; }","Tunnels: Restore support for IP restriction in client tunnels (MR !45) Removed in May 2011 when we added fast tier slices Also add support in exploratory tunnels Create MaskedIPSet in peer selectors, pass to ProfileOrganizer.selectXXX() for each call. Not required for one-hop tunnels. Disable for test networks (i2np.allowLocal) Reported by 'vulnerability_reports' http://zzz.i2p/topics/3215",https://github.com/i2p/i2p.i2p/commit/5995b0b7a75326d83998a657141ff1ddcbba5dd7,,,router/java/src/net/i2p/router/tunnel/pool/ClientPeerSelector.java,3,java,False,2021-12-18T11:14:09Z "private boolean isProcessing(Channel channel) { return mProcessingChains.containsKey(channel) && mProcessingChains.get(channel).isProcessing(); }","private boolean isProcessing(Channel channel) { boolean isProcessing = false; mLock.lock(); try { isProcessing = mProcessingChains.containsKey(channel) && mProcessingChains.get(channel).isProcessing(); } finally { mLock.unlock(); } return isProcessing; }","#1243 Updates USB tuner error handling to prevent stack overflow when tuner error occurs while streaming. (#1247) Co-authored-by: Dennis Sheirer ",https://github.com/DSheirer/sdrtrunk/commit/8bfb1d54702ce89f44094a76346e98f4b9f7e255,,,src/main/java/io/github/dsheirer/controller/channel/ChannelProcessingManager.java,3,java,False,2022-05-09T11:16:35Z "public static void damageItem(ItemStack stack, EntityLivingBase entity, int damage) { if (!(stack.getItem() instanceof IGTTool)) { stack.damageItem(damage, entity); } else { if (stack.getTagCompound() != null && stack.getTagCompound().getBoolean(UNBREAKABLE_KEY)) { return; } IGTTool tool = (IGTTool) stack.getItem(); if (!(entity instanceof EntityPlayer) || !((EntityPlayer) entity).capabilities.isCreativeMode) { if (tool.isElectric()) { int electricDamage = damage * ConfigHolder.machines.energyUsageMultiplier; IElectricItem electricItem = stack.getCapability(GregtechCapabilities.CAPABILITY_ELECTRIC_ITEM, null); if (electricItem != null) { electricItem.discharge(electricDamage, tool.getElectricTier(), true, false, false); if (electricItem.getCharge() > 0 && entity.getRNG().nextInt(100) > ConfigHolder.tools.rngDamageElectricTools) { return; } } else { throw new IllegalStateException(""Electric tool does not have an attached electric item capability.""); } } int unbreakingLevel = EnchantmentHelper.getEnchantmentLevel(Enchantments.UNBREAKING, stack); int negated = 0; for (int k = 0; unbreakingLevel > 0 && k < damage; k++) { if (EnchantmentDurability.negateDamage(stack, unbreakingLevel, entity.getRNG())) { negated++; } } damage -= negated; if (damage <= 0) { return; } int newDurability = stack.getItemDamage() + damage; if (entity instanceof EntityPlayerMP) { CriteriaTriggers.ITEM_DURABILITY_CHANGED.trigger((EntityPlayerMP) entity, stack, newDurability); } stack.setItemDamage(newDurability); if (newDurability > stack.getMaxDamage()) { if (entity instanceof EntityPlayer) { EntityPlayer entityplayer = (EntityPlayer) entity; entityplayer.addStat(StatList.getObjectBreakStats(stack.getItem())); } entity.renderBrokenItemStack(stack); stack.shrink(1); } } } }","public static void damageItem(@Nonnull ItemStack stack, @Nullable EntityLivingBase entity, int damage) { if (!(stack.getItem() instanceof IGTTool)) { if (entity != null) stack.damageItem(damage, entity); } else { if (stack.getTagCompound() != null && stack.getTagCompound().getBoolean(UNBREAKABLE_KEY)) { return; } IGTTool tool = (IGTTool) stack.getItem(); if (!(entity instanceof EntityPlayer) || !((EntityPlayer) entity).capabilities.isCreativeMode) { Random random = entity == null ? GTValues.RNG : entity.getRNG(); if (tool.isElectric()) { int electricDamage = damage * ConfigHolder.machines.energyUsageMultiplier; IElectricItem electricItem = stack.getCapability(GregtechCapabilities.CAPABILITY_ELECTRIC_ITEM, null); if (electricItem != null) { electricItem.discharge(electricDamage, tool.getElectricTier(), true, false, false); if (electricItem.getCharge() > 0 && random.nextInt(100) > ConfigHolder.tools.rngDamageElectricTools) { return; } } else { throw new IllegalStateException(""Electric tool does not have an attached electric item capability.""); } } int unbreakingLevel = EnchantmentHelper.getEnchantmentLevel(Enchantments.UNBREAKING, stack); int negated = 0; for (int k = 0; unbreakingLevel > 0 && k < damage; k++) { if (EnchantmentDurability.negateDamage(stack, unbreakingLevel, random)) { negated++; } } damage -= negated; if (damage <= 0) { return; } int newDurability = stack.getItemDamage() + damage; if (entity instanceof EntityPlayerMP) { CriteriaTriggers.ITEM_DURABILITY_CHANGED.trigger((EntityPlayerMP) entity, stack, newDurability); } stack.setItemDamage(newDurability); if (newDurability > stack.getMaxDamage()) { if (entity instanceof EntityPlayer) { StatBase stat = StatList.getObjectBreakStats(stack.getItem()); if (stat != null) { ((EntityPlayer) entity).addStat(stat); } } if (entity != null) { entity.renderBrokenItemStack(stack); } stack.shrink(1); } } } }",fix crash when damaging tools with null players (#1400),https://github.com/GregTechCEu/GregTech/commit/4fba4b48b3c2baee324f6510b7241ff8ce19401c,,,src/main/java/gregtech/api/items/toolitem/ToolHelper.java,3,java,False,2023-01-09T00:39:25Z "private void global(AdminPerformer performer, CommandParser.Arguments arguments) { performer.success(""Admin console usage""); performer.info(""For execute a command, simply type the command name, and add arguments separated by a single space.""); performer.error(""(!) The command and arguments are case sensitive, i.e. HELP and help are not the same !""); performer.info( ""Some commands needs a context to works. The context should be set in front of the command : [context] [command] [arguments...].\n"" + ""The context can define the target user or account. The contexts syntax are :\n"" + ""! - The current user\n"" + ""@John - The player 'John'\n"" + ""#Foo - The account 'Foo'\n"" + ""* - The server context\n"" + "": - Contains debug commands"" ); performer.success(""List of available commands :""); performer.info(""(i) You can click on the command name for open its help page""); for (Command command : arguments.context().commands()) { performer.info( ""{} - {}"", new Link() .text(command.name()) .execute((arguments.contextPath().isEmpty() ? """" : arguments.contextPath() + "" "") + arguments.command() + "" "" + command.name()), command.help().description() ); } }","private void global(AdminPerformer performer, CommandParser.Arguments arguments) { performer.success(""Admin console usage""); performer.info(""For execute a command, simply type the command name, and add arguments separated by a single space.""); performer.error(""(!) The command and arguments are case sensitive, i.e. HELP and help are not the same !""); performer.info( ""Some commands needs a context to works. The context should be set in front of the command : [context] [command] [arguments...].\n"" + ""The context can define the target user or account. The contexts syntax are :\n"" + ""! - The current user\n"" + ""@John - The player 'John'\n"" + ""#Foo - The account 'Foo'\n"" + ""* - The server context\n"" + "": - Contains debug commands"" ); performer.success(""List of available commands :""); performer.info(""(i) You can click on the command name for open its help page""); for (Command command : arguments.context().commands()) { if (!performer.isGranted(command.permissions())) { continue; } performer.info( ""{} - {}"", new Link() .text(command.name()) .execute((arguments.contextPath().isEmpty() ? """" : arguments.contextPath() + "" "") + arguments.command() + "" "" + command.name()), command.help().description() ); } }",close #181 Filter unauthorized commands on help,https://github.com/Arakne/Araknemu/commit/5e1642079225346e581f2f4454ad328fc435b93f,,,src/main/java/fr/quatrevieux/araknemu/game/admin/global/Help.java,3,java,False,2021-06-27T13:42:42Z "@Override public void draw(Canvas canvas) { int saveCount = canvas.saveLayer(0, 0, getIntrinsicWidth(), getIntrinsicHeight(), mPaint); if (mClipPath != null) { canvas.clipPath(mClipPath); } mAppWidgetHostView.draw(canvas); canvas.restoreToCount(saveCount); }","@Override public void draw(Canvas canvas) { int saveCount = canvas.saveLayer(0, 0, getIntrinsicWidth(), getIntrinsicHeight(), mPaint); if (mClipPath != null) { canvas.clipPath(mClipPath); } // If the view was never attached, or is current attached, then draw. Otherwise do not try // to draw, or we might trigger bugs with items that get drawn while requiring the view to // be attached. if (!mWasAttached || mAppWidgetHostView.isAttachedToWindow()) { mAppWidgetHostView.draw(canvas); } canvas.restoreToCount(saveCount); }","Prevent launcher crash when an App Widget is removed. If an App Widget with a scrollable element is removed, we may end up in a situation where we try to draw the view directly on a canvas while the it has already been detached from the workspace. This can crash as some of the drawing the scroll indicators require the view to be attached. In general, we should never draw a view by calling the draw method directly, even more so when the view is detached: the behavior is undefined as the method expects the canvas to be properly set up, and it is not. A crash can therefore be expected. This patch should avoid crashing the launcher until we stop doing that altogether. Fix: 183386115 Test: Manally add a view with a preview layout Test: Manually remove an app widget with a list view Change-Id: I8e1aa581700a08d6747eab085199c2b293e0e3fb",https://github.com/LineageOS/android_packages_apps_Trebuchet/commit/712a8bf0041dde1ee1611d2c107db1ce9fb11a47,,,src/com/android/launcher3/dragndrop/AppWidgetHostViewDrawable.java,3,java,False,2021-04-01T10:19:20Z "private void onAttackEntity(AttackEntityEvent event) { PlayerEntity player = event.getPlayer(); PlayerInventoryProvider.runOnBackpacks(player, (backpack, inventoryHandlerName, slot) -> backpack.getCapability(CapabilityBackpackWrapper.getCapabilityInstance()) .map(wrapper -> { for (IAttackEntityResponseUpgrade upgrade : wrapper.getUpgradeHandler().getWrappersThatImplement(IAttackEntityResponseUpgrade.class)) { if (upgrade.onAttackEntity(player)) { return true; } } return false; }).orElse(false)); }","private void onAttackEntity(AttackEntityEvent event) { PlayerEntity player = event.getPlayer(); if (player.level.isClientSide) { return; } PlayerInventoryProvider.runOnBackpacks(player, (backpack, inventoryHandlerName, slot) -> backpack.getCapability(CapabilityBackpackWrapper.getCapabilityInstance()) .map(wrapper -> { for (IAttackEntityResponseUpgrade upgrade : wrapper.getUpgradeHandler().getWrappersThatImplement(IAttackEntityResponseUpgrade.class)) { if (upgrade.onAttackEntity(player)) { return true; } } return false; }).orElse(false)); }",fix: 🐛 Only running block and entity click logic server side. Should prevent CMEs in player inventory providers as what I guess was happening is both render server thread triggering click logic at the same time and crashing on the CME because of that.,https://github.com/P3pp3rF1y/SophisticatedBackpacks/commit/607cca5a0b59b89d1b94e1235746a092894fac59,,,src/main/java/net/p3pp3rf1y/sophisticatedbackpacks/common/CommonProxy.java,3,java,False,2021-08-31T18:51:59Z "private static BlockPos rotate(BlockPos origin, int x, int y, EnumFacing sideHit, EnumFacing horizontalFacing) { switch (sideHit.getAxis()) { case X: return origin.add(0, y, x); case Z: return origin.add(x, y, 0); case Y: return rotateVertical(origin, x, y, horizontalFacing); default: return BlockPos.ORIGIN; } }","private static BlockPos rotate(BlockPos origin, int x, int y, EnumFacing sideHit, EnumFacing horizontalFacing) { if (sideHit == null) { return BlockPos.ORIGIN; } switch (sideHit.getAxis()) { case X: return origin.add(0, y, x); case Z: return origin.add(x, y, 0); case Y: return rotateVertical(origin, x, y, horizontalFacing); default: return BlockPos.ORIGIN; } }",Fix NullPointerException crash when using mining hammers on blocks supporting gravity-based blocks (#331),https://github.com/GregTechCEu/GregTech/commit/3a6a50826157bb5c65c21b7d1b39c8bed4d5bf80,,,src/main/java/gregtech/common/tools/ToolMiningHammer.java,3,java,False,2021-12-12T04:54:17Z "static inline void prefetch_table(const void *tab, size_t len) { const volatile byte *vtab = tab; size_t i; for (i = 0; i < len; i += 8 * 32) { (void)vtab[i + 0 * 32]; (void)vtab[i + 1 * 32]; (void)vtab[i + 2 * 32]; (void)vtab[i + 3 * 32]; (void)vtab[i + 4 * 32]; (void)vtab[i + 5 * 32]; (void)vtab[i + 6 * 32]; (void)vtab[i + 7 * 32]; } (void)vtab[len - 1]; }","static inline void prefetch_table(const void *tab, size_t len) { const volatile byte *vtab = tab; size_t i; for (i = 0; len - i >= 8 * 32; i += 8 * 32) { (void)vtab[i + 0 * 32]; (void)vtab[i + 1 * 32]; (void)vtab[i + 2 * 32]; (void)vtab[i + 3 * 32]; (void)vtab[i + 4 * 32]; (void)vtab[i + 5 * 32]; (void)vtab[i + 6 * 32]; (void)vtab[i + 7 * 32]; } for (; i < len; i += 32) { (void)vtab[i]; } (void)vtab[len - 1]; }","GCM: move look-up table to .data section and unshare between processes * cipher/cipher-gcm.c (ATTR_ALIGNED_64): New. (gcmR): Move to 'gcm_table' structure. (gcm_table): New structure for look-up table with counters before and after. (gcmR): New macro. (prefetch_table): Handle input with length not multiple of 256. (do_prefetch_tables): Modify pre- and post-table counters to unshare look-up table pages between processes. -- GnuPG-bug-id: 4541 Signed-off-by: Jussi Kivilinna ",https://github.com/gpg/libgcrypt/commit/a4c561aab1014c3630bc88faf6f5246fee16b020,,,cipher/cipher-gcm.c,3,c,False,2019-05-31T14:27:25Z "public Time getTime(int col) throws SQLException { DB db = getDatabase(); switch (db.column_type(stmt.pointer, markCol(col))) { case SQLITE_NULL: return null; case SQLITE_TEXT: try { return new Time( getConnectionConfig() .getDateFormat() .parse(db.column_text(stmt.pointer, markCol(col))) .getTime()); } catch (Exception e) { SQLException error = new SQLException(""Error parsing time""); error.initCause(e); throw error; } case SQLITE_FLOAT: return new Time( julianDateToCalendar(db.column_double(stmt.pointer, markCol(col))) .getTimeInMillis()); default: // SQLITE_INTEGER return new Time( db.column_long(stmt.pointer, markCol(col)) * getConnectionConfig().getDateMultiplier()); } }","public Time getTime(int col) throws SQLException { DB db = getDatabase(); switch (safeGetColumnType(markCol(col))) { case SQLITE_NULL: return null; case SQLITE_TEXT: try { return new Time( getConnectionConfig() .getDateFormat() .parse(safeGetColumnText(col)) .getTime()); } catch (Exception e) { SQLException error = new SQLException(""Error parsing time""); error.initCause(e); throw error; } case SQLITE_FLOAT: return new Time(julianDateToCalendar(safeGetDoubleCol(col)).getTimeInMillis()); default: // SQLITE_INTEGER return new Time(safeGetLongCol(col) * getConnectionConfig().getDateMultiplier()); } }",Wrap Statement Pointers to prevent use after free race,https://github.com/xerial/sqlite-jdbc/commit/e1d282cb2887ef427c7ad93d4fe7dd05a6c11473,,,src/main/java/org/sqlite/jdbc3/JDBC3ResultSet.java,3,java,False,2022-07-29T03:54:01Z "void client_reset(t_client *client) { char *hash; char *msg; char *cidinfo; debug(LOG_DEBUG, ""Resetting client [%s]"", client->mac); // Reset traffic counters client->counters.incoming = 0; client->counters.outgoing = 0; client->counters.last_updated = time(NULL); // Reset session time client->session_start = 0; client->session_end = 0; // Reset token and hid hash = safe_calloc(STATUS_BUF); client->token = safe_calloc(STATUS_BUF); safe_snprintf(client->token, STATUS_BUF, ""%04hx%04hx"", rand16(), rand16()); hash_str(hash, STATUS_BUF, client->token); client->hid = safe_strdup(hash); free(hash); // Reset custom and client_type client->custom = safe_calloc(MID_BUF); client->client_type = safe_calloc(STATUS_BUF); //Reset cid and remove cidfile using rmcid if (client->cid) { if (strlen(client->cid) > 0) { msg = safe_calloc(SMALL_BUF); cidinfo = safe_calloc(MID_BUF); safe_snprintf(cidinfo, MID_BUF, ""cid=\""%s\"""", client->cid); write_client_info(msg, SMALL_BUF, ""rmcid"", client->cid, cidinfo); free(msg); free(cidinfo); } client->cid = safe_calloc(SMALL_BUF); } }","void client_reset(t_client *client) { char *hash; char *msg; char *cidinfo; debug(LOG_DEBUG, ""Resetting client [%s]"", client->mac); // Reset traffic counters client->counters.incoming = 0; client->counters.outgoing = 0; client->counters.last_updated = time(NULL); // Reset session time client->session_start = 0; client->session_end = 0; // Reset token and hid hash = safe_calloc(STATUS_BUF); client->token = safe_calloc(STATUS_BUF); safe_snprintf(client->token, STATUS_BUF, ""%04hx%04hx"", rand16(), rand16()); hash_str(hash, STATUS_BUF, client->token); client->hid = safe_strdup(hash); free(hash); // Reset custom, client_type and cpi_query client->custom = safe_calloc(MID_BUF); client->client_type = safe_calloc(STATUS_BUF); if (!client->cpi_query) { client->cpi_query = safe_calloc(STATUS_BUF); } //Reset cid and remove cidfile using rmcid if (client->cid) { if (strlen(client->cid) > 0) { msg = safe_calloc(SMALL_BUF); cidinfo = safe_calloc(MID_BUF); safe_snprintf(cidinfo, MID_BUF, ""cid=\""%s\"""", client->cid); write_client_info(msg, SMALL_BUF, ""rmcid"", client->cid, cidinfo); free(msg); free(cidinfo); } } client->cid = safe_calloc(SMALL_BUF); }","Fix - memory leak when deleting client from client list Signed-off-by: Rob White ",https://github.com/openNDS/openNDS/commit/31dbf4aa069c5bb39a7926d86036ce3b04312b51,,,src/client_list.c,3,c,False,2023-09-16T10:51:21Z "private void uploadFile(HttpServletRequest request, ViewEditForm form) throws Exception { if (WebUtils.hasSubmitParameter(request, SUBMIT_UPLOAD)) { if (form.getBackgroundImageMP() != null) { byte[] bytes = form.getBackgroundImageMP().getBytes(); if (bytes != null && bytes.length > 0) { // Create the path to the upload directory. String path = request.getSession().getServletContext().getRealPath(uploadDirectory); LOG.info(""ViewEditController:uploadFile: realpath=""+path); // Make sure the directory exists. File dir = new File(path); dir.mkdirs(); boolean validExtension = false; String[] supportedExtensions = new String[] { ""gif"", ""jpg"", ""jpeg"", ""jfif"", ""pjpeg"", ""pjp"", ""png"", ""bmp"", ""dib"", ""svg"" }; String extension; int foo = form.getBackgroundImageMP().getOriginalFilename().lastIndexOf('.') + 1; extension = form.getBackgroundImageMP().getOriginalFilename().substring(foo); for (String s : supportedExtensions) { if (s.equals(extension.toLowerCase())) { validExtension = true; break; } } // Valid image! Add it to uploads if (validExtension) { int imageId = getNextImageId(dir); // Get an image id. String filename = Integer.toString(imageId); // Create the image file name. int dot = form.getBackgroundImageMP().getOriginalFilename().lastIndexOf('.'); if (dot != -1) filename += form.getBackgroundImageMP().getOriginalFilename().substring(dot); // Save the file. FileOutputStream fos = new FileOutputStream(new File(dir, filename)); fos.write(bytes); fos.close(); form.getView().setBackgroundFilename(uploadDirectory + filename); } } } } }","private void uploadFile(HttpServletRequest request, ViewEditForm form) throws Exception { if (WebUtils.hasSubmitParameter(request, SUBMIT_UPLOAD)) { if (form.getBackgroundImageMP() != null) { byte[] bytes = form.getBackgroundImageMP().getBytes(); if (bytes != null && bytes.length > 0) { // Create the path to the upload directory. String path = request.getSession().getServletContext().getRealPath(uploadDirectory); LOG.info(""ViewEditController:uploadFile: realpath=""+path); // Make sure the directory exists. File dir = new File(path); dir.mkdirs(); MultipartFile file = form.getBackgroundImageMP(); String fileName = file.getOriginalFilename(); if(fileName != null) { Stream.of(SUPPORTED_EXTENSIONS) .filter(fileName::endsWith) .findFirst() .ifPresent(ext -> { // Valid image! Add it to uploads int imageId = getNextImageId(dir); // Get an image id. String filename = imageId + ext; // Create the image file name. File image = new File(dir, filename); if(saveFile(bytes, image)) { // Save the file. form.getView().setBackgroundFilename(uploadDirectory + filename); LOG.info(""Image file has been successfully uploaded: "" + image.getName()); } else { LOG.warn(""Failed to save image file: "" + image.getName()); } }); } else { LOG.warn(""Image file not attached: "" + fileName); } } } } }",#1734 Vulnerabilities from ScadaBR - refactor,https://github.com/SCADA-LTS/Scada-LTS/commit/6309c15f40374cbab0a4be0bb3a4b78652d4200d,,,src/org/scada_lts/web/mvc/controller/ViewEditContorller.java,3,java,False,2022-02-15T12:23:09Z "public static void onClickSearchAction(Launcher launcher, SearchActionItemInfo itemInfo) { if (itemInfo.getIntent() != null) { if (itemInfo.hasFlags(SearchActionItemInfo.FLAG_SHOULD_START_FOR_RESULT)) { launcher.startActivityForResult(itemInfo.getIntent(), 0); } else { launcher.startActivity(itemInfo.getIntent()); } } else if (itemInfo.getPendingIntent() != null) { try { PendingIntent pendingIntent = itemInfo.getPendingIntent(); if (!itemInfo.hasFlags(SearchActionItemInfo.FLAG_SHOULD_START)) { pendingIntent.send(); } else if (itemInfo.hasFlags(SearchActionItemInfo.FLAG_SHOULD_START_FOR_RESULT)) { launcher.startIntentSenderForResult(pendingIntent.getIntentSender(), 0, null, 0, 0, 0); } else { launcher.startIntentSender(pendingIntent.getIntentSender(), null, 0, 0, 0); } } catch (PendingIntent.CanceledException | IntentSender.SendIntentException e) { Toast.makeText(launcher, launcher.getResources().getText(R.string.shortcut_not_available), Toast.LENGTH_SHORT).show(); } } if (itemInfo.hasFlags(SearchActionItemInfo.FLAG_SEARCH_IN_APP)) { launcher.getStatsLogManager().logger().withItemInfo(itemInfo).log( LAUNCHER_ALLAPPS_SEARCHINAPP_LAUNCH); } else { launcher.getStatsLogManager().logger().withItemInfo(itemInfo).log( LAUNCHER_APP_LAUNCH_TAP); } }","public static void onClickSearchAction(Launcher launcher, SearchActionItemInfo itemInfo) { if (itemInfo.getIntent() != null) { try { if (itemInfo.hasFlags(SearchActionItemInfo.FLAG_SHOULD_START_FOR_RESULT)) { launcher.startActivityForResult(itemInfo.getIntent(), 0); } else { launcher.startActivity(itemInfo.getIntent()); } } catch (ActivityNotFoundException e) { Toast.makeText(launcher, launcher.getResources().getText(R.string.shortcut_not_available), Toast.LENGTH_SHORT).show(); } } else if (itemInfo.getPendingIntent() != null) { try { PendingIntent pendingIntent = itemInfo.getPendingIntent(); if (!itemInfo.hasFlags(SearchActionItemInfo.FLAG_SHOULD_START)) { pendingIntent.send(); } else if (itemInfo.hasFlags(SearchActionItemInfo.FLAG_SHOULD_START_FOR_RESULT)) { launcher.startIntentSenderForResult(pendingIntent.getIntentSender(), 0, null, 0, 0, 0); } else { launcher.startIntentSender(pendingIntent.getIntentSender(), null, 0, 0, 0); } } catch (PendingIntent.CanceledException | IntentSender.SendIntentException e) { Toast.makeText(launcher, launcher.getResources().getText(R.string.shortcut_not_available), Toast.LENGTH_SHORT).show(); } } if (itemInfo.hasFlags(SearchActionItemInfo.FLAG_SEARCH_IN_APP)) { launcher.getStatsLogManager().logger().withItemInfo(itemInfo).log( LAUNCHER_ALLAPPS_SEARCHINAPP_LAUNCH); } else { launcher.getStatsLogManager().logger().withItemInfo(itemInfo).log( LAUNCHER_APP_LAUNCH_TAP); } }","Catch exception to prevent crash. Bug: 258234624 Test: QA verify Change-Id: I31df77b33f19426d136673d1ce9866fa6e60729c",https://github.com/LawnchairLauncher/lawnchair/commit/259723de32428a62f518263c3079ba0e4eba29e4,,,src/com/android/launcher3/touch/ItemClickHandler.java,3,java,False,2022-11-22T19:54:13Z "void luaD_call (lua_State *L, StkId func, int nresults) { lua_CFunction f; retry: switch (ttypetag(s2v(func))) { case LUA_VCCL: /* C closure */ f = clCvalue(s2v(func))->f; goto Cfunc; case LUA_VLCF: /* light C function */ f = fvalue(s2v(func)); Cfunc: { int n; /* number of returns */ CallInfo *ci = next_ci(L); checkstackp(L, LUA_MINSTACK, func); /* ensure minimum stack size */ ci->nresults = nresults; ci->callstatus = CIST_C; ci->top = L->top + LUA_MINSTACK; ci->func = func; L->ci = ci; lua_assert(ci->top <= L->stack_last); if (L->hookmask & LUA_MASKCALL) { int narg = cast_int(L->top - func) - 1; luaD_hook(L, LUA_HOOKCALL, -1, 1, narg); } lua_unlock(L); n = (*f)(L); /* do the actual call */ lua_lock(L); api_checknelems(L, n); luaD_poscall(L, ci, n); break; } case LUA_VLCL: { /* Lua function */ CallInfo *ci = next_ci(L); Proto *p = clLvalue(s2v(func))->p; int narg = cast_int(L->top - func) - 1; /* number of real arguments */ int nfixparams = p->numparams; int fsize = p->maxstacksize; /* frame size */ checkstackp(L, fsize, func); ci->nresults = nresults; ci->u.l.savedpc = p->code; /* starting point */ ci->callstatus = 0; ci->top = func + 1 + fsize; ci->func = func; L->ci = ci; for (; narg < nfixparams; narg++) setnilvalue(s2v(L->top++)); /* complete missing arguments */ lua_assert(ci->top <= L->stack_last); luaV_execute(L, ci); /* run the function */ break; } default: { /* not a function */ checkstackp(L, 1, func); /* space for metamethod */ luaD_tryfuncTM(L, func); /* try to get '__call' metamethod */ goto retry; /* try again with metamethod */ } } }","void luaD_call (lua_State *L, StkId func, int nresults) { lua_CFunction f; retry: switch (ttypetag(s2v(func))) { case LUA_VCCL: /* C closure */ f = clCvalue(s2v(func))->f; goto Cfunc; case LUA_VLCF: /* light C function */ f = fvalue(s2v(func)); Cfunc: { int n; /* number of returns */ CallInfo *ci; checkstackGCp(L, LUA_MINSTACK, func); /* ensure minimum stack size */ L->ci = ci = next_ci(L); ci->nresults = nresults; ci->callstatus = CIST_C; ci->top = L->top + LUA_MINSTACK; ci->func = func; lua_assert(ci->top <= L->stack_last); if (L->hookmask & LUA_MASKCALL) { int narg = cast_int(L->top - func) - 1; luaD_hook(L, LUA_HOOKCALL, -1, 1, narg); } lua_unlock(L); n = (*f)(L); /* do the actual call */ lua_lock(L); api_checknelems(L, n); luaD_poscall(L, ci, n); break; } case LUA_VLCL: { /* Lua function */ CallInfo *ci; Proto *p = clLvalue(s2v(func))->p; int narg = cast_int(L->top - func) - 1; /* number of real arguments */ int nfixparams = p->numparams; int fsize = p->maxstacksize; /* frame size */ checkstackGCp(L, fsize, func); L->ci = ci = next_ci(L); ci->nresults = nresults; ci->u.l.savedpc = p->code; /* starting point */ ci->callstatus = 0; ci->top = func + 1 + fsize; ci->func = func; L->ci = ci; for (; narg < nfixparams; narg++) setnilvalue(s2v(L->top++)); /* complete missing arguments */ lua_assert(ci->top <= L->stack_last); luaV_execute(L, ci); /* run the function */ break; } default: { /* not a function */ checkstackGCp(L, 1, func); /* space for metamethod */ luaD_tryfuncTM(L, func); /* try to get '__call' metamethod */ goto retry; /* try again with metamethod */ } } }","Fixed bugs of stack reallocation x GC Macro 'checkstackGC' was doing a GC step after resizing the stack; the GC could shrink the stack and undo the resize. Moreover, macro 'checkstackp' also does a GC step, which could remove the preallocated CallInfo when calling a function. (Its name has been changed to 'checkstackGCp' to emphasize that it calls the GC.)",https://github.com/lua/lua/commit/eb41999461b6f428186c55abd95f4ce1a76217d5,,,ldo.c,3,c,False,2020-07-07T21:03:48Z "private static TypeDef projectDefinition(ClassRef ref) { List arguments = ref.getArguments(); TypeDef definition = GetDefinition.of(ref); if (arguments.isEmpty()) { return definition; } List parameters = definition.getParameters(); Map mappings = new HashMap<>(); for (int i = 0; i < arguments.size(); i++) { String name = parameters.get(i).getName(); TypeRef typeRef = arguments.get(i); mappings.put(name, typeRef); } return new TypeDefBuilder(definition) .accept(mapClassRefArguments(mappings), mapGenericProperties(mappings)) .build(); }","private static TypeDef projectDefinition(ClassRef ref) { TypeDef definition = GetDefinition.of(ref); Map mappings = TypeArguments.getGenericArgumentsMappings(ref, definition); if (mappings.isEmpty()) { return definition; } else { return new TypeDefBuilder(definition) .accept(new ApplyTypeParamMappingToTypeArguments(mappings)) // existing type arguments must be handled before methods and properties .accept(new ApplyTypeParamMappingToProperty(mappings), new ApplyTypeParamMappingToMethod(mappings)) .build(); } }","fix: Stack overflow on multimaps (and other non-trivial generic classes), schema for multimaps is wrong Logic in sundrio that is responsible for replacing generic type arguments on methods and properties with their concrete instantiations from subclasses contained a bug, in which it looped infinitely if the same type argument name was used at multiple classes in the hierarchy. A common occurence were multimaps. A very similar code was also present in crd-generator, also suffering from the same bug. Sundrio has been updated to account for this situation, and updated utilities from sundrio have been introduced to crd-generator, which replace the previous implementation of the same algorithm. A test has been added to validate that multimaps (like `class MultiMap implements Map>`) are generated correctly. Fixes fabric8io/kubernetes-client#4357 Fixes fabric8io/kubernetes-client#4487",https://github.com/fabric8io/kubernetes-client/commit/dad9c22283605df66311c27daaa1e76084daddaa,,,crd-generator/api/src/main/java/io/fabric8/crd/generator/utils/Types.java,3,java,False,2022-09-13T09:43:26Z "@Override public final String toString() { return label; }","@Override public final String toString() { if (safeToStringRepresentation == null) { safeToStringRepresentation = toSafeRepesentation(label); } return safeToStringRepresentation; }","Sanitize DNS labels (and names) in toString() The c-ares library was recently affected by an issue where a string potentially containing a null byte (and other non-printable characters) was handed to the user (CVE-2021-3672) [1]. This, and furhter DNS related attacks, where presented by Jeitner and Shulman at USENIX Security '21 [2]. I currently believe that MiniDNS is not affected by the attacks shown in the paper. Mostly because MiniDNS has dedicated classes for DnsName and DnsLabel. And especially the former, DnsName, implements an equal() method that is not based on the pure String comparision, but instead compres bytes of the serialized labels. I think that this should render most of the attacks of the paper ineffective. However, I did not had time to thoroughly review the paper and MiniDNS' code base, and perform some experiments. For now, this changes the String representation of DnsName and DnsLabel to a format where ""malicious"" characters are explicitly escaped. Note that the ""dangerous"" DnsName/DnsLabel representation can still be retrieved, however a Javadoc comment was added, that nobody is going to read, hinting towards the security implications of using the unescaped representation. 1: https://www.openwall.com/lists/oss-security/2021/08/10/1 2: Jeitner, Philipp and Haya Shulman. “Injection Attacks Reloaded: Tunnelling Malicious Payloads over DNS”. In: 30th USENIX Security Symposium (USENIX Security 21). USENIX Association, Aug. 2021, pp. 3165–3182. isbn: 978-1- 939133-24-3. url: https://www.usenix.org/conference/usenixsecurity21/ presentation/jeitner",https://github.com/MiniDNS/minidns/commit/cfaf45a841038d0625d224842ec4796ccc2b25cb,,,minidns-core/src/main/java/org/minidns/dnslabel/DnsLabel.java,3,java,False,2021-08-10T09:02:31Z "public void nationAdd(Player player, String[] names) throws TownyException { if (names.length < 1) throw new TownyException(""Eg: /nation add [names]""); Nation nation = getNationFromPlayerOrThrow(player); if (TownySettings.getMaxTownsPerNation() > 0 && nation.getTowns().size() >= TownySettings.getMaxTownsPerNation()) throw new TownyException(Translatable.of(""msg_err_nation_over_town_limit"", TownySettings.getMaxTownsPerNation())); // The list of valid invites. List newtownlist = new ArrayList<>(); // List of invites to be removed. List removeinvites = new ArrayList<>(); for (String townname : new ArrayList<>(Arrays.asList(names))) { if (townname.startsWith(""-"")) { // Add them to removing, remove the ""-"" removeinvites.add(townname.substring(1)); continue; } if (nation.hasTown(townname)) { // Town is already part of the nation. removeinvites.add(townname); continue; } // add them to adding. newtownlist.add(townname); } names = newtownlist.toArray(new String[0]); String[] namestoremove = removeinvites.toArray(new String[0]); if (namestoremove.length >= 1) { nationRevokeInviteTown(player, nation, TownyAPI.getInstance().getTowns(namestoremove)); } if (names.length >= 1) { nationAdd(player, nation, TownyAPI.getInstance().getTowns(names)); } }","public void nationAdd(Player player, String[] names) throws TownyException { if (names.length < 1) throw new TownyException(""Eg: /nation add [names]""); Nation nation = getNationFromPlayerOrThrow(player); if (testNationMaxTowns(nation)) throw new TownyException(Translatable.of(""msg_err_nation_over_town_limit"", TownySettings.getMaxTownsPerNation())); // The list of valid invites. List newtownlist = new ArrayList<>(); // List of invites to be removed. List removeinvites = new ArrayList<>(); for (String townname : new ArrayList<>(Arrays.asList(names))) { if (townname.startsWith(""-"")) { // Add them to removing, remove the ""-"" removeinvites.add(townname.substring(1)); continue; } Town town = null; try { town = getTownOrThrow(townname); } catch (NotRegisteredException e) { // The Town doesn't actually exist or was mis-spelled. removeinvites.add(townname); continue; } if (nation.hasTown(town) || town.hasNation()) { // Town is already part of the nation. removeinvites.add(townname); continue; } if (testNationMaxResidents(nation, town)) { // Town has too many residents to join the nation removeinvites.add(townname); TownyMessaging.sendErrorMsg(player, Translatable.of(""msg_err_cannot_join_nation_over_resident_limit"", TownySettings.getMaxResidentsPerNation(), townname)); continue; } // add them to adding. newtownlist.add(townname); } names = newtownlist.toArray(new String[0]); String[] namestoremove = removeinvites.toArray(new String[0]); if (namestoremove.length >= 1) { nationRevokeInviteTown(player, nation, TownyAPI.getInstance().getTowns(namestoremove)); } if (names.length >= 1) { nationAdd(player, nation, TownyAPI.getInstance().getTowns(names)); } }","Added max residents per nation (#6264) * Added max residents per nation * Fixes * Changed lang node * Added lang string for reaching the limit on nation join * Fix exploitable post-invite tom-foolery - Recheck town/nations meet requirements before finally adding the town to the nation, something that occurs after a nation invite is accepted by a town. - Replace spaces with tabs. - Add another lang string for messaging feedback, add contexts for crowdin. Co-authored-by: LlmDl ",https://github.com/TownyAdvanced/Towny/commit/643fec972fb666eb50a9d94687671383e4e14851,,,src/com/palmergames/bukkit/towny/command/NationCommand.java,3,java,False,2022-10-28T14:24:55Z "public static Path getResourceCachePath(String resourceURI) throws IOException { URI uri = URI.create(resourceURI); return getResourceCachePath(uri); }","public static Path getResourceCachePath(String resourceURI) throws IOException { URI uri = null; try { uri = URI.create(resourceURI); } catch (Exception e) { throw new InvalidURIException(resourceURI, InvalidURIError.ILLEGAL_SYNTAX, e); } return getResourceCachePath(uri); }","Prevent suspicious directory traversal Signed-off-by: Fred Bricon ",https://github.com/eclipse/lemminx/commit/48f23ab4dae19268027ede6c923d12e0b5e8d1fe,,,org.eclipse.lemminx/src/main/java/org/eclipse/lemminx/uriresolver/CacheResourcesManager.java,3,java,False,2022-02-07T16:38:01Z "public static String getMappedIdpRoleClaimUri(String idpRoleClaimUri, StepConfig stepConfig, AuthenticationContext context) { // Finally return the incoming idpClaimUri if it is in expected dialect. String idpRoleMappingURI = idpRoleClaimUri; ApplicationAuthenticator authenticator = stepConfig. getAuthenticatedAutenticator().getApplicationAuthenticator(); // Read the value from management console. boolean useDefaultIdpDialect = context.getExternalIdP().useDefaultLocalIdpDialect(); // Read value from file based configuration. boolean useLocalClaimDialectForClaimMappings = FileBasedConfigurationBuilder.getInstance().isCustomClaimMappingsForAuthenticatorsAllowed(); Map carbonToStandardClaimMapping = new HashMap<>(); // Check whether to use the default dialect or custom dialect. if (useDefaultIdpDialect || useLocalClaimDialectForClaimMappings) { String idPStandardDialect = authenticator.getClaimDialectURI(); try { if (StringUtils.isNotBlank(idPStandardDialect)) { // Maps the idps dialect to standard dialect. carbonToStandardClaimMapping = ClaimMetadataHandler.getInstance() .getMappingsMapFromOtherDialectToCarbon(idPStandardDialect, null, context.getTenantDomain(), false); } // check for role claim uri in the idaps dialect. for (Entry entry : carbonToStandardClaimMapping.entrySet()) { if (idpRoleMappingURI.equalsIgnoreCase(entry.getValue())) { idpRoleMappingURI = entry.getKey(); } } } catch (ClaimMetadataException e) { if (log.isDebugEnabled()) { log.debug(""Error in getting the mapping between idps and standard dialect.Thus returning the "" + ""unmapped RoleClaimUri: "" + idpRoleMappingURI, e); } } } return idpRoleMappingURI; }","public static String getMappedIdpRoleClaimUri(String idpRoleClaimUri, StepConfig stepConfig, AuthenticationContext context) { // Finally return the incoming idpClaimUri if it is in expected dialect. String idpRoleMappingURI = idpRoleClaimUri; ApplicationAuthenticator authenticator = stepConfig. getAuthenticatedAutenticator().getApplicationAuthenticator(); // Read the value from management console. boolean useDefaultIdpDialect = context.getExternalIdP().useDefaultLocalIdpDialect(); // Read value from file based configuration. boolean useLocalClaimDialectForClaimMappings = FileBasedConfigurationBuilder.getInstance().isCustomClaimMappingsForAuthenticatorsAllowed(); Map carbonToStandardClaimMapping = new HashMap<>(); // Check whether to use the default dialect or custom dialect. if (useDefaultIdpDialect || useLocalClaimDialectForClaimMappings) { String idPStandardDialect = authenticator.getClaimDialectURI(); try { if (StringUtils.isNotBlank(idPStandardDialect)) { // Maps the idps dialect to standard dialect. carbonToStandardClaimMapping = ClaimMetadataHandler.getInstance() .getMappingsMapFromOtherDialectToCarbon(idPStandardDialect, null, context.getTenantDomain(), false); } // check for role claim uri in the idaps dialect. for (Entry entry : carbonToStandardClaimMapping.entrySet()) { if (StringUtils.isNotEmpty(idpRoleMappingURI) && idpRoleMappingURI.equalsIgnoreCase(entry.getValue())) { idpRoleMappingURI = entry.getKey(); } } } catch (ClaimMetadataException e) { if (log.isDebugEnabled()) { log.debug(""Error in getting the mapping between idps and standard dialect.Thus returning the "" + ""unmapped RoleClaimUri: "" + idpRoleMappingURI, e); } } } return idpRoleMappingURI; }","Fix NPE in empty role claim URI of federated authentication (#4429) * Update FrameworkUtils.java * Update FrameworkUtils.java",https://github.com/wso2/carbon-identity-framework/commit/bfeb731dac6f2f52c9ac408d6576c3460860df40,,,components/authentication-framework/org.wso2.carbon.identity.application.authentication.framework/src/main/java/org/wso2/carbon/identity/application/authentication/framework/util/FrameworkUtils.java,3,java,False,2023-01-31T17:02:15Z "public void setWebpages(String[] webpages) { this.webpages = webpages; }","public void setWebpages(String[] webpages) { this.webpages = webpages != null ? webpages.clone() : null; }","Fix the vulnerability that public array is assigned to private variable Signed-off-by: yugeeklab ",https://github.com/fosslight/fosslight/commit/bb27243bc40aa2c02f4e32469a0bea85b33bff27,,,src/main/java/oss/fosslight/domain/LicenseMaster.java,3,java,False,2021-11-25T06:34:58Z "@Override public int getMemoryEstimate() { if (memoryEstimate == -1) { memoryEstimate = memoryOffset + (buffer != null ? buffer.capacity() : 0) + (properties != null ? properties.getMemoryOffset() : 0); } return memoryEstimate; }","@Override public int getMemoryEstimate() { if (memoryEstimate == -1) { if (buffer != null && !isLargeMessage()) { if (!validBuffer) { // this can happen if a message is modified // eg clustered messages get additional routing information // that need to be correctly accounted in memory checkEncode(); } } final TypedProperties properties = this.properties; memoryEstimate = memoryOffset + (buffer != null ? buffer.capacity() : 0) + (properties != null ? properties.getMemoryOffset() : 0); } return memoryEstimate; }",ARTEMIS-3021 OOM due to wrong CORE clustered message memory estimation,https://github.com/apache/activemq-artemis/commit/ad4f6a133af9130f206a78e43ad387d4e3ee5f8f,,,artemis-core-client/src/main/java/org/apache/activemq/artemis/core/message/impl/CoreMessage.java,3,java,False,2020-12-05T23:07:29Z "static int expandrow2(UINT8* dest, const UINT8* src, int n, int z, int xsize) { UINT8 pixel, count; for (;n > 0; n--) { pixel = src[1]; src+=2; if (n == 1 && pixel != 0) return n; count = pixel & RLE_MAX_RUN; if (!count) return count; if (count > xsize) { return -1; } if (pixel & RLE_COPY_FLAG) { while(count--) { memcpy(dest, src, 2); src += 2; dest += z * 2; } } else { while (count--) { memcpy(dest, src, 2); dest += z * 2; } src+=2; } } return 0; }","static int expandrow2(UINT8* dest, const UINT8* src, int n, int z, int xsize) { UINT8 pixel, count; int x = 0; for (;n > 0; n--) { pixel = src[1]; src+=2; if (n == 1 && pixel != 0) return n; count = pixel & RLE_MAX_RUN; if (!count) return count; if (x + count > xsize) { return -1; } x += count; if (pixel & RLE_COPY_FLAG) { while(count--) { memcpy(dest, src, 2); src += 2; dest += z * 2; } } else { while (count--) { memcpy(dest, src, 2); dest += z * 2; } src+=2; } } return 0; }","Track number of pixels, not the number of runs",https://github.com/python-pillow/Pillow/commit/394d6a180a4b63a149a223b13e98a3209f837147,,,src/libImaging/SgiRleDecode.c,3,c,False,2020-03-28T13:00:46Z "private ClassicHttpResponse executeHijacked( ClassicHttpRequest request, HttpClientConnection conn, HttpContext context, InputStream hijackedInput ) throws HttpException, IOException { try { context.setAttribute(HttpCoreContext.SSL_SESSION, conn.getSSLSession()); context.setAttribute(HttpCoreContext.CONNECTION_ENDPOINT, conn.getEndpointDetails()); final ProtocolVersion transportVersion = request.getVersion(); if (transportVersion != null) { context.setProtocolVersion(transportVersion); } conn.sendRequestHeader(request); conn.sendRequestEntity(request); conn.flush(); ClassicHttpResponse response = conn.receiveResponseHeader(); if (response.getCode() != HttpStatus.SC_SWITCHING_PROTOCOLS) { conn.terminateRequest(request); throw new ProtocolException(""Expected 101 Switching Protocols, got: "" + new StatusLine(response)); } Thread thread = new Thread(() -> { try { BasicClassicHttpRequest fakeRequest = new BasicClassicHttpRequest(""POST"", ""/""); fakeRequest.setHeader(HttpHeaders.CONTENT_LENGTH, Long.MAX_VALUE); fakeRequest.setEntity(new HijackedEntity(hijackedInput)); conn.sendRequestEntity(fakeRequest); } catch (Exception e) { throw new RuntimeException(e); } }); thread.setName(""docker-java-httpclient5-hijacking-stream-"" + System.identityHashCode(request)); thread.setDaemon(true); thread.start(); // 101 -> 200 response.setCode(200); conn.receiveResponseEntity(response); return response; } catch (final HttpException | IOException | RuntimeException ex) { Closer.closeQuietly(conn); throw ex; } }","private ClassicHttpResponse executeHijacked( ClassicHttpRequest request, HttpClientConnection conn, HttpContext context, InputStream hijackedInput ) throws HttpException, IOException { try { context.setAttribute(HttpCoreContext.SSL_SESSION, conn.getSSLSession()); context.setAttribute(HttpCoreContext.CONNECTION_ENDPOINT, conn.getEndpointDetails()); final ProtocolVersion transportVersion = request.getVersion(); if (transportVersion != null) { context.setProtocolVersion(transportVersion); } conn.sendRequestHeader(request); conn.sendRequestEntity(request); conn.flush(); ClassicHttpResponse response = conn.receiveResponseHeader(); if (response.getCode() != HttpStatus.SC_SWITCHING_PROTOCOLS) { conn.terminateRequest(request); throw new ProtocolException(""Expected 101 Switching Protocols, got: "" + new StatusLine(response)); } Thread thread = new Thread(() -> { try { BasicClassicHttpRequest fakeRequest = new BasicClassicHttpRequest(""POST"", ""/""); fakeRequest.setHeader(HttpHeaders.CONTENT_LENGTH, Long.MAX_VALUE); fakeRequest.setEntity(new HijackedEntity(hijackedInput)); conn.sendRequestEntity(fakeRequest); if (conn instanceof ManagedHttpClientConnection) { ((ManagedHttpClientConnection) conn).getSocket().shutdownOutput(); } } catch (Exception e) { throw new RuntimeException(e); } }); thread.setName(""docker-java-httpclient5-hijacking-stream-"" + System.identityHashCode(request)); thread.setDaemon(true); thread.start(); // 101 -> 200 response.setCode(200); conn.receiveResponseEntity(response); return response; } catch (final HttpException | IOException | RuntimeException ex) { Closer.closeQuietly(conn); throw ex; } }","Shutdown hijacked stdin Fixes #1448",https://github.com/docker-java/docker-java/commit/a356f66c04549d231dc748d204bcc7caab3930ff,,,docker-java-transport-httpclient5/src/main/java/com/github/dockerjava/httpclient5/HijackingHttpRequestExecutor.java,3,java,False,2021-03-26T10:13:47Z "@SubscribeEvent public void checkDamageLabelFound(LocationEvent.LabelFoundEvent event) { String value = TextFormatting.getTextWithoutFormattingCodes(event.getLabel()); Entity i = event.getEntity(); Map damageList = new HashMap<>(); if (value.contains(""Combat"") || value.contains(""Guild"")) return; Matcher m = MOB_DAMAGE.matcher(value); while (m.find()) { damageList.put(DamageType.fromSymbol(m.group(2)), Integer.valueOf(m.group(1))); } if (damageList.isEmpty()) return; FrameworkManager.getEventBus().post(new GameEvent.DamageEntity(damageList, i)); }","@SubscribeEvent public void checkDamageLabelFound(LocationEvent.LabelFoundEvent event) { String value = TextFormatting.getTextWithoutFormattingCodes(event.getLabel()); Entity i = event.getEntity(); UUID id = i.getUniqueID(); damageLabelSet.releaseEntries(); for (UUID setUuid : damageLabelSet) { if (id.equals(setUuid)) return; } damageLabelSet.put(id); Map damageList = new HashMap<>(); if (value.contains(""Combat"") || value.contains(""Guild"")) return; Matcher m = MOB_DAMAGE.matcher(value); while (m.find()) { damageList.put(DamageType.fromSymbol(m.group(2)), Integer.valueOf(m.group(1))); } if (damageList.isEmpty()) return; FrameworkManager.getEventBus().post(new GameEvent.DamageEntity(damageList, i)); }","Fix 14 issues found in ticket backlog (#502) * Fix IndexOutOfBoundsException in QuestBookListPage Signed-off-by: kristofbolyai * Fix crash if OverlayConfig.GameUpdate.INSTANCE.messageMaxLength is 1 Signed-off-by: kristofbolyai * Fix crash related to deleting chat tabs and ChatGUI not updating Signed-off-by: kristofbolyai * Fix crash related to deleting chat tabs and ChatGUI not updating Signed-off-by: kristofbolyai * Fix translation cache becoming null Signed-off-by: kristofbolyai * Fix objective parsing if player is in party Signed-off-by: kristofbolyai * Fix guild objective not being removed upon completion Signed-off-by: kristofbolyai * Fix race condition in ServerEvents Signed-off-by: kristofbolyai * Fix race condition in ClientEvents Signed-off-by: kristofbolyai * Fix NPE in ServerEvents Signed-off-by: kristofbolyai * Fix AreaDPS value not being correct Signed-off-by: kristofbolyai * Fix NPE in fix :) Signed-off-by: kristofbolyai * Fix quest dialogue spoofing Signed-off-by: kristofbolyai * Fix Keyholder related crash Signed-off-by: kristofbolyai * Fix totem tracking Signed-off-by: kristofbolyai * Dialogue Page gets updated correctly Signed-off-by: kristofbolyai * Register ChatGUI correctly Signed-off-by: kristofbolyai * Use MC's GameSettings to check for isKeyDown Signed-off-by: kristofbolyai * Make multi line if have braces Signed-off-by: kristofbolyai ",https://github.com/Wynntils/Wynntils/commit/c8f6effe187ff68f17bcff809d2bc440ec07128d,,,src/main/java/com/wynntils/modules/core/events/ClientEvents.java,3,java,False,2022-04-15T17:16:00Z "private Result verifyFile(String name, ResourceType type, MultipartFile file) { Result result = new Result<>(); putMsg(result, Status.SUCCESS); if (file != null) { // file is empty if (file.isEmpty()) { logger.error(""file is empty: {}"", RegexUtils.escapeNRT(file.getOriginalFilename())); putMsg(result, Status.RESOURCE_FILE_IS_EMPTY); return result; } // file suffix String fileSuffix = Files.getFileExtension(file.getOriginalFilename()); String nameSuffix = Files.getFileExtension(name); // determine file suffix if (!(StringUtils.isNotEmpty(fileSuffix) && fileSuffix.equalsIgnoreCase(nameSuffix))) { // rename file suffix and original suffix must be consistent logger.error(""rename file suffix and original suffix must be consistent: {}"", RegexUtils.escapeNRT(file.getOriginalFilename())); putMsg(result, Status.RESOURCE_SUFFIX_FORBID_CHANGE); return result; } //If resource type is UDF, only jar packages are allowed to be uploaded, and the suffix must be .jar if (Constants.UDF.equals(type.name()) && !JAR.equalsIgnoreCase(fileSuffix)) { logger.error(Status.UDF_RESOURCE_SUFFIX_NOT_JAR.getMsg()); putMsg(result, Status.UDF_RESOURCE_SUFFIX_NOT_JAR); return result; } if (file.getSize() > Constants.MAX_FILE_SIZE) { logger.error(""file size is too large: {}"", RegexUtils.escapeNRT(file.getOriginalFilename())); putMsg(result, Status.RESOURCE_SIZE_EXCEED_LIMIT); return result; } } return result; }","private Result verifyFile(String name, ResourceType type, MultipartFile file) { Result result = new Result<>(); putMsg(result, Status.SUCCESS); if (FileUtils.directoryTraversal(name)) { logger.error(""file alias name {} verify failed"", name); putMsg(result, Status.VERIFY_PARAMETER_NAME_FAILED); return result; } if (file != null && FileUtils.directoryTraversal(Objects.requireNonNull(file.getOriginalFilename()))) { logger.error(""file original name {} verify failed"", file.getOriginalFilename()); putMsg(result, Status.VERIFY_PARAMETER_NAME_FAILED); return result; } if (file != null) { // file is empty if (file.isEmpty()) { logger.error(""file is empty: {}"", RegexUtils.escapeNRT(file.getOriginalFilename())); putMsg(result, Status.RESOURCE_FILE_IS_EMPTY); return result; } // file suffix String fileSuffix = Files.getFileExtension(file.getOriginalFilename()); String nameSuffix = Files.getFileExtension(name); // determine file suffix if (!(StringUtils.isNotEmpty(fileSuffix) && fileSuffix.equalsIgnoreCase(nameSuffix))) { // rename file suffix and original suffix must be consistent logger.error(""rename file suffix and original suffix must be consistent: {}"", RegexUtils.escapeNRT(file.getOriginalFilename())); putMsg(result, Status.RESOURCE_SUFFIX_FORBID_CHANGE); return result; } //If resource type is UDF, only jar packages are allowed to be uploaded, and the suffix must be .jar if (Constants.UDF.equals(type.name()) && !JAR.equalsIgnoreCase(fileSuffix)) { logger.error(Status.UDF_RESOURCE_SUFFIX_NOT_JAR.getMsg()); putMsg(result, Status.UDF_RESOURCE_SUFFIX_NOT_JAR); return result; } if (file.getSize() > Constants.MAX_FILE_SIZE) { logger.error(""file size is too large: {}"", RegexUtils.escapeNRT(file.getOriginalFilename())); putMsg(result, Status.RESOURCE_SIZE_EXCEED_LIMIT); return result; } } return result; }","[fix] Enhance name pre checker in resource center (#10094) (#10759) * [fix] Enhance name pre checker in resource center (#10094) * [fix] Enhance name pre checker in resource center Add file name and directory checker to avoid directory traversal * add some missing change and change docs * change var name in directoryTraversal * Fix ci (cherry picked from commit 63f835715f8ca8bff79c0e7177ebfa5917ebb3bd) * Add new constants",https://github.com/apache/dolphinscheduler/commit/23fae510dfdde1753e0a161f747c30ae5171fba1,,,dolphinscheduler-api/src/main/java/org/apache/dolphinscheduler/api/service/impl/ResourcesServiceImpl.java,3,java,False,2022-07-04T06:04:23Z "@Override public void execute(ServiceTask task) { if (connection.isClosed()) { // prevents QUIT、CLOSE_STMT from losing cumulative if (task.getOrgData().length > 4 && (task.getOrgData()[4] == MySQLPacket.COM_QUIT || task.getOrgData()[4] == MySQLPacket.COM_STMT_CLOSE)) { this.handleInnerData(task.getOrgData()); } return; } ServiceTask executeTask = null; synchronized (this) { if (currentTask != null) { //currentTask is executing. taskToPriorityQueue(task); return; } executeTask = taskQueue.peek(); if (executeTask == null) { return; } if (executeTask != task) { //out of order,adjust it. taskToPriorityQueue(task); return; } //drop head task of the queue taskQueue.poll(); currentTask = executeTask; } try { byte[] data = executeTask.getOrgData(); if (data != null && !executeTask.isReuse()) { this.setPacketId(executeTask.getLastSequenceId()); } this.handleInnerData(data); } finally { synchronized (this) { currentTask = null; } } }","@Override public void execute(ServiceTask task) { if (connection.isClosed()) { // prevents QUIT、CLOSE_STMT from losing cumulative if (task.getOrgData().length > 4 && (task.getOrgData()[4] == MySQLPacket.COM_QUIT || task.getOrgData()[4] == MySQLPacket.COM_STMT_CLOSE)) { this.handleInnerData(task.getOrgData()); } return; } ServiceTask executeTask = null; synchronized (this) { if (currentTask != null) { //currentTask is executing. taskToPriorityQueue(task); return; } executeTask = taskQueue.peek(); if (executeTask == null) { return; } if (executeTask != task) { //out of order,adjust it. taskToPriorityQueue(task); return; } //drop head task of the queue taskQueue.poll(); currentTask = executeTask; } try { byte[] data = executeTask.getOrgData(); if (data != null && !executeTask.isReuse()) { this.setPacketId(executeTask.getLastSequenceId()); } this.handleInnerData(data); } catch (Throwable e) { LOGGER.error(""process task error"", e); writeErrMessage(ErrorCode.ER_YES, ""process task error, exception is "" + e); connection.close(""process task error""); } finally { synchronized (this) { currentTask = null; } } }","inner-1124:prevent illegal auth packet (#2673) Signed-off-by: dcy ",https://github.com/actiontech/dble/commit/3a4f861790722748c4195eed768c362d3db420d5,,,src/main/java/com/actiontech/dble/services/FrontendService.java,3,java,False,2021-05-24T05:20:16Z "public void agentDisconnected(String packageName) { // TODO: handle backup being interrupted synchronized (mAgentConnectLock) { if (Binder.getCallingUid() == Process.SYSTEM_UID) { mConnectedAgent = null; mConnecting = false; } else { Slog.w( TAG, addUserIdToLogMessage( mUserId, ""Non-system process uid="" + Binder.getCallingUid() + "" claiming agent disconnected"")); } mAgentConnectLock.notifyAll(); } }","public void agentDisconnected(String packageName) { synchronized (mAgentConnectLock) { if (Binder.getCallingUid() == Process.SYSTEM_UID) { mConnectedAgent = null; mConnecting = false; } else { Slog.w( TAG, addUserIdToLogMessage( mUserId, ""Non-system process uid="" + Binder.getCallingUid() + "" claiming agent disconnected"")); } Slog.w(TAG, ""agentDisconnected: the backup agent for "" + packageName + "" died: cancel current operations""); // handleCancel() causes the PerformFullTransportBackupTask to go on to // tearDownAgentAndKill: that will unbindBackupAgent in the Activity Manager, so // that the package being backed up doesn't get stuck in restricted mode until the // backup time-out elapses. for (int token : mOperationStorage.operationTokensForPackage(packageName)) { if (MORE_DEBUG) { Slog.d(TAG, ""agentDisconnected: will handleCancel(all) for token:"" + Integer.toHexString(token)); } handleCancel(token, true /* cancelAll */); } mAgentConnectLock.notifyAll(); } }","Trigger unbindBackupAgent if app dies during backup This is to fix a bug where, if an app crashes in restricted mode, when the user restarts the app, it would be launched still in restricted mode. That happens because ActivityManager still has a BackupRecord indicating that the app should be in restricted mode, so next time the app launches, attachApplicationLocked() calls IApplicationThread.bindApplication() with the restricted mode flag set. To avoid this we must complete the clean up actions done when backup agents report errors. UserBackupManagerService has a call-back method agentDisconnected() that is notified if an agent dies. In that method we call handleCancel() on all outstanding operations that are linked to the package name, according to OperationStorage. The result is a call to the Activity Manager's unbindBackupAgent() which then removes the obsolete BackupRecord. Two new tests for agentDisconnected() verify that appropriate calls are made to OperationStore. BUG: 161089758 Test: atest FrameworksServicesTests:com.android.server.backup atest BackupFrameworksServicesRoboTests atest CtsBackupHostTestCases atest CtsBackupTestCases atest GtsBackupTestCase Also, manual testing with an app that deliberately dies during full backup: the lifecycle operation storage is used to cancel the backup; the app restarts in normal and not restricted mode. Change-Id: Ic4cf3875d59e3580b026340e884093f3aa1b09b9",https://github.com/omnirom/android_frameworks_base/commit/6118857c97474f3e3e2ab6bc59c6122afb1dd727,,,services/backup/java/com/android/server/backup/UserBackupManagerService.java,3,java,False,2021-12-07T16:39:32Z "public void setText(CharSequence text, BufferType type) { setText(text, type, true, 0); if (mCharWrapper != null) { mCharWrapper.mChars = null; } }","public void setText(CharSequence text, BufferType type) { setText(text, type, true, 0); // drop any potential mCharWrappper leaks mCharWrapper = null; }","Don't crash after unsetting char[] in TextView TextView.setText(char[]) is from API 1 and follows a running with scissors API style of not copying the passed array. To avoid a leak, in TextView.setText(String), the char[] would be nulled out. However, an internal object could have been read using .getText() prior to this second setText would immmediatly become a CharSequence that crashed when you called any methods on it. After this change, the CharWrapper will stay valid if had been previously retrieved. The general shape of the API will be maintained. Fixes: b/227218386 Test: atest android.widget.TextViewTest Relnote: ""Calling TextView.getText() after calling TextView.setText(char[]) will now return a valid CharSequence. The char[] pointed to by this char sequnece may still be mutated by future calls to setText(char[]), but it will no longer allow a (char[]) null to be set, which lead to crashes when reading CharSequence returned from getText on TextView."" Change-Id: I35a2a76d58ec1946dace2f615cacf6a6085efdeb",https://github.com/LineageOS/android_frameworks_base/commit/166c7217f45d312f026ea2be94101e7b39b6a2c5,,,core/java/android/widget/TextView.java,3,java,False,2022-07-12T20:55:44Z "@Override public void load(FastJCanvas canvas) { playerMetadata = createPlayerMetaData(); playerHealthBar = createPlayerHealthBar(); PlayerHealthBar playerHealthBarScript = new PlayerHealthBar(playerMetadata, this); playerHealthBar.addBehavior(playerHealthBarScript, this) .addTag(Tags.PlayerHealthBar, this); PlayerController playerControllerScript = new PlayerController(5f, 3f); PlayerCannon playerCannonScript = new PlayerCannon(this); player = createPlayer(); player.addBehavior(playerControllerScript, this) .addBehavior(playerCannonScript, this) .addTag(Tags.Player, this); // add game objects to the screen in order! drawableManager.addGameObject(player); drawableManager.addGameObject(playerHealthBar); drawableManager.addGameObject(playerMetadata); enemies = new HashMap<>(); newWave(); inputManager.addKeyboardActionListener(new KeyboardActionListener() { @Override public void onKeyRecentlyPressed(KeyboardStateEvent keyboardStateEvent) { switch (keyboardStateEvent.getKey()) { case Q: { FastJEngine.log(""current bullet count: "" + playerCannonScript.getBulletCount()); break; } case P: { FastJEngine.log(""current enemy count: "" + enemies.size()); break; } case L: { FastJEngine.log(""printing enemy statuses...""); enemies.values().forEach(enemy -> FastJEngine.log(""enemy {}: {}"", enemy.getID(), enemy.toString())); } } } }); }","@Override public void load(FastJCanvas canvas) { playerMetadata = createPlayerMetaData(); playerHealthBar = createPlayerHealthBar(); PlayerHealthBar playerHealthBarScript = new PlayerHealthBar(playerMetadata, this); playerHealthBar.addBehavior(playerHealthBarScript, this) .addTag(Tags.PlayerHealthBar, this); PlayerController playerControllerScript = new PlayerController(5f, 3f); PlayerCannon playerCannonScript = new PlayerCannon(this); player = createPlayer(); player.addBehavior(playerControllerScript, this) .addBehavior(playerCannonScript, this) .addTag(Tags.Player, this); // add game objects to the screen in order! drawableManager.addGameObject(player); drawableManager.addGameObject(playerHealthBar); drawableManager.addGameObject(playerMetadata); enemies = new ConcurrentHashMap<>(); newWave(); inputManager.addKeyboardActionListener(new KeyboardActionListener() { @Override public void onKeyRecentlyPressed(KeyboardStateEvent keyboardStateEvent) { switch (keyboardStateEvent.getKey()) { case Q: { FastJEngine.log(""current bullet count: "" + playerCannonScript.getBulletCount()); break; } case P: { FastJEngine.log(""current enemy count: "" + enemies.size()); break; } case L: { FastJEngine.log(""printing enemy statuses...""); enemies.values().forEach(enemy -> FastJEngine.log(""enemy {}: {}"", enemy.getID(), enemy.toString())); } } } }); }","fixed a ton of concurrency issues New Additions - `Drawable#isDestroyed` -- boolean for checking if a given `Drawable` has been destroyed - This boolean also effects the outcome of `Drawable#shouldRender` -- if the `Drawable` is destroyed, then it will not be rendered - `ManagedList` -- a type of `List` with convenient managed actions via a `ScheduledExecutorService`, providing a safe and manageable way to start and stop important list actions at a moment's notice Bug Fixes - Fixed occasional crashes on null pointers with enemies in `GameScene` - Fixed occasional concurrent modification exceptions on `AfterUpdateList` and `AfterRenderList` in `FastJEngine` - Fixed double-`exit` situation on closing `SimpleDisplay` - Fixed occasional concurrenct modification exceptions on `behavior` lists from `GameObject` - Sensibly removed as many `null` values as possible from `Model2D/Polygon2D/Sprite2D/Text2D` - Fixed buggy threading code/occasional concurrent modification exceptions in `InputManager` Breaking Changes - `BehaviorManager#reset` now destroys all the behaviors in each of its behavior lists Other Changes - Moved transform resetting on `destroyTheRest` up from `GameObject` to `Drawable` - Changed `GameObjectTests#tryUpdateBehaviorWithoutInitializing_shouldThrowNullPointerException`'s exception throwing to match the underlying `behaviors` list's exception - added trace-level logging to unit tests",https://github.com/fastjengine/FastJ/commit/3cf252b71786d782a98fdfb976eba13154e57757,,,examples/java/tech/fastj/examples/bullethell/scenes/GameScene.java,3,java,False,2021-12-20T17:24:53Z "@Override public void unregisterModule(PluginModule pluginModule, SuperiorSkyblockPlugin plugin) { String moduleName = pluginModule.getName().toLowerCase(); Preconditions.checkState(modulesMap.containsKey(moduleName), ""PluginModule with the name "" + moduleName + "" is not registered in the plugin anymore.""); SuperiorSkyblockPlugin.log(""&cDisabling the module "" + pluginModule.getName() + ""...""); pluginModule.onDisable(plugin); ModuleData moduleData = modulesData.remove(pluginModule); if (moduleData != null) { if (moduleData.getListeners() != null) Arrays.stream(moduleData.getListeners()).forEach(HandlerList::unregisterAll); if (moduleData.getCommands() != null) Arrays.stream(moduleData.getCommands()).forEach(plugin.getCommands()::unregisterCommand); if (moduleData.getAdminCommands() != null) Arrays.stream(moduleData.getAdminCommands()).forEach(plugin.getCommands()::unregisterAdminCommand); } pluginModule.disableModule(); modulesMap.remove(moduleName); }","@Override public void unregisterModule(PluginModule pluginModule, SuperiorSkyblockPlugin plugin) { String moduleName = pluginModule.getName().toLowerCase(); Preconditions.checkState(modulesMap.containsKey(moduleName), ""PluginModule with the name "" + moduleName + "" is not registered in the plugin anymore.""); SuperiorSkyblockPlugin.log(""&cDisabling the module "" + pluginModule.getName() + ""...""); try { pluginModule.onDisable(plugin); } catch (Throwable error) { SuperiorSkyblockPlugin.log(""&cAn error occurred while disabling the module "" + pluginModule.getName() + "":""); SuperiorSkyblockPlugin.log(""&cContact "" + pluginModule.getAuthor() + "" regarding this, this has nothing to do with the plugin.""); error.printStackTrace(); } ModuleData moduleData = modulesData.remove(pluginModule); if (moduleData != null) { if (moduleData.getListeners() != null) Arrays.stream(moduleData.getListeners()).forEach(HandlerList::unregisterAll); if (moduleData.getCommands() != null) Arrays.stream(moduleData.getCommands()).forEach(plugin.getCommands()::unregisterCommand); if (moduleData.getAdminCommands() != null) Arrays.stream(moduleData.getAdminCommands()).forEach(plugin.getCommands()::unregisterAdminCommand); } pluginModule.disableModule(); modulesMap.remove(moduleName); }",Fixed potential crashes when modules throw errors,https://github.com/BG-Software-LLC/SuperiorSkyblock2/commit/f32b9b3a8f3af502b87eb2f6f08cfffb38dc4297,,,src/main/java/com/bgsoftware/superiorskyblock/module/container/DefaultModulesContainer.java,3,java,False,2022-02-26T13:17:11Z "public void encodeHeadersAndProperties(final ByteBuf buffer) { final TypedProperties properties = getProperties(); messageIDPosition = buffer.writerIndex(); buffer.writeLong(messageID); SimpleString.writeNullableSimpleString(buffer, address); if (userID == null) { buffer.writeByte(DataConstants.NULL); } else { buffer.writeByte(DataConstants.NOT_NULL); buffer.writeBytes(userID.asBytes()); } buffer.writeByte(type); buffer.writeBoolean(durable); buffer.writeLong(expiration); buffer.writeLong(timestamp); buffer.writeByte(priority); properties.encode(buffer); }","public void encodeHeadersAndProperties(final ByteBuf buffer) { final TypedProperties properties = getProperties(); final int initialWriterIndex = buffer.writerIndex(); messageIDPosition = initialWriterIndex; final UUID userID = this.userID; final int userIDEncodedSize = userID == null ? Byte.BYTES : Byte.BYTES + userID.asBytes().length; final SimpleString address = this.address; final int addressEncodedBytes = SimpleString.sizeofNullableString(address); final int headersSize = Long.BYTES + // messageID addressEncodedBytes + // address userIDEncodedSize + // userID Byte.BYTES + // type Byte.BYTES + // durable Long.BYTES + // expiration Long.BYTES + // timestamp Byte.BYTES; // priority synchronized (properties) { final int propertiesEncodeSize = properties.getEncodeSize(); final int totalEncodedSize = headersSize + propertiesEncodeSize; ensureExactWritable(buffer, totalEncodedSize); buffer.writeLong(messageID); SimpleString.writeNullableSimpleString(buffer, address); if (userID == null) { buffer.writeByte(DataConstants.NULL); } else { buffer.writeByte(DataConstants.NOT_NULL); buffer.writeBytes(userID.asBytes()); } buffer.writeByte(type); buffer.writeBoolean(durable); buffer.writeLong(expiration); buffer.writeLong(timestamp); buffer.writeByte(priority); assert buffer.writerIndex() == initialWriterIndex + headersSize : ""Bad Headers encode size estimation""; final int realPropertiesEncodeSize = properties.encode(buffer); assert realPropertiesEncodeSize == propertiesEncodeSize : ""TypedProperties has a wrong encode size estimation or is being modified concurrently""; } }",ARTEMIS-3021 OOM due to wrong CORE clustered message memory estimation,https://github.com/apache/activemq-artemis/commit/ad4f6a133af9130f206a78e43ad387d4e3ee5f8f,,,artemis-core-client/src/main/java/org/apache/activemq/artemis/core/message/impl/CoreMessage.java,3,java,False,2020-12-05T23:07:29Z "public Vector3f getViewPosition(Vector3f dest) { ClientComponent clientComponent = getClientEntity().getComponent(ClientComponent.class); LocationComponent location = clientComponent.camera.getComponent(LocationComponent.class); return location.getWorldPosition(dest); }","public Vector3f getViewPosition(Vector3f dest) { ClientComponent clientComponent = getClientEntity().getComponent(ClientComponent.class); if (clientComponent.camera.exists()) { LocationComponent location = clientComponent.camera.getComponent(LocationComponent.class); return location.getWorldPosition(dest); } else { return getPosition(dest); } }","fix(LocalPlayer): do not crash when the camera is not on Restores the alternate behavior described in the docstring, correcting a regression introduced in #4795. This ""LocalPlayer without camera"" situation has come up in headless MTE tests.",https://github.com/MovingBlocks/Terasology/commit/b6e85b6e44e58e78ad3cc975fd8bbddcdee3f50e,,,engine/src/main/java/org/terasology/engine/logic/players/LocalPlayer.java,3,java,False,2022-05-10T18:28:00Z "@Override public int compareTo(LevelResponseBean levelResponseBean) { return LevelConstants.getOrdinal(this.level) - LevelConstants.getOrdinal(levelResponseBean.getLevel()); }","@Override public int compareTo(LevelResponseBean levelResponseBean) { ToIntFunction variantOrdinal = level -> level.contains(""SECURE"") ? SecureConstants.getIncrementedOrdinal(level) : LevelConstants.getOrdinal(level); return variantOrdinal.applyAsInt(this.getLevel()) - variantOrdinal.applyAsInt(levelResponseBean.getLevel()); }",Introduce 'SECURE' vulnerability variant handled both on API and UI,https://github.com/SasanLabs/VulnerableApp/commit/06349636d22a4edd20c289ed5f46c783829a0073,,,src/main/java/org/sasanlabs/beans/LevelResponseBean.java,3,java,False,2021-04-26T19:49:40Z "@DoNotStrip public void setJSResponder( final int surfaceId, final int reactTag, final int initialReactTag, final boolean blockNativeResponder) { addMountItem( new MountItem() { @Override public void execute(MountingManager mountingManager) { mountingManager.setJSResponder( surfaceId, reactTag, initialReactTag, blockNativeResponder); } @Override public int getSurfaceId() { return surfaceId; } }); }","@DoNotStrip public void setJSResponder( final int surfaceId, final int reactTag, final int initialReactTag, final boolean blockNativeResponder) { addMountItem( new MountItem() { @Override public void execute(MountingManager mountingManager) { SurfaceMountingManager surfaceMountingManager = mountingManager.getSurfaceManager(surfaceId); if (surfaceMountingManager != null) { surfaceMountingManager.setJSResponder( reactTag, initialReactTag, blockNativeResponder); } else { FLog.e( TAG, ""setJSResponder skipped, surface no longer available ["" + surfaceId + ""]""); } } @Override public int getSurfaceId() { return surfaceId; } }); }","Fix crash associated with setJSResponderHandler Summary: In Fabric we're seeing setJSResponderHandler called during teardown of a surface, which causes a crash because the SurfaceId is no longer available at that point. Guard against setJSResponderHandler being called on a dead surface. Changelog: [Internal] Reviewed By: mdvacca Differential Revision: D26734786 fbshipit-source-id: 838d682ee0dd1d4de49993fa479dc2097cf33521",https://github.com/react-native-tvos/react-native-tvos/commit/21a434ceec97681574aeedf5e8340f2c58f6f80e,,,ReactAndroid/src/main/java/com/facebook/react/fabric/FabricUIManager.java,3,java,False,2021-03-01T23:46:07Z "@Override public int getAvailabilityStatus() { return AVAILABLE; }","@Override public int getAvailabilityStatus() { if (DevelopmentSettingsEnabler.isDevelopmentSettingsEnabled(mContext)) { return AVAILABLE; } else { return CONDITIONALLY_UNAVAILABLE; } }","Avoid media transcode can be bypass guard of developer options When developer options switch is off, a user including guest user can still configure media transcoding settings via slices. Bug: 244569778 Test: manual Change-Id: I3d70045c2498e683bf615cbe521e2f98d50b7eec",https://github.com/LineageOS/android_packages_apps_Settings/commit/a94e8d0bc72ad4aae6a62cad3673b099d72dcd13,,,src/com/android/settings/development/transcode/TranscodeDefaultOptionPreferenceController.java,3,java,False,2022-11-17T10:19:31Z "private ServiceResponse executePost(ServiceRequest request, ServiceResponse response) { String urlPath = request.getUrlPath(); if (urlPath == null || urlPath.equals(""/"")) { return errorResponse(response, 400, POST_ONLY_ALLOWED_TO_COLLECTIONS); } PersistenceManager pm = getPm(); try { return handlePost(pm, urlPath, response, request); } catch (IllegalArgumentException e) { LOGGER.debug(""User Error: {}"", e.getMessage()); if (pm != null) { pm.rollbackAndClose(); } return errorResponse(response, 400, ""Incorrect request: "" + e.getMessage()); } catch (IOException | RuntimeException e) { LOGGER.error("""", e); if (pm != null) { pm.rollbackAndClose(); } return errorResponse(response, 500, ""Failed to store data.""); } finally { maybeRollbackAndClose(); } }","private ServiceResponse executePost(ServiceRequest request, ServiceResponse response) { String urlPath = request.getUrlPath(); if (urlPath == null || urlPath.equals(""/"")) { return errorResponse(response, 400, POST_ONLY_ALLOWED_TO_COLLECTIONS); } PersistenceManager pm = getPm(); try { return handlePost(pm, urlPath, response, request); } catch (UnauthorizedException e) { rollbackAndClose(pm); return errorResponse(response, 401, e.getMessage()); } catch (ForbiddenException e) { rollbackAndClose(pm); return errorResponse(response, 403, e.getMessage()); } catch (IllegalArgumentException e) { LOGGER.debug(""User Error: {}"", e.getMessage()); rollbackAndClose(pm); return errorResponse(response, 400, ""Incorrect request: "" + e.getMessage()); } catch (IOException | RuntimeException e) { LOGGER.error("""", e); rollbackAndClose(pm); return errorResponse(response, 500, ""Failed to store data.""); } finally { maybeRollbackAndClose(); } }",Added Forbidden- and UnauthorizedExceptions,https://github.com/FraunhoferIOSB/FROST-Server/commit/e72e4ee2e7d33b58da29c434d0ff63de5f656ee4,,,FROST-Server.Core/src/main/java/de/fraunhofer/iosb/ilt/frostserver/service/Service.java,3,java,False,2021-12-01T19:48:43Z "@Override public boolean createNotificationChannel(String pkg, int uid, NotificationChannel channel, boolean fromTargetApp, boolean hasDndAccess) { Objects.requireNonNull(pkg); Objects.requireNonNull(channel); Objects.requireNonNull(channel.getId()); Preconditions.checkArgument(!TextUtils.isEmpty(channel.getName())); boolean needsPolicyFileChange = false, wasUndeleted = false; synchronized (mPackagePreferences) { PackagePreferences r = getOrCreatePackagePreferencesLocked(pkg, uid); if (r == null) { throw new IllegalArgumentException(""Invalid package""); } if (channel.getGroup() != null && !r.groups.containsKey(channel.getGroup())) { throw new IllegalArgumentException(""NotificationChannelGroup doesn't exist""); } if (NotificationChannel.DEFAULT_CHANNEL_ID.equals(channel.getId())) { throw new IllegalArgumentException(""Reserved id""); } NotificationChannel existing = r.channels.get(channel.getId()); if (existing != null && fromTargetApp) { // Actually modifying an existing channel - keep most of the existing settings if (existing.isDeleted()) { // The existing channel was deleted - undelete it. existing.setDeleted(false); needsPolicyFileChange = true; wasUndeleted = true; // log a resurrected channel as if it's new again MetricsLogger.action(getChannelLog(channel, pkg).setType( com.android.internal.logging.nano.MetricsProto.MetricsEvent.TYPE_OPEN)); mNotificationChannelLogger.logNotificationChannelCreated(channel, uid, pkg); } if (!Objects.equals(channel.getName().toString(), existing.getName().toString())) { existing.setName(channel.getName().toString()); needsPolicyFileChange = true; } if (!Objects.equals(channel.getDescription(), existing.getDescription())) { existing.setDescription(channel.getDescription()); needsPolicyFileChange = true; } if (channel.isBlockable() != existing.isBlockable()) { existing.setBlockable(channel.isBlockable()); needsPolicyFileChange = true; } if (channel.getGroup() != null && existing.getGroup() == null) { existing.setGroup(channel.getGroup()); needsPolicyFileChange = true; } // Apps are allowed to downgrade channel importance if the user has not changed any // fields on this channel yet. final int previousExistingImportance = existing.getImportance(); final int previousLoggingImportance = NotificationChannelLogger.getLoggingImportance(existing); if (existing.getUserLockedFields() == 0 && channel.getImportance() < existing.getImportance()) { existing.setImportance(channel.getImportance()); needsPolicyFileChange = true; } // system apps and dnd access apps can bypass dnd if the user hasn't changed any // fields on the channel yet if (existing.getUserLockedFields() == 0 && hasDndAccess) { boolean bypassDnd = channel.canBypassDnd(); if (bypassDnd != existing.canBypassDnd()) { existing.setBypassDnd(bypassDnd); needsPolicyFileChange = true; if (bypassDnd != mAreChannelsBypassingDnd || previousExistingImportance != existing.getImportance()) { updateChannelsBypassingDnd(mContext.getUserId()); } } } if (existing.getOriginalImportance() == IMPORTANCE_UNSPECIFIED) { existing.setOriginalImportance(channel.getImportance()); needsPolicyFileChange = true; } updateConfig(); if (needsPolicyFileChange && !wasUndeleted) { mNotificationChannelLogger.logNotificationChannelModified(existing, uid, pkg, previousLoggingImportance, false); } return needsPolicyFileChange; } if (r.channels.size() >= NOTIFICATION_CHANNEL_COUNT_LIMIT) { throw new IllegalStateException(""Limit exceed; cannot create more channels""); } needsPolicyFileChange = true; if (channel.getImportance() < IMPORTANCE_NONE || channel.getImportance() > NotificationManager.IMPORTANCE_MAX) { throw new IllegalArgumentException(""Invalid importance level""); } // Reset fields that apps aren't allowed to set. if (fromTargetApp && !hasDndAccess) { channel.setBypassDnd(r.priority == Notification.PRIORITY_MAX); } if (fromTargetApp) { channel.setLockscreenVisibility(r.visibility); channel.setAllowBubbles(existing != null ? existing.getAllowBubbles() : NotificationChannel.DEFAULT_ALLOW_BUBBLE); } clearLockedFieldsLocked(channel); channel.setImportanceLockedByOEM(r.oemLockedImportance); if (!channel.isImportanceLockedByOEM()) { if (r.oemLockedChannels.contains(channel.getId())) { channel.setImportanceLockedByOEM(true); } } channel.setImportanceLockedByCriticalDeviceFunction(r.defaultAppLockedImportance); if (channel.getLockscreenVisibility() == Notification.VISIBILITY_PUBLIC) { channel.setLockscreenVisibility( NotificationListenerService.Ranking.VISIBILITY_NO_OVERRIDE); } if (!r.showBadge) { channel.setShowBadge(false); } channel.setOriginalImportance(channel.getImportance()); // validate parent if (channel.getParentChannelId() != null) { Preconditions.checkArgument(r.channels.containsKey(channel.getParentChannelId()), ""Tried to create a conversation channel without a preexisting parent""); } r.channels.put(channel.getId(), channel); if (channel.canBypassDnd() != mAreChannelsBypassingDnd) { updateChannelsBypassingDnd(mContext.getUserId()); } MetricsLogger.action(getChannelLog(channel, pkg).setType( com.android.internal.logging.nano.MetricsProto.MetricsEvent.TYPE_OPEN)); mNotificationChannelLogger.logNotificationChannelCreated(channel, uid, pkg); } return needsPolicyFileChange; }","@Override public boolean createNotificationChannel(String pkg, int uid, NotificationChannel channel, boolean fromTargetApp, boolean hasDndAccess) { Objects.requireNonNull(pkg); Objects.requireNonNull(channel); Objects.requireNonNull(channel.getId()); Preconditions.checkArgument(!TextUtils.isEmpty(channel.getName())); boolean needsPolicyFileChange = false, wasUndeleted = false; synchronized (mPackagePreferences) { PackagePreferences r = getOrCreatePackagePreferencesLocked(pkg, uid); if (r == null) { throw new IllegalArgumentException(""Invalid package""); } if (channel.getGroup() != null && !r.groups.containsKey(channel.getGroup())) { throw new IllegalArgumentException(""NotificationChannelGroup doesn't exist""); } if (NotificationChannel.DEFAULT_CHANNEL_ID.equals(channel.getId())) { throw new IllegalArgumentException(""Reserved id""); } NotificationChannel existing = r.channels.get(channel.getId()); if (existing != null && fromTargetApp) { // Actually modifying an existing channel - keep most of the existing settings if (existing.isDeleted()) { // The existing channel was deleted - undelete it. existing.setDeleted(false); needsPolicyFileChange = true; wasUndeleted = true; // log a resurrected channel as if it's new again MetricsLogger.action(getChannelLog(channel, pkg).setType( com.android.internal.logging.nano.MetricsProto.MetricsEvent.TYPE_OPEN)); mNotificationChannelLogger.logNotificationChannelCreated(channel, uid, pkg); } if (!Objects.equals(channel.getName().toString(), existing.getName().toString())) { existing.setName(channel.getName().toString()); needsPolicyFileChange = true; } if (!Objects.equals(channel.getDescription(), existing.getDescription())) { existing.setDescription(channel.getDescription()); needsPolicyFileChange = true; } if (channel.isBlockable() != existing.isBlockable()) { existing.setBlockable(channel.isBlockable()); needsPolicyFileChange = true; } if (channel.getGroup() != null && existing.getGroup() == null) { existing.setGroup(channel.getGroup()); needsPolicyFileChange = true; } // Apps are allowed to downgrade channel importance if the user has not changed any // fields on this channel yet. final int previousExistingImportance = existing.getImportance(); final int previousLoggingImportance = NotificationChannelLogger.getLoggingImportance(existing); if (existing.getUserLockedFields() == 0 && channel.getImportance() < existing.getImportance()) { existing.setImportance(channel.getImportance()); needsPolicyFileChange = true; } // system apps and dnd access apps can bypass dnd if the user hasn't changed any // fields on the channel yet if (existing.getUserLockedFields() == 0 && hasDndAccess) { boolean bypassDnd = channel.canBypassDnd(); if (bypassDnd != existing.canBypassDnd() || wasUndeleted) { existing.setBypassDnd(bypassDnd); needsPolicyFileChange = true; if (bypassDnd != mAreChannelsBypassingDnd || previousExistingImportance != existing.getImportance()) { updateChannelsBypassingDnd(); } } } if (existing.getOriginalImportance() == IMPORTANCE_UNSPECIFIED) { existing.setOriginalImportance(channel.getImportance()); needsPolicyFileChange = true; } updateConfig(); if (needsPolicyFileChange && !wasUndeleted) { mNotificationChannelLogger.logNotificationChannelModified(existing, uid, pkg, previousLoggingImportance, false); } return needsPolicyFileChange; } if (r.channels.size() >= NOTIFICATION_CHANNEL_COUNT_LIMIT) { throw new IllegalStateException(""Limit exceed; cannot create more channels""); } needsPolicyFileChange = true; if (channel.getImportance() < IMPORTANCE_NONE || channel.getImportance() > NotificationManager.IMPORTANCE_MAX) { throw new IllegalArgumentException(""Invalid importance level""); } // Reset fields that apps aren't allowed to set. if (fromTargetApp && !hasDndAccess) { channel.setBypassDnd(r.priority == Notification.PRIORITY_MAX); } if (fromTargetApp) { channel.setLockscreenVisibility(r.visibility); channel.setAllowBubbles(existing != null ? existing.getAllowBubbles() : NotificationChannel.DEFAULT_ALLOW_BUBBLE); } clearLockedFieldsLocked(channel); channel.setImportanceLockedByOEM(r.oemLockedImportance); if (!channel.isImportanceLockedByOEM()) { if (r.oemLockedChannels.contains(channel.getId())) { channel.setImportanceLockedByOEM(true); } } channel.setImportanceLockedByCriticalDeviceFunction(r.defaultAppLockedImportance); if (channel.getLockscreenVisibility() == Notification.VISIBILITY_PUBLIC) { channel.setLockscreenVisibility( NotificationListenerService.Ranking.VISIBILITY_NO_OVERRIDE); } if (!r.showBadge) { channel.setShowBadge(false); } channel.setOriginalImportance(channel.getImportance()); // validate parent if (channel.getParentChannelId() != null) { Preconditions.checkArgument(r.channels.containsKey(channel.getParentChannelId()), ""Tried to create a conversation channel without a preexisting parent""); } r.channels.put(channel.getId(), channel); if (channel.canBypassDnd() != mAreChannelsBypassingDnd) { updateChannelsBypassingDnd(); } MetricsLogger.action(getChannelLog(channel, pkg).setType( com.android.internal.logging.nano.MetricsProto.MetricsEvent.TYPE_OPEN)); mNotificationChannelLogger.logNotificationChannelCreated(channel, uid, pkg); } return needsPolicyFileChange; }","[Notification] Fix Notification channel Dnd bypass for multiusers -Permission granted for a given package using shell cmd (user system) are not sufficient due to a check of notification uid vs packagepreference uid. -If the packagepreference is deleted then restored, the channel preference are not taken into account. Bug: 178032672 Test: CTS/AudioManagerTest Signed-off-by: Francois Gaffie Change-Id: Ia26467f27b31bc048bdb141beac7d764fcb27f51 Merged-in: Ia26467f27b31bc048bdb141beac7d764fcb27f51",https://github.com/omnirom/android_frameworks_base/commit/92a9f5fc1d07d5ab8b89b02d09b73f355595449c,,,services/core/java/com/android/server/notification/PreferencesHelper.java,3,java,False,2021-02-24T16:26:29Z "def try_ldap_login(login, password): """""" Connect to a LDAP directory to verify user login/passwords"""""" result = ""Wrong login/password"" s = Server(config.LDAPURI, port=config.LDAPPORT, use_ssl=False, get_info=ALL) # 1. connection with service account to find the user uid uid = useruid(s, escape_rdn(login)) if uid: # 2. Try to bind the user to the LDAP c = Connection(s, user = uid , password = password, auto_bind = True) c.open() c.bind() result = c.result[""description""] # ""success"" if bind is ok c.unbind() return result","def try_ldap_login(login, password): """""" Connect to a LDAP directory to verify user login/passwords"""""" result = ""Wrong login/password"" s = Server(config.LDAPURI, port=config.LDAPPORT, use_ssl=False, get_info=ALL) # 1. connection with service account to find the user uid uid = useruid(s, escape_filter_chars(login)) if uid: # 2. Try to bind the user to the LDAP c = Connection(s, user = uid , password = password, auto_bind = True) c.open() c.bind() result = c.result[""description""] # ""success"" if bind is ok c.unbind() return result",Replace escape_rdn with escape_filter_chars,https://github.com/LibrIT/passhport/commit/1dcd0f7dff9e2ad800c26fad7a3d59294dc5a7de,,,passhportd/app/views_mod/user/user.py,3,py,False,2021-03-25T09:51:37Z "function baseMerge(object, source, srcIndex, customizer, stack) { if (object === source) { return; } baseFor(source, function(srcValue, key) { if (isObject(srcValue)) { stack || (stack = new Stack); baseMergeDeep(object, source, key, srcIndex, baseMerge, customizer, stack); } else { var newValue = customizer ? customizer(object[key], srcValue, (key + ''), object, source, stack) : undefined; if (newValue === undefined) { newValue = srcValue; } assignMergeValue(object, key, newValue); } }, keysIn); }","function baseMerge(object, source, srcIndex, customizer, stack) { if (object === source) { return; } baseFor(source, function(srcValue, key) { if (isObject(srcValue)) { stack || (stack = new Stack); baseMergeDeep(object, source, key, srcIndex, baseMerge, customizer, stack); } else { var newValue = customizer ? customizer(safeGet(object, key), srcValue, (key + ''), object, source, stack) : undefined; if (newValue === undefined) { newValue = srcValue; } assignMergeValue(object, key, newValue); } }, keysIn); }",Avoid merging properties on to __proto__ objects.,https://github.com/lodash/lodash/commit/d8e069cc3410082e44eb18fcf8e7f3d08ebe1d4a,CVE-2018-3721,"['NVD-CWE-noinfo', 'CWE-471']",lodash.js,3,js,False,2018-01-31T07:21:12Z "public static String var(int id) { if (id == 36) { return ""#""; } for (int i = 0; i < cachedCustomComponents.size(); i++) { HashMap component = cachedCustomComponents.get(i); Object componentId = component.get(""id""); if (componentId instanceof String) { try { int componentIdInteger = Integer.parseInt((String) componentId); if (componentIdInteger == id) { Object componentVarName = component.get(""varName""); if (componentVarName instanceof String) { return (String) componentVarName; } else { SketchwareUtil.toastError(""Invalid variable name entry for Custom Component #"" + (i + 1), Toast.LENGTH_LONG); break; } } } catch (NumberFormatException e) { SketchwareUtil.toastError(""Invalid ID entry for Custom Component #"" + (i + 1), Toast.LENGTH_LONG); } } else { SketchwareUtil.toastError(""Invalid ID entry for Custom Component #"" + (i + 1), Toast.LENGTH_LONG); } } return """"; }","public static String var(int id) { if (id == 36) { return ""#""; } for (int i = 0; i < cachedCustomComponents.size(); i++) { HashMap component = cachedCustomComponents.get(i); if (component != null) { Object componentId = component.get(""id""); if (componentId instanceof String) { try { int componentIdInteger = Integer.parseInt((String) componentId); if (componentIdInteger == id) { Object componentVarName = component.get(""varName""); if (componentVarName instanceof String) { return (String) componentVarName; } else { SketchwareUtil.toastError(""Invalid variable name entry for Custom Component #"" + (i + 1), Toast.LENGTH_LONG); break; } } } catch (NumberFormatException e) { SketchwareUtil.toastError(""Invalid ID entry for Custom Component #"" + (i + 1), Toast.LENGTH_LONG); } } else { SketchwareUtil.toastError(""Invalid ID entry for Custom Component #"" + (i + 1), Toast.LENGTH_LONG); } } else { SketchwareUtil.toastError(""Invalid (null) Custom Component at position "" + i); } } return """"; }","fix: Handle null Custom Components and don't crash on an NPE Related to commit 2db1b76b7ac5631b52e6ce15e801aa1a4063d856: ""fix: Handle null Custom Events and don't crash on an NPE"".",https://github.com/Sketchware-Pro/Sketchware-Pro/commit/833da0d273674c5a0a0ee138c209b3ba28886690,,,app/src/main/java/mod/hilal/saif/components/ComponentsHandler.java,3,java,False,2022-09-25T09:44:49Z "public void refundConsumed(){ for(ItemStack i : consumedStacks){ ItemEntity entity = new ItemEntity(level, getX(), getY(), getZ(), i); level.addFreshEntity(entity); consumedStacks = new ArrayList<>(); } if(recipe != null) { int exp = recipe.exp; if (level instanceof ServerLevel serverLevel) ExperienceOrb.award(serverLevel, new Vec3(getX(), getY(), getZ()), exp); } }","public void refundConsumed(){ for(ItemStack i : consumedStacks){ ItemEntity entity = new ItemEntity(level, getX(), getY(), getZ(), i); level.addFreshEntity(entity); consumedStacks = new ArrayList<>(); } if(recipe != null) { int exp = recipe.exp; if (level instanceof ServerLevel serverLevel) ExperienceOrb.award(serverLevel, new Vec3(getX(), getY(), getZ()), exp); } recipe = null; recipeID = null; craftingTicks = 0; crafting = false; updateBlock(); }",Fix glyph crafting exploit #496,https://github.com/baileyholl/Ars-Nouveau/commit/b894c1cabdf6e51dbb33f724355a5bb4ba31f3f7,,,src/main/java/com/hollingsworth/arsnouveau/common/block/tile/ScribesTile.java,3,java,False,2022-04-15T02:23:50Z "public static MessageContainer queueMessage(String message) { if (!Reference.onWorld) return null; if (OverlayConfig.GameUpdate.INSTANCE.messageMaxLength != 0 && OverlayConfig.GameUpdate.INSTANCE.messageMaxLength < message.length()) { message = message.substring(0, OverlayConfig.GameUpdate.INSTANCE.messageMaxLength - 4); if (message.endsWith(""§"")) { message = message.substring(0, OverlayConfig.GameUpdate.INSTANCE.messageMaxLength - 5); } message = message + ""...""; } String processedMessage = message; LogManager.getFormatterLogger(""GameTicker"").info(""Message Queued: "" + processedMessage); MessageContainer msgContainer = new MessageContainer(processedMessage); McIf.mc().addScheduledTask(() -> { messageQueue.add(msgContainer); if (OverlayConfig.GameUpdate.INSTANCE.overrideNewMessages && messageQueue.size() > OverlayConfig.GameUpdate.INSTANCE.messageLimit) messageQueue.remove(0); }); return msgContainer; }","public static MessageContainer queueMessage(String message) { if (!Reference.onWorld) return null; if (OverlayConfig.GameUpdate.INSTANCE.messageMaxLength != 0 && OverlayConfig.GameUpdate.INSTANCE.messageMaxLength < message.length()) { message = message.substring(0, Math.max(2, OverlayConfig.GameUpdate.INSTANCE.messageMaxLength - 4)); if (message.endsWith(""§"")) { message = message.substring(0, Math.max(2, OverlayConfig.GameUpdate.INSTANCE.messageMaxLength - 5)); } message = message + ""...""; } String processedMessage = message; LogManager.getFormatterLogger(""GameTicker"").info(""Message Queued: "" + processedMessage); MessageContainer msgContainer = new MessageContainer(processedMessage); McIf.mc().addScheduledTask(() -> { messageQueue.add(msgContainer); if (OverlayConfig.GameUpdate.INSTANCE.overrideNewMessages && messageQueue.size() > OverlayConfig.GameUpdate.INSTANCE.messageLimit) messageQueue.remove(0); }); return msgContainer; }","Fix 14 issues found in ticket backlog (#502) * Fix IndexOutOfBoundsException in QuestBookListPage Signed-off-by: kristofbolyai * Fix crash if OverlayConfig.GameUpdate.INSTANCE.messageMaxLength is 1 Signed-off-by: kristofbolyai * Fix crash related to deleting chat tabs and ChatGUI not updating Signed-off-by: kristofbolyai * Fix crash related to deleting chat tabs and ChatGUI not updating Signed-off-by: kristofbolyai * Fix translation cache becoming null Signed-off-by: kristofbolyai * Fix objective parsing if player is in party Signed-off-by: kristofbolyai * Fix guild objective not being removed upon completion Signed-off-by: kristofbolyai * Fix race condition in ServerEvents Signed-off-by: kristofbolyai * Fix race condition in ClientEvents Signed-off-by: kristofbolyai * Fix NPE in ServerEvents Signed-off-by: kristofbolyai * Fix AreaDPS value not being correct Signed-off-by: kristofbolyai * Fix NPE in fix :) Signed-off-by: kristofbolyai * Fix quest dialogue spoofing Signed-off-by: kristofbolyai * Fix Keyholder related crash Signed-off-by: kristofbolyai * Fix totem tracking Signed-off-by: kristofbolyai * Dialogue Page gets updated correctly Signed-off-by: kristofbolyai * Register ChatGUI correctly Signed-off-by: kristofbolyai * Use MC's GameSettings to check for isKeyDown Signed-off-by: kristofbolyai * Make multi line if have braces Signed-off-by: kristofbolyai ",https://github.com/Wynntils/Wynntils/commit/c8f6effe187ff68f17bcff809d2bc440ec07128d,,,src/main/java/com/wynntils/modules/utilities/overlays/hud/GameUpdateOverlay.java,3,java,False,2022-04-15T17:16:00Z "@Override @Transactional(rollbackFor = Exception.class) public Result onlineCreateResource(User loginUser, ResourceType type, String fileName, String fileSuffix, String desc, String content, int pid, String currentDir) { Result result = checkResourceUploadStartupState(); if (!result.getCode().equals(Status.SUCCESS.getCode())) { return result; } //check file suffix String nameSuffix = fileSuffix.trim(); String resourceViewSuffixes = FileUtils.getResourceViewSuffixes(); if (StringUtils.isNotEmpty(resourceViewSuffixes)) { List strList = Arrays.asList(resourceViewSuffixes.split("","")); if (!strList.contains(nameSuffix)) { logger.error(""resource suffix {} not support create"", nameSuffix); putMsg(result, Status.RESOURCE_SUFFIX_NOT_SUPPORT_VIEW); return result; } } String name = fileName.trim() + ""."" + nameSuffix; String fullName = getFullName(currentDir, name); result = verifyResource(loginUser, type, fullName, pid); if (!result.getCode().equals(Status.SUCCESS.getCode())) { return result; } // save data Date now = new Date(); Resource resource = new Resource(pid, name, fullName, false, desc, name, loginUser.getId(), type, content.getBytes().length, now, now); resourcesMapper.insert(resource); updateParentResourceSize(resource, resource.getSize()); putMsg(result, Status.SUCCESS); Map resultMap = new HashMap<>(); for (Map.Entry entry : new BeanMap(resource).entrySet()) { if (!Constants.CLASS.equalsIgnoreCase(entry.getKey().toString())) { resultMap.put(entry.getKey().toString(), entry.getValue()); } } result.setData(resultMap); String tenantCode = tenantMapper.queryById(loginUser.getTenantId()).getTenantCode(); result = uploadContentToStorage(fullName, tenantCode, content); if (!result.getCode().equals(Status.SUCCESS.getCode())) { throw new ServiceException(result.getMsg()); } return result; }","@Override @Transactional(rollbackFor = Exception.class) public Result onlineCreateResource(User loginUser, ResourceType type, String fileName, String fileSuffix, String desc, String content, int pid, String currentDir) { Result result = checkResourceUploadStartupState(); if (!result.getCode().equals(Status.SUCCESS.getCode())) { return result; } if (FileUtils.directoryTraversal(fileName)) { putMsg(result, Status.VERIFY_PARAMETER_NAME_FAILED); return result; } //check file suffix String nameSuffix = fileSuffix.trim(); String resourceViewSuffixes = FileUtils.getResourceViewSuffixes(); if (StringUtils.isNotEmpty(resourceViewSuffixes)) { List strList = Arrays.asList(resourceViewSuffixes.split("","")); if (!strList.contains(nameSuffix)) { logger.error(""resource suffix {} not support create"", nameSuffix); putMsg(result, Status.RESOURCE_SUFFIX_NOT_SUPPORT_VIEW); return result; } } String name = fileName.trim() + ""."" + nameSuffix; String fullName = getFullName(currentDir, name); result = verifyResource(loginUser, type, fullName, pid); if (!result.getCode().equals(Status.SUCCESS.getCode())) { return result; } // save data Date now = new Date(); Resource resource = new Resource(pid, name, fullName, false, desc, name, loginUser.getId(), type, content.getBytes().length, now, now); resourcesMapper.insert(resource); updateParentResourceSize(resource, resource.getSize()); putMsg(result, Status.SUCCESS); Map resultMap = new HashMap<>(); for (Map.Entry entry : new BeanMap(resource).entrySet()) { if (!Constants.CLASS.equalsIgnoreCase(entry.getKey().toString())) { resultMap.put(entry.getKey().toString(), entry.getValue()); } } result.setData(resultMap); String tenantCode = tenantMapper.queryById(loginUser.getTenantId()).getTenantCode(); result = uploadContentToStorage(fullName, tenantCode, content); if (!result.getCode().equals(Status.SUCCESS.getCode())) { throw new ServiceException(result.getMsg()); } return result; }","[fix] Enhance name pre checker in resource center (#10094) * [fix] Enhance name pre checker in resource center Add file name and directory checker to avoid directory traversal * add some missing change and change docs * change var name in directoryTraversal * Fix ci",https://github.com/apache/dolphinscheduler/commit/63f835715f8ca8bff79c0e7177ebfa5917ebb3bd,,,dolphinscheduler-api/src/main/java/org/apache/dolphinscheduler/api/service/impl/ResourcesServiceImpl.java,3,java,False,2022-05-18T10:40:17Z "void execOrFail(ExecutorNames _executor, Runnable _r) { execOrFail(_executor, _r, 0); }","void execOrFail(ExecutorNames _executor, Runnable _r) { if (_r == null || _executor == null) { // ignore invalid runnables or executors return; } int failCount = 0; while (failCount < MAX_RETRIES) { try { ExecutorService exec = executors.get(_executor); if (exec == null) { // this should never happen, map is initialized in constructor throw new IllegalThreadPoolStateException(""No executor found for "" + _executor); } else if (closed || exec.isShutdown() || exec.isTerminated()) { throw new IllegalThreadPoolStateException(""Receiving service already closed""); } exec.execute(_r); break; // execution done, no retry needed } catch (IllegalThreadPoolStateException _ex) { // just throw our exception throw _ex; } catch (Exception _ex) { if (retryHandler == null) { logger.error(""Could not handle runnable for executor {}, runnable will be dropped"", _executor, _ex); break; // no handler, assume ignoring runnable is ok } failCount++; if (!retryHandler.handle(_executor, _ex)) { logger.trace(""Ignoring unhandled runnable for executor {} due to {}, dropped by retry handler"", _executor, _ex.getClass().getName()); } } } if (failCount >= MAX_RETRIES) { logger.error(""Could not handle runnable for executor {} after {} retries, runnable will be dropped"", _executor, failCount); } }",Added missing initialization; Fixed wrong javadoc,https://github.com/hypfvieh/dbus-java/commit/d222cd35dc8100917829eb9fc2b8550358d5d4ef,,,dbus-java-core/src/main/java/org/freedesktop/dbus/connections/ReceivingService.java,3,java,False,2022-07-14T18:39:25Z "static async getInitialProps (ctx) { const session = new Session({req: ctx.req}); let initialProps = {}; if (Component.getInitialProps) { initialProps = Component.getInitialProps({...ctx, session}); } const sessionData = await session.getSession(); let isLoggedIn = false; if (sessionData.user && sessionData.user.username) { isLoggedIn = true; } return {session: sessionData, isLoggedIn, ...initialProps}; }","static async getInitialProps (ctx) { const session = new Session({req: ctx.req}); let initialProps = {}; if (Component.getInitialProps) { initialProps = Component.getInitialProps({...ctx, session}); } const sessionData = await session.getSession(); let isLoggedIn = false; if (sessionData.user && sessionData.user.username && sessionData.authToken) { isLoggedIn = true; } return {session: sessionData, isLoggedIn, ...initialProps}; }",force login if token doesn't exist,https://github.com/open5gs/open5gs/commit/8b321f103b8ae669e487c8ece1a3308f93801b6c,CVE-2021-28122,['CWE-306'],webui/src/helpers/with-session.js,3,js,False,2021-03-11T15:27:26Z "@Override public Authentication authenticate(Authentication authentication) throws AuthenticationException { if (authentication.isAuthenticated()) { return authentication; } ExtendedAuthenticationToken token = (ExtendedAuthenticationToken) authentication; String code = token.getCode(); IamAccount account = accountRepo.findByUsername(authentication.getName()) .orElseThrow(() -> new BadCredentialsException(""Invalid login details"")); IamTotpMfa totpMfa = account.getTotpMfa(); if (code != null && totpMfa != null && totpMfa.isActive()) { if (codeVerifier.isValidCode(totpMfa.getSecret(), code)) { IamAuthenticationMethodReference otp = new IamAuthenticationMethodReference(ONE_TIME_PASSWORD.getValue()); Set refs = token.getAuthenticationMethodReferences(); refs.add(otp); token.setAuthenticationMethodReferences(refs); token.setAuthenticated(true); List authorities = new ArrayList<>(); for (GrantedAuthority authority : authentication.getAuthorities()) { authorities.add(new SimpleGrantedAuthority(authority.getAuthority())); } authorities.remove(new SimpleGrantedAuthority(""ROLE_PRE_AUTHENTICATED"")); account.getAuthorities() .stream() .forEach( authority -> authorities.add(new SimpleGrantedAuthority(authority.getAuthority()))); ExtendedAuthenticationToken newToken = new ExtendedAuthenticationToken(token.getPrincipal(), token.getCredentials(), authorities, token.getAuthenticationMethodReferences()); newToken.setAuthenticated(true); return newToken; } } return null; }","@Override public Authentication authenticate(Authentication authentication) throws AuthenticationException { ExtendedAuthenticationToken token = (ExtendedAuthenticationToken) authentication; IamAccount account = accountRepo.findByUsername(authentication.getName()) .orElseThrow(() -> new BadCredentialsException(""Invalid login details"")); String mfaSecret = account.getTotpMfa().getSecret(); String code = token.getCode(); if (!codeVerifier.isValidCode(mfaSecret, code)) { throw new BadCredentialsException(""Bad code""); } IamAuthenticationMethodReference otp = new IamAuthenticationMethodReference(ONE_TIME_PASSWORD.getValue()); Set refs = token.getAuthenticationMethodReferences(); refs.add(otp); token.setAuthenticationMethodReferences(refs); List authorities = new ArrayList<>(); for (GrantedAuthority authority : authentication.getAuthorities()) { authorities.add(new SimpleGrantedAuthority(authority.getAuthority())); } authorities.remove(new SimpleGrantedAuthority(""ROLE_PRE_AUTHENTICATED"")); account.getAuthorities() .stream() .forEach(authority -> authorities.add(new SimpleGrantedAuthority(authority.getAuthority()))); ExtendedAuthenticationToken newToken = new ExtendedAuthenticationToken(token.getPrincipal(), token.getCredentials(), authorities, token.getAuthenticationMethodReferences()); newToken.setAuthenticated(true); return newToken; }","Fixing TOTP verification process Incorrect setting of failure handlers and handling of errors in general meant incorrect TOTPs would cause a crash. Incorrect codes now redirect back to the /verify endpoint in the same way as a failed credential check would redirect back to the /login endpoint",https://github.com/indigo-iam/iam/commit/dc01d78eec671b039faa79f9614d087cfa09b96a,,,iam-login-service/src/main/java/it/infn/mw/iam/authn/multi_factor_authentication/MultiFactorCodeCheckProvider.java,3,java,False,2022-02-25T18:02:03Z "@SubscribeEvent public static void registerRankConfigHandler(RegisterRankConfigHandlerEvent event) { LoggingHandler.felog.debug(""registerRankConfigHandler()""); if (!FTBUtilitiesConfig.ranks.enabled) { event.setHandler(INSTANCE); } else { LoggingHandler.felog.info(""Ranks are active... Not registering configs!""); } }","@SubscribeEvent public static void registerRankConfigHandler(RegisterRankConfigHandlerEvent event) { LoggingHandler.felog.debug(""registerRankConfigHandler()""); if (INSTANCE.isFTBURanksActive()) { LoggingHandler.felog.info(""Ranks are active... Not registering configs!""); } else { event.setHandler(INSTANCE); } }",Fix Rank Config Handler to not crash if FTBU is not installed and FTBLib is,https://github.com/ForgeEssentials/ForgeEssentials/commit/be72745fd2c1998970dc0fa115e06a429a92adec,,,src/main/java/com/forgeessentials/permissions/ftbu_compat/FTBURankConfigHandler.java,3,java,False,2021-07-07T17:47:22Z "@Override public void process(final NoPayloadStruct payload, final Player player) throws Exception { if (player == null || !player.getWorld().getServer().getConfig().SHOW_TUTORIAL_SKIP_OPTION) { return; } player.skipTutorial(); }","@Override public void process(final NoPayloadStruct payload, final Player player) throws Exception { if (player == null) { return; } player.skipTutorial(); }",CF-3001 | Moved show_tutorial_skip_option to skipTutorial function to avoid bypassing the tutorial via ::skiptutorial,https://github.com/Open-RSC/Core-Framework/commit/7ff993f96a077756e1b0e7ff96d72f8c40c585b9,,,server/src/com/openrsc/server/net/rsc/handlers/TutorialHandler.java,3,java,False,2021-09-16T03:49:28Z "private void upgradePermissions(final int version, final Rank rank) { // keep this consistent with loadRanks(), as that's still used for new colonies if (version < 4) { if (rank.isHostile()) { this.setPermission(rank, Action.HURT_CITIZEN); this.setPermission(rank, Action.HURT_VISITOR); } if (rank.isColonyManager()) { this.setPermission(rank, Action.MAP_DEATHS); } this.setPermission(rank, Action.MAP_BORDER); } // if (version < 5) ... }","private void upgradePermissions(final int version, final Rank rank) { // keep this consistent with loadRanks(), as that's still used for new colonies if (version < 4) { if (rank.isHostile()) { this.setPermission(rank, Action.HURT_CITIZEN, true); this.setPermission(rank, Action.HURT_VISITOR, true); } if (rank.isColonyManager()) { this.setPermission(rank, Action.MAP_DEATHS, true); } this.setPermission(rank, Action.MAP_BORDER, true); } // if (version < 5) ... // Fix bad saved values if (rank == getRankOwner()) { rank.addPermission(Action.EDIT_PERMISSIONS); rank.addPermission(Action.ACCESS_HUTS); rank.addPermission(Action.MANAGE_HUTS); } }","Fix permission issues (#7972) Ranks are no longer a static map, which was used as a per-colony map thus causing crashes and desyncs. If the last colony loaded had a custom rank, all other colonies would crash out due to not matching permissions for that rank. Permission/Rank seperation is removed, permission flag is now part of the rank instead of an externally synced map, which also auto-corrects bad stored data to default permissions. UI now has non-changeable permission buttons disabled.",https://github.com/ldtteam/minecolonies/commit/b1b86dffe64dd4c0f9d3060769fc418fd5d2869a,,,src/main/java/com/minecolonies/coremod/colony/permissions/Permissions.java,3,java,False,2022-01-23T12:23:45Z "private void updateVulnerability(String ecosystem, DSLContext dbContext) { updateVulnerabilityPatchData(); logger.info(vulnerability.getId() + "": Inserting vulnerability into the database for ecosystem: "" + ""\"""" + ecosystem + ""\"".""); var relevantPurls = getPurlsForEcosystem(vulnerability.getValidatedPurls(), ecosystem); // TODO: call clean-up method here this.vulnerabilityId = metadataUtility.insertVulnerability(vulnerability, relevantPurls, dbContext); updatePurls(relevantPurls, null, dbContext); }","private void updateVulnerability(String ecosystem, DSLContext dbContext) { updateVulnerabilityPatchData(); logger.info(vulnerability.getId() + "": Inserting vulnerability into the database for ecosystem: "" + ""\"""" + ecosystem + ""\"".""); var relevantPurls = getPurlsForEcosystem(vulnerability.getValidatedPurls(), ecosystem); vulnerabilityId = metadataUtility.insertVulnerability(vulnerability, dbContext); metadataUtility.deleteVulnerabilityData(vulnerability.getId(), vulnerabilityId, dbContext); metadataUtility.insertPurls(vulnerabilityId, relevantPurls, dbContext); updatePackageVersions(relevantPurls, null, dbContext); }","Added methods to clean up existing vulnerability data in package versions and callables, prior to adding the new data.",https://github.com/fasten-project/fasten/commit/c2cc86b44e4b65f0f1e541cece1da2b239cd6809,,,analyzer/vulnerability-statements-processor/src/main/java/eu/fasten/analyzer/vulnerabilitystatementsprocessor/VulnerabilityStatementsProcessor.java,3,java,False,2022-01-15T22:32:55Z "@Inject public void init( @Named(""dataDirectory"") Path dataDirectory, ConfigLoader configLoader, FloodgateConfigHolder configHolder, PacketHandlers packetHandlers, HandshakeHandlers handshakeHandlers) { if (!Files.isDirectory(dataDirectory)) { try { Files.createDirectory(dataDirectory); } catch (IOException exception) { logger.error(""Failed to create the data folder"", exception); throw new RuntimeException(""Failed to create the data folder"", exception); } } config = configLoader.load(); if (config.isDebug()) { logger.enableDebug(); } configHolder.set(config); guice = guice.createChildInjector(new ConfigLoadedModule(config)); PlayerLink link = guice.getInstance(PlayerLinkLoader.class).load(); TimeSyncerHolder.init(); InstanceHolder.set(api, link, this.injector, packetHandlers, handshakeHandlers, KEY); // for Geyser dump FloodgateInfoHolder.setGitProperties(properties.getProperties()); guice.getInstance(NewsChecker.class).start(); }","@Inject public void init( @Named(""dataDirectory"") Path dataDirectory, ConfigLoader configLoader, FloodgateConfigHolder configHolder, PacketHandlers packetHandlers, HandshakeHandlers handshakeHandlers) { if (!Files.isDirectory(dataDirectory)) { try { Files.createDirectory(dataDirectory); } catch (IOException exception) { logger.error(""Failed to create the data folder"", exception); throw new RuntimeException(""Failed to create the data folder"", exception); } } config = configLoader.load(); if (config.isDebug()) { logger.enableDebug(); } configHolder.set(config); guice = guice.createChildInjector(new ConfigLoadedModule(config)); PlayerLink link = guice.getInstance(PlayerLinkLoader.class).load(); if (config.isProxy()) { // We can't assume, for now, that the backend Floodgate instances are updated to remove this TimeSyncerHolder.init(); } InstanceHolder.set(api, link, this.injector, packetHandlers, handshakeHandlers, KEY); // for Geyser dump FloodgateInfoHolder.setGitProperties(properties.getProperties()); guice.getInstance(NewsChecker.class).start(); }","Remove time syncer checks This check has caused more harm than good (with needing to use an external NTP source and some providers not allowing Cloudflare's NTP server), and is also a technical vulnerability in BungeeGuard. In order to exploit this, you would need to capture traffic between the Geyser server and the Floodgate instance.",https://github.com/GeyserMC/Floodgate/commit/08178f51b7bdda09ac208c0cdd1ee7704dbe15fd,,,common/src/main/java/org/geysermc/floodgate/FloodgatePlatform.java,3,java,False,2021-09-27T18:45:53Z "@Override public void doGet(HttpServletRequest request, HttpServletResponse response) { final String host = request.getParameter(""host""); // Validate that we're connected to the host final SessionManager sessionManager = SessionManager.getInstance(); final Optional optionalHost = Stream .concat(sessionManager.getIncomingServers().stream(), sessionManager.getOutgoingServers().stream()) .filter(remoteServerHost -> remoteServerHost.equalsIgnoreCase(host)) .findAny(); if (!optionalHost.isPresent()) { LOGGER.info(""Request to unconnected host {} ignored - using default response"", host); writeBytesToStream(defaultBytes, response); return; } // Check special cases where we need to change host to get a favicon final String hostToUse = ""gmail.com"".equals(host) ? ""google.com"" : host; byte[] bytes = getImage(hostToUse, defaultBytes); if (bytes != null) { writeBytesToStream(bytes, response); } }","@Override public void doGet(HttpServletRequest request, HttpServletResponse response) { final String host = request.getParameter(""host""); // OF-1885: Ensure that the provided value is a valid hostname. try { //noinspection ResultOfMethodCallIgnored InetAddress.getByName(host); } catch (UnknownHostException e) { LOGGER.info(""Request for favicon of hostname that can't be parsed as a valid hostname '{}' is ignored."", host, e); writeBytesToStream(defaultBytes, response); return; } // Validate that we're connected to the host final SessionManager sessionManager = SessionManager.getInstance(); final Optional optionalHost = Stream .concat(sessionManager.getIncomingServers().stream(), sessionManager.getOutgoingServers().stream()) .filter(remoteServerHost -> remoteServerHost.equalsIgnoreCase(host)) .findAny(); if (!optionalHost.isPresent()) { LOGGER.info(""Request to unconnected host {} ignored - using default response"", host); writeBytesToStream(defaultBytes, response); return; } // Check special cases where we need to change host to get a favicon final String hostToUse = ""gmail.com"".equals(host) ? ""google.com"" : host; byte[] bytes = getImage(hostToUse, defaultBytes); if (bytes != null) { writeBytesToStream(bytes, response); } }","OF-2518: Attempt to load favicon over HTTPS This adds an additional attempt to load the favicon. With this, both HTTPS and HTTP are attempted. Additionally, the URL that's used is now being constructed through a builder, which should further reduce the attack vector of using 'user-provided input'.",https://github.com/igniterealtime/Openfire/commit/1b6722fdd8d660c6a60509c3ad252041220f47e0,,,xmppserver/src/main/java/org/jivesoftware/util/FaviconServlet.java,3,java,False,2022-10-04T18:46:22Z "public void update() { try (Cursor cursor = mContext.getContentResolver().query( Downloads.Impl.ALL_DOWNLOADS_CONTENT_URI, UpdateQuery.PROJECTION, Downloads.Impl.COLUMN_DELETED + "" == '0'"", null, null)) { synchronized (mActiveNotifs) { updateWithLocked(cursor); } } }","public void update() { try (Cursor cursor = mContext.getContentResolver().query( Downloads.Impl.ALL_DOWNLOADS_CONTENT_URI, UpdateQuery.PROJECTION, Downloads.Impl.COLUMN_DELETED + "" == '0'"", null, null)) { if (cursor == null) { Log.e(TAG, ""Cursor is null, will ignore update""); return; } synchronized (mActiveNotifs) { updateWithLocked(cursor); } } }","Fix potential crash when calling update but query db failed This crash should not happen in normal case, but we can improve robustness of the code since ContentResolver.query() can possibly return null as its comment says Fixes: 254186235 Test: manual Change-Id: Ic4bb48b2f2048921681d7b3c45471c3b818f95b6",https://github.com/aosp-mirror/platform_packages_providers_downloadprovider/commit/98491a4ef11f7a412e067f69b644c09227b2e419,,,src/com/android/providers/downloads/DownloadNotifier.java,3,java,False,2022-10-18T07:27:10Z "def urlopen(self, method, url, redirect=True, **kw): """""" Same as :meth:`urllib3.connectionpool.HTTPConnectionPool.urlopen` with custom cross-host redirect logic and only sends the request-uri portion of the ``url``. The given ``url`` parameter must be absolute, such that an appropriate :class:`urllib3.connectionpool.ConnectionPool` can be chosen for it. """""" u = parse_url(url) conn = self.connection_from_host(u.host, port=u.port, scheme=u.scheme) kw['assert_same_host'] = False kw['redirect'] = False if 'headers' not in kw: kw['headers'] = self.headers.copy() if self.proxy is not None and u.scheme == ""http"": response = conn.urlopen(method, url, **kw) else: response = conn.urlopen(method, u.request_uri, **kw) redirect_location = redirect and response.get_redirect_location() if not redirect_location: return response # Support relative URLs for redirecting. redirect_location = urljoin(url, redirect_location) # RFC 7231, Section 6.4.4 if response.status == 303: method = 'GET' retries = kw.get('retries') if not isinstance(retries, Retry): retries = Retry.from_int(retries, redirect=redirect) # Strip headers marked as unsafe to forward to the redirected location. # Check remove_headers_on_redirect to avoid a potential network call within # conn.is_same_host() which may use socket.gethostbyname() in the future. if (retries.remove_headers_on_redirect and not conn.is_same_host(redirect_location)): for header in retries.remove_headers_on_redirect: kw['headers'].pop(header, None) try: retries = retries.increment(method, url, response=response, _pool=conn) except MaxRetryError: if retries.raise_on_redirect: raise return response kw['retries'] = retries kw['redirect'] = redirect log.info(""Redirecting %s -> %s"", url, redirect_location) return self.urlopen(method, redirect_location, **kw)","def urlopen(self, method, url, redirect=True, **kw): """""" Same as :meth:`urllib3.connectionpool.HTTPConnectionPool.urlopen` with custom cross-host redirect logic and only sends the request-uri portion of the ``url``. The given ``url`` parameter must be absolute, such that an appropriate :class:`urllib3.connectionpool.ConnectionPool` can be chosen for it. """""" u = parse_url(url) conn = self.connection_from_host(u.host, port=u.port, scheme=u.scheme) kw['assert_same_host'] = False kw['redirect'] = False if 'headers' not in kw: kw['headers'] = self.headers.copy() if self.proxy is not None and u.scheme == ""http"": response = conn.urlopen(method, url, **kw) else: response = conn.urlopen(method, u.request_uri, **kw) redirect_location = redirect and response.get_redirect_location() if not redirect_location: return response # Support relative URLs for redirecting. redirect_location = urljoin(url, redirect_location) # RFC 7231, Section 6.4.4 if response.status == 303: method = 'GET' retries = kw.get('retries') if not isinstance(retries, Retry): retries = Retry.from_int(retries, redirect=redirect) # Strip headers marked as unsafe to forward to the redirected location. # Check remove_headers_on_redirect to avoid a potential network call within # conn.is_same_host() which may use socket.gethostbyname() in the future. if (retries.remove_headers_on_redirect and not conn.is_same_host(redirect_location)): headers = list(six.iterkeys(kw['headers'])) for header in headers: if header.lower() in retries.remove_headers_on_redirect: kw['headers'].pop(header, None) try: retries = retries.increment(method, url, response=response, _pool=conn) except MaxRetryError: if retries.raise_on_redirect: raise return response kw['retries'] = retries kw['redirect'] = redirect log.info(""Redirecting %s -> %s"", url, redirect_location) return self.urlopen(method, redirect_location, **kw)","Release 1.24.2 (#1564) * Don't load system certificates by default when any other ``ca_certs``, ``ca_certs_dir`` or ``ssl_context`` parameters are specified. * Remove Authorization header regardless of case when redirecting to cross-site. (Issue #1510) * Add support for IPv6 addresses in subjectAltName section of certificates. (Issue #1269)",https://github.com/urllib3/urllib3/commit/1efadf43dc63317cd9eaa3e0fdb9e05ab07254b1,,,src/urllib3/poolmanager.py,3,py,False,2019-04-17T17:46:22Z "private static boolean packageHasCarrierPrivileges(TelephonyManager tm, String packageName) { return tm.checkCarrierPrivilegesForPackageAnyPhone(packageName) == TelephonyManager.CARRIER_PRIVILEGE_STATUS_HAS_ACCESS; }","private static boolean packageHasCarrierPrivileges(TelephonyManager tm, String packageName) { final long token = Binder.clearCallingIdentity(); try { return tm.checkCarrierPrivilegesForPackageAnyPhone(packageName) == TelephonyManager.CARRIER_PRIVILEGE_STATUS_HAS_ACCESS; } finally { Binder.restoreCallingIdentity(token); } }","Security fix: as part of enforcing read privilege permission to check package privileges in TelephonyManager, clear calling identity to ensure current functionalities work Bug: 180938364 Test: cts Change-Id: I722ca5cdde260bccd73fdfd0bf6447c2cd7beff9",https://github.com/aosp-mirror/platform_packages_providers_contactsprovider/commit/3363c4a75c7b489628d4e874f53aa5d647bea9d2,,,src/com/android/providers/contacts/VoicemailPermissions.java,3,java,False,2021-04-06T18:32:14Z "@Override public void onTrigger(String cliBuffer) { Matcher matcher = pattern.matcher(cliBuffer); if (matcher.find()) { String url = matcher.group(1); CustomTabsIntent.Builder builder = new CustomTabsIntent.Builder(); CustomTabsIntent customTabsIntent = builder.build(); customTabsIntent.launchUrl(context, Uri.parse(url)); } else { FLog.w(TAG, ""onTrigger: could not extract auth URL from buffer: %s"", cliBuffer); } }","@Override public void onTrigger(String cliBuffer) { Matcher matcher = pattern.matcher(cliBuffer); if (matcher.find()) { String url = matcher.group(1); if (url != null) { launchBrowser(context, url); } } else { FLog.w(TAG, ""onTrigger: could not extract auth URL from buffer: %s"", cliBuffer); } }","Fix: Crash when using OAuth on misconfigured devices Some devices will try to open the browser launch intent with a non-exported third party activity leading to a crash. We cannot fix the third party app, but this fix at least prevents the crash. Ref: SecurityException @ OauthHelper:72",https://github.com/x0b/rcx/commit/49a5bd3abf07424c4291f0f902946d602351f856,,,app/src/main/java/ca/pkay/rcloneexplorer/RemoteConfig/OauthHelper.java,3,java,False,2020-12-07T20:17:18Z "@Override public void readAdditional(@Nonnull CompoundNBT compound) { super.readAdditional(compound); PlayerEntity playerEntity = this.world.getPlayerByUuid(compound.getUniqueId(""MarkedForDeathTarget"")); if (playerEntity != null) { this.markedTarget = playerEntity; } }","@Override public void readAdditional(@Nonnull CompoundNBT compound) { super.readAdditional(compound); if (compound.contains(""MarkedForDeathTarget"")) { PlayerEntity playerEntity = this.world.getPlayerByUuid(compound.getUniqueId(""MarkedForDeathTarget"")); if (playerEntity != null) { this.markedTarget = playerEntity; } } }","Add NBT check, to prevent edge case crashes with the Assassins MarkedForDeathTarget. Closes #348",https://github.com/TeamMetallurgy/Atum2/commit/32ad11c6bea75c80aafc9a92fdb456aee8ac902d,,,src/main/java/com/teammetallurgy/atum/entity/bandit/AssassinEntity.java,3,java,False,2021-09-23T13:19:11Z "@Override public String retrieveReportPDF(final String reportName, final String type, final Map queryParams, final boolean isSelfServiceUserReport) { final String fileLocation = FileSystemContentRepository.FINERACT_BASE_DIR + File.separator + """"; if (!new File(fileLocation).isDirectory()) { new File(fileLocation).mkdirs(); } final String genaratePdf = fileLocation + File.separator + reportName + "".pdf""; try { final GenericResultsetData result = retrieveGenericResultset(reportName, type, queryParams, isSelfServiceUserReport); final List columnHeaders = result.getColumnHeaders(); final List data = result.getData(); List row; LOG.info(""NO. of Columns: {}"", columnHeaders.size()); final Integer chSize = columnHeaders.size(); final Document document = new Document(PageSize.B0.rotate()); PdfWriter.getInstance(document, new FileOutputStream(new File(fileLocation + reportName + "".pdf""))); document.open(); final PdfPTable table = new PdfPTable(chSize); table.setWidthPercentage(100); for (int i = 0; i < chSize; i++) { table.addCell(columnHeaders.get(i).getColumnName()); } table.completeRow(); Integer rSize; String currColType; String currVal; LOG.info(""NO. of Rows: {}"", data.size()); for (ResultsetRowData element : data) { row = element.getRow(); rSize = row.size(); for (int j = 0; j < rSize; j++) { currColType = columnHeaders.get(j).getColumnType(); currVal = row.get(j); if (currVal != null) { if (currColType.equals(""DECIMAL"") || currColType.equals(""DOUBLE"") || currColType.equals(""BIGINT"") || currColType.equals(""SMALLINT"") || currColType.equals(""INT"")) { table.addCell(currVal.toString()); } else { table.addCell(currVal.toString()); } } } } table.completeRow(); document.add(table); document.close(); return genaratePdf; } catch (final Exception e) { LOG.error(""error.msg.reporting.error:"", e); throw new PlatformDataIntegrityException(""error.msg.exception.error"", e.getMessage(), e); } }","@Override public String retrieveReportPDF(final String reportName, final String type, final Map queryParams, final boolean isSelfServiceUserReport) { final String fileLocation = FileSystemContentRepository.FINERACT_BASE_DIR + File.separator + """"; if (!new File(fileLocation).isDirectory()) { new File(fileLocation).mkdirs(); } final String genaratePdf = fileLocation + File.separator + reportName + "".pdf""; try { final GenericResultsetData result = retrieveGenericResultset(reportName, type, queryParams, isSelfServiceUserReport); final List columnHeaders = result.getColumnHeaders(); final List data = result.getData(); List row; LOG.info(""NO. of Columns: {}"", columnHeaders.size()); final Integer chSize = columnHeaders.size(); final Document document = new Document(PageSize.B0.rotate()); String validatedFileName = ESAPI.encoder().encodeForOS(new UnixCodec(), reportName); PdfWriter.getInstance(document, new FileOutputStream(fileLocation + validatedFileName + "".pdf"")); document.open(); final PdfPTable table = new PdfPTable(chSize); table.setWidthPercentage(100); for (int i = 0; i < chSize; i++) { table.addCell(columnHeaders.get(i).getColumnName()); } table.completeRow(); Integer rSize; String currColType; String currVal; LOG.info(""NO. of Rows: {}"", data.size()); for (ResultsetRowData element : data) { row = element.getRow(); rSize = row.size(); for (int j = 0; j < rSize; j++) { currColType = columnHeaders.get(j).getColumnType(); currVal = row.get(j); if (currVal != null) { if (currColType.equals(""DECIMAL"") || currColType.equals(""DOUBLE"") || currColType.equals(""BIGINT"") || currColType.equals(""SMALLINT"") || currColType.equals(""INT"")) { table.addCell(currVal.toString()); } else { table.addCell(currVal.toString()); } } } } table.completeRow(); document.add(table); document.close(); return genaratePdf; } catch (final Exception e) { LOG.error(""error.msg.reporting.error:"", e); throw new PlatformDataIntegrityException(""error.msg.exception.error"", e.getMessage(), e); } }",FINERACT-1562: Excluding persistence.xml from being picked up by Spring,https://github.com/apache/fineract/commit/f22807b9442dafa0ca07d0fad4e24c2de84e8e33,,,fineract-provider/src/main/java/org/apache/fineract/infrastructure/dataqueries/service/ReadReportingServiceImpl.java,3,java,False,2022-03-17T13:12:10Z "static void SkipRGBMipmaps(Image *image, DDSInfo *dds_info, int pixel_size) { MagickOffsetType offset; register ssize_t i; size_t h, w; /* Only skip mipmaps for textures and cube maps */ if (dds_info->ddscaps1 & DDSCAPS_MIPMAP && (dds_info->ddscaps1 & DDSCAPS_TEXTURE || dds_info->ddscaps2 & DDSCAPS2_CUBEMAP)) { w = DIV2(dds_info->width); h = DIV2(dds_info->height); /* Mipmapcount includes the main image, so start from one */ for (i=1; (i < (ssize_t) dds_info->mipmapcount) && w && h; i++) { offset = (MagickOffsetType) w * h * pixel_size; (void) SeekBlob(image, offset, SEEK_CUR); w = DIV2(w); h = DIV2(h); } } }","static MagickBooleanType SkipRGBMipmaps(Image *image,DDSInfo *dds_info, int pixel_size,ExceptionInfo *exception) { MagickOffsetType offset; register ssize_t i; size_t h, w; /* Only skip mipmaps for textures and cube maps */ if (dds_info->ddscaps1 & DDSCAPS_MIPMAP && (dds_info->ddscaps1 & DDSCAPS_TEXTURE || dds_info->ddscaps2 & DDSCAPS2_CUBEMAP)) { if (EOFBlob(image) != MagickFalse) { ThrowFileException(exception,CorruptImageError,""UnexpectedEndOfFile"", image->filename); return(MagickFalse); } w = DIV2(dds_info->width); h = DIV2(dds_info->height); /* Mipmapcount includes the main image, so start from one */ for (i=1; (i < (ssize_t) dds_info->mipmapcount) && w && h; i++) { offset = (MagickOffsetType) w * h * pixel_size; (void) SeekBlob(image, offset, SEEK_CUR); w = DIV2(w); h = DIV2(h); } } return(MagickTrue); }",Added extra EOF check and some minor refactoring.,https://github.com/ImageMagick/ImageMagick/commit/d7325bac173492b358417a0ad49fabad44447d52,,,coders/dds.c,3,c,False,2014-12-29T21:00:14Z "@Override public List retrieveDatatableNames(final String appTable) { String andClause; if (appTable == null) { andClause = """"; } else { validateAppTable(appTable); SQLInjectionValidator.validateSQLInput(appTable); andClause = "" and application_table_name = '"" + appTable + ""'""; } // PERMITTED datatables final String sql = ""select application_table_name, registered_table_name, entity_subtype "" + "" from x_registered_table "" + "" where exists"" + "" (select 'f'"" + "" from m_appuser_role ur "" + "" join m_role r on r.id = ur.role_id"" + "" left join m_role_permission rp on rp.role_id = r.id"" + "" left join m_permission p on p.id = rp.permission_id"" + "" where ur.appuser_id = "" + this.context.authenticatedUser().getId() + "" and (p.code in ('ALL_FUNCTIONS', 'ALL_FUNCTIONS_READ') or p.code = concat('READ_', registered_table_name))) "" + andClause + "" order by application_table_name, registered_table_name""; final SqlRowSet rs = this.jdbcTemplate.queryForRowSet(sql); final List datatables = new ArrayList<>(); while (rs.next()) { final String appTableName = rs.getString(""application_table_name""); final String registeredDatatableName = rs.getString(""registered_table_name""); final String entitySubType = rs.getString(""entity_subtype""); final List columnHeaderData = this.genericDataService .fillResultsetColumnHeaders(registeredDatatableName); datatables.add(DatatableData.create(appTableName, registeredDatatableName, entitySubType, columnHeaderData)); } return datatables; }","@Override public List retrieveDatatableNames(final String appTable) { // PERMITTED datatables final String sql = ""select application_table_name, registered_table_name, entity_subtype "" + "" from x_registered_table "" + "" where exists"" + "" (select 'f'"" + "" from m_appuser_role ur "" + "" join m_role r on r.id = ur.role_id"" + "" left join m_role_permission rp on rp.role_id = r.id"" + "" left join m_permission p on p.id = rp.permission_id"" + "" where ur.appuser_id = ? and (p.code in ('ALL_FUNCTIONS', 'ALL_FUNCTIONS_READ') or p.code = concat"" + ""('READ_', registered_table_name))) "" + "" and application_table_name like ? order by application_table_name, registered_table_name""; final List datatables = new ArrayList<>(); final SqlRowSet rowSet = jdbcTemplate.queryForRowSet(sql, new Object[] { this.context.authenticatedUser().getId(), appTable }); // NOSONAR while (rowSet.next()) { final String appTableName = rowSet.getString(""application_table_name""); final String registeredDatatableName = rowSet.getString(""registered_table_name""); final String entitySubType = rowSet.getString(""entity_subtype""); final List columnHeaderData = genericDataService.fillResultsetColumnHeaders(registeredDatatableName); datatables.add(DatatableData.create(appTableName, registeredDatatableName, entitySubType, columnHeaderData)); } return datatables; }",FINERACT-1562: Excluding persistence.xml from being picked up by Spring,https://github.com/apache/fineract/commit/f22807b9442dafa0ca07d0fad4e24c2de84e8e33,,,fineract-provider/src/main/java/org/apache/fineract/infrastructure/dataqueries/service/ReadWriteNonCoreDataServiceImpl.java,3,java,False,2022-03-17T13:12:10Z "av_cold void ff_vc2enc_free_transforms(VC2TransformContext *s) { av_freep(&s->buffer); }","av_cold void ff_vc2enc_free_transforms(VC2TransformContext *s) { av_free(s->buffer - s->padding); s->buffer = NULL; }","vc2enc_dwt: pad the temporary buffer by the slice size Since non-Haar wavelets need to look into pixels outside the frame, we need to pad the buffer. The old factor of two seemed to be a workaround that fact and only padded to the left and bottom. This correctly pads by the slice size and as such reduces memory usage and potential exploits. Reported by Liu Bingchang. Ideally, there should be no temporary buffer but the encoder is designed to deinterleave the coefficients into the classical wavelet structure with the lower frequency values in the top left corner. Signed-off-by: Rostislav Pehlivanov (cherry picked from commit 3228ac730c11eca49d5680d5550128e397061c85)",https://github.com/FFmpeg/FFmpeg/commit/94e538aebbc9f9c529e8b1f2eda860cfb8c473b1,,,libavcodec/vc2enc_dwt.c,3,c,False,2017-11-08T23:50:04Z "private void handleEventWith(State stateHandler, MotionEvent event, MotionEvent rawEvent, int policyFlags) { // To keep InputEventConsistencyVerifiers within GestureDetectors happy mPanningScalingState.mScrollGestureDetector.onTouchEvent(event); mPanningScalingState.mScaleGestureDetector.onTouchEvent(event); stateHandler.onMotionEvent(event, rawEvent, policyFlags); }","private void handleEventWith(State stateHandler, MotionEvent event, MotionEvent rawEvent, int policyFlags) { // To keep InputEventConsistencyVerifiers within GestureDetectors happy mPanningScalingState.mScrollGestureDetector.onTouchEvent(event); mPanningScalingState.mScaleGestureDetector.onTouchEvent(event); try { stateHandler.onMotionEvent(event, rawEvent, policyFlags); } catch (GestureException e) { Slog.e(mLogTag, ""Error processing motion event"", e); clearAndTransitionToStateDetecting(); } }","fix(magnification): don't crash when reciving unexpected motion events. This fixes an issue where the device was crashing and rebooting when triple tapping to activate magnification at the same time as covering the proxmity sensor while on a voice call. Bug: b/236875528 Test: manual: 1. Perform a voice call 2. While on voice call, execute the ""Triple tap on screen"" gesture, holding down your finger on the last tap and then cover the proximity sensor. 3. The device should not crash Change-Id: I9415c5b378b32342c016b17dfcef12cde45ce237",https://github.com/LineageOS/android_frameworks_base/commit/f7dcf990fdcf3dc1d855efcb4fd9b7aa7ce49611,,,services/accessibility/java/com/android/server/accessibility/magnification/FullScreenMagnificationGestureHandler.java,3,java,False,2022-06-24T21:56:54Z "public static void fillAllSuperTypes(@Nonnull Types types, @Nonnull TypeMirror type, @Nonnull List result) { try { List superTypes = types.directSupertypes(type); for (TypeMirror t : superTypes) { result.add(t); fillAllSuperTypes(types, t, result); } } catch (RuntimeException e) { LOG.debug(""Failed to find all super types of type '"" + toHumanReadableString(type) + "". Possibly "" + ""missing classes?"", e); } }","private static void fillAllSuperTypes(@Nonnull Types types, @Nonnull TypeMirror type, @Nonnull Set result) { try { List superTypes = types.directSupertypes(type); for (TypeMirror t : superTypes) { if (result.add(t)) { fillAllSuperTypes(types, t, result); } } } catch (RuntimeException e) { LOG.debug(""Failed to find all super types of type '"" + toHumanReadableString(type) + "". Possibly "" + ""missing classes?"", e); } }",Prevent stack overflow when getting all super types,https://github.com/revapi/revapi/commit/e559e6f68474e6481573b78336699cab1f8e1bca,,,revapi-java-spi/src/main/java/org/revapi/java/spi/Util.java,3,java,False,2022-07-21T19:17:01Z "@Override public void onEntityUpdate() { // Remove this Monolith if it's not in Limbo or in a pocket dungeon if (!(world.provider instanceof WorldProviderLimbo || world.provider instanceof WorldProviderDungeonPocket)) { setDead(); super.onEntityUpdate(); return; } super.onEntityUpdate(); // Check for players and update aggro levels even if there are no players in range EntityPlayer player = world.getClosestPlayerToEntity(this, MAX_AGGRO_RANGE); boolean visibility = player != null && player.canEntityBeSeen(this); updateAggroLevel(player, visibility); // Change orientation and face a player if one is in range if (player != null) { facePlayer(player); if (!world.isRemote && isDangerous()) { // Play sounds on the server side, if the player isn't in Limbo. // Limbo is excluded to avoid drowning out its background music. // Also, since it's a large open area with many Monoliths, some // of the sounds that would usually play for a moment would // keep playing constantly and would get very annoying. playSounds(player.getPosition()); } if (visibility) { // Only spawn particles on the client side and outside Limbo if (world.isRemote && isDangerous()) { spawnParticles(player); } // Teleport the target player if various conditions are met if (aggro >= MAX_AGGRO && !world.isRemote && ModConfig.monoliths.monolithTeleportation && !player.isCreative() && isDangerous()) { aggro = 0; Location destination = WorldProviderLimbo.getLimboSkySpawn(player); TeleportUtils.teleport(player, destination, 0, 0); player.world.playSound(null, player.getPosition(), ModSounds.CRACK, SoundCategory.HOSTILE, 13, 1); } } } }","@Override public void onEntityUpdate() { // Remove this Monolith if it's not in Limbo or in a pocket dungeon if (!(world.provider instanceof WorldProviderLimbo || world.provider instanceof WorldProviderDungeonPocket)) { setDead(); super.onEntityUpdate(); return; } super.onEntityUpdate(); // Check for players and update aggro levels even if there are no players in range EntityPlayer player = world.getClosestPlayerToEntity(this, MAX_AGGRO_RANGE); boolean visibility = player != null && player.canEntityBeSeen(this); updateAggroLevel(player, visibility); // Change orientation and face a player if one is in range if (player != null) { facePlayer(player); if (!world.isRemote && isDangerous()) { // Play sounds on the server side, if the player isn't in Limbo. // Limbo is excluded to avoid drowning out its background music. // Also, since it's a large open area with many Monoliths, some // of the sounds that would usually play for a moment would // keep playing constantly and would get very annoying. playSounds(player.getPosition()); } if (visibility) { // Only spawn particles on the client side and outside Limbo if (world.isRemote && isDangerous()) { spawnParticles(player); } // Teleport the target player if various conditions are met if (aggro >= MAX_AGGRO && !world.isRemote && ModConfig.monoliths.monolithTeleportation && !player.isCreative() && isDangerous()) { aggro = 0; Location destination; if(player.world.provider instanceof WorldProviderLimbo) { destination = WorldProviderLimbo.getLimboSkySpawn(player); TeleportUtils.teleport(player, destination, 0, 0); } else { //If teleport the player to limbo if the player is not already there //This should fix the crash related to dangerousLimboMonoliths and monolithTeleportation double x = player.posX + MathHelper.clamp(player.world.rand.nextDouble(), 100, 100); double z = player.posZ + MathHelper.clamp(player.world.rand.nextDouble(), -100, 100); TeleportUtils.teleport(player, ModDimensions.getLimboDim(),x,700,z,player.rotationYaw,player.rotationPitch); } player.world.playSound(null, player.getPosition(), ModSounds.CRACK, SoundCategory.HOSTILE, 13, 1); } } } }","- Updated the mappings and forge requirements to the latest - Removed the annoying build number from the build.gradle - Updated gradle to 6.8.3 and forge gradle to 4.1.10 - Fixed item.null.name - Added a config option to toggle limbo decay on/off - Added a config option to blacklist block from decaying in limbo - Fixed a null crash related to dangerousLimboMonoliths and monolithTeleportation - Wild rifts will now convert nearby blocks into world thread as they used to - Added toggle and blacklist config options to go along with the world thread conversion",https://github.com/DimensionalDevelopment/DimDoors/commit/95b00fac2e2fdd2e4fbcaca1ef9ed2f3b0e26432,,,src/main/java/org/dimdev/dimdoors/shared/entities/EntityMonolith.java,3,java,False,2022-04-30T12:05:35Z "protected boolean checkContent() { XMLParser parser = new XMLParser(new ValidationContextBuilder(context).mimetype(""opf"").build()); initHandler(); for (XMLValidator validator : validatorMap.getValidators(context)) { parser.addValidator(validator); } parser.addContentHandler(opfHandler); parser.process(); for (OPFItem item : opfHandler.getItems()) { // only check the filename in single-file mode // (it is checked by the container checker in full-publication mode) // and for local resources (i.e. computed to a file URL) if (!context.container.isPresent() && !item.isRemote() && !item.hasDataURL()) { new OCFFilenameChecker(item.getPath(), context, item.getLocation()).check(); } if (!item.equals(opfHandler.getItemByURL(item.getURL()).orNull())) { // FIXME 2022 check duplicates at build time (in OPFHandler) report.message(MessageId.OPF_074, item.getLocation(), item.getPath()); } else { checkItem(item, opfHandler); } } if (!opfHandler.getSpineItems().isEmpty()) { boolean linearFound = false; int spineIndex = 0; for (OPFItem item : opfHandler.getSpineItems()) { checkSpineItem(item, opfHandler); if (item.isLinear()) { linearFound = true; } report.info(item.getPath(), FeatureEnum.SPINE_INDEX, Integer.toString(spineIndex++)); } if (!linearFound) { report.message(MessageId.OPF_033, EPUBLocation.of(context)); } } if (version == EPUBVersion.VERSION_2) { // check for >1 itemrefs to any given spine item // http://code.google.com/p/epubcheck/issues/detail?id=182 Set seen = new HashSet(); for (OPFItem item : opfHandler.getSpineItems()) { if (seen.contains(item)) { report.message(MessageId.OPF_034, item.getLocation(), item.getId()); } else { seen.add(item); } } } return true; }","protected boolean checkContent() { XMLParser parser = new XMLParser(new ValidationContextBuilder(context).mimetype(""opf"").build()); initHandler(); for (XMLValidator validator : validatorMap.getValidators(context)) { parser.addValidator(validator); } parser.addContentHandler(opfHandler); parser.process(); for (OPFItem item : opfHandler.getItems()) { // only check the filename in single-file mode // (it is checked by the container checker in full-publication mode) // and for local resources (i.e. computed to a file URL) if (!context.container.isPresent() && !item.isRemote() && !item.hasDataURL()) { new OCFFilenameChecker(item.getPath(), context, item.getLocation()).check(); } if (!item.equals(opfHandler.getItemByURL(item.getURL()).orNull())) { // FIXME 2022 check duplicates at build time (in OPFHandler) report.message(MessageId.OPF_074, item.getLocation(), item.getPath()); } // check that the manifest does not include the package document itself else if (item.getURL().equals(context.url)) { report.message(MessageId.OPF_099, item.getLocation()); } else { checkItem(item, opfHandler); } } if (!opfHandler.getSpineItems().isEmpty()) { boolean linearFound = false; int spineIndex = 0; for (OPFItem item : opfHandler.getSpineItems()) { checkSpineItem(item, opfHandler); if (item.isLinear()) { linearFound = true; } report.info(item.getPath(), FeatureEnum.SPINE_INDEX, Integer.toString(spineIndex++)); } if (!linearFound) { report.message(MessageId.OPF_033, EPUBLocation.of(context)); } } if (version == EPUBVersion.VERSION_2) { // check for >1 itemrefs to any given spine item // http://code.google.com/p/epubcheck/issues/detail?id=182 Set seen = new HashSet(); for (OPFItem item : opfHandler.getSpineItems()) { if (seen.contains(item)) { report.message(MessageId.OPF_034, item.getLocation(), item.getId()); } else { seen.add(item); } } } return true; }","feat: check that the manifest is not self-referencing This commit adds a new check, reported as `OPF-099` (error), to verify that the package document `manifest` does not include an `item` element that refers to the package document itself. This statement was apparently not checked by EPUBCheck previously. Worse, the code was entering an infinite loop, as the package document checker was creating a new checker for itself, recursively. Fix #1453",https://github.com/w3c/epubcheck/commit/2c76420bda04422367474ec16aa64bcd94892cfa,,,src/main/java/com/adobe/epubcheck/opf/OPFChecker.java,3,java,False,2022-12-22T15:47:54Z "@Path(""/{group-id}"") @DELETE void deleteGroup(@PathParam(""group-id"") String groupId);","@Path(""/{group-id}"") @DELETE @Authorized(AuthorizedStyle.GroupOnly) void deleteGroup(@PathParam(""group-id"") String groupId);","Implement owner-only authorization support (optional, enabled via appication.properties) (#1407) * trying to implement simple authorization using CDI interceptors * added @Authorized to appropriate methods * updated the auth test * Removed some debugging statements * Improved and applied authn/z to other APIs (v1, cncf, etc) * Fixed some issues with GroupOnly authorization * Disable the IBM API by default due to authorization issues * fix the IBM api test",https://github.com/Apicurio/apicurio-registry/commit/90a856197b104c99032163fa26c04d01465bf487,,,app/src/main/java/io/apicurio/registry/cncf/schemaregistry/SchemagroupsResource.java,3,java,False,2021-04-13T09:08:58Z "private boolean processActivity(ActivityRecord r, boolean isTargetTask) { // End processing if we have reached the root. if (r == mRoot) return true; mAllActivities.add(r); final int flags = r.info.flags; final boolean finishOnTaskLaunch = (flags & ActivityInfo.FLAG_FINISH_ON_TASK_LAUNCH) != 0; final boolean allowTaskReparenting = (flags & ActivityInfo.FLAG_ALLOW_TASK_REPARENTING) != 0; final boolean clearWhenTaskReset = (r.intent.getFlags() & Intent.FLAG_ACTIVITY_CLEAR_WHEN_TASK_RESET) != 0; if (isTargetTask) { if (!finishOnTaskLaunch && !clearWhenTaskReset) { if (r.resultTo != null) { // If this activity is sending a reply to a previous activity, we can't do // anything with it now until we reach the start of the reply chain. // NOTE: that we are assuming the result is always to the previous activity, // which is almost always the case but we really shouldn't count on. mResultActivities.add(r); return false; } if (allowTaskReparenting && r.taskAffinity != null && !r.taskAffinity.equals(mTask.affinity)) { // If this activity has an affinity for another task, then we need to move // it out of here. We will move it as far out of the way as possible, to the // bottom of the activity root task. This also keeps it correctly ordered with // any activities we previously moved. // Handle this activity after we have done traversing the hierarchy. mPendingReparentActivities.add(r); return false; } } if (mForceReset || finishOnTaskLaunch || clearWhenTaskReset) { // If the activity should just be removed either because it asks for it, or the // task should be cleared, then finish it and anything that is part of its reply // chain. if (clearWhenTaskReset) { // In this case, we want to finish this activity and everything above it, // so be sneaky and pretend like these are all in the reply chain. finishActivities(mAllActivities, ""clearWhenTaskReset""); } else { mResultActivities.add(r); finishActivities(mResultActivities, ""reset-task""); } mResultActivities.clear(); return false; } else { // If we were in the middle of a chain, well the activity that started it all // doesn't want anything special, so leave it all as-is. mResultActivities.clear(); } return false; } else { mResultActivities.add(r); if (r.resultTo != null) { // If this activity is sending a reply to a previous activity, we can't do // anything with it now until we reach the start of the reply chain. // NOTE: that we are assuming the result is always to the previous activity, // which is almost always the case but we really shouldn't count on. return false; } else if (mTargetTaskFound && allowTaskReparenting && mTargetTask.affinity != null && mTargetTask.affinity.equals(r.taskAffinity)) { // This activity has an affinity for our task. Either remove it if we are // clearing or move it over to our task. Note that we currently punt on the case // where we are resetting a task that is not at the top but who has activities // above with an affinity to it... this is really not a normal case, and we will // need to later pull that task to the front and usually at that point we will // do the reset and pick up those remaining activities. (This only happens if // someone starts an activity in a new task from an activity in a task that is // not currently on top.) if (mForceReset || finishOnTaskLaunch) { finishActivities(mResultActivities, ""move-affinity""); return false; } if (mActivityReparentPosition == -1) { mActivityReparentPosition = mTargetTask.getChildCount(); } processResultActivities( r, mTargetTask, mActivityReparentPosition, false, false); // Now we've moved it in to place...but what if this is a singleTop activity and // we have put it on top of another instance of the same activity? Then we drop // the instance below so it remains singleTop. if (r.info.launchMode == ActivityInfo.LAUNCH_SINGLE_TOP) { final ActivityRecord p = mTargetTask.getActivityBelow(r); if (p != null) { if (p.intent.getComponent().equals(r.intent.getComponent())) { p.finishIfPossible(""replace"", false /* oomAdj */); } } } } return false; } }","private boolean processActivity(ActivityRecord r, boolean isTargetTask) { // End processing if we have reached the root. if (r == mRoot) return true; mAllActivities.add(r); final int flags = r.info.flags; final boolean finishOnTaskLaunch = (flags & ActivityInfo.FLAG_FINISH_ON_TASK_LAUNCH) != 0; final boolean allowTaskReparenting = (flags & ActivityInfo.FLAG_ALLOW_TASK_REPARENTING) != 0; final boolean clearWhenTaskReset = (r.intent.getFlags() & Intent.FLAG_ACTIVITY_CLEAR_WHEN_TASK_RESET) != 0; if (isTargetTask) { if (!finishOnTaskLaunch && !clearWhenTaskReset) { if (r.resultTo != null) { // If this activity is sending a reply to a previous activity, we can't do // anything with it now until we reach the start of the reply chain. // NOTE: that we are assuming the result is always to the previous activity, // which is almost always the case but we really shouldn't count on. mResultActivities.add(r); return false; } if (allowTaskReparenting && r.taskAffinity != null && !r.taskAffinity.equals(mTask.affinity)) { // If this activity has an affinity for another task, then we need to move // it out of here. We will move it as far out of the way as possible, to the // bottom of the activity root task. This also keeps it correctly ordered with // any activities we previously moved. // Handle this activity after we have done traversing the hierarchy. mPendingReparentActivities.add(r); return false; } } if (mForceReset || finishOnTaskLaunch || clearWhenTaskReset) { // If the activity should just be removed either because it asks for it, or the // task should be cleared, then finish it and anything that is part of its reply // chain. if (clearWhenTaskReset) { // In this case, we want to finish this activity and everything above it, // so be sneaky and pretend like these are all in the reply chain. finishActivities(mAllActivities, ""clearWhenTaskReset""); } else { mResultActivities.add(r); finishActivities(mResultActivities, ""reset-task""); } mResultActivities.clear(); return false; } else { // If we were in the middle of a chain, well the activity that started it all // doesn't want anything special, so leave it all as-is. mResultActivities.clear(); } return false; } else { if (r.resultTo != null) { // If this activity is sending a reply to a previous activity, we can't do // anything with it now until we reach the start of the reply chain. // NOTE: that we are assuming the result is always to the previous activity, // which is almost always the case but we really shouldn't count on. mResultActivities.add(r); return false; } else if (mTargetTaskFound && allowTaskReparenting && mTargetTask.affinity != null && mTargetTask.affinity.equals(r.taskAffinity)) { mResultActivities.add(r); // This activity has an affinity for our task. Either remove it if we are // clearing or move it over to our task. Note that we currently punt on the case // where we are resetting a task that is not at the top but who has activities // above with an affinity to it... this is really not a normal case, and we will // need to later pull that task to the front and usually at that point we will // do the reset and pick up those remaining activities. (This only happens if // someone starts an activity in a new task from an activity in a task that is // not currently on top.) if (mForceReset || finishOnTaskLaunch) { finishActivities(mResultActivities, ""move-affinity""); return false; } if (mActivityReparentPosition == -1) { mActivityReparentPosition = mTargetTask.getChildCount(); } processResultActivities( r, mTargetTask, mActivityReparentPosition, false, false); // Now we've moved it in to place...but what if this is a singleTop activity and // we have put it on top of another instance of the same activity? Then we drop // the instance below so it remains singleTop. if (r.info.launchMode == ActivityInfo.LAUNCH_SINGLE_TOP) { final ActivityRecord p = mTargetTask.getActivityBelow(r); if (p != null) { if (p.intent.getComponent().equals(r.intent.getComponent())) { p.finishIfPossible(""replace"", false /* oomAdj */); } } } } return false; } }","[RESTRICT AUTOMERGE] Allow activity to be reparent while allowTaskReparenting is applied Any malicious application could hijack tasks by android:allowTaskReparenting. This vulnerability can perform UI spoofing or spying on user’s activities. This CL only allows activities to be reparent while android:allowTaskReparenting is applied and the affinity of activity is same with the target task. Bug: 240663194 Test: atest IntentTests Change-Id: I73abb9ec05af95bc14f887ae825a9ada9600f771",https://github.com/LineageOS/android_frameworks_base/commit/7af50c4d5f0354438872167b0e446930caca9deb,,,services/core/java/com/android/server/wm/ResetTargetTaskHelper.java,3,java,False,2022-09-14T09:32:53Z "private void extendXref(int capacity) { PdfIndirectReference[] newXref = new PdfIndirectReference[capacity]; System.arraycopy(xref, 0, newXref, 0, xref.length); xref = newXref; }","private void extendXref(int capacity) { if (this.memoryLimitsAwareHandler != null) { this.memoryLimitsAwareHandler.checkIfXrefStructureExceedsTheLimit(capacity); } PdfIndirectReference[] newXref = new PdfIndirectReference[capacity]; System.arraycopy(this.xref, 0, newXref, 0, this.xref.length); this.xref = newXref; }","Add safe guards to avoid OOM on parsing xref structures Add ability to set max size of xref array Ignore flaky tests in LtvVerificationTest class DEVSIX-6247",https://github.com/itext/itext-java/commit/75b236479a077a658fb38e76e44c5a3deeec516f,,,kernel/src/main/java/com/itextpdf/kernel/pdf/PdfXrefTable.java,3,java,False,2022-02-03T03:01:20Z "private void initForFilename(String filename) throws IOException { FileInputStream in = null; mAssetInputStream = null; mFilename = filename; mIsInputStream = false; try { in = new FileInputStream(filename); ParcelFileDescriptor modernFd; try { modernFd = FileUtils.convertToModernFd(in.getFD()); } catch (IOException e) { modernFd = null; } if (modernFd != null) { closeQuietly(in); in = new FileInputStream(modernFd.getFileDescriptor()); mSeekableFileDescriptor = null; } else if (isSeekableFD(in.getFD())) { mSeekableFileDescriptor = in.getFD(); } loadAttributes(in); } finally { closeQuietly(in); } }","private void initForFilename(String filename) throws IOException { FileInputStream in = null; ParcelFileDescriptor modernFd = null; mAssetInputStream = null; mFilename = filename; mIsInputStream = false; try { in = new FileInputStream(filename); modernFd = FileUtils.convertToModernFd(in.getFD()); if (modernFd != null) { closeQuietly(in); in = new FileInputStream(modernFd.getFileDescriptor()); mSeekableFileDescriptor = null; } else if (isSeekableFD(in.getFD())) { mSeekableFileDescriptor = in.getFD(); } loadAttributes(in); } finally { closeQuietly(in); if (modernFd != null) { modernFd.close(); } } }","Fix fd leak while bypassing transcoding in media APIs To call the media service while bypassing transcoding there are 4 file descriptors involved: A: The original file descriptor the app owns and is responsible for closing B: Dupe of A, to pass into the MediaStore API as an input to receive a non-transoding fd C: The output from the MediaStore API D: Final fd owned by the media service, after C gets duped over binder as part of setDataSource We were leaking (B) and (C). Now we close them appropriately. See I0124ec8fbd0471237e99bab321f903544f8fe1f8 for another 2 fd leak fix in MediaProvider Test: atest TranscodeTest Test: Manual with 'adb shell lsof | grep ' Bug: 194828489 Bug: 179804072 Change-Id: I978257bbc4a8f6813b6e6a5ce22124257204f432",https://github.com/omnirom/android_frameworks_base/commit/eccf1db4f797ebd99505b684ed7aadf53cdaca7d,,,media/java/android/media/ExifInterface.java,3,java,False,2021-07-29T19:51:10Z "TPM_RC TPMS_PCR_SELECTION_Unmarshal(TPMS_PCR_SELECTION *target, BYTE **buffer, INT32 *size) { TPM_RC rc = TPM_RC_SUCCESS; if (rc == TPM_RC_SUCCESS) { rc = TPMI_ALG_HASH_Unmarshal(&target->hash, buffer, size, NO); } if (rc == TPM_RC_SUCCESS) { rc = UINT8_Unmarshal(&target->sizeofSelect, buffer, size); } if (rc == TPM_RC_SUCCESS) { if ((target->sizeofSelect < PCR_SELECT_MIN) || (target->sizeofSelect > PCR_SELECT_MAX)) { rc = TPM_RC_VALUE; } } if (rc == TPM_RC_SUCCESS) { rc = Array_Unmarshal(target->pcrSelect, target->sizeofSelect, buffer, size); } return rc; }","TPM_RC TPMS_PCR_SELECTION_Unmarshal(TPMS_PCR_SELECTION *target, BYTE **buffer, INT32 *size) { TPM_RC rc = TPM_RC_SUCCESS; if (rc == TPM_RC_SUCCESS) { rc = TPMI_ALG_HASH_Unmarshal(&target->hash, buffer, size, NO); } if (rc == TPM_RC_SUCCESS) { rc = UINT8_Unmarshal(&target->sizeofSelect, buffer, size); } if (rc == TPM_RC_SUCCESS) { if ((target->sizeofSelect < PCR_SELECT_MIN) || (target->sizeofSelect > PCR_SELECT_MAX)) { rc = TPM_RC_VALUE; target->sizeofSelect = 0; // libtpms added } } if (rc == TPM_RC_SUCCESS) { rc = Array_Unmarshal(target->pcrSelect, target->sizeofSelect, buffer, size); } return rc; }","tpm2: Reset TPM2B buffer sizes after test fails for valid buffer size Reset the buffer size indicator in a TPM2B type of buffer after it failed the test for the maximum buffer size it allows. This prevents having bad buffer sizes in memory that can come to haunt us when writing the volatile state for example. Signed-off-by: Stefan Berger ",https://github.com/stefanberger/libtpms/commit/2f30d62,,,src/tpm2/Unmarshal.c,3,c,False,2021-06-21T18:04:34Z "@Nonnull public static List getAllSuperTypes(@Nonnull Types types, @Nonnull TypeMirror type) { ArrayList ret = new ArrayList<>(); fillAllSuperTypes(types, type, ret); return ret; }","@Nonnull public static Set getAllSuperTypes(@Nonnull Types types, @Nonnull TypeMirror type) { Set ret = new LinkedHashSet<>(); fillAllSuperTypes(types, type, ret); return ret; }",Prevent stack overflow when getting all super types,https://github.com/revapi/revapi/commit/e559e6f68474e6481573b78336699cab1f8e1bca,,,revapi-java-spi/src/main/java/org/revapi/java/spi/Util.java,3,java,False,2022-07-21T19:17:01Z "@Override public long interceptKeyBeforeDispatching(IBinder focusedToken, KeyEvent event, int policyFlags) { final boolean keyguardOn = keyguardOn(); final int keyCode = event.getKeyCode(); final int repeatCount = event.getRepeatCount(); final int metaState = event.getMetaState(); final int flags = event.getFlags(); final boolean down = event.getAction() == KeyEvent.ACTION_DOWN; final boolean canceled = event.isCanceled(); final int displayId = event.getDisplayId(); final long key_consumed = -1; final long key_not_consumed = 0; if (DEBUG_INPUT) { Log.d(TAG, ""interceptKeyTi keyCode="" + keyCode + "" down="" + down + "" repeatCount="" + repeatCount + "" keyguardOn="" + keyguardOn + "" canceled="" + canceled); } if (mKeyCombinationManager.isKeyConsumed(event)) { return key_consumed; } if ((flags & KeyEvent.FLAG_FALLBACK) == 0) { final long now = SystemClock.uptimeMillis(); final long interceptTimeout = mKeyCombinationManager.getKeyInterceptTimeout(keyCode); if (now < interceptTimeout) { return interceptTimeout - now; } } // Cancel any pending meta actions if we see any other keys being pressed between the down // of the meta key and its corresponding up. if (mPendingMetaAction && !KeyEvent.isMetaKey(keyCode)) { mPendingMetaAction = false; } // Any key that is not Alt or Meta cancels Caps Lock combo tracking. if (mPendingCapsLockToggle && !KeyEvent.isMetaKey(keyCode) && !KeyEvent.isAltKey(keyCode)) { mPendingCapsLockToggle = false; } if (isUserSetupComplete() && !keyguardOn) { if (mModifierShortcutManager.interceptKey(event)) { dismissKeyboardShortcutsMenu(); mPendingMetaAction = false; mPendingCapsLockToggle = false; return key_consumed; } } switch(keyCode) { case KeyEvent.KEYCODE_HOME: // First we always handle the home key here, so applications // can never break it, although if keyguard is on, we do let // it handle it, because that gives us the correct 5 second // timeout. DisplayHomeButtonHandler handler = mDisplayHomeButtonHandlers.get(displayId); if (handler == null) { handler = new DisplayHomeButtonHandler(displayId); mDisplayHomeButtonHandlers.put(displayId, handler); } return handler.handleHomeButton(focusedToken, event); case KeyEvent.KEYCODE_MENU: // Hijack modified menu keys for debugging features final int chordBug = KeyEvent.META_SHIFT_ON; if (down && repeatCount == 0) { if (mEnableShiftMenuBugReports && (metaState & chordBug) == chordBug) { Intent intent = new Intent(Intent.ACTION_BUG_REPORT); mContext.sendOrderedBroadcastAsUser(intent, UserHandle.CURRENT, null, null, null, 0, null, null); return key_consumed; } } break; case KeyEvent.KEYCODE_APP_SWITCH: if (!keyguardOn) { if (down && repeatCount == 0) { preloadRecentApps(); } else if (!down) { toggleRecentApps(); } } return key_consumed; case KeyEvent.KEYCODE_N: if (down && event.isMetaPressed()) { IStatusBarService service = getStatusBarService(); if (service != null) { try { service.expandNotificationsPanel(); } catch (RemoteException e) { // do nothing. } return key_consumed; } } break; case KeyEvent.KEYCODE_S: if (down && event.isMetaPressed() && event.isCtrlPressed() && repeatCount == 0) { int type = event.isShiftPressed() ? TAKE_SCREENSHOT_SELECTED_REGION : TAKE_SCREENSHOT_FULLSCREEN; interceptScreenshotChord(type, SCREENSHOT_KEY_OTHER, 0 /*pressDelay*/); return key_consumed; } break; case KeyEvent.KEYCODE_SLASH: if (down && repeatCount == 0 && event.isMetaPressed() && !keyguardOn) { toggleKeyboardShortcutsMenu(event.getDeviceId()); return key_consumed; } break; case KeyEvent.KEYCODE_ASSIST: Slog.wtf(TAG, ""KEYCODE_ASSIST should be handled in interceptKeyBeforeQueueing""); return key_consumed; case KeyEvent.KEYCODE_VOICE_ASSIST: Slog.wtf(TAG, ""KEYCODE_VOICE_ASSIST should be handled in"" + "" interceptKeyBeforeQueueing""); return key_consumed; case KeyEvent.KEYCODE_VIDEO_APP_1: case KeyEvent.KEYCODE_VIDEO_APP_2: case KeyEvent.KEYCODE_VIDEO_APP_3: case KeyEvent.KEYCODE_VIDEO_APP_4: case KeyEvent.KEYCODE_VIDEO_APP_5: case KeyEvent.KEYCODE_VIDEO_APP_6: case KeyEvent.KEYCODE_VIDEO_APP_7: case KeyEvent.KEYCODE_VIDEO_APP_8: case KeyEvent.KEYCODE_FEATURED_APP_1: case KeyEvent.KEYCODE_FEATURED_APP_2: case KeyEvent.KEYCODE_FEATURED_APP_3: case KeyEvent.KEYCODE_FEATURED_APP_4: case KeyEvent.KEYCODE_DEMO_APP_1: case KeyEvent.KEYCODE_DEMO_APP_2: case KeyEvent.KEYCODE_DEMO_APP_3: case KeyEvent.KEYCODE_DEMO_APP_4: Slog.wtf(TAG, ""KEYCODE_APP_X should be handled in interceptKeyBeforeQueueing""); return key_consumed; case KeyEvent.KEYCODE_BRIGHTNESS_UP: case KeyEvent.KEYCODE_BRIGHTNESS_DOWN: if (down) { int direction = keyCode == KeyEvent.KEYCODE_BRIGHTNESS_UP ? 1 : -1; // Disable autobrightness if it's on int auto = Settings.System.getIntForUser( mContext.getContentResolver(), Settings.System.SCREEN_BRIGHTNESS_MODE, Settings.System.SCREEN_BRIGHTNESS_MODE_MANUAL, UserHandle.USER_CURRENT_OR_SELF); if (auto != 0) { Settings.System.putIntForUser(mContext.getContentResolver(), Settings.System.SCREEN_BRIGHTNESS_MODE, Settings.System.SCREEN_BRIGHTNESS_MODE_MANUAL, UserHandle.USER_CURRENT_OR_SELF); } float min = mPowerManager.getBrightnessConstraint( PowerManager.BRIGHTNESS_CONSTRAINT_TYPE_MINIMUM); float max = mPowerManager.getBrightnessConstraint( PowerManager.BRIGHTNESS_CONSTRAINT_TYPE_MAXIMUM); float step = (max - min) / BRIGHTNESS_STEPS * direction; int screenDisplayId = displayId < 0 ? DEFAULT_DISPLAY : displayId; float brightness = mDisplayManager.getBrightness(screenDisplayId); brightness += step; // Make sure we don't go beyond the limits. brightness = Math.min(max, brightness); brightness = Math.max(min, brightness); mDisplayManager.setBrightness(screenDisplayId, brightness); startActivityAsUser(new Intent(Intent.ACTION_SHOW_BRIGHTNESS_DIALOG), UserHandle.CURRENT_OR_SELF); } return key_consumed; case KeyEvent.KEYCODE_VOLUME_UP: case KeyEvent.KEYCODE_VOLUME_DOWN: case KeyEvent.KEYCODE_VOLUME_MUTE: if (mUseTvRouting || mHandleVolumeKeysInWM) { // On TVs or when the configuration is enabled, volume keys never // go to the foreground app. dispatchDirectAudioEvent(event); return key_consumed; } // If the device is in VR mode and keys are ""internal"" (e.g. on the side of the // device), then drop the volume keys and don't forward it to the // application/dispatch the audio event. if (mDefaultDisplayPolicy.isPersistentVrModeEnabled()) { final InputDevice d = event.getDevice(); if (d != null && !d.isExternal()) { return key_consumed; } } break; case KeyEvent.KEYCODE_TAB: if (event.isMetaPressed()) { // Pass through keyboard navigation keys. return key_not_consumed; } // Display task switcher for ALT-TAB. if (down && repeatCount == 0) { if (mRecentAppsHeldModifiers == 0 && !keyguardOn && isUserSetupComplete()) { final int shiftlessModifiers = event.getModifiers() & ~KeyEvent.META_SHIFT_MASK; if (KeyEvent.metaStateHasModifiers( shiftlessModifiers, KeyEvent.META_ALT_ON)) { mRecentAppsHeldModifiers = shiftlessModifiers; showRecentApps(true); return key_consumed; } } } break; case KeyEvent.KEYCODE_ALL_APPS: if (!down) { mHandler.removeMessages(MSG_HANDLE_ALL_APPS); Message msg = mHandler.obtainMessage(MSG_HANDLE_ALL_APPS); msg.setAsynchronous(true); msg.sendToTarget(); } return key_consumed; case KeyEvent.KEYCODE_NOTIFICATION: if (!down) { toggleNotificationPanel(); } return key_consumed; case KeyEvent.KEYCODE_SPACE: // Handle keyboard layout switching. (META + SPACE) if ((metaState & KeyEvent.META_META_MASK) == 0) { return key_not_consumed; } // Share the same behavior with KEYCODE_LANGUAGE_SWITCH. case KeyEvent.KEYCODE_LANGUAGE_SWITCH: if (down && repeatCount == 0) { int direction = (metaState & KeyEvent.META_SHIFT_MASK) != 0 ? -1 : 1; mWindowManagerFuncs.switchKeyboardLayout(event.getDeviceId(), direction); return key_consumed; } break; case KeyEvent.KEYCODE_META_LEFT: case KeyEvent.KEYCODE_META_RIGHT: if (down) { if (event.isAltPressed()) { mPendingCapsLockToggle = true; mPendingMetaAction = false; } else { mPendingCapsLockToggle = false; mPendingMetaAction = true; } } else { // Toggle Caps Lock on META-ALT. if (mPendingCapsLockToggle) { mInputManagerInternal.toggleCapsLock(event.getDeviceId()); mPendingCapsLockToggle = false; } else if (mPendingMetaAction) { if (!canceled) { launchAssistAction(Intent.EXTRA_ASSIST_INPUT_HINT_KEYBOARD, event.getDeviceId(), event.getEventTime(), AssistUtils.INVOCATION_TYPE_UNKNOWN); } mPendingMetaAction = false; } } return key_consumed; case KeyEvent.KEYCODE_ALT_LEFT: case KeyEvent.KEYCODE_ALT_RIGHT: if (down) { if (event.isMetaPressed()) { mPendingCapsLockToggle = true; mPendingMetaAction = false; } else { mPendingCapsLockToggle = false; } } else { // hide recent if triggered by ALT-TAB. if (mRecentAppsHeldModifiers != 0 && (metaState & mRecentAppsHeldModifiers) == 0) { mRecentAppsHeldModifiers = 0; hideRecentApps(true, false); return key_consumed; } // Toggle Caps Lock on META-ALT. if (mPendingCapsLockToggle) { mInputManagerInternal.toggleCapsLock(event.getDeviceId()); mPendingCapsLockToggle = false; return key_consumed; } } break; } if (isValidGlobalKey(keyCode) && mGlobalKeyManager.handleGlobalKey(mContext, keyCode, event)) { return key_consumed; } // Reserve all the META modifier combos for system behavior if ((metaState & KeyEvent.META_META_ON) != 0) { return key_consumed; } // Let the application handle the key. return key_not_consumed; }","@Override public long interceptKeyBeforeDispatching(IBinder focusedToken, KeyEvent event, int policyFlags) { final boolean keyguardOn = keyguardOn(); final int keyCode = event.getKeyCode(); final int repeatCount = event.getRepeatCount(); final int metaState = event.getMetaState(); final int flags = event.getFlags(); final boolean down = event.getAction() == KeyEvent.ACTION_DOWN; final boolean canceled = event.isCanceled(); final int displayId = event.getDisplayId(); final long key_consumed = -1; final long key_not_consumed = 0; if (DEBUG_INPUT) { Log.d(TAG, ""interceptKeyTi keyCode="" + keyCode + "" down="" + down + "" repeatCount="" + repeatCount + "" keyguardOn="" + keyguardOn + "" canceled="" + canceled); } if (mKeyCombinationManager.isKeyConsumed(event)) { return key_consumed; } if ((flags & KeyEvent.FLAG_FALLBACK) == 0) { final long now = SystemClock.uptimeMillis(); final long interceptTimeout = mKeyCombinationManager.getKeyInterceptTimeout(keyCode); if (now < interceptTimeout) { return interceptTimeout - now; } } // Cancel any pending meta actions if we see any other keys being pressed between the down // of the meta key and its corresponding up. if (mPendingMetaAction && !KeyEvent.isMetaKey(keyCode)) { mPendingMetaAction = false; } // Any key that is not Alt or Meta cancels Caps Lock combo tracking. if (mPendingCapsLockToggle && !KeyEvent.isMetaKey(keyCode) && !KeyEvent.isAltKey(keyCode)) { mPendingCapsLockToggle = false; } if (isUserSetupComplete() && !keyguardOn) { if (mModifierShortcutManager.interceptKey(event)) { dismissKeyboardShortcutsMenu(); mPendingMetaAction = false; mPendingCapsLockToggle = false; return key_consumed; } } switch(keyCode) { case KeyEvent.KEYCODE_HOME: // First we always handle the home key here, so applications // can never break it, although if keyguard is on, we do let // it handle it, because that gives us the correct 5 second // timeout. DisplayHomeButtonHandler handler = mDisplayHomeButtonHandlers.get(displayId); if (handler == null) { handler = new DisplayHomeButtonHandler(displayId); mDisplayHomeButtonHandlers.put(displayId, handler); } return handler.handleHomeButton(focusedToken, event); case KeyEvent.KEYCODE_MENU: // Hijack modified menu keys for debugging features final int chordBug = KeyEvent.META_SHIFT_ON; if (down && repeatCount == 0) { if (mEnableShiftMenuBugReports && (metaState & chordBug) == chordBug) { Intent intent = new Intent(Intent.ACTION_BUG_REPORT); mContext.sendOrderedBroadcastAsUser(intent, UserHandle.CURRENT, null, null, null, 0, null, null); return key_consumed; } } break; case KeyEvent.KEYCODE_APP_SWITCH: if (!keyguardOn) { if (down && repeatCount == 0) { preloadRecentApps(); } else if (!down) { toggleRecentApps(); } } return key_consumed; case KeyEvent.KEYCODE_N: if (down && event.isMetaPressed()) { IStatusBarService service = getStatusBarService(); if (service != null) { try { service.expandNotificationsPanel(); } catch (RemoteException e) { // do nothing. } return key_consumed; } } break; case KeyEvent.KEYCODE_S: if (down && event.isMetaPressed() && event.isCtrlPressed() && repeatCount == 0) { int type = event.isShiftPressed() ? TAKE_SCREENSHOT_SELECTED_REGION : TAKE_SCREENSHOT_FULLSCREEN; interceptScreenshotChord(type, SCREENSHOT_KEY_OTHER, 0 /*pressDelay*/); return key_consumed; } break; case KeyEvent.KEYCODE_SLASH: if (down && repeatCount == 0 && event.isMetaPressed() && !keyguardOn) { toggleKeyboardShortcutsMenu(event.getDeviceId()); return key_consumed; } break; case KeyEvent.KEYCODE_ASSIST: Slog.wtf(TAG, ""KEYCODE_ASSIST should be handled in interceptKeyBeforeQueueing""); return key_consumed; case KeyEvent.KEYCODE_VOICE_ASSIST: Slog.wtf(TAG, ""KEYCODE_VOICE_ASSIST should be handled in"" + "" interceptKeyBeforeQueueing""); return key_consumed; case KeyEvent.KEYCODE_VIDEO_APP_1: case KeyEvent.KEYCODE_VIDEO_APP_2: case KeyEvent.KEYCODE_VIDEO_APP_3: case KeyEvent.KEYCODE_VIDEO_APP_4: case KeyEvent.KEYCODE_VIDEO_APP_5: case KeyEvent.KEYCODE_VIDEO_APP_6: case KeyEvent.KEYCODE_VIDEO_APP_7: case KeyEvent.KEYCODE_VIDEO_APP_8: case KeyEvent.KEYCODE_FEATURED_APP_1: case KeyEvent.KEYCODE_FEATURED_APP_2: case KeyEvent.KEYCODE_FEATURED_APP_3: case KeyEvent.KEYCODE_FEATURED_APP_4: case KeyEvent.KEYCODE_DEMO_APP_1: case KeyEvent.KEYCODE_DEMO_APP_2: case KeyEvent.KEYCODE_DEMO_APP_3: case KeyEvent.KEYCODE_DEMO_APP_4: Slog.wtf(TAG, ""KEYCODE_APP_X should be handled in interceptKeyBeforeQueueing""); return key_consumed; case KeyEvent.KEYCODE_BRIGHTNESS_UP: case KeyEvent.KEYCODE_BRIGHTNESS_DOWN: if (down) { int direction = keyCode == KeyEvent.KEYCODE_BRIGHTNESS_UP ? 1 : -1; // Disable autobrightness if it's on int auto = Settings.System.getIntForUser( mContext.getContentResolver(), Settings.System.SCREEN_BRIGHTNESS_MODE, Settings.System.SCREEN_BRIGHTNESS_MODE_MANUAL, UserHandle.USER_CURRENT_OR_SELF); if (auto != 0) { Settings.System.putIntForUser(mContext.getContentResolver(), Settings.System.SCREEN_BRIGHTNESS_MODE, Settings.System.SCREEN_BRIGHTNESS_MODE_MANUAL, UserHandle.USER_CURRENT_OR_SELF); } float min = mPowerManager.getBrightnessConstraint( PowerManager.BRIGHTNESS_CONSTRAINT_TYPE_MINIMUM); float max = mPowerManager.getBrightnessConstraint( PowerManager.BRIGHTNESS_CONSTRAINT_TYPE_MAXIMUM); float step = (max - min) / BRIGHTNESS_STEPS * direction; int screenDisplayId = displayId < 0 ? DEFAULT_DISPLAY : displayId; float brightness = mDisplayManager.getBrightness(screenDisplayId); brightness += step; // Make sure we don't go beyond the limits. brightness = Math.min(max, brightness); brightness = Math.max(min, brightness); mDisplayManager.setBrightness(screenDisplayId, brightness); startActivityAsUser(new Intent(Intent.ACTION_SHOW_BRIGHTNESS_DIALOG), UserHandle.CURRENT_OR_SELF); } return key_consumed; case KeyEvent.KEYCODE_VOLUME_UP: case KeyEvent.KEYCODE_VOLUME_DOWN: case KeyEvent.KEYCODE_VOLUME_MUTE: if (mUseTvRouting || mHandleVolumeKeysInWM) { // On TVs or when the configuration is enabled, volume keys never // go to the foreground app. dispatchDirectAudioEvent(event); return key_consumed; } // If the device is in VR mode and keys are ""internal"" (e.g. on the side of the // device), then drop the volume keys and don't forward it to the // application/dispatch the audio event. if (mDefaultDisplayPolicy.isPersistentVrModeEnabled()) { final InputDevice d = event.getDevice(); if (d != null && !d.isExternal()) { return key_consumed; } } break; case KeyEvent.KEYCODE_TAB: if (event.isMetaPressed()) { // Pass through keyboard navigation keys. return key_not_consumed; } // Display task switcher for ALT-TAB. if (down && repeatCount == 0) { if (mRecentAppsHeldModifiers == 0 && !keyguardOn && isUserSetupComplete()) { final int shiftlessModifiers = event.getModifiers() & ~KeyEvent.META_SHIFT_MASK; if (KeyEvent.metaStateHasModifiers( shiftlessModifiers, KeyEvent.META_ALT_ON)) { mRecentAppsHeldModifiers = shiftlessModifiers; showRecentApps(true); return key_consumed; } } } break; case KeyEvent.KEYCODE_ALL_APPS: if (!down) { mHandler.removeMessages(MSG_HANDLE_ALL_APPS); Message msg = mHandler.obtainMessage(MSG_HANDLE_ALL_APPS); msg.setAsynchronous(true); msg.sendToTarget(); } return key_consumed; case KeyEvent.KEYCODE_NOTIFICATION: if (!down) { toggleNotificationPanel(); } return key_consumed; case KeyEvent.KEYCODE_SPACE: // Handle keyboard layout switching. (META + SPACE) if ((metaState & KeyEvent.META_META_MASK) == 0) { return key_not_consumed; } // Share the same behavior with KEYCODE_LANGUAGE_SWITCH. case KeyEvent.KEYCODE_LANGUAGE_SWITCH: if (down && repeatCount == 0) { int direction = (metaState & KeyEvent.META_SHIFT_MASK) != 0 ? -1 : 1; mWindowManagerFuncs.switchKeyboardLayout(event.getDeviceId(), direction); return key_consumed; } break; case KeyEvent.KEYCODE_META_LEFT: case KeyEvent.KEYCODE_META_RIGHT: if (down) { if (event.isAltPressed()) { mPendingCapsLockToggle = true; mPendingMetaAction = false; } else { mPendingCapsLockToggle = false; mPendingMetaAction = true; } } else { // Toggle Caps Lock on META-ALT. if (mPendingCapsLockToggle) { mInputManagerInternal.toggleCapsLock(event.getDeviceId()); mPendingCapsLockToggle = false; } else if (mPendingMetaAction) { if (!canceled) { launchAssistAction(Intent.EXTRA_ASSIST_INPUT_HINT_KEYBOARD, event.getDeviceId(), event.getEventTime(), AssistUtils.INVOCATION_TYPE_UNKNOWN); } mPendingMetaAction = false; } } return key_consumed; case KeyEvent.KEYCODE_ALT_LEFT: case KeyEvent.KEYCODE_ALT_RIGHT: if (down) { if (event.isMetaPressed()) { mPendingCapsLockToggle = true; mPendingMetaAction = false; } else { mPendingCapsLockToggle = false; } } else { // hide recent if triggered by ALT-TAB. if (mRecentAppsHeldModifiers != 0 && (metaState & mRecentAppsHeldModifiers) == 0) { mRecentAppsHeldModifiers = 0; hideRecentApps(true, false); return key_consumed; } // Toggle Caps Lock on META-ALT. if (mPendingCapsLockToggle) { mInputManagerInternal.toggleCapsLock(event.getDeviceId()); mPendingCapsLockToggle = false; return key_consumed; } } break; } if (isValidGlobalKey(keyCode) && mGlobalKeyManager.handleGlobalKey(mContext, keyCode, event)) { return key_consumed; } // Specific device key handling if (dispatchKeyToKeyHandlers(event)) { return -1; } // Reserve all the META modifier combos for system behavior if ((metaState & KeyEvent.META_META_ON) != 0) { return key_consumed; } // Let the application handle the key. return key_not_consumed; }","Support for device specific key handlers This is a squash commit of the following changes, only modified for the new SDK. Carbon Edits: get away from SDK Author: Alexander Hofbauer Date: Thu Apr 12 01:24:24 2012 +0200 Dispatch keys to a device specific key handler Injects a device key handler into the input path to handle additional keys (as found on some docks with a hardware keyboard). Configurable via overlay settings config_deviceKeyHandlerLib and config_deviceKeyHandlerClass. Change-Id: I6678c89c7530fdb1d4d516ba4f1d2c9e30ce79a4 Author: Jorge Ruesga Date: Thu Jan 24 02:34:49 2013 +0100 DeviceKeyHandle: The device should consume only known keys When the device receive the key, only should consume it if the device know about the key. Otherwise, the key must be handle by the active app. Also make mDeviceKeyHandler private (is not useful outside this class) Change-Id: I4b9ea57b802e8c8c88c8b93a63d510f5952b0700 Signed-off-by: Jorge Ruesga Author: Danesh Mondegarian Date: Sun Oct 20 00:34:48 2013 -0700 DeviceKeyHandler : Allow handling keyevents while screen off Some devices require the keyevents to be processed while the screen is off, this patchset addresses that by moving the filter up in the call hierarchy. Change-Id: If71beecc81aa5e453dcd08aba72b7bea5c210590 Author: Steve Kondik Date: Sun Sep 11 00:49:41 2016 -0700 policy: Use PathClassLoader for loading the keyhandler * Fix crash on start due to getCacheDir throwing an exception. * We can't do this anymore due to the new storage/crypto in N. Change-Id: I28426a5df824460ebc74aa19068192adb00d4f7c Author: Zhao Wei Liew Date: Sun Nov 20 08:20:15 2016 +0800 PhoneWindowManager: Support multiple key handlers Convert the string overlay to a string-array overlay to allow devices to specify an array of key handlers. Note that the keyhandlers towards the start of the array take precedence when loading. Change-Id: Iaaab737f1501a97d7016d8d519ccf127ca059218 Author: Paul Keith Date: Thu Nov 23 21:47:51 2017 +0100 fw/b: Return a KeyEvent instead of a boolean in KeyHandler * Allows handlers to modify the event before sending it off to another KeyHandler class, to handle things like rotation Change-Id: I481107e050f6323c5897260a5d241e64b4e031ac Change-Id: Ibac1c348717c83fdf9a2894a5d91dc035f9f3a18",https://github.com/AOSPA/android_frameworks_base/commit/8de6f90ea9aa71f1950d7e3e42bf722e8eaa6205,,,services/core/java/com/android/server/policy/PhoneWindowManager.java,3,java,False,2017-10-11T20:11:49Z "protected String submitRequests(Locale locale, Profile profile, IAuthToken authToken, IRequest[] reqs) { String auditSubjectID = auditSubjectID(); String auditRequesterID = ILogger.UNIDENTIFIED; String errorCode = null; String errorReason = null; CAEngine engine = CAEngine.getInstance(); for (IRequest req : reqs) { try { // reset the ""auditRequesterID"" auditRequesterID = auditRequesterID(req); logger.info(""CertProcessor: Processing certificate request:""); if (req != null) { Enumeration reqKeys = req.getExtDataKeys(); while (reqKeys.hasMoreElements()) { String reqKey = reqKeys.nextElement(); String reqVal = req.getExtDataInString(reqKey); if (reqVal != null) { logger.info(""CertProcessor: - "" + reqKey + "": "" + reqVal); } } } logger.info(""CertProcessor: Submitting certificate request to "" + profile.getId() + "" profile""); profile.submit(authToken, req); req.setRequestStatus(RequestStatus.COMPLETE); X509CertImpl x509cert = req.getExtDataInCert(EnrollProfile.REQUEST_ISSUED_CERT); if (x509cert != null) { signedAuditLogger.log(CertRequestProcessedEvent.createSuccessEvent( auditSubjectID, auditRequesterID, ILogger.SIGNED_AUDIT_ACCEPTANCE, x509cert)); } } catch (EDeferException e) { logger.warn(""Certificate request deferred: "" + e.getMessage()); req.setRequestStatus(RequestStatus.PENDING); // need to notify INotify notify = engine.getRequestQueue().getPendingNotify(); if (notify != null) { notify.notify(req); } errorCode = ""2""; req.setExtData(IRequest.ERROR_CODE, errorCode); // do NOT store a message in the signed audit log file // as this errorCode indicates that a process has been // deferred for manual acceptance/cancellation/rejection } catch (ERejectException e) { logger.warn(""Certificate request rejected: "" + e.getMessage(), e); req.setRequestStatus(RequestStatus.REJECTED); errorCode = ""3""; req.setExtData(IRequest.ERROR, e.toString()); req.setExtData(IRequest.ERROR_CODE, errorCode); signedAuditLogger.log(CertRequestProcessedEvent.createFailureEvent( auditSubjectID, auditRequesterID, ILogger.SIGNED_AUDIT_REJECTION, codeToReason(locale, errorCode, e.toString(), req.getRequestId()))); } catch (Throwable e) { logger.warn(""Certificate request failed: "" + e.getMessage(), e); errorCode = ""1""; errorReason = codeToReason(locale, errorCode, null, req.getRequestId()); req.setExtData(IRequest.ERROR, errorReason); req.setExtData(IRequest.ERROR_CODE, errorCode); signedAuditLogger.log(CertRequestProcessedEvent.createFailureEvent( auditSubjectID, auditRequesterID, ILogger.SIGNED_AUDIT_REJECTION, errorReason)); } try { logger.info(""Updating certificate request""); if (errorCode == null) { engine.getRequestQueue().markAsServiced(req); } else { engine.getRequestQueue().updateRequest(req); } } catch (EBaseException e) { logger.warn(""Unable to update certificate request: "" + e.getMessage(), e); } } return errorCode; }","protected String submitRequests(Locale locale, Profile profile, IAuthToken authToken, IRequest[] reqs) { String auditSubjectID = auditSubjectID(); String auditRequesterID = ILogger.UNIDENTIFIED; String errorCode = null; String errorReason = null; CAEngine engine = CAEngine.getInstance(); for (IRequest req : reqs) { try { IConfigStore profileConf = profile.getConfigStore().getSubStore(""auth""); boolean explicitApprovalRequired = profileConf.getBoolean(""explicitApprovalRequired"", false); // reset the ""auditRequesterID"" auditRequesterID = auditRequesterID(req); logger.info(""CertProcessor: Processing certificate request:""); if (req != null) { Enumeration reqKeys = req.getExtDataKeys(); while (reqKeys.hasMoreElements()) { String reqKey = reqKeys.nextElement(); String reqVal = req.getExtDataInString(reqKey); if (reqVal != null) { logger.info(""CertProcessor: - "" + reqKey + "": "" + reqVal); } } } logger.info(""CertProcessor: Submitting certificate request to "" + profile.getId() + "" profile""); profile.submit(authToken, req); profile.submit(authToken, req, explicitApprovalRequired); req.setRequestStatus(RequestStatus.COMPLETE); X509CertImpl x509cert = req.getExtDataInCert(EnrollProfile.REQUEST_ISSUED_CERT); if (x509cert != null) { signedAuditLogger.log(CertRequestProcessedEvent.createSuccessEvent( auditSubjectID, auditRequesterID, ILogger.SIGNED_AUDIT_ACCEPTANCE, x509cert)); } } catch (EDeferException e) { logger.warn(""Certificate request deferred: "" + e.getMessage()); req.setRequestStatus(RequestStatus.PENDING); // need to notify INotify notify = engine.getRequestQueue().getPendingNotify(); if (notify != null) { notify.notify(req); } errorCode = ""2""; req.setExtData(IRequest.ERROR_CODE, errorCode); // do NOT store a message in the signed audit log file // as this errorCode indicates that a process has been // deferred for manual acceptance/cancellation/rejection } catch (ERejectException e) { logger.warn(""Certificate request rejected: "" + e.getMessage(), e); req.setRequestStatus(RequestStatus.REJECTED); errorCode = ""3""; req.setExtData(IRequest.ERROR, e.toString()); req.setExtData(IRequest.ERROR_CODE, errorCode); signedAuditLogger.log(CertRequestProcessedEvent.createFailureEvent( auditSubjectID, auditRequesterID, ILogger.SIGNED_AUDIT_REJECTION, codeToReason(locale, errorCode, e.toString(), req.getRequestId()))); } catch (Throwable e) { logger.warn(""Certificate request failed: "" + e.getMessage(), e); errorCode = ""1""; errorReason = codeToReason(locale, errorCode, null, req.getRequestId()); req.setExtData(IRequest.ERROR, errorReason); req.setExtData(IRequest.ERROR_CODE, errorCode); signedAuditLogger.log(CertRequestProcessedEvent.createFailureEvent( auditSubjectID, auditRequesterID, ILogger.SIGNED_AUDIT_REJECTION, errorReason)); } try { logger.info(""Updating certificate request""); if (errorCode == null) { engine.getRequestQueue().markAsServiced(req); } else { engine.getRequestQueue().updateRequest(req); } } catch (EBaseException e) { logger.warn(""Unable to update certificate request: "" + e.getMessage(), e); } } return errorCode; }","Bug1976010-restrict EE profile list and enrollment submission per LDAP group without immediate issuance It's always been the case by design that if authentication (auth.instance_id=X) is specified in a profile, then as long as a request passes both authentication and authorization (authz.Y) then the issuance would be granted. In this patch, an option per profile is added to override such design and would require explicit agent approval even when both auth and authz passed. This new option is auth.explicitApprovalRequired and the value is true or false,with false being the default if not set. An example configuration in a directory-based authentication profile would have something like the following: auth.instance_id=UserDirEnrollment auth.explicitApprovalRequired=true authz.acl=group=requestors addressed https://bugzilla.redhat.com/show_bug.cgi?id=1976010",https://github.com/dogtagpki/pki/commit/c0b428722a911b2fe37a79266257b31d89d2c97b,,,base/ca/src/main/java/com/netscape/cms/servlet/cert/CertProcessor.java,3,java,False,2021-06-26T00:28:19Z "private static String getQueryString(HttpServletRequest req, String p, String st, String so, String s) { StringBuilder buf = new StringBuilder(64); if (p == null) { p = req.getParameter(""p""); if (p != null) p = DataHelper.stripHTML(p); } if (p != null && !p.equals("""")) buf.append(""?p="").append(p); if (so == null) { so = req.getParameter(""sort""); if (so != null) so = DataHelper.stripHTML(so); } if (so != null && !so.equals("""")) { if (buf.length() <= 0) buf.append(""?sort=""); else buf.append(""&sort=""); buf.append(so); } if (st == null) { st = req.getParameter(""st""); if (st != null) st = DataHelper.stripHTML(st); } if (st != null && !st.equals("""")) { if (buf.length() <= 0) buf.append(""?st=""); else buf.append(""&st=""); buf.append(st); } if (s == null) { s = req.getParameter(""s""); if (s != null) s = DataHelper.escapeHTML(s); } if (s != null && !s.equals("""")) { if (buf.length() <= 0) buf.append(""?s=""); else buf.append(""&s=""); buf.append(s); } return buf.toString(); }","private static String getQueryString(HttpServletRequest req, String p, String st, String so, String s) { StringBuilder buf = new StringBuilder(64); if (p == null) { p = req.getParameter(""p""); if (p != null) p = DataHelper.stripHTML(p); } if (p != null && !p.equals("""")) buf.append(""?p="").append(p); if (so == null) { so = req.getParameter(""sort""); if (so != null) so = DataHelper.stripHTML(so); } if (so != null && !so.equals("""")) { if (buf.length() <= 0) buf.append(""?sort=""); else buf.append(""&sort=""); buf.append(so); } if (st == null) { st = req.getParameter(""st""); if (st != null) st = DataHelper.stripHTML(st); } if (st != null && !st.equals("""")) { if (buf.length() <= 0) buf.append(""?st=""); else buf.append(""&st=""); buf.append(st); } if (s == null) { s = req.getParameter(""nf_s""); if (s != null) s = DataHelper.escapeHTML(s); } if (s != null && !s.equals("""")) { if (buf.length() <= 0) buf.append(""?nf_s=""); else buf.append(""&nf_s=""); buf.append(s); } return buf.toString(); }","i2psnark: Rename search param to bypass the XSS filter Fix encode/decode search param Copy CSS to non-default themes, not tweaked yet Add support for shorter nf_ prefix to XSS filter Remove unneeded float_right, reported by drzed",https://github.com/i2p/i2p.i2p/commit/0cbbe6297e2f2079fcb33b7b1da23b94c8f83f4f,,,apps/i2psnark/java/src/org/klomp/snark/web/I2PSnarkServlet.java,3,java,False,2023-01-18T17:21:29Z "@Override public void handle(GameSession session, byte[] header, byte[] payload) throws Exception { CombatInvocationsNotify notif = CombatInvocationsNotify.parseFrom(payload); for (CombatInvokeEntry entry : notif.getInvokeListList()) { // Handle combat invoke switch (entry.getArgumentType()) { case COMBAT_TYPE_ARGUMENT_EVT_BEING_HIT: EvtBeingHitInfo hitInfo = EvtBeingHitInfo.parseFrom(entry.getCombatData()); AttackResult attackResult = hitInfo.getAttackResult(); Player player = session.getPlayer(); // Handle damage player.getAttackResults().add(attackResult); player.getEnergyManager().handleAttackHit(hitInfo); break; case COMBAT_TYPE_ARGUMENT_ENTITY_MOVE: // Handle movement EntityMoveInfo moveInfo = EntityMoveInfo.parseFrom(entry.getCombatData()); GameEntity entity = session.getPlayer().getScene().getEntityById(moveInfo.getEntityId()); if (entity != null) { // Move player MotionInfo motionInfo = moveInfo.getMotionInfo(); MotionState motionState = motionInfo.getState(); // Call entity move event. EntityMoveEvent event = new EntityMoveEvent( entity, new Position(motionInfo.getPos()), new Position(motionInfo.getRot()), motionState); event.call(); entity.move(event.getPosition(), event.getRotation()); entity.setLastMoveSceneTimeMs(moveInfo.getSceneTime()); entity.setLastMoveReliableSeq(moveInfo.getReliableSeq()); entity.setMotionState(motionState); session.getPlayer().getStaminaManager().handleCombatInvocationsNotify(session, moveInfo, entity); // TODO: handle MOTION_FIGHT landing which has a different damage factor // Also, for plunge attacks, LAND_SPEED is always -30 and is not useful. // May need the height when starting plunge attack. // MOTION_LAND_SPEED and MOTION_FALL_ON_GROUND arrive in different packets. // Cache land speed for later use. if (motionState == MotionState.MOTION_STATE_LAND_SPEED) { cachedLandingSpeed = motionInfo.getSpeed().getY(); cachedLandingTimeMillisecond = System.currentTimeMillis(); monitorLandingEvent = true; } if (monitorLandingEvent) { if (motionState == MotionState.MOTION_STATE_FALL_ON_GROUND) { monitorLandingEvent = false; handleFallOnGround(session, entity, motionState); } } // MOTION_STATE_NOTIFY = Dont send to other players if (motionState == MotionState.MOTION_STATE_NOTIFY) { continue; } } break; case COMBAT_TYPE_ARGUMENT_ANIMATOR_PARAMETER_CHANGED: EvtAnimatorParameterInfo paramInfo = EvtAnimatorParameterInfo.parseFrom(entry.getCombatData()); if (paramInfo.getIsServerCache()) { paramInfo = paramInfo.toBuilder().setIsServerCache(false).build(); entry = entry.toBuilder().setCombatData(paramInfo.toByteString()).build(); } break; default: break; } session.getPlayer().getCombatInvokeHandler().addEntry(entry.getForwardType(), entry); } }","@Override public void handle(GameSession session, byte[] header, byte[] payload) throws Exception { CombatInvocationsNotify notif = CombatInvocationsNotify.parseFrom(payload); for (CombatInvokeEntry entry : notif.getInvokeListList()) { // Handle combat invoke switch (entry.getArgumentType()) { case COMBAT_TYPE_ARGUMENT_EVT_BEING_HIT -> { EvtBeingHitInfo hitInfo = EvtBeingHitInfo.parseFrom(entry.getCombatData()); AttackResult attackResult = hitInfo.getAttackResult(); Player player = session.getPlayer(); // Check if the player is invulnerable. if ( attackResult.getAttackerId() != player.getTeamManager().getCurrentAvatarEntity().getId() && player.getAbilityManager().isAbilityInvulnerable() ) break; // Handle damage player.getAttackResults().add(attackResult); player.getEnergyManager().handleAttackHit(hitInfo); } case COMBAT_TYPE_ARGUMENT_ENTITY_MOVE -> { // Handle movement EntityMoveInfo moveInfo = EntityMoveInfo.parseFrom(entry.getCombatData()); GameEntity entity = session.getPlayer().getScene().getEntityById(moveInfo.getEntityId()); if (entity != null) { // Move player MotionInfo motionInfo = moveInfo.getMotionInfo(); MotionState motionState = motionInfo.getState(); // Call entity move event. EntityMoveEvent event = new EntityMoveEvent( entity, new Position(motionInfo.getPos()), new Position(motionInfo.getRot()), motionState); event.call(); entity.move(event.getPosition(), event.getRotation()); entity.setLastMoveSceneTimeMs(moveInfo.getSceneTime()); entity.setLastMoveReliableSeq(moveInfo.getReliableSeq()); entity.setMotionState(motionState); session.getPlayer().getStaminaManager().handleCombatInvocationsNotify(session, moveInfo, entity); // TODO: handle MOTION_FIGHT landing which has a different damage factor // Also, for plunge attacks, LAND_SPEED is always -30 and is not useful. // May need the height when starting plunge attack. // MOTION_LAND_SPEED and MOTION_FALL_ON_GROUND arrive in different packets. // Cache land speed for later use. if (motionState == MotionState.MOTION_STATE_LAND_SPEED) { cachedLandingSpeed = motionInfo.getSpeed().getY(); cachedLandingTimeMillisecond = System.currentTimeMillis(); monitorLandingEvent = true; } if (monitorLandingEvent) { if (motionState == MotionState.MOTION_STATE_FALL_ON_GROUND) { monitorLandingEvent = false; handleFallOnGround(session, entity, motionState); } } // MOTION_STATE_NOTIFY = Dont send to other players if (motionState == MotionState.MOTION_STATE_NOTIFY) { continue; } } } case COMBAT_TYPE_ARGUMENT_ANIMATOR_PARAMETER_CHANGED -> { EvtAnimatorParameterInfo paramInfo = EvtAnimatorParameterInfo.parseFrom(entry.getCombatData()); if (paramInfo.getIsServerCache()) { paramInfo = paramInfo.toBuilder().setIsServerCache(false).build(); entry = entry.toBuilder().setCombatData(paramInfo.toByteString()).build(); } } default -> { } } session.getPlayer().getCombatInvokeHandler().addEntry(entry.getForwardType(), entry); } }",Add invoke-level invulnerability for bursts.,https://github.com/Grasscutters/Grasscutter/commit/6ec372e64f4fcd6b9265823fe48242e5719ddaf5,,,src/main/java/emu/grasscutter/server/packet/recv/HandlerCombatInvocationsNotify.java,3,java,False,2022-08-07T03:35:57Z "public HttpResponse sendRequest(HttpUriRequest uriRequest) { if (httpClient == null) { httpClient = getHttpClient(); } if (log.isTraceEnabled()) { log.trace(""sending http request: \n\tmethod: {}\n\turi: {}"", uriRequest.getMethod(), uriRequest.getURI().toString()); } try (CloseableHttpResponse response = httpClient.execute(uriRequest)) { return toResponse(response); } catch (SSLHandshakeException ex) { throw new SSLHandshakeRuntimeException(""handshake error during connection setup"", ex); } catch (ConnectTimeoutException ex) { throw new ConnectTimeoutRuntimeException(""connection timeout after '"" + scimClientConfig.getConnectTimeout() + ""' seconds"", ex); } catch (SocketTimeoutException ex) { throw new SocketTimeoutRuntimeException(""socket timeout after '"" + scimClientConfig.getSocketTimeout() + ""' seconds"", ex); } catch (UnknownHostException ex) { throw new UnknownHostRuntimeException(""could not find host '"" + uriRequest.getURI().getHost() + ""'"", ex); } catch (IOException ex) { throw new IORuntimeException(""communication with server failed"", ex); } }","public HttpResponse sendRequest(HttpUriRequest uriRequest) { if (httpClient == null) { httpClient = getHttpClient(); } setAuthenticationIfMissing(uriRequest); if (log.isTraceEnabled()) { log.trace(""sending http request: \n\tmethod: {}\n\turi: {}"", uriRequest.getMethod(), uriRequest.getURI().toString()); } try (CloseableHttpResponse response = httpClient.execute(uriRequest)) { return toResponse(response); } catch (SSLHandshakeException ex) { throw new SSLHandshakeRuntimeException(""handshake error during connection setup"", ex); } catch (ConnectTimeoutException ex) { throw new ConnectTimeoutRuntimeException(""connection timeout after '"" + scimClientConfig.getConnectTimeout() + ""' seconds"", ex); } catch (SocketTimeoutException ex) { throw new SocketTimeoutRuntimeException(""socket timeout after '"" + scimClientConfig.getSocketTimeout() + ""' seconds"", ex); } catch (UnknownHostException ex) { throw new UnknownHostRuntimeException(""could not find host '"" + uriRequest.getURI().getHost() + ""'"", ex); } catch (IOException ex) { throw new IORuntimeException(""communication with server failed"", ex); } }","Fix unused basic authentication for ScimHttpClient fixes: #136",https://github.com/Captain-P-Goldfish/SCIM-SDK/commit/da59b6bbdff9a01804d33d0f5c43623a15d75b20,,,scim-sdk-client/src/main/java/de/captaingoldfish/scim/sdk/client/http/ScimHttpClient.java,3,java,False,2021-04-07T20:02:01Z "private void uploadFile(HttpServletRequest request, ViewEditForm form) throws Exception { if (WebUtils.hasSubmitParameter(request, SUBMIT_UPLOAD)) { if (form.getBackgroundImageMP() != null) { byte[] bytes = form.getBackgroundImageMP().getBytes(); if (bytes != null && bytes.length > 0) { // Create the path to the upload directory. String path = request.getSession().getServletContext().getRealPath(uploadDirectory); LOG.info(""ViewEditController:uploadFile: realpath=""+path); // Make sure the directory exists. File dir = new File(path); dir.mkdirs(); // Get an image id. int imageId = getNextImageId(dir); // Create the image file name. String filename = Integer.toString(imageId); int dot = form.getBackgroundImageMP().getOriginalFilename().lastIndexOf('.'); if (dot != -1) filename += form.getBackgroundImageMP().getOriginalFilename().substring(dot); // Save the file. FileOutputStream fos = new FileOutputStream(new File(dir, filename)); fos.write(bytes); fos.close(); form.getView().setBackgroundFilename(uploadDirectory + filename); } } } }","private void uploadFile(HttpServletRequest request, ViewEditForm form) throws Exception { if (WebUtils.hasSubmitParameter(request, SUBMIT_UPLOAD)) { MultipartFile file = form.getBackgroundImageMP(); if (file != null) { upload(request, form, file); } else { LOG.warn(""Image file is not attached.""); } } }",#1734 Fix vulnerabilities reported in - correct merge ViewEditController,https://github.com/SCADA-LTS/Scada-LTS/commit/a4dd48a66fcec85293de3f3e60e05d334c142d76,,,src/org/scada_lts/web/mvc/controller/ViewEditController.java,3,java,False,2022-02-15T09:32:08Z "@EventHandler(priority = EventPriority.MONITOR) public void onJoin(@NotNull final PlayerJoinEvent event) { synchronized (NametagTimerChecker.nametagTimer_Lock){ main.nametagTimerChecker.nametagCooldownQueue.put(event.getPlayer(), new WeakHashMap<>()); } parseCompatibilityChecker(event.getPlayer()); parseUpdateChecker(event.getPlayer()); updateNametagsInWorldAsync(event.getPlayer(), event.getPlayer().getWorld().getEntities()); if (main.migratedFromPre30 && event.getPlayer().isOp()){ event.getPlayer().sendMessage(MessageUtils.colorizeStandardCodes(""&b&lLevelledMobs: &cWARNING &7You have migrated from an older version. All settings have been reverted. Please edit rules.yml"")); } }","@EventHandler(priority = EventPriority.MONITOR) public void onJoin(@NotNull final PlayerJoinEvent event) { main.nametagTimerChecker.addPlayerToQueue(new PlayerQueueItem(event.getPlayer(), true)); parseCompatibilityChecker(event.getPlayer()); parseUpdateChecker(event.getPlayer()); updateNametagsInWorldAsync(event.getPlayer(), event.getPlayer().getWorld().getEntities()); if (main.migratedFromPre30 && event.getPlayer().isOp()){ event.getPlayer().sendMessage(MessageUtils.colorizeStandardCodes(""&b&lLevelledMobs: &cWARNING &7You have migrated from an older version. All settings have been reverted. Please edit rules.yml"")); } }","3.2.3 b539 * fix for potential server crash with callstack me.lokka30.levelledmobs.listeners.PlayerJoinListener.onJoin(PlayerJoinListener.java:48)",https://github.com/ArcanePlugins/LevelledMobs/commit/c1cc9748fc251e02825a4fb16bcfe9b06c1a0656,,,src/main/java/me/lokka30/levelledmobs/listeners/PlayerJoinListener.java,3,java,False,2021-10-18T20:16:44Z "private static void loadSkin(GameProfile profile, String fallback) { if (skins.containsKey(profile.getName())) { return; } ResourceLocation fallbackIdentifier = new ResourceLocation(""plasmo_voice"", ""skins/"" + profile.getName().toLowerCase()); try { Minecraft.getInstance().getTextureManager().register( fallbackIdentifier, new DynamicTexture(NativeImage.fromBase64(fallback)) ); } catch (IOException e) { e.printStackTrace(); } // fallback skins.put(profile.getName(), fallbackIdentifier); if (profile.getId().equals(VoiceClient.NIL_UUID)) { return; } Map textures = Minecraft.getInstance().getSkinManager().getInsecureSkinInformation(profile); if (textures == null || textures.isEmpty()) { Minecraft.getInstance().getSkinManager().registerSkins( profile, (type, identifier, texture) -> { if (type.equals(MinecraftProfileTexture.Type.SKIN)) { skins.put(profile.getName(), identifier); } }, false); } else { String hash = Hashing.sha1().hashUnencodedChars(textures.get(MinecraftProfileTexture.Type.SKIN).getHash()).toString(); ResourceLocation identifier = new ResourceLocation(""skins/"" + hash); skins.put(profile.getName(), identifier); } }","private static void loadSkin(GameProfile profile, String fallback) { if (skins.containsKey(profile.getName())) { return; } if (fallback != null) { ResourceLocation fallbackIdentifier = new ResourceLocation(""plasmo_voice"", ""skins/"" + Hashing.sha1().hashUnencodedChars(profile.getName().toLowerCase()).toString()); try { Minecraft.getInstance().getTextureManager().register( fallbackIdentifier, new DynamicTexture(NativeImage.fromBase64(fallback)) ); } catch (IOException e) { e.printStackTrace(); } // fallback skins.put(profile.getName(), fallbackIdentifier); } Map textures = Minecraft.getInstance().getSkinManager().getInsecureSkinInformation(profile); if (textures == null || textures.isEmpty()) { Minecraft.getInstance().getSkinManager().registerSkins( profile, (type, identifier, texture) -> { if (type.equals(MinecraftProfileTexture.Type.SKIN)) { skins.put(profile.getName(), identifier); } }, false); } else { String hash = Hashing.sha1().hashUnencodedChars(textures.get(MinecraftProfileTexture.Type.SKIN).getHash()).toString(); ResourceLocation identifier = new ResourceLocation(""skins/"" + hash); skins.put(profile.getName(), identifier); } }","Fixed multiple crashes that were hard to trigger Fixed About tab in the menu not showing translators",https://github.com/plasmoapp/plasmo-voice/commit/4df99521021d084395d2b6c27f3daa711c0de8d6,,,common/src/main/java/su/plo/voice/client/gui/tabs/AboutTabWidget.java,3,java,False,2021-10-19T09:35:35Z "@Override public Cancellable register(Discoverable discoverable) { // Create or update the k8s Service // The service is created with label selector based on the current pod labels String serviceName = namePrefix + discoverable.getName().toLowerCase().replace('.', '-'); try { CoreV1Api api = getCoreApi(); while (true) { // First try to create the service if (createV1Service(api, serviceName, discoverable)) { break; } // If creation failed, we update the service. // To update, first need to find the service version. Optional currentService = getV1Service(api, serviceName, discoverable.getName()); if (!currentService.isPresent()) { // Loop and try to create again continue; } // Update service. if (updateV1Service(api, currentService.get(), discoverable)) { break; } } } catch (ApiException e) { throw new RuntimeException(""Failure response from API service, code="" + e.getCode() + "", body="" + e.getResponseBody(), e); } catch (IOException e) { throw new RuntimeException(""Failed to connect to API server"", e); } // We don't delete the service on cancelling since the service should stay when on restarting of one instance // It is the CDAP K8s operator task to remove services on CRD instance deletion by the label selector. return () -> { }; }","@Override public Cancellable register(Discoverable discoverable) { // Create or update the k8s Service // The service is created with label selector based on the current pod labels String serviceName = namePrefix + discoverable.getName().toLowerCase().replace('.', '-'); try { CoreV1Api api = getCoreApi(); while (true) { Optional currentService = getV1Service(api, serviceName, discoverable.getName()); if (!currentService.isPresent()) { if (createV1Service(api, serviceName, discoverable)) { break; } // Service create encountered a conflict, loop and check for service again continue; } // Update service. if (updateV1Service(api, currentService.get(), discoverable)) { break; } } } catch (ApiException e) { throw new RuntimeException(""Failure response from API service, code="" + e.getCode() + "", body="" + e.getResponseBody(), e); } catch (IOException e) { throw new RuntimeException(""Failed to connect to API server"", e); } // We don't delete the service on cancelling since the service should stay when on restarting of one instance // It is the CDAP K8s operator task to remove services on CRD instance deletion by the label selector. return () -> { }; }","[CDAP-19376] Explicitly Check for Existing Service In KubeDiscoveryService Trying to create service when all IP addresses are assigned results in unhandled error. This is possible in RBAC enabled private network environments with /27 address space because there we create exactly 31 services. After initial startup, if any pod which performs the KubeDiscoveryService restarts, it will keep crashing on this issue. The taskworker pods restart quite often and face this issue the most. Testing Done - 1. Create a RBAC enabled private network with /27 address space. 2. After a few hours, observe that ALL taskworker pods are in INIT/terminate loop. 3. Update the image for all those pods with this fix. 4. Observe that taskworker pods now come up successfully. No pod restarts after couple of hours. 5. Deleted other pods such as runtime and appfabric pods. Observed the pods come up successfully.",https://github.com/cdapio/cdap/commit/1a3566c102d8a3b29468569b31a6c1cee5c1c83a,,,cdap-kubernetes/src/main/java/io/cdap/cdap/k8s/discovery/KubeDiscoveryService.java,3,java,False,2022-07-14T01:16:55Z "@Keep public void handleLoadPackage(Context applicationContext, final XC_LoadPackage.LoadPackageParam loadPackageParam) throws Throwable { if (loadPackageParam == null) { return; } final ArrayList[] mBlockList; mBlockList = newArray(1); xSP = new RemotePreferences(applicationContext, Constant.ACTIVITY_NAME, ""data""); String pkg = xSP.getString(PACKAGE_NAME_NAME, """"); applicationContext.bindService(new Intent(""RemoteViewMessager""), new ServiceConnection() { @Override public void onServiceConnected(ComponentName name, IBinder service) { viewMessager = IViewMessager.Stub.asInterface(service); } @Override public void onServiceDisconnected(ComponentName name) { } }, Context.BIND_AUTO_CREATE); //读取设置 try { superMode = Boolean.valueOf(xSP.getString(SUPER_MODE_NAME, String.valueOf(false))); onlyOnce = Boolean.valueOf(xSP.getString(ONLY_ONCE_NAME, String.valueOf(false))); standardMode = Boolean.valueOf(xSP.getString(STANDARD_MODE_NAME, String.valueOf(true))); enableLog = Boolean.valueOf(xSP.getString(ENABLE_LOG_NAME, String.valueOf(true))); } catch (Exception e) { e.printStackTrace(); superMode = false; onlyOnce = false; standardMode = true; enableLog = true; } log(""净眼:开始HOOK --> "" + loadPackageParam.packageName); log(""净眼:检测模块正常 -->"" + pkg); if ((loadPackageParam.packageName.equals(pkg))) { if (standardMode) { log(""净眼:hook -->setOnClickListener""); XposedHelpers.findAndHookMethod(View.class, ""setOnClickListener"", View.OnClickListener.class, new XC_MethodHook() { @Override protected void beforeHookedMethod(final MethodHookParam param) throws Throwable { super.beforeHookedMethod(param); final View.OnClickListener clickListener = (View.OnClickListener) param.args[0]; param.args[0] = new View.OnClickListener() { @Override public void onClick(View view) { //处理,显示参数 try { handleClick(view); } catch (Throwable e) { e.printStackTrace(); } //如果是ListView中的项目,手动CALL一次监听器 ViewArg model = getListView(view); if (model != null) { log(""in ListView!""); try { int position = (int) XposedHelpers.callMethod(model.adapterView, ""getPositionForView"", new Class[]{View.class}, model.subView); long id = (long) XposedHelpers.callMethod(model.adapterView, ""getItemIdAtPosition"", new Class[]{int.class}, position); XposedHelpers.callMethod(model.adapterView, ""performItemClick"", new Class[]{View.class, int.class, int.class}, model.subView, position, id); } catch (Throwable e) { e.printStackTrace(); } } if (clickListener != null) { clickListener.onClick(view); } } }; } }); } else { log(""净眼:hook -->setOnTouchListener""); XposedHelpers.findAndHookMethod(View.class, ""setOnTouchListener"", View.OnTouchListener.class, new XC_MethodHook() { @Override protected void beforeHookedMethod(final MethodHookParam param) throws Throwable { super.beforeHookedMethod(param); final View.OnTouchListener touchListener = (View.OnTouchListener) param.args[0]; param.args[0] = new View.OnTouchListener() { @Override public boolean onTouch(View view, MotionEvent motionEvent) { if (motionEvent.getAction() == MotionEvent.ACTION_DOWN) //处理,显示参数 { try { handleTouch(view); } catch (PackageManager.NameNotFoundException e) { e.printStackTrace(); } } return touchListener != null && touchListener.onTouch(view, motionEvent); } }; } }); } log(""净眼:hook -->setClickable""); XposedHelpers.findAndHookMethod(View.class, ""setClickable"", boolean.class, new BooleanSetterHooker(true)); //XposedHelpers.findAndHookMethod(View.class, ""isClickable"", XC_MethodReplacement.returnConstant(true)); log(""净眼:hook -->setLongClickable""); XposedHelpers.findAndHookMethod(View.class, ""setLongClickable"", boolean.class, new BooleanSetterHooker(true)); log(""净眼:hook -->View""); XposedBridge.hookAllConstructors(View.class, new ConstructorHooker()); try { XposedHelpers.findAndHookMethod(""android.view.WindowManagerGlobal"", Dialog.class.getClassLoader(), ""removeView"", View.class, boolean.class, new WindowHooker()); } catch (Throwable throwable) { throwable.printStackTrace(); } XposedHelpers.findAndHookMethod(""android.view.WindowManagerImpl"", Dialog.class.getClassLoader(), ""removeView"", View.class, new WindowHooker()); XposedHelpers.findAndHookMethod(""android.view.WindowManagerImpl"", Dialog.class.getClassLoader(), ""removeViewImmediate"", View.class, new WindowHooker()); } /* ------------------------------------标记部分结束,以下为拦截部分------------------------ 读取屏蔽列表 */ mBlockList[0] = readBlockList(loadPackageParam.packageName); //以下为Hook //对话框取消那个APP,其实核心就这一行代码... log(""净眼:hook -->setCancelable""); XposedHelpers.findAndHookMethod(Dialog.class, ""setCancelable"", boolean.class, new BooleanSetterHooker(true)); if (isBlockPackage(mBlockList[0], loadPackageParam.packageName) && !loadPackageParam.packageName.equals(pkg)) { XposedBridge.hookAllMethods(Activity.class, ""onCreate"", new XC_MethodHook() { @Override protected void beforeHookedMethod(MethodHookParam param) throws Throwable { super.beforeHookedMethod(param); //Reload it! mBlockList[0] = readBlockList(loadPackageParam.packageName); } }); XposedHelpers.findAndHookMethod(View.class, ""setVisibility"", int.class, new XC_MethodHook() { @Override protected void beforeHookedMethod(MethodHookParam param) throws Throwable { super.beforeHookedMethod(param); View v = (View) param.thisObject; if ((int) param.args[0] == View.GONE) { return; } if (ViewBlocker.getInstance().isBlocked(mBlockList[0], v)) { param.args[0] = View.GONE; ViewBlocker.getInstance().block(v); } } }); XposedHelpers.findAndHookMethod(TextView.class, ""setText"", CharSequence.class, new XC_MethodHook() { @Override protected void afterHookedMethod(MethodHookParam param) throws Throwable { super.afterHookedMethod(param); TextView v = (TextView) param.thisObject; if (ViewBlocker.getInstance().isBlocked(mBlockList[0], v)) { ViewBlocker.getInstance().block(v); } } }); XposedHelpers.findAndHookMethod(View.class, ""setLayoutParams"", ViewGroup.LayoutParams.class, new XC_MethodHook() { @Override protected void beforeHookedMethod(MethodHookParam param) throws Throwable { ViewGroup.LayoutParams layoutParams = (ViewGroup.LayoutParams) param.args[0]; if (layoutParams != null) { if (layoutParams.height == 0 && layoutParams.width == 0) { return; } if (ViewBlocker.getInstance().isBlocked(mBlockList[0], param.thisObject)) { ViewBlocker.getInstance().block(param.thisObject); } } } }); final boolean fsuperMode = superMode; final XC_MethodHook viewHooker = new XC_MethodHook() { @Override protected void afterHookedMethod(MethodHookParam param) throws Throwable { super.afterHookedMethod(param); final View v = (View) param.thisObject; v.getViewTreeObserver().addOnGlobalLayoutListener(new ViewTreeObserver.OnGlobalLayoutListener() { @Override public void onGlobalLayout() { if (fsuperMode) { if (ViewBlocker.getInstance().isBlocked(mBlockList[0], v)) { v.getViewTreeObserver().removeGlobalOnLayoutListener(this); ViewBlocker.getInstance().block(v); } } else { v.getViewTreeObserver().removeGlobalOnLayoutListener(this); if (ViewBlocker.getInstance().isBlocked(mBlockList[0], v)) { ViewBlocker.getInstance().block(v); } } } }); } }; XposedBridge.hookAllConstructors(View.class, viewHooker); XposedBridge.hookAllConstructors(ViewGroup.class, viewHooker); log(""净眼:hook -->addView""); //Dialog blocking XposedHelpers.findAndHookMethod(""android.view.WindowManagerImpl"", loadPackageParam.classLoader, ""addView"", View.class, ViewGroup.LayoutParams.class, new XC_MethodHook() { @Override protected void afterHookedMethod(MethodHookParam param) throws Throwable { super.afterHookedMethod(param); View view = (View) param.args[0]; WindowManager windowManager = (WindowManager) param.thisObject; if (view == null) { return; } if (DialogBlocker.getInstance().isBlocked(mBlockList[0], view)) { windowManager.removeViewImmediate(view); } } }); } }","@Keep public void handleLoadPackage(Context applicationContext, final XC_LoadPackage.LoadPackageParam loadPackageParam) throws Throwable { if (loadPackageParam == null) { return; } final ArrayList[] mBlockList; mBlockList = newArray(1); xSP = new RemotePreferences(applicationContext, Constant.ACTIVITY_NAME, ""data""); String pkg = xSP.getString(PACKAGE_NAME_NAME, """"); applicationContext.bindService(new Intent(""RemoteViewMessager"").setPackage(BuildConfig.APPLICATION_ID), new ServiceConnection() { @Override public void onServiceConnected(ComponentName name, IBinder service) { viewMessager = IViewMessager.Stub.asInterface(service); } @Override public void onServiceDisconnected(ComponentName name) { } }, Context.BIND_AUTO_CREATE); //读取设置 try { superMode = Boolean.parseBoolean(xSP.getString(SUPER_MODE_NAME, String.valueOf(false))); onlyOnce = Boolean.parseBoolean(xSP.getString(ONLY_ONCE_NAME, String.valueOf(false))); standardMode = Boolean.parseBoolean(xSP.getString(STANDARD_MODE_NAME, String.valueOf(true))); enableLog = Boolean.parseBoolean(xSP.getString(ENABLE_LOG_NAME, String.valueOf(true))); } catch (Exception e) { e.printStackTrace(); superMode = false; onlyOnce = false; standardMode = true; enableLog = true; } log(""净眼:开始HOOK -->"" + loadPackageParam.packageName); log(""净眼:新的消息!""); log(""净眼:检测模块正常 -->"" + pkg); if ((loadPackageParam.packageName.equals(pkg))) { if (standardMode) { log(""净眼:hook -->setOnClickListener""); XposedHelpers.findAndHookMethod(View.class, ""setOnClickListener"", View.OnClickListener.class, new XC_MethodHook() { @Override protected void beforeHookedMethod(final MethodHookParam param) throws Throwable { super.beforeHookedMethod(param); log(""净眼:set OnClickListener for "" + param.thisObject.getClass()); final View.OnClickListener clickListener = (View.OnClickListener) param.args[0]; log(""净眼:start set OnClickListener!""); param.args[0] = (View.OnClickListener) view -> { log(""净眼:onclick!""); //处理,显示参数 try { handleClick(view); } catch (Throwable e) { e.printStackTrace(); } //如果是ListView中的项目,手动CALL一次监听器 ViewArg model = getListView(view); if (model != null) { log(""in ListView!""); try { int position = (int) XposedHelpers.callMethod(model.adapterView, ""getPositionForView"", new Class[]{View.class}, model.subView); long id = (long) XposedHelpers.callMethod(model.adapterView, ""getItemIdAtPosition"", new Class[]{int.class}, position); XposedHelpers.callMethod(model.adapterView, ""performItemClick"", new Class[]{View.class, int.class, int.class}, model.subView, position, id); } catch (Throwable e) { e.printStackTrace(); } } if (clickListener != null) { clickListener.onClick(view); } }; } }); } else { log(""净眼:hook -->setOnTouchListener""); XposedHelpers.findAndHookMethod(View.class, ""setOnTouchListener"", View.OnTouchListener.class, new XC_MethodHook() { @Override protected void beforeHookedMethod(final MethodHookParam param) throws Throwable { super.beforeHookedMethod(param); final View.OnTouchListener touchListener = (View.OnTouchListener) param.args[0]; param.args[0] = new View.OnTouchListener() { @Override public boolean onTouch(View view, MotionEvent motionEvent) { if (motionEvent.getAction() == MotionEvent.ACTION_DOWN) //处理,显示参数 { try { handleTouch(view); } catch (PackageManager.NameNotFoundException e) { e.printStackTrace(); } } return touchListener != null && touchListener.onTouch(view, motionEvent); } }; } }); } log(""净眼:hook -->setClickable""); XposedHelpers.findAndHookMethod(View.class, ""setClickable"", boolean.class, new BooleanSetterHooker(true)); //XposedHelpers.findAndHookMethod(View.class, ""isClickable"", XC_MethodReplacement.returnConstant(true)); log(""净眼:hook -->setLongClickable""); XposedHelpers.findAndHookMethod(View.class, ""setLongClickable"", boolean.class, new BooleanSetterHooker(true)); log(""净眼:hook -->View""); XposedBridge.hookAllConstructors(View.class, new ConstructorHooker()); XposedBridge.hookAllConstructors(XposedHelpers.findClass(""android.view.View"", loadPackageParam.classLoader), new ConstructorHooker()); try { XposedHelpers.findAndHookMethod(""android.view.WindowManagerGlobal"", Dialog.class.getClassLoader(), ""removeView"", View.class, boolean.class, new WindowHooker()); } catch (Throwable throwable) { throwable.printStackTrace(); } XposedHelpers.findAndHookMethod(""android.view.WindowManagerImpl"", Dialog.class.getClassLoader(), ""removeView"", View.class, new WindowHooker()); XposedHelpers.findAndHookMethod(""android.view.WindowManagerImpl"", Dialog.class.getClassLoader(), ""removeViewImmediate"", View.class, new WindowHooker()); } /* ------------------------------------标记部分结束,以下为拦截部分------------------------ 读取屏蔽列表 */ mBlockList[0] = readBlockList(loadPackageParam.packageName); //以下为Hook //对话框取消那个APP,其实核心就这一行代码... log(""净眼:hook -->setCancelable""); XposedHelpers.findAndHookMethod(Dialog.class, ""setCancelable"", boolean.class, new BooleanSetterHooker(true)); if (isBlockPackage(mBlockList[0], loadPackageParam.packageName) && !loadPackageParam.packageName.equals(pkg)) { XposedBridge.hookAllMethods(Activity.class, ""onCreate"", new XC_MethodHook() { @Override protected void beforeHookedMethod(MethodHookParam param) throws Throwable { super.beforeHookedMethod(param); //Reload it! mBlockList[0] = readBlockList(loadPackageParam.packageName); } }); XposedHelpers.findAndHookMethod(View.class, ""setVisibility"", int.class, new XC_MethodHook() { @Override protected void beforeHookedMethod(MethodHookParam param) throws Throwable { super.beforeHookedMethod(param); View v = (View) param.thisObject; if ((int) param.args[0] == View.GONE) { return; } if (ViewBlocker.getInstance().isBlocked(mBlockList[0], v)) { param.args[0] = View.GONE; ViewBlocker.getInstance().block(v); } } }); XposedHelpers.findAndHookMethod(TextView.class, ""setText"", CharSequence.class, new XC_MethodHook() { @Override protected void afterHookedMethod(MethodHookParam param) throws Throwable { super.afterHookedMethod(param); TextView v = (TextView) param.thisObject; if (ViewBlocker.getInstance().isBlocked(mBlockList[0], v)) { ViewBlocker.getInstance().block(v); } } }); XposedHelpers.findAndHookMethod(View.class, ""setLayoutParams"", ViewGroup.LayoutParams.class, new XC_MethodHook() { @Override protected void beforeHookedMethod(MethodHookParam param) throws Throwable { ViewGroup.LayoutParams layoutParams = (ViewGroup.LayoutParams) param.args[0]; if (layoutParams != null) { if (layoutParams.height == 0 && layoutParams.width == 0) { return; } if (ViewBlocker.getInstance().isBlocked(mBlockList[0], param.thisObject)) { ViewBlocker.getInstance().block(param.thisObject); } } } }); final boolean fsuperMode = superMode; final XC_MethodHook viewHooker = new XC_MethodHook() { @Override protected void afterHookedMethod(MethodHookParam param) throws Throwable { super.afterHookedMethod(param); final View v = (View) param.thisObject; v.getViewTreeObserver().addOnGlobalLayoutListener(new ViewTreeObserver.OnGlobalLayoutListener() { @Override public void onGlobalLayout() { if (fsuperMode) { if (ViewBlocker.getInstance().isBlocked(mBlockList[0], v)) { v.getViewTreeObserver().removeGlobalOnLayoutListener(this); ViewBlocker.getInstance().block(v); } } else { v.getViewTreeObserver().removeGlobalOnLayoutListener(this); if (ViewBlocker.getInstance().isBlocked(mBlockList[0], v)) { ViewBlocker.getInstance().block(v); } } } }); } }; XposedBridge.hookAllConstructors(View.class, viewHooker); XposedBridge.hookAllConstructors(ViewGroup.class, viewHooker); log(""净眼:hook -->addView""); //Dialog blocking XposedHelpers.findAndHookMethod(""android.view.WindowManagerImpl"", loadPackageParam.classLoader, ""addView"", View.class, ViewGroup.LayoutParams.class, new XC_MethodHook() { @Override protected void afterHookedMethod(MethodHookParam param) throws Throwable { super.afterHookedMethod(param); View view = (View) param.args[0]; WindowManager windowManager = (WindowManager) param.thisObject; if (view == null) { return; } if (DialogBlocker.getInstance().isBlocked(mBlockList[0], view)) { windowManager.removeViewImmediate(view); } } }); } }",fix: settings page crashes; update: update Gradle Version to adapt Android 12,https://github.com/w568w/fuckView/commit/f58d66432c9d1ccf7ffe4dbef68b39eb0f381086,,,app/src/main/java/ml/qingsu/fuckview/hook/Hook.java,3,java,False,2022-03-06T04:25:53Z "private void logout() { if (subject != null) { subject.logout(); subject = null; } }","private void logout() { if (subject != null) { securityService.logout(channelId); subject = null; } }","GEODE-9676: Limit array and string sizes for unauthenticated Radish connections (#6994) - This applies the same fix as introduced by CVE-2021-32675 for Redis. When security is enabled, unuauthenticated requests limit the size of arrays and bulk strings to 10 and 16384 respectively. Once connections are authenticated, the size restriction is not applied. - When security is not enabled, this restriction does not apply. - Re-enable the relevant Redis TCL test.",https://github.com/apache/geode/commit/4398bec6eac70ee7bfa3b296655a8326543fc3b7,,,geode-for-redis/src/main/java/org/apache/geode/redis/internal/netty/ExecutionHandlerContext.java,3,java,False,2021-10-19T15:29:54Z "public void processUpdate(ConnectionUpdate update) { // The ""update_type"" is used to limit the amount of data sent via the JNI if((update.update_type & ConnectionUpdate.UPDATE_STATS) != 0) { sent_bytes = update.sent_bytes; rcvd_bytes = update.rcvd_bytes; sent_pkts = update.sent_pkts; rcvd_pkts = update.rcvd_pkts; blocked_pkts = update.blocked_pkts; status = (update.status & 0x00FF); netd_block_missed = (update.status & 0x0800) != 0; is_blocked = (update.status & 0x0400) != 0; blacklisted_ip = (update.status & 0x0100) != 0; blacklisted_host = (update.status & 0x0200) != 0; last_seen = update.last_seen; tcp_flags = update.tcp_flags; // NOTE: only for root capture // see MitmReceiver.handlePayload if((status == ConnectionDescriptor.CONN_STATUS_CLOSED) && (decryption_error != null)) status = ConnectionDescriptor.CONN_STATUS_CLIENT_ERROR; // with mitm we account the TLS payload length instead if(!mitm_decrypt) payload_length = update.payload_length; } if((update.update_type & ConnectionUpdate.UPDATE_INFO) != 0) { info = update.info; url = update.url; l7proto = update.l7proto; encrypted_l7 = ((update.info_flags & ConnectionUpdate.UPDATE_INFO_FLAG_ENCRYPTED_L7) != 0); } if((update.update_type & ConnectionUpdate.UPDATE_PAYLOAD) != 0) { // Payload for decryptable connections should be received via the MitmReceiver assert(isNotDecryptable()); // Some pending updates with payload may still be received after low memory has been // triggered and payload disabled if(!CaptureService.isLowMemory()) { payload_chunks = update.payload_chunks; payload_truncated = update.payload_truncated; } } }","public void processUpdate(ConnectionUpdate update) { // The ""update_type"" is used to limit the amount of data sent via the JNI if((update.update_type & ConnectionUpdate.UPDATE_STATS) != 0) { sent_bytes = update.sent_bytes; rcvd_bytes = update.rcvd_bytes; sent_pkts = update.sent_pkts; rcvd_pkts = update.rcvd_pkts; blocked_pkts = update.blocked_pkts; status = (update.status & 0x00FF); netd_block_missed = (update.status & 0x0800) != 0; is_blocked = (update.status & 0x0400) != 0; blacklisted_ip = (update.status & 0x0100) != 0; blacklisted_host = (update.status & 0x0200) != 0; last_seen = update.last_seen; tcp_flags = update.tcp_flags; // NOTE: only for root capture // see MitmReceiver.handlePayload if((status == ConnectionDescriptor.CONN_STATUS_CLOSED) && (decryption_error != null)) status = ConnectionDescriptor.CONN_STATUS_CLIENT_ERROR; // with mitm we account the TLS payload length instead if(!mitm_decrypt) payload_length = update.payload_length; } if((update.update_type & ConnectionUpdate.UPDATE_INFO) != 0) { info = update.info; url = update.url; l7proto = update.l7proto; encrypted_l7 = ((update.info_flags & ConnectionUpdate.UPDATE_INFO_FLAG_ENCRYPTED_L7) != 0); } if((update.update_type & ConnectionUpdate.UPDATE_PAYLOAD) != 0) { // Payload for decryptable connections should be received via the MitmReceiver assert(isNotDecryptable()); // Some pending updates with payload may still be received after low memory has been // triggered and payload disabled if(!CaptureService.isLowMemory()) { synchronized (this) { payload_chunks.addAll(update.payload_chunks); payload_truncated = update.payload_truncated; } } } }","Fix possible JNI local reference overflow and races Dumping connections payload requires creating (local) references, which are limited to 512. This commit greatly reduces their lifetime, from several seconds to less than 1 second, reducing the likehood of an overflow. Moreover it adds missing synchronization to the connection payload.",https://github.com/emanuele-f/PCAPdroid/commit/2fddba63017b1b5db11c0b0aa067ba467bb3da2b,,,app/src/main/java/com/emanuelef/remote_capture/model/ConnectionDescriptor.java,3,java,False,2022-08-13T14:10:38Z "public static boolean deleteFile(String filePath) { boolean flag = false; File file = new File(filePath); if (file.isFile() && file.exists()) { boolean deleteResult = file.delete(); log.info(""deleteFile deleteResult:{}"", deleteResult); flag = true; } return flag; }","public static boolean deleteFile(String filePath) { boolean flag = false; File file = new File(CleanPathUtil.cleanString(filePath)); if (file.isFile() && file.exists()) { boolean deleteResult = file.delete(); log.info(""deleteFile deleteResult:{}"", deleteResult); flag = true; } return flag; }",fix security scan,https://github.com/WeBankBlockchain/WeBASE-Front/commit/7c14dcde8af19c79357bfb337e00c948fe62d673,,,src/main/java/com/webank/webase/front/util/CommonUtils.java,3,java,False,2021-04-01T09:17:57Z "default boolean nullCheck() { return mc.player != null || mc.world != null; }","default boolean nullCheck() { return mc.player != null && mc.world != null; }",[FIX] OnTick Crash (#201),https://github.com/momentumdevelopment/cosmos/commit/929855a21d988756a5164b80ab171333d08a3bf7,,,src/main/java/cope/cosmos/util/Wrapper.java,3,java,False,2022-02-14T16:16:56Z "static Counters updateMetrics(final UUID uuid) throws Exception { LOGGER.debug(""Executing metrics update for component "" + uuid); final var counters = new Counters(); try (final var qm = new QueryManager()) { final PersistenceManager pm = qm.getPersistenceManager(); final Component component = qm.getObjectByUuid(Component.class, uuid, List.of(Component.FetchGroup.METRICS_UPDATE.name())); if (component == null) { throw new NoSuchElementException(""Component "" + uuid + "" does not exist""); } for (final Vulnerability vulnerability : getVulnerabilities(pm, component)) { counters.vulnerabilities++; switch (vulnerability.getSeverity()) { case CRITICAL -> counters.critical++; case HIGH -> counters.high++; case MEDIUM -> counters.medium++; case LOW, INFO -> counters.low++; case UNASSIGNED -> counters.unassigned++; } } counters.findingsTotal = toIntExact(counters.vulnerabilities); counters.findingsAudited = toIntExact(getTotalAuditedFindings(pm, component)); counters.findingsUnaudited = counters.findingsTotal - counters.findingsAudited; counters.suppressions = toIntExact(getTotalSuppressedFindings(pm, component)); counters.inheritedRiskScore = Metrics.inheritedRiskScore(counters.critical, counters.high, counters.medium, counters.low, counters.unassigned); for (final PolicyViolationProjection violation : getPolicyViolations(pm, component)) { counters.policyViolationsTotal++; switch (PolicyViolation.Type.valueOf(violation.type().name())) { case LICENSE -> counters.policyViolationsLicenseTotal++; case OPERATIONAL -> counters.policyViolationsOperationalTotal++; case SECURITY -> counters.policyViolationsSecurityTotal++; } switch (Policy.ViolationState.valueOf(violation.violationState().name())) { case FAIL -> counters.policyViolationsFail++; case WARN -> counters.policyViolationsWarn++; case INFO -> counters.policyViolationsInfo++; } } if (counters.policyViolationsLicenseTotal > 0) { counters.policyViolationsLicenseAudited = toIntExact(getTotalAuditedPolicyViolations(pm, component, PolicyViolation.Type.LICENSE)); counters.policyViolationsLicenseUnaudited = counters.policyViolationsLicenseTotal - counters.policyViolationsLicenseAudited; } if (counters.policyViolationsOperationalTotal > 0) { counters.policyViolationsOperationalAudited = toIntExact(getTotalAuditedPolicyViolations(pm, component, PolicyViolation.Type.OPERATIONAL)); counters.policyViolationsOperationalUnaudited = counters.policyViolationsOperationalTotal - counters.policyViolationsOperationalAudited; } if (counters.policyViolationsSecurityTotal > 0) { counters.policyViolationsSecurityAudited = toIntExact(getTotalAuditedPolicyViolations(pm, component, PolicyViolation.Type.SECURITY)); counters.policyViolationsSecurityUnaudited = counters.policyViolationsSecurityTotal - counters.policyViolationsSecurityAudited; } counters.policyViolationsAudited = counters.policyViolationsLicenseAudited + counters.policyViolationsOperationalAudited + counters.policyViolationsSecurityAudited; counters.policyViolationsUnaudited = counters.policyViolationsTotal - counters.policyViolationsAudited; qm.runInTransaction(() -> { final DependencyMetrics latestMetrics = qm.getMostRecentDependencyMetrics(component); if (!counters.hasChanged(latestMetrics)) { LOGGER.debug(""Metrics of component "" + uuid + "" did not change""); latestMetrics.setLastOccurrence(counters.measuredAt); } else { LOGGER.debug(""Metrics of component "" + uuid + "" changed""); final DependencyMetrics metrics = counters.createComponentMetrics(component); pm.makePersistent(metrics); } }); if (component.getLastInheritedRiskScore() == null || component.getLastInheritedRiskScore() != counters.inheritedRiskScore) { LOGGER.debug(""Updating inherited risk score of component "" + uuid); qm.runInTransaction(() -> component.setLastInheritedRiskScore(counters.inheritedRiskScore)); } } LOGGER.debug(""Completed metrics update for component "" + uuid + "" in "" + DurationFormatUtils.formatDuration(new Date().getTime() - counters.measuredAt.getTime(), ""mm:ss:SS"")); return counters; }","static Counters updateMetrics(final UUID uuid) throws Exception { LOGGER.debug(""Executing metrics update for component "" + uuid); final var counters = new Counters(); try (final var qm = new QueryManager()) { final PersistenceManager pm = qm.getPersistenceManager(); final Component component = qm.getObjectByUuid(Component.class, uuid, List.of(Component.FetchGroup.METRICS_UPDATE.name())); if (component == null) { throw new NoSuchElementException(""Component "" + uuid + "" does not exist""); } final Set aliasesSeen = new HashSet<>(); for (final Vulnerability vulnerability : getVulnerabilities(pm, component)) { // Quick pre-flight check whether we already encountered an alias of this particular vulnerability final String alias = vulnerability.getSource() + ""|"" + vulnerability.getVulnId(); if (aliasesSeen.contains(alias)) { LOGGER.debug(""An alias of "" + alias + "" has already been processed; Skipping""); continue; } // Fetch all aliases for this vulnerability and consider all of them as ""seen"" qm.getVulnerabilityAliases(vulnerability).stream() .map(VulnerabilityAlias::getAllBySource) .flatMap(vulnIdsBySource -> vulnIdsBySource.entrySet().stream()) .map(vulnIdBySource -> vulnIdBySource.getKey() + ""|"" + vulnIdBySource.getValue()) .forEach(aliasesSeen::add); counters.vulnerabilities++; switch (vulnerability.getSeverity()) { case CRITICAL -> counters.critical++; case HIGH -> counters.high++; case MEDIUM -> counters.medium++; case LOW, INFO -> counters.low++; case UNASSIGNED -> counters.unassigned++; } } counters.findingsTotal = toIntExact(counters.vulnerabilities); counters.findingsAudited = toIntExact(getTotalAuditedFindings(pm, component)); counters.findingsUnaudited = counters.findingsTotal - counters.findingsAudited; counters.suppressions = toIntExact(getTotalSuppressedFindings(pm, component)); counters.inheritedRiskScore = Metrics.inheritedRiskScore(counters.critical, counters.high, counters.medium, counters.low, counters.unassigned); for (final PolicyViolationProjection violation : getPolicyViolations(pm, component)) { counters.policyViolationsTotal++; switch (PolicyViolation.Type.valueOf(violation.type().name())) { case LICENSE -> counters.policyViolationsLicenseTotal++; case OPERATIONAL -> counters.policyViolationsOperationalTotal++; case SECURITY -> counters.policyViolationsSecurityTotal++; } switch (Policy.ViolationState.valueOf(violation.violationState().name())) { case FAIL -> counters.policyViolationsFail++; case WARN -> counters.policyViolationsWarn++; case INFO -> counters.policyViolationsInfo++; } } if (counters.policyViolationsLicenseTotal > 0) { counters.policyViolationsLicenseAudited = toIntExact(getTotalAuditedPolicyViolations(pm, component, PolicyViolation.Type.LICENSE)); counters.policyViolationsLicenseUnaudited = counters.policyViolationsLicenseTotal - counters.policyViolationsLicenseAudited; } if (counters.policyViolationsOperationalTotal > 0) { counters.policyViolationsOperationalAudited = toIntExact(getTotalAuditedPolicyViolations(pm, component, PolicyViolation.Type.OPERATIONAL)); counters.policyViolationsOperationalUnaudited = counters.policyViolationsOperationalTotal - counters.policyViolationsOperationalAudited; } if (counters.policyViolationsSecurityTotal > 0) { counters.policyViolationsSecurityAudited = toIntExact(getTotalAuditedPolicyViolations(pm, component, PolicyViolation.Type.SECURITY)); counters.policyViolationsSecurityUnaudited = counters.policyViolationsSecurityTotal - counters.policyViolationsSecurityAudited; } counters.policyViolationsAudited = counters.policyViolationsLicenseAudited + counters.policyViolationsOperationalAudited + counters.policyViolationsSecurityAudited; counters.policyViolationsUnaudited = counters.policyViolationsTotal - counters.policyViolationsAudited; qm.runInTransaction(() -> { final DependencyMetrics latestMetrics = qm.getMostRecentDependencyMetrics(component); if (!counters.hasChanged(latestMetrics)) { LOGGER.debug(""Metrics of component "" + uuid + "" did not change""); latestMetrics.setLastOccurrence(counters.measuredAt); } else { LOGGER.debug(""Metrics of component "" + uuid + "" changed""); final DependencyMetrics metrics = counters.createComponentMetrics(component); pm.makePersistent(metrics); } }); if (component.getLastInheritedRiskScore() == null || component.getLastInheritedRiskScore() != counters.inheritedRiskScore) { LOGGER.debug(""Updating inherited risk score of component "" + uuid); qm.runInTransaction(() -> component.setLastInheritedRiskScore(counters.inheritedRiskScore)); } } LOGGER.debug(""Completed metrics update for component "" + uuid + "" in "" + DurationFormatUtils.formatDuration(new Date().getTime() - counters.measuredAt.getTime(), ""mm:ss:SS"")); return counters; }","Fix vulnerability aliases not being considered during metrics calculation This functionality got lost when resolving merge conflicts in #1912. It has now been adapted to the new metrics calculation method. Signed-off-by: nscuro ",https://github.com/DependencyTrack/dependency-track/commit/9cbb9af9afaebe55937c83eaa08cb6cf216e31aa,,,src/main/java/org/dependencytrack/tasks/metrics/ComponentMetricsUpdateTask.java,3,java,False,2022-10-05T11:09:57Z "@Override protected void doFilter(HttpServletRequest request, HttpServletResponse response, FilterChain chain) throws IOException, ServletException { WebApplication webApp = (WebApplication) request.getServletContext(); AuthenticationManager authManager = webApp.getManager(AuthenticationManager.class); if (request.getUserPrincipal() != null) { chain.doFilter(request, response); } else if (authManager.needsAuthentication(request)) { chain.doFilter(request, response); } else { chain.doFilter(request, response); } }","@Override protected void doFilter(HttpServletRequest request, HttpServletResponse response, FilterChain chain) throws IOException, ServletException { WebApplication webApp = (WebApplication) request.getServletContext(); AuthenticationManager authManager = webApp.getManager(AuthenticationManager.class); if (request.getUserPrincipal() != null) { chain.doFilter(request, response); } else if (authManager.needsAuthentication(request)) { boolean authenticated = authManager.authenticate(request, response); if (authenticated) { chain.doFilter(request, response); } else { authManager.requestAuthentication(request, response); } } else { chain.doFilter(request, response); } }",Fixes issue #2067 - Fix code smells,https://github.com/piranhacloud/piranha/commit/e2a779fa7428f939f445e1c7495f8f88a6b2d9d3,,,extension/security-file/src/main/java/cloud/piranha/extension/security/file/FileAuthenticationFilter.java,3,java,False,2021-11-07T14:33:13Z "@Override public String call() { Subject subject = Subjects.ROOT; Restriction restriction = Restrictions.none(); BulkRequest request = new BulkRequest(); request.setUrlPrefix(""ssh://admin""); request.setTarget(new ArrayList<>(Arrays.asList(target.split("","")))); request.setActivity(activity.toUpperCase()); request.setCancelOnFailure(cancelOnFailure); request.setClearOnSuccess(clearOnSuccess); request.setClearOnFailure(clearOnFailure); request.setDelayClear(delayClear); request.setExpandDirectories(Depth.valueOf(expand.toUpperCase())); request.setId(UUID.randomUUID().toString()); request.setPrestore(activity.equalsIgnoreCase(""STAGE"") || prestore); if (arguments != null) { request.setArguments(Splitter.on(',') .trimResults() .omitEmptyStrings() .withKeyValueSeparator(':') .split(arguments)); } BulkRequestMessage message = new BulkRequestMessage(request, restriction); message.setSubject(subject); service.messageArrived(message); return ""Sent message to service to submit "" + request.getUrlPrefix() + ""/"" + request.getId(); }","@Override public String call() throws Exception { Sorter sorter = new Sorter(SortOrder.valueOf(sort.toUpperCase())); String activities = activityFactory.getProviders().entrySet() .stream() .map(BulkServiceCommands::formatActivity) .sorted(sorter) .collect(joining(""\n"")); if (activities == null) { return ""There are no mapped activities!""; } return String.format(FORMAT_ACTIVITY, ""NAME"", ""CLASS"", ""TYPE"", ""PERMITS"") + ""\n"" + activities; }","dcache-bulk: deprecate/no longer support 'delay' option on request clear Motivation: The version 1 spec for bulk requests https://docs.google.com/document/d/14sdrRmJts5JYBFKSvedKCxT1tcrWtWchR-PJhxdunT8/edit#heading=h.lassqf5agt8x included a ""delay"" option/attribute by which the user can specify a time lapse before automatic clearing of the request on either success or failure occurs. This is currently implemented in memory using a scheduled executor, and is thus vulnerable to provoking an OOM in case of many such requests with long delays being queued up. Also, there is currently no provision on restart for requeuing delayed clears which have not yet taken place (an oversight on my part). However, I would now argue that this option is not necessary (and the actual user requested clear is probably not either, but we can leave those be for the moment), and it overburdens the system with additional consistency issues. It may very well be that some cleanup on the database may be desirable (for performance reasons), but this should be a server-side policy. Modification: Eliminate support for the `delay` option. Result: Unnecessary code eliminated. Documentation updated (will also update the above specification when this patch is committed). Target: master Patch: https://rb.dcache.org/r/13767/ Requires-notes: yes Requires-book: yes (provided by patch) Acked-by: Tigran",https://github.com/dCache/dcache/commit/e83f39ab5d974454fbaaaf6a454e3e8c01fa0776,,,modules/dcache-bulk/src/main/java/org/dcache/services/bulk/BulkServiceCommands.java,3,java,False,2022-11-11T14:15:16Z "private static String processStringType(final TypeDefinition stringType, final ObjectNode property, final String nodeName) { StringTypeDefinition type = (StringTypeDefinition) stringType; Optional lengthConstraints = ((StringTypeDefinition) stringType).getLengthConstraint(); while (lengthConstraints.isEmpty() && type.getBaseType() != null) { type = type.getBaseType(); lengthConstraints = type.getLengthConstraint(); } if (lengthConstraints.isPresent()) { final Range range = lengthConstraints.get().getAllowedRanges().span(); putIfNonNull(property, MIN_LENGTH_KEY, range.lowerEndpoint()); putIfNonNull(property, MAX_LENGTH_KEY, range.upperEndpoint()); } if (type.getPatternConstraints().iterator().hasNext()) { final PatternConstraint pattern = type.getPatternConstraints().iterator().next(); String regex = pattern.getJavaPatternString(); regex = regex.substring(1, regex.length() - 1); String defaultValue = """"; try { final Generex generex = new Generex(regex); defaultValue = generex.random(); } catch (IllegalArgumentException ex) { LOG.warn(""Cannot create example string for type: {} with regex: {}."", stringType.getQName(), regex); } setDefaultValue(property, defaultValue); } else { setDefaultValue(property, ""Some "" + nodeName); } return STRING_TYPE; }","private static String processStringType(final TypeDefinition stringType, final ObjectNode property, final String nodeName) { StringTypeDefinition type = (StringTypeDefinition) stringType; Optional lengthConstraints = ((StringTypeDefinition) stringType).getLengthConstraint(); while (lengthConstraints.isEmpty() && type.getBaseType() != null) { type = type.getBaseType(); lengthConstraints = type.getLengthConstraint(); } if (lengthConstraints.isPresent()) { final Range range = lengthConstraints.get().getAllowedRanges().span(); putIfNonNull(property, MIN_LENGTH_KEY, range.lowerEndpoint()); putIfNonNull(property, MAX_LENGTH_KEY, range.upperEndpoint()); } if (type.getPatternConstraints().iterator().hasNext()) { final PatternConstraint pattern = type.getPatternConstraints().iterator().next(); String regex = pattern.getJavaPatternString(); regex = regex.substring(1, regex.length() - 1); // Escape special characters to prevent issues inside Generex. regex = AUTOMATON_SPECIAL_CHARACTERS.matcher(regex).replaceAll(""\\\\$0""); String defaultValue = """"; try { final Generex generex = new Generex(regex); defaultValue = generex.random(); } catch (IllegalArgumentException ex) { LOG.warn(""Cannot create example string for type: {} with regex: {}."", stringType.getQName(), regex); } setDefaultValue(property, defaultValue); } else { setDefaultValue(property, ""Some "" + nodeName); } return STRING_TYPE; }","Fix Stackoverflow in sal-rest-docgen Add escaping of chars which underlying library consider as special characters (and we do not). JIRA: NETCONF-713 Change-Id: Ife63c31cd9c4912a74db10562b9f927623bc4695 Signed-off-by: Samuel Schneider ",https://github.com/opendaylight/netconf/commit/7c022319559356346bf5b0e9b1d9f18a9b87b928,,,restconf/sal-rest-docgen/src/main/java/org/opendaylight/netconf/sal/rest/doc/impl/DefinitionGenerator.java,3,java,False,2022-03-03T09:14:22Z "public static String typeName(int id) { if (id == 36) { return ""AsyncTask""; } for (int i = 0; i < cachedCustomComponents.size(); i++) { HashMap component = cachedCustomComponents.get(i); Object componentId = component.get(""id""); if (componentId instanceof String) { try { int idInt = Integer.parseInt((String) componentId); if (idInt == id) { Object componentTypeName = component.get(""typeName""); if (componentTypeName instanceof String) { return (String) componentTypeName; } else { SketchwareUtil.toastError(""Invalid type name entry at Custom Component #"" + (i + 1), Toast.LENGTH_LONG); break; } } } catch (NumberFormatException e) { SketchwareUtil.toastError(""Invalid ID entry at Custom Component #"" + (i + 1), Toast.LENGTH_LONG); } } else { SketchwareUtil.toastError(""Invalid ID entry at Custom Component #"" + (i + 1), Toast.LENGTH_LONG); } } return """"; }","public static String typeName(int id) { if (id == 36) { return ""AsyncTask""; } for (int i = 0; i < cachedCustomComponents.size(); i++) { HashMap component = cachedCustomComponents.get(i); if (component != null) { Object componentId = component.get(""id""); if (componentId instanceof String) { try { int idInt = Integer.parseInt((String) componentId); if (idInt == id) { Object componentTypeName = component.get(""typeName""); if (componentTypeName instanceof String) { return (String) componentTypeName; } else { SketchwareUtil.toastError(""Invalid type name entry at Custom Component #"" + (i + 1), Toast.LENGTH_LONG); break; } } } catch (NumberFormatException e) { SketchwareUtil.toastError(""Invalid ID entry at Custom Component #"" + (i + 1), Toast.LENGTH_LONG); } } else { SketchwareUtil.toastError(""Invalid ID entry at Custom Component #"" + (i + 1), Toast.LENGTH_LONG); } } else { SketchwareUtil.toastError(""Invalid (null) Custom Component at position "" + i); } } return """"; }","fix: Handle null Custom Components and don't crash on an NPE Related to commit 2db1b76b7ac5631b52e6ce15e801aa1a4063d856: ""fix: Handle null Custom Events and don't crash on an NPE"".",https://github.com/Sketchware-Pro/Sketchware-Pro/commit/833da0d273674c5a0a0ee138c209b3ba28886690,,,app/src/main/java/mod/hilal/saif/components/ComponentsHandler.java,3,java,False,2022-09-25T09:44:49Z "function drawChart() { currentSettings.width = $('#resizer').width() - 20; currentSettings.height = $('#resizer').height() - 20; // TODO: a better way using .redraw() ? if (currentChart !== null) { currentChart.destroy(); } var columnNames = []; $('select[name=""chartXAxis""] option').each(function () { columnNames.push($(this).text()); }); try { currentChart = PMA_queryChart(chart_data, columnNames, currentSettings); if (currentChart != null) { $('#saveChart').attr('href', currentChart.toImageString()); } } catch (err) { PMA_ajaxShowMessage(err.message, false); } }","function drawChart() { currentSettings.width = $('#resizer').width() - 20; currentSettings.height = $('#resizer').height() - 20; // TODO: a better way using .redraw() ? if (currentChart !== null) { currentChart.destroy(); } var columnNames = []; $('select[name=""chartXAxis""] option').each(function () { columnNames.push(escapeHtml($(this).text())); }); try { currentChart = PMA_queryChart(chart_data, columnNames, currentSettings); if (currentChart != null) { $('#saveChart').attr('href', currentChart.toImageString()); } } catch (err) { PMA_ajaxShowMessage(err.message, false); } }","Fixed rendering of chart of columns with HTML inside Signed-off-by: Michal Čihař ",https://github.com/phpmyadmin/phpmyadmin/commit/4d21b5c077db50c2a54b7f569d20f463cc2651f5,CVE-2016-5733,['CWE-79'],js/tbl_chart.js,3,js,False,2016-06-22T11:07:32Z "private void processPhonebookAccess() { if (mDevice.getBondState() != BluetoothDevice.BOND_BONDED) return; ParcelUuid[] uuids = mDevice.getUuids(); if (BluetoothUuid.containsAnyUuid(uuids, PbapServerProfile.PBAB_CLIENT_UUIDS)) { // The pairing dialog now warns of phone-book access for paired devices. // No separate prompt is displayed after pairing. if (mDevice.getPhonebookAccessPermission() == BluetoothDevice.ACCESS_UNKNOWN) { if (mDevice.getBluetoothClass().getDeviceClass() == BluetoothClass.Device.AUDIO_VIDEO_HANDSFREE || mDevice.getBluetoothClass().getDeviceClass() == BluetoothClass.Device.AUDIO_VIDEO_WEARABLE_HEADSET) { EventLog.writeEvent(0x534e4554, ""138529441"", -1, """"); } mDevice.setPhonebookAccessPermission(BluetoothDevice.ACCESS_REJECTED); } } }","private void processPhonebookAccess() { if (mDevice.getBondState() != BluetoothDevice.BOND_BONDED) return; ParcelUuid[] uuids = mDevice.getUuids(); if (BluetoothUuid.containsAnyUuid(uuids, PbapServerProfile.PBAB_CLIENT_UUIDS)) { // The pairing dialog now warns of phone-book access for paired devices. // No separate prompt is displayed after pairing. final BluetoothClass bluetoothClass = mDevice.getBluetoothClass(); if (mDevice.getPhonebookAccessPermission() == BluetoothDevice.ACCESS_UNKNOWN) { if (bluetoothClass != null && (bluetoothClass.getDeviceClass() == BluetoothClass.Device.AUDIO_VIDEO_HANDSFREE || bluetoothClass.getDeviceClass() == BluetoothClass.Device.AUDIO_VIDEO_WEARABLE_HEADSET)) { EventLog.writeEvent(0x534e4554, ""138529441"", -1, """"); } mDevice.setPhonebookAccessPermission(BluetoothDevice.ACCESS_REJECTED); } } }","Fix java crash This CL added a null check when getting bluetooth class to avoid java crash. Bug: 180019938 Test: make -j42 RunSettingsLibRoboTests Change-Id: Id1d7c7f021edde3bbbd4f715eeabd7c468b2a794",https://github.com/omnirom/android_frameworks_base/commit/e0881dfb3e01962fe4958376851de02a488e79b4,,,packages/SettingsLib/src/com/android/settingslib/bluetooth/CachedBluetoothDevice.java,3,java,False,2021-02-23T07:11:57Z "private PropertiesFile getCachedDataFile(String resolverName, ModuleRevisionId mRevId) { // we append "".${resolverName} onto the end of the regular ivydata location return new PropertiesFile(new File(getRepositoryCacheRoot(), IvyPatternHelper.substitute(getDataFilePattern(), mRevId) + ""."" + resolverName), ""ivy cached data file for "" + mRevId); }","private PropertiesFile getCachedDataFile(String resolverName, ModuleRevisionId mRevId) { // we append "".${resolverName} onto the end of the regular ivydata location File file = new File(getRepositoryCacheRoot(), IvyPatternHelper.substitute(getDataFilePattern(), mRevId) + ""."" + resolverName); assertInsideCache(file); return new PropertiesFile(file, ""ivy cached data file for "" + mRevId); }",CVE-2022-37865 ZipPacking allows overwriting arbitrary files,https://github.com/apache/ant-ivy/commit/3f374602d4d63691398951b9af692960d019f4d9,,,src/java/org/apache/ivy/core/cache/DefaultRepositoryCacheManager.java,3,java,False,2022-08-21T16:54:43Z "int psf_binheader_readf (SF_PRIVATE *psf, char const *format, ...) { va_list argptr ; sf_count_t *countptr, countdata ; unsigned char *ucptr, sixteen_bytes [16] ; unsigned int *intptr, intdata ; unsigned short *shortptr ; char *charptr ; float *floatptr ; double *doubleptr ; char c ; int byte_count = 0, count ; if (! format) return psf_ftell (psf) ; va_start (argptr, format) ; while ((c = *format++)) { switch (c) { case 'e' : /* All conversions are now from LE to host. */ psf->rwf_endian = SF_ENDIAN_LITTLE ; break ; case 'E' : /* All conversions are now from BE to host. */ psf->rwf_endian = SF_ENDIAN_BIG ; break ; case 'm' : /* 4 byte marker value eg 'RIFF' */ intptr = va_arg (argptr, unsigned int*) ; ucptr = (unsigned char*) intptr ; byte_count += header_read (psf, ucptr, sizeof (int)) ; *intptr = GET_MARKER (ucptr) ; break ; case 'h' : intptr = va_arg (argptr, unsigned int*) ; ucptr = (unsigned char*) intptr ; byte_count += header_read (psf, sixteen_bytes, sizeof (sixteen_bytes)) ; { int k ; intdata = 0 ; for (k = 0 ; k < 16 ; k++) intdata ^= sixteen_bytes [k] << k ; } *intptr = intdata ; break ; case '1' : charptr = va_arg (argptr, char*) ; *charptr = 0 ; byte_count += header_read (psf, charptr, sizeof (char)) ; break ; case '2' : /* 2 byte value with the current endian-ness */ shortptr = va_arg (argptr, unsigned short*) ; *shortptr = 0 ; ucptr = (unsigned char*) shortptr ; byte_count += header_read (psf, ucptr, sizeof (short)) ; if (psf->rwf_endian == SF_ENDIAN_BIG) *shortptr = GET_BE_SHORT (ucptr) ; else *shortptr = GET_LE_SHORT (ucptr) ; break ; case '3' : /* 3 byte value with the current endian-ness */ intptr = va_arg (argptr, unsigned int*) ; *intptr = 0 ; byte_count += header_read (psf, sixteen_bytes, 3) ; if (psf->rwf_endian == SF_ENDIAN_BIG) *intptr = GET_BE_3BYTE (sixteen_bytes) ; else *intptr = GET_LE_3BYTE (sixteen_bytes) ; break ; case '4' : /* 4 byte value with the current endian-ness */ intptr = va_arg (argptr, unsigned int*) ; *intptr = 0 ; ucptr = (unsigned char*) intptr ; byte_count += header_read (psf, ucptr, sizeof (int)) ; if (psf->rwf_endian == SF_ENDIAN_BIG) *intptr = psf_get_be32 (ucptr, 0) ; else *intptr = psf_get_le32 (ucptr, 0) ; break ; case '8' : /* 8 byte value with the current endian-ness */ countptr = va_arg (argptr, sf_count_t *) ; *countptr = 0 ; byte_count += header_read (psf, sixteen_bytes, 8) ; if (psf->rwf_endian == SF_ENDIAN_BIG) countdata = psf_get_be64 (sixteen_bytes, 0) ; else countdata = psf_get_le64 (sixteen_bytes, 0) ; *countptr = countdata ; break ; case 'f' : /* Float conversion */ floatptr = va_arg (argptr, float *) ; *floatptr = 0.0 ; byte_count += header_read (psf, floatptr, sizeof (float)) ; if (psf->rwf_endian == SF_ENDIAN_BIG) *floatptr = float32_be_read ((unsigned char*) floatptr) ; else *floatptr = float32_le_read ((unsigned char*) floatptr) ; break ; case 'd' : /* double conversion */ doubleptr = va_arg (argptr, double *) ; *doubleptr = 0.0 ; byte_count += header_read (psf, doubleptr, sizeof (double)) ; if (psf->rwf_endian == SF_ENDIAN_BIG) *doubleptr = double64_be_read ((unsigned char*) doubleptr) ; else *doubleptr = double64_le_read ((unsigned char*) doubleptr) ; break ; case 's' : psf_log_printf (psf, ""Format conversion 's' not implemented yet.\n"") ; /* strptr = va_arg (argptr, char *) ; size = strlen (strptr) + 1 ; size += (size & 1) ; longdata = H2LE_32 (size) ; get_int (psf, longdata) ; memcpy (&(psf->header [psf->headindex]), strptr, size) ; psf->headindex += size ; */ break ; case 'b' : /* Raw bytes */ charptr = va_arg (argptr, char*) ; count = va_arg (argptr, size_t) ; if (count > 0) byte_count += header_read (psf, charptr, count) ; break ; case 'G' : charptr = va_arg (argptr, char*) ; count = va_arg (argptr, size_t) ; if (count > 0) byte_count += header_gets (psf, charptr, count) ; break ; case 'z' : psf_log_printf (psf, ""Format conversion 'z' not implemented yet.\n"") ; /* size = va_arg (argptr, size_t) ; while (size) { psf->header [psf->headindex] = 0 ; psf->headindex ++ ; size -- ; } ; */ break ; case 'p' : /* Get the seek position first. */ count = va_arg (argptr, size_t) ; header_seek (psf, count, SEEK_SET) ; byte_count = count ; break ; case 'j' : /* Get the seek position first. */ count = va_arg (argptr, size_t) ; if (count) { header_seek (psf, count, SEEK_CUR) ; byte_count += count ; } ; break ; default : psf_log_printf (psf, ""*** Invalid format specifier `%c'\n"", c) ; psf->error = SFE_INTERNAL ; break ; } ; } ; va_end (argptr) ; return byte_count ; }","int psf_binheader_readf (SF_PRIVATE *psf, char const *format, ...) { va_list argptr ; sf_count_t *countptr, countdata ; unsigned char *ucptr, sixteen_bytes [16] ; unsigned int *intptr, intdata ; unsigned short *shortptr ; char *charptr ; float *floatptr ; double *doubleptr ; char c ; int byte_count = 0, count = 0 ; if (! format) return psf_ftell (psf) ; va_start (argptr, format) ; while ((c = *format++)) { if (psf->header.indx + 16 >= psf->header.len && psf_bump_header_allocation (psf, 16)) return count ; switch (c) { case 'e' : /* All conversions are now from LE to host. */ psf->rwf_endian = SF_ENDIAN_LITTLE ; break ; case 'E' : /* All conversions are now from BE to host. */ psf->rwf_endian = SF_ENDIAN_BIG ; break ; case 'm' : /* 4 byte marker value eg 'RIFF' */ intptr = va_arg (argptr, unsigned int*) ; *intptr = 0 ; ucptr = (unsigned char*) intptr ; byte_count += header_read (psf, ucptr, sizeof (int)) ; *intptr = GET_MARKER (ucptr) ; break ; case 'h' : intptr = va_arg (argptr, unsigned int*) ; *intptr = 0 ; ucptr = (unsigned char*) intptr ; byte_count += header_read (psf, sixteen_bytes, sizeof (sixteen_bytes)) ; { int k ; intdata = 0 ; for (k = 0 ; k < 16 ; k++) intdata ^= sixteen_bytes [k] << k ; } *intptr = intdata ; break ; case '1' : charptr = va_arg (argptr, char*) ; *charptr = 0 ; byte_count += header_read (psf, charptr, sizeof (char)) ; break ; case '2' : /* 2 byte value with the current endian-ness */ shortptr = va_arg (argptr, unsigned short*) ; *shortptr = 0 ; ucptr = (unsigned char*) shortptr ; byte_count += header_read (psf, ucptr, sizeof (short)) ; if (psf->rwf_endian == SF_ENDIAN_BIG) *shortptr = GET_BE_SHORT (ucptr) ; else *shortptr = GET_LE_SHORT (ucptr) ; break ; case '3' : /* 3 byte value with the current endian-ness */ intptr = va_arg (argptr, unsigned int*) ; *intptr = 0 ; byte_count += header_read (psf, sixteen_bytes, 3) ; if (psf->rwf_endian == SF_ENDIAN_BIG) *intptr = GET_BE_3BYTE (sixteen_bytes) ; else *intptr = GET_LE_3BYTE (sixteen_bytes) ; break ; case '4' : /* 4 byte value with the current endian-ness */ intptr = va_arg (argptr, unsigned int*) ; *intptr = 0 ; ucptr = (unsigned char*) intptr ; byte_count += header_read (psf, ucptr, sizeof (int)) ; if (psf->rwf_endian == SF_ENDIAN_BIG) *intptr = psf_get_be32 (ucptr, 0) ; else *intptr = psf_get_le32 (ucptr, 0) ; break ; case '8' : /* 8 byte value with the current endian-ness */ countptr = va_arg (argptr, sf_count_t *) ; *countptr = 0 ; byte_count += header_read (psf, sixteen_bytes, 8) ; if (psf->rwf_endian == SF_ENDIAN_BIG) countdata = psf_get_be64 (sixteen_bytes, 0) ; else countdata = psf_get_le64 (sixteen_bytes, 0) ; *countptr = countdata ; break ; case 'f' : /* Float conversion */ floatptr = va_arg (argptr, float *) ; *floatptr = 0.0 ; byte_count += header_read (psf, floatptr, sizeof (float)) ; if (psf->rwf_endian == SF_ENDIAN_BIG) *floatptr = float32_be_read ((unsigned char*) floatptr) ; else *floatptr = float32_le_read ((unsigned char*) floatptr) ; break ; case 'd' : /* double conversion */ doubleptr = va_arg (argptr, double *) ; *doubleptr = 0.0 ; byte_count += header_read (psf, doubleptr, sizeof (double)) ; if (psf->rwf_endian == SF_ENDIAN_BIG) *doubleptr = double64_be_read ((unsigned char*) doubleptr) ; else *doubleptr = double64_le_read ((unsigned char*) doubleptr) ; break ; case 's' : psf_log_printf (psf, ""Format conversion 's' not implemented yet.\n"") ; /* strptr = va_arg (argptr, char *) ; size = strlen (strptr) + 1 ; size += (size & 1) ; longdata = H2LE_32 (size) ; get_int (psf, longdata) ; memcpy (&(psf->header.ptr [psf->header.indx]), strptr, size) ; psf->header.indx += size ; */ break ; case 'b' : /* Raw bytes */ charptr = va_arg (argptr, char*) ; count = va_arg (argptr, size_t) ; memset (charptr, 0, count) ; byte_count += header_read (psf, charptr, count) ; break ; case 'G' : charptr = va_arg (argptr, char*) ; count = va_arg (argptr, size_t) ; memset (charptr, 0, count) ; if (psf->header.indx + count >= psf->header.len && psf_bump_header_allocation (psf, count)) return 0 ; byte_count += header_gets (psf, charptr, count) ; break ; case 'z' : psf_log_printf (psf, ""Format conversion 'z' not implemented yet.\n"") ; /* size = va_arg (argptr, size_t) ; while (size) { psf->header.ptr [psf->header.indx] = 0 ; psf->header.indx ++ ; size -- ; } ; */ break ; case 'p' : /* Seek to position from start. */ count = va_arg (argptr, size_t) ; header_seek (psf, count, SEEK_SET) ; byte_count = count ; break ; case 'j' : /* Seek to position from current position. */ count = va_arg (argptr, size_t) ; header_seek (psf, count, SEEK_CUR) ; byte_count += count ; break ; default : psf_log_printf (psf, ""*** Invalid format specifier `%c'\n"", c) ; psf->error = SFE_INTERNAL ; break ; } ; } ; va_end (argptr) ; return byte_count ; }","src/ : Move to a variable length header buffer Previously, the `psf->header` buffer was a fixed length specified by `SF_HEADER_LEN` which was set to `12292`. This was problematic for two reasons; this value was un-necessarily large for the majority of files and too small for some others. Now the size of the header buffer starts at 256 bytes and grows as necessary up to a maximum of 100k.",https://github.com/erikd/libsndfile/commit/708e996c87c5fae77b104ccfeb8f6db784c32074,,,src/common.c,3,c,False,2016-11-27T05:12:46Z "static int ext4_split_extent(handle_t *handle, struct inode *inode, struct ext4_ext_path *path, struct ext4_map_blocks *map, int split_flag, int flags) { ext4_lblk_t ee_block; struct ext4_extent *ex; unsigned int ee_len, depth; int err = 0; int uninitialized; int split_flag1, flags1; depth = ext_depth(inode); ex = path[depth].p_ext; ee_block = le32_to_cpu(ex->ee_block); ee_len = ext4_ext_get_actual_len(ex); uninitialized = ext4_ext_is_uninitialized(ex); if (map->m_lblk + map->m_len < ee_block + ee_len) { split_flag1 = split_flag & EXT4_EXT_MAY_ZEROOUT ? EXT4_EXT_MAY_ZEROOUT : 0; flags1 = flags | EXT4_GET_BLOCKS_PRE_IO; if (uninitialized) split_flag1 |= EXT4_EXT_MARK_UNINIT1 | EXT4_EXT_MARK_UNINIT2; err = ext4_split_extent_at(handle, inode, path, map->m_lblk + map->m_len, split_flag1, flags1); if (err) goto out; } ext4_ext_drop_refs(path); path = ext4_ext_find_extent(inode, map->m_lblk, path); if (IS_ERR(path)) return PTR_ERR(path); if (map->m_lblk >= ee_block) { split_flag1 = split_flag & EXT4_EXT_MAY_ZEROOUT ? EXT4_EXT_MAY_ZEROOUT : 0; if (uninitialized) split_flag1 |= EXT4_EXT_MARK_UNINIT1; if (split_flag & EXT4_EXT_MARK_UNINIT2) split_flag1 |= EXT4_EXT_MARK_UNINIT2; err = ext4_split_extent_at(handle, inode, path, map->m_lblk, split_flag1, flags); if (err) goto out; } ext4_ext_show_leaf(inode, path); out: return err ? err : map->m_len; }","static int ext4_split_extent(handle_t *handle, struct inode *inode, struct ext4_ext_path *path, struct ext4_map_blocks *map, int split_flag, int flags) { ext4_lblk_t ee_block; struct ext4_extent *ex; unsigned int ee_len, depth; int err = 0; int uninitialized; int split_flag1, flags1; depth = ext_depth(inode); ex = path[depth].p_ext; ee_block = le32_to_cpu(ex->ee_block); ee_len = ext4_ext_get_actual_len(ex); uninitialized = ext4_ext_is_uninitialized(ex); if (map->m_lblk + map->m_len < ee_block + ee_len) { split_flag1 = split_flag & EXT4_EXT_MAY_ZEROOUT; flags1 = flags | EXT4_GET_BLOCKS_PRE_IO; if (uninitialized) split_flag1 |= EXT4_EXT_MARK_UNINIT1 | EXT4_EXT_MARK_UNINIT2; if (split_flag & EXT4_EXT_DATA_VALID2) split_flag1 |= EXT4_EXT_DATA_VALID1; err = ext4_split_extent_at(handle, inode, path, map->m_lblk + map->m_len, split_flag1, flags1); if (err) goto out; } ext4_ext_drop_refs(path); path = ext4_ext_find_extent(inode, map->m_lblk, path); if (IS_ERR(path)) return PTR_ERR(path); if (map->m_lblk >= ee_block) { split_flag1 = split_flag & (EXT4_EXT_MAY_ZEROOUT | EXT4_EXT_DATA_VALID2); if (uninitialized) split_flag1 |= EXT4_EXT_MARK_UNINIT1; if (split_flag & EXT4_EXT_MARK_UNINIT2) split_flag1 |= EXT4_EXT_MARK_UNINIT2; err = ext4_split_extent_at(handle, inode, path, map->m_lblk, split_flag1, flags); if (err) goto out; } ext4_ext_show_leaf(inode, path); out: return err ? err : map->m_len; }","ext4: race-condition protection for ext4_convert_unwritten_extents_endio We assumed that at the time we call ext4_convert_unwritten_extents_endio() extent in question is fully inside [map.m_lblk, map->m_len] because it was already split during submission. But this may not be true due to a race between writeback vs fallocate. If extent in question is larger than requested we will split it again. Special precautions should being done if zeroout required because [map.m_lblk, map->m_len] already contains valid data. Signed-off-by: Dmitry Monakhov Signed-off-by: ""Theodore Ts'o"" Cc: stable@vger.kernel.org",https://github.com/torvalds/linux/commit/dee1f973ca341c266229faa5a1a5bb268bed3531,,,fs/ext4/extents.c,3,c,False,2012-10-10T05:04:58Z "@Override public boolean onTouchEvent(MotionEvent event) { try { if (event.getActionMasked() == MotionEvent.ACTION_DOWN) { Editable edit = getText(); int off = Helper.getOffset(this, edit, event); ClipImageSpan[] spans = edit.getSpans(off, off, ClipImageSpan.class); if (spans.length == 1) edit.removeSpan(spans[0]); } } catch (Throwable ex) { Log.w(ex); } return super.onTouchEvent(event); }","@Override public boolean onTouchEvent(MotionEvent event) { try { if (event.getActionMasked() == MotionEvent.ACTION_DOWN) { Editable edit = getText(); int off = Helper.getOffset(this, edit, event); ClipImageSpan[] spans = edit.getSpans(off, off, ClipImageSpan.class); if (spans.length == 1) post(new Runnable() { @Override public void run() { try { edit.removeSpan(spans[0]); } catch (Throwable ex) { Log.e(ex); } } }); } } catch (Throwable ex) { Log.w(ex); } return super.onTouchEvent(event); }",Prevent crash,https://github.com/M66B/FairEmail/commit/10f8a980439033b225653acfcc521f3448070f2e,,,app/src/main/java/eu/faircode/email/EditTextMultiAutoComplete.java,3,java,False,2022-02-23T16:07:24Z "private void createNewUser(@UserIdInt int userId, int userSerialNumber) { synchronized (mUserCreationAndRemovalLock) { // Before PHASE_BOOT_COMPLETED, don't actually create the synthetic password yet, but // rather automatically delay it to later. We do this because protecting the synthetic // password requires the Weaver HAL if the device supports it, and some devices don't // make Weaver available until fairly late in the boot process. This logic ensures a // consistent flow across all devices, regardless of their Weaver implementation. if (!mBootComplete) { Slogf.i(TAG, ""Delaying locksettings state creation for user %d until boot complete"", userId); mEarlyCreatedUsers.put(userId, userSerialNumber); mEarlyRemovedUsers.delete(userId); return; } removeStateForReusedUserIdIfNecessary(userId, userSerialNumber); synchronized (mSpManager) { initializeSyntheticPasswordLocked(userId); } } }","private void createNewUser(@UserIdInt int userId, int userSerialNumber) { synchronized (mUserCreationAndRemovalLock) { // During early boot, don't actually create the synthetic password yet, but rather // automatically delay it to later. We do this because protecting the synthetic // password requires the Weaver HAL if the device supports it, and some devices don't // make Weaver available until fairly late in the boot process. This logic ensures a // consistent flow across all devices, regardless of their Weaver implementation. if (!mThirdPartyAppsStarted) { Slogf.i(TAG, ""Delaying locksettings state creation for user %d until third-party "" + ""apps are started"", userId); mEarlyCreatedUsers.put(userId, userSerialNumber); mEarlyRemovedUsers.delete(userId); return; } removeStateForReusedUserIdIfNecessary(userId, userSerialNumber); synchronized (mSpManager) { initializeSyntheticPasswordLocked(userId); } } }","Allow migration to SP to be rolled back by filesystem checkpoint On upgrade from Android 13 or earlier, LockSettingsService is creating a synthetic password (SP) for all users that didn't have one before, and re-encrypting the user's CE key with the SP. Currently this happens at PHASE_BOOT_COMPLETED, since Weaver is not yet guaranteed to be available at the previous phase, PHASE_THIRD_PARTY_APPS_CAN_START. An issue with using PHASE_BOOT_COMPLETED is that during an upgrade, PHASE_BOOT_COMPLETED happens after the userdata filesystem checkpoint has already been committed. Therefore, if a problem occurs with the migration to SP, the changes won't be rolled back and the device will be left in a broken state, recoverable only via a factory reset. Important migrations like this should happen before the checkpoint is committed. Therefore, replace the use of PHASE_BOOT_COMPLETED with a direct call into LockSettingsService in an appropriate place, similar to the existing LockSettingsService.systemReady() call. I also considered creating a PHASE_THIRD_PARTY_APPS_STARTED boot phase. However, any new boot phase would become part of the services API (services/api/current.txt), which is more than I'd like to do here. Test: Made an intentionally broken build with LockSettingsService.onThirdPartyAppsStarted() changed to throw a RuntimeException at the end, crashing system_server. Tested an OTA from tm-qpr2-release to that build, on a device that didn't have a lockscreen credential set on user 0 (so that user 0 was migrated to SP-based credentials just before the crash). The OTA failed as expected and successfully rolled back to the original build, with user 0's data still accessible (this was not possible before this change). Bug: 232452368 Change-Id: I77d30f9be57de7b7c4818680732331549ecb73c8",https://github.com/aosp-mirror/platform_frameworks_base/commit/ff116c879e64c19130726320b5a6c94ea37824f4,,,services/core/java/com/android/server/locksettings/LockSettingsService.java,3,java,False,2022-11-09T05:48:02Z "private void addSecurityFilter(RepositoryContext context, final ExpressionBuilder builder) { final User user = context.service(User.class); if (user.isAdministrator() || user.hasPermission(Permission.requireAll(Permission.OPERATION_BROWSE, Permission.ALL))) { return; } // no need to perform security filtering when we are asking the metadata repository // TODO store the resourceUri/Id on the Commit objects to allow filtering by external authorization systems if (context.info().id().equals(""resources"")) { return; } final Set accessibleResources = context.optionalService(AuthorizationService.class) .orElse(AuthorizationService.DEFAULT) .getAccessibleResources(context, user); final Set exactResourceIds = Sets.newHashSet(); final Set wildResourceIds = Sets.newHashSet(); final Multimap branchesByResourceId = HashMultimap.create(); accessibleResources.stream() .forEach(resource -> { if (resource.endsWith(""*"")) { if (resource.endsWith(""/*"")) { // wild only match wildResourceIds.add(resource.replace(""/*"", """")); } else { // append to both exact and wild match String resourceToAdd = resource.replace(""*"", """"); wildResourceIds.add(resourceToAdd); exactResourceIds.add(resourceToAdd); } } else if (resource.contains(Branch.SEPARATOR)) { branchesByResourceId.put(resource.substring(0, resource.indexOf(Branch.SEPARATOR)), resource.substring(resource.indexOf(Branch.SEPARATOR) + 1, resource.length())); } else { exactResourceIds.add(resource); } }); Set resourceIdsToSearchFor = ImmutableSet.builder() .addAll(exactResourceIds) .addAll(wildResourceIds) .addAll(branchesByResourceId.keySet()) .build(); ExpressionBuilder branchFilter = Expressions.bool(); ResourceRequests.prepareSearch() .filterByIds(resourceIdsToSearchFor) .setLimit(resourceIdsToSearchFor.size()) .setFields(ResourceDocument.Fields.ID, ResourceDocument.Fields.BRANCH_PATH, ResourceDocument.Fields.RESOURCE_TYPE) .buildAsync() .getRequest() .execute(context) .stream() .filter(TerminologyResource.class::isInstance) .map(TerminologyResource.class::cast) .forEach(res -> { // if present as prefix query, append the branch regex filter if (wildResourceIds.contains(res.getId())) { final String branchPattern = String.format(""%s/[a-zA-Z0-9.~_\\-]{1,%d}"", res.getBranchPath(), DEFAULT_MAXIMUM_BRANCH_NAME_LENGTH); branchFilter.should(regexp(BRANCH, branchPattern)); } // if present as exact query, append exact match if (exactResourceIds.contains(res.getId())) { branchFilter.should(exactMatch(BRANCH, res.getBranchPath())); } // if present as exact branch match, then append a terms filter final Collection exactBranchesToMatch = branchesByResourceId.removeAll(res.getId()); if (!exactBranchesToMatch.isEmpty()) { branchFilter.should(Commit.Expressions.branches(exactBranchesToMatch.stream().map(res::getRelativeBranchPath).collect(Collectors.toSet()))); } }); // if the built expression does not have any clauses Expression authorizationClause = branchFilter.build(); if (authorizationClause instanceof MatchAll) { // then match no documents instead throw new NoResultException(); } builder.filter(authorizationClause); }","private void addSecurityFilter(RepositoryContext context, final ExpressionBuilder builder) { final User user = context.service(User.class); if (user.isAdministrator() || user.hasPermission(Permission.requireAll(Permission.OPERATION_BROWSE, Permission.ALL))) { return; } final Set accessibleResources = context.optionalService(AuthorizationService.class) .orElse(AuthorizationService.DEFAULT) .getAccessibleResources(context, user); // perform security filter when accessing the resources repository using dedicated resource filtering via detail filtering if (context.info().id().equals(""resources"")) { builder.filter(Commit.Expressions.affectedObjects(accessibleResources)); return; } final Set exactResourceIds = Sets.newHashSet(); final Set wildResourceIds = Sets.newHashSet(); final Multimap branchesByResourceId = HashMultimap.create(); accessibleResources.stream() .forEach(resource -> { if (resource.endsWith(""*"")) { if (resource.endsWith(""/*"")) { // wild only match wildResourceIds.add(resource.replace(""/*"", """")); } else { // append to both exact and wild match String resourceToAdd = resource.replace(""*"", """"); wildResourceIds.add(resourceToAdd); exactResourceIds.add(resourceToAdd); } } else if (resource.contains(Branch.SEPARATOR)) { branchesByResourceId.put(resource.substring(0, resource.indexOf(Branch.SEPARATOR)), resource.substring(resource.indexOf(Branch.SEPARATOR) + 1, resource.length())); } else { exactResourceIds.add(resource); } }); Set resourceIdsToSearchFor = ImmutableSet.builder() .addAll(exactResourceIds) .addAll(wildResourceIds) .addAll(branchesByResourceId.keySet()) .build(); ExpressionBuilder branchFilter = Expressions.bool(); ResourceRequests.prepareSearch() .filterByIds(resourceIdsToSearchFor) .setLimit(resourceIdsToSearchFor.size()) .setFields(ResourceDocument.Fields.ID, ResourceDocument.Fields.BRANCH_PATH, ResourceDocument.Fields.RESOURCE_TYPE) .buildAsync() .getRequest() .execute(context) .stream() .filter(TerminologyResource.class::isInstance) .map(TerminologyResource.class::cast) .forEach(res -> { // if present as prefix query, append the branch regex filter if (wildResourceIds.contains(res.getId())) { final String branchPattern = String.format(""%s/[a-zA-Z0-9.~_\\-]{1,%d}"", res.getBranchPath(), DEFAULT_MAXIMUM_BRANCH_NAME_LENGTH); branchFilter.should(regexp(BRANCH, branchPattern)); } // if present as exact query, append exact match if (exactResourceIds.contains(res.getId())) { branchFilter.should(exactMatch(BRANCH, res.getBranchPath())); } // if present as exact branch match, then append a terms filter final Collection exactBranchesToMatch = branchesByResourceId.removeAll(res.getId()); if (!exactBranchesToMatch.isEmpty()) { branchFilter.should(Commit.Expressions.branches(exactBranchesToMatch.stream().map(res::getRelativeBranchPath).collect(Collectors.toSet()))); } }); // if the built expression does not have any clauses Expression authorizationClause = branchFilter.build(); if (authorizationClause instanceof MatchAll) { // then match no documents instead throw new NoResultException(); } builder.filter(authorizationClause); }","fix(core): ensure that resource commits get authorized properly... ...based on the available external authorization service information",https://github.com/b2ihealthcare/snow-owl/commit/aca4daa9d96fe20172fd5fcb52270a2e10d51859,,,core/com.b2international.snowowl.core/src/com/b2international/snowowl/core/commit/CommitInfoSearchRequest.java,3,java,False,2022-11-17T17:00:30Z "public void clearParameters() throws SQLException { checkOpen(); conn.getDatabase().clear_bindings(pointer); if (batch != null) for (int i = batchPos; i < batchPos + paramCount; i++) batch[i] = null; }","public void clearParameters() throws SQLException { checkOpen(); pointer.safeRunConsume(DB::clear_bindings); if (batch != null) for (int i = batchPos; i < batchPos + paramCount; i++) batch[i] = null; }",Wrap Statement Pointers to prevent use after free race,https://github.com/xerial/sqlite-jdbc/commit/e1d282cb2887ef427c7ad93d4fe7dd05a6c11473,,,src/main/java/org/sqlite/jdbc3/JDBC3PreparedStatement.java,3,java,False,2022-07-29T03:54:01Z "public JSObject getSavedNotificationAsJSObject(String key) { SharedPreferences storage = getStorage(NOTIFICATION_STORE_ID); String notificationString = storage.getString(key, null); if (notificationString == null) { return null; } JSObject jsNotification; try { jsNotification = new JSObject(notificationString); } catch (JSONException ex) { return null; } return jsNotification; }","public JSObject getSavedNotificationAsJSObject(String key) { SharedPreferences storage = getStorage(NOTIFICATION_STORE_ID); String notificationString; try { notificationString = storage.getString(key, null); } catch (ClassCastException ex) { return null; } if (notificationString == null) { return null; } JSObject jsNotification; try { jsNotification = new JSObject(notificationString); } catch (JSONException ex) { return null; } return jsNotification; }",fix(local-notifications): prevent crash on restoring old notifications (#1156),https://github.com/ionic-team/capacitor-plugins/commit/8c655843ebbee5ab02503d7a10dd8296aa56ab04,,,local-notifications/android/src/main/java/com/capacitorjs/plugins/localnotifications/NotificationStorage.java,3,java,False,2022-09-09T15:47:11Z "static void nlmclnt_unlock_callback(struct rpc_task *task, void *data) { struct nlm_rqst *req = data; u32 status = ntohl(req->a_res.status); if (RPC_ASSASSINATED(task)) goto die; if (task->tk_status < 0) { dprintk(""lockd: unlock failed (err = %d)\n"", -task->tk_status); goto retry_rebind; } if (status == NLM_LCK_DENIED_GRACE_PERIOD) { rpc_delay(task, NLMCLNT_GRACE_WAIT); goto retry_unlock; } if (status != NLM_LCK_GRANTED) printk(KERN_WARNING ""lockd: unexpected unlock status: %d\n"", status); die: return; retry_rebind: nlm_rebind_host(req->a_host); retry_unlock: rpc_restart_call(task); }","static void nlmclnt_unlock_callback(struct rpc_task *task, void *data) { struct nlm_rqst *req = data; u32 status = ntohl(req->a_res.status); if (RPC_ASSASSINATED(task)) goto die; if (task->tk_status < 0) { dprintk(""lockd: unlock failed (err = %d)\n"", -task->tk_status); switch (task->tk_status) { case -EACCES: case -EIO: goto die; default: goto retry_rebind; } } if (status == NLM_LCK_DENIED_GRACE_PERIOD) { rpc_delay(task, NLMCLNT_GRACE_WAIT); goto retry_unlock; } if (status != NLM_LCK_GRANTED) printk(KERN_WARNING ""lockd: unexpected unlock status: %d\n"", status); die: return; retry_rebind: nlm_rebind_host(req->a_host); retry_unlock: rpc_restart_call(task); }","NLM: Don't hang forever on NLM unlock requests If the NLM daemon is killed on the NFS server, we can currently end up hanging forever on an 'unlock' request, instead of aborting. Basically, if the rpcbind request fails, or the server keeps returning garbage, we really want to quit instead of retrying. Tested-by: Vasily Averin Signed-off-by: Trond Myklebust Cc: stable@kernel.org",https://github.com/torvalds/linux/commit/0b760113a3a155269a3fba93a409c640031dd68f,,,fs/lockd/clntproc.c,3,c,False,2011-05-31T19:15:34Z "public static synchronized void loadTranslationCache() { File f = new File(TRANSLATION_CACHE_ROOT, ""translations.json""); if (!f.exists()) { translationCaches = new HashMap<>(); return; } try { String json = FileUtils.readFileToString(f, ""UTF-8""); Gson gson = new Gson(); Type type = new TypeToken>>(){}.getType(); translationCaches = gson.fromJson(json, type); } catch (IOException e) { e.printStackTrace(); } }","public static synchronized void loadTranslationCache() { File f = new File(TRANSLATION_CACHE_ROOT, ""translations.json""); if (!f.exists()) { translationCaches = new HashMap<>(); return; } try { String json = FileUtils.readFileToString(f, ""UTF-8""); Gson gson = new Gson(); Type type = new TypeToken>>(){}.getType(); translationCaches = gson.fromJson(json, type); } catch (IOException e) { e.printStackTrace(); } finally { if (translationCaches == null) { translationCaches = new HashMap<>(); } } }","Fix 14 issues found in ticket backlog (#502) * Fix IndexOutOfBoundsException in QuestBookListPage Signed-off-by: kristofbolyai * Fix crash if OverlayConfig.GameUpdate.INSTANCE.messageMaxLength is 1 Signed-off-by: kristofbolyai * Fix crash related to deleting chat tabs and ChatGUI not updating Signed-off-by: kristofbolyai * Fix crash related to deleting chat tabs and ChatGUI not updating Signed-off-by: kristofbolyai * Fix translation cache becoming null Signed-off-by: kristofbolyai * Fix objective parsing if player is in party Signed-off-by: kristofbolyai * Fix guild objective not being removed upon completion Signed-off-by: kristofbolyai * Fix race condition in ServerEvents Signed-off-by: kristofbolyai * Fix race condition in ClientEvents Signed-off-by: kristofbolyai * Fix NPE in ServerEvents Signed-off-by: kristofbolyai * Fix AreaDPS value not being correct Signed-off-by: kristofbolyai * Fix NPE in fix :) Signed-off-by: kristofbolyai * Fix quest dialogue spoofing Signed-off-by: kristofbolyai * Fix Keyholder related crash Signed-off-by: kristofbolyai * Fix totem tracking Signed-off-by: kristofbolyai * Dialogue Page gets updated correctly Signed-off-by: kristofbolyai * Register ChatGUI correctly Signed-off-by: kristofbolyai * Use MC's GameSettings to check for isKeyDown Signed-off-by: kristofbolyai * Make multi line if have braces Signed-off-by: kristofbolyai ",https://github.com/Wynntils/Wynntils/commit/c8f6effe187ff68f17bcff809d2bc440ec07128d,,,src/main/java/com/wynntils/webapi/services/CachingTranslationService.java,3,java,False,2022-04-15T17:16:00Z "public static void start(final SubscriptionService ss) { final Config config = Config.get(); if (!config.isIastEnabled()) { log.debug(""IAST is disabled""); return; } log.debug(""IAST is starting""); final Reporter reporter = new Reporter(); final IastModule iastModule = new IastModuleImpl(config, reporter); InstrumentationBridge.registerIastModule(iastModule); registerRequestStartedCallback(ss); registerRequestEndedCallback(ss); }","public static void start(final SubscriptionService ss) { final Config config = Config.get(); if (!config.isIastEnabled()) { log.debug(""IAST is disabled""); return; } log.debug(""IAST is starting""); final Reporter reporter = new Reporter(); final OverheadController overheadController = new OverheadController(config, AgentTaskScheduler.INSTANCE); final IastModule iastModule = new IastModuleImpl(config, reporter, overheadController); InstrumentationBridge.registerIastModule(iastModule); registerRequestStartedCallback(ss, overheadController); registerRequestEndedCallback(ss, overheadController); }","[IAST] OverheadController to add caps on analyzed requests and reported vulnerabilities (#3694) The OverheadController ensures that the overhead does not go over a maximum limit. It will measure operations being executed in a request and it will deactivate detection (and therefore reduce the overhead to nearly 0) if a certain threshold is reached. First approach sets threshold to: - Only about 30% of the requests will be analysed - 2 concurrent request - 2 vulnerabilities per request - 2 vulnerabilities out of request Future versions will implement a more fine-tuned policy for different operation types. The current PR implements one of the simplest policies. Co-authored-by: Santiago Mola ",https://github.com/DataDog/dd-trace-java/commit/c81fa9bbd95258ecc9b485ff6a1c1bef0f3bd961,,,dd-java-agent/iast/src/main/java/com/datadog/iast/IastSystem.java,3,java,False,2022-09-23T07:09:28Z "build_version_comments(docinfo, out) { var me = this; docinfo.versions.forEach(function(version) { if(!version.data) return; var data = JSON.parse(version.data); // comment if(data.comment) { out.push(me.get_version_comment(version, data.comment, data.comment_type)); return; } // value changed in parent if(data.changed && data.changed.length) { var parts = []; data.changed.every(function(p) { if(p[0]==='docstatus') { if(p[2]==1) { out.push(me.get_version_comment(version, __('submitted this document'))); } else if (p[2]==2) { out.push(me.get_version_comment(version, __('cancelled this document'))); } } else { var df = frappe.meta.get_docfield(me.frm.doctype, p[0], me.frm.docname); if(df && !df.hidden) { var field_display_status = frappe.perm.get_field_display_status(df, null, me.frm.perm); if(field_display_status === 'Read' || field_display_status === 'Write') { parts.push(__('{0} from {1} to {2}', [ __(df.label), (frappe.ellipsis(frappe.utils.html2text(p[1]), 40) || '""""').bold(), (frappe.ellipsis(frappe.utils.html2text(p[2]), 40) || '""""').bold() ])); } } } return parts.length < 3; }); if(parts.length) { out.push(me.get_version_comment(version, __(""changed value of {0}"", [parts.join(', ').bold()]))); } } // value changed in table field if(data.row_changed && data.row_changed.length) { var parts = [], count = 0; data.row_changed.every(function(row) { row[3].every(function(p) { var df = me.frm.fields_dict[row[0]] && frappe.meta.get_docfield(me.frm.fields_dict[row[0]].grid.doctype, p[0], me.frm.docname); if(df && !df.hidden) { var field_display_status = frappe.perm.get_field_display_status(df, null, me.frm.perm); if(field_display_status === 'Read' || field_display_status === 'Write') { parts.push(__('{0} from {1} to {2} in row #{3}', [ frappe.meta.get_label(me.frm.fields_dict[row[0]].grid.doctype, p[0]), (frappe.ellipsis(p[1], 40) || '""""').bold(), (frappe.ellipsis(p[2], 40) || '""""').bold(), row[1] ])); } } return parts.length < 3; }); return parts.length < 3; }); if(parts.length) { out.push(me.get_version_comment(version, __(""changed values for {0}"", [parts.join(', ')]))); } } // rows added / removed // __('added'), __('removed') # for translation, don't remove ['added', 'removed'].forEach(function(key) { if(data[key] && data[key].length) { parts = (data[key] || []).map(function(p) { var df = frappe.meta.get_docfield(me.frm.doctype, p[0], me.frm.docname); if(df && !df.hidden) { var field_display_status = frappe.perm.get_field_display_status(df, null, me.frm.perm); if(field_display_status === 'Read' || field_display_status === 'Write') { return frappe.meta.get_label(me.frm.doctype, p[0]) } } }); parts = parts.filter(function(p) { return p; }); if(parts.length) { out.push(me.get_version_comment(version, __(""{0} rows for {1}"", [__(key), parts.join(', ')]))); } } }); }); }","build_version_comments(docinfo, out) { var me = this; docinfo.versions.forEach(function(version) { if(!version.data) return; var data = JSON.parse(version.data); // comment if(data.comment) { out.push(me.get_version_comment(version, data.comment, data.comment_type)); return; } // value changed in parent if(data.changed && data.changed.length) { var parts = []; data.changed.every(function(p) { if(p[0]==='docstatus') { if(p[2]==1) { out.push(me.get_version_comment(version, __('submitted this document'))); } else if (p[2]==2) { out.push(me.get_version_comment(version, __('cancelled this document'))); } } else { var df = frappe.meta.get_docfield(me.frm.doctype, p[0], me.frm.docname); if(df && !df.hidden) { var field_display_status = frappe.perm.get_field_display_status(df, null, me.frm.perm); if(field_display_status === 'Read' || field_display_status === 'Write') { parts.push(__('{0} from {1} to {2}', [ __(df.label), (frappe.ellipsis(frappe.utils.html2text(p[1]), 40) || '""""').bold(), (frappe.ellipsis(frappe.utils.html2text(p[2]), 40) || '""""').bold() ])); } } } return parts.length < 3; }); if(parts.length) { parts = parts.map(frappe.utils.escape_html); out.push(me.get_version_comment(version, __(""changed value of {0}"", [parts.join(', ').bold()]))); } } // value changed in table field if(data.row_changed && data.row_changed.length) { var parts = [], count = 0; data.row_changed.every(function(row) { row[3].every(function(p) { var df = me.frm.fields_dict[row[0]] && frappe.meta.get_docfield(me.frm.fields_dict[row[0]].grid.doctype, p[0], me.frm.docname); if(df && !df.hidden) { var field_display_status = frappe.perm.get_field_display_status(df, null, me.frm.perm); if(field_display_status === 'Read' || field_display_status === 'Write') { parts.push(__('{0} from {1} to {2} in row #{3}', [ frappe.meta.get_label(me.frm.fields_dict[row[0]].grid.doctype, p[0]), (frappe.ellipsis(p[1], 40) || '""""').bold(), (frappe.ellipsis(p[2], 40) || '""""').bold(), row[1] ])); } } return parts.length < 3; }); return parts.length < 3; }); if(parts.length) { out.push(me.get_version_comment(version, __(""changed values for {0}"", [parts.join(', ')]))); } } // rows added / removed // __('added'), __('removed') # for translation, don't remove ['added', 'removed'].forEach(function(key) { if(data[key] && data[key].length) { parts = (data[key] || []).map(function(p) { var df = frappe.meta.get_docfield(me.frm.doctype, p[0], me.frm.docname); if(df && !df.hidden) { var field_display_status = frappe.perm.get_field_display_status(df, null, me.frm.perm); if(field_display_status === 'Read' || field_display_status === 'Write') { return frappe.meta.get_label(me.frm.doctype, p[0]) } } }); parts = parts.filter(function(p) { return p; }); if(parts.length) { out.push(me.get_version_comment(version, __(""{0} rows for {1}"", [__(key), parts.join(', ')]))); } } }); }); }",fix: Escape html in timeline,https://github.com/frappe/frappe/commit/6aebe0f522e02186313ec6a8f6f265ec11122ce9,CVE-2019-15700,['CWE-79'],frappe/public/js/frappe/form/footer/timeline.js,3,js,False,2019-08-26T09:24:52Z "private RebootPreparationError armRebootEscrow(String packageName, boolean slotSwitch) { if (packageName == null) { Slog.w(TAG, ""Missing packageName when rebooting with lskf.""); return new RebootPreparationError( RESUME_ON_REBOOT_REBOOT_ERROR_INVALID_PACKAGE_NAME, ARM_REBOOT_ERROR_NONE); } if (!isLskfCaptured(packageName)) { return new RebootPreparationError(RESUME_ON_REBOOT_REBOOT_ERROR_LSKF_NOT_CAPTURED, ARM_REBOOT_ERROR_NONE); } if (!verifySlotForNextBoot(slotSwitch)) { return new RebootPreparationError(RESUME_ON_REBOOT_REBOOT_ERROR_SLOT_MISMATCH, ARM_REBOOT_ERROR_NONE); } final long origId = Binder.clearCallingIdentity(); int providerErrorCode; try { providerErrorCode = mInjector.getLockSettingsService().armRebootEscrow(); } finally { Binder.restoreCallingIdentity(origId); } if (providerErrorCode != ARM_REBOOT_ERROR_NONE) { Slog.w(TAG, ""Failure to escrow key for reboot, providerErrorCode: "" + providerErrorCode); return new RebootPreparationError( RESUME_ON_REBOOT_REBOOT_ERROR_PROVIDER_PREPARATION_FAILURE, providerErrorCode); } return new RebootPreparationError(RESUME_ON_REBOOT_REBOOT_ERROR_NONE, ARM_REBOOT_ERROR_NONE); }","private RebootPreparationError armRebootEscrow(String packageName, boolean slotSwitch) { if (packageName == null) { Slog.w(TAG, ""Missing packageName when rebooting with lskf.""); return new RebootPreparationError( RESUME_ON_REBOOT_REBOOT_ERROR_INVALID_PACKAGE_NAME, ARM_REBOOT_ERROR_NONE); } if (!isLskfCaptured(packageName)) { return new RebootPreparationError(RESUME_ON_REBOOT_REBOOT_ERROR_LSKF_NOT_CAPTURED, ARM_REBOOT_ERROR_NONE); } if (!verifySlotForNextBoot(slotSwitch)) { return new RebootPreparationError(RESUME_ON_REBOOT_REBOOT_ERROR_SLOT_MISMATCH, ARM_REBOOT_ERROR_NONE); } final long origId = Binder.clearCallingIdentity(); int providerErrorCode; try { LockSettingsInternal lockSettings = mInjector.getLockSettingsService(); if (lockSettings == null) { Slog.e(TAG, ""Failed to get lock settings service, skipping"" + "" armRebootEscrow""); return new RebootPreparationError( RESUME_ON_REBOOT_REBOOT_ERROR_PROVIDER_PREPARATION_FAILURE, ARM_REBOOT_ERROR_NO_PROVIDER); } providerErrorCode = lockSettings.armRebootEscrow(); } finally { Binder.restoreCallingIdentity(origId); } if (providerErrorCode != ARM_REBOOT_ERROR_NONE) { Slog.w(TAG, ""Failure to escrow key for reboot, providerErrorCode: "" + providerErrorCode); return new RebootPreparationError( RESUME_ON_REBOOT_REBOOT_ERROR_PROVIDER_PREPARATION_FAILURE, providerErrorCode); } return new RebootPreparationError(RESUME_ON_REBOOT_REBOOT_ERROR_NONE, ARM_REBOOT_ERROR_NONE); }","Check null for before using LockSettingsService If the locksettings service fails to start, the resume on reboot APIs will throw a nullptr exception in RecoverySystemService. Add some check to prevent crashing the system server. Bug: 184596745 Test: build Change-Id: I5b1781612ec8d855d94b2828b5b5cfee9a84aebe",https://github.com/omnirom/android_frameworks_base/commit/31b3cbf029ac96066e096328aff6902b29e5df62,,,services/core/java/com/android/server/recoverysystem/RecoverySystemService.java,3,java,False,2021-04-13T18:04:36Z "@Override public Base getBase() throws UnsupportedEncodingException, IOException, FHIRException { if (type == null || type.equals(""Resource"") || type.equals(""BackboneElement"") || type.equals(""Element"")) return null; if (element.hasElementProperty()) { return element; } ByteArrayOutputStream xml = new ByteArrayOutputStream(); try { new XmlParser(context.getWorker()).compose(element, xml, OutputStyle.PRETTY, null); } catch (Exception e) { throw new FHIRException(e.getMessage(), e); } if (context.getParser() == null) { System.out.println(""No version specific parser provided""); } if (context.getParser() == null) { throw new Error(""No type parser provided to renderer context""); } else { return context.getParser().parseType(xml.toString(), type); } }","@Override public Base getBase() throws UnsupportedEncodingException, IOException, FHIRException { if (type == null || type.equals(""Resource"") || type.equals(""BackboneElement"") || type.equals(""Element"")) return null; if (element.hasElementProperty()) { return element; } ByteArrayOutputStream xml = new ByteArrayOutputStream(); try { new XmlParser(context.getWorker()).compose(element, xml, OutputStyle.PRETTY, null); } catch (Exception e) { throw new FHIRException(e.getMessage(), e); } if (context.getParser() == null) { System.out.println(""No version specific parser provided""); } if (context.getParser() == null) { throw new Error(""No type parser provided to renderer context""); } else { try { return context.getParser().parseType(xml.toString(StandardCharsets.UTF_8), type); } catch (Exception e) { return new StringType(""Illegal syntax: ""+e.getMessage()); } } }",fix crash in IG publisher rendering illegal content,https://github.com/hapifhir/org.hl7.fhir.core/commit/108bfe715b04be15fb5775cdb7aa35d66169b951,,,org.hl7.fhir.r5/src/main/java/org/hl7/fhir/r5/renderers/utils/ElementWrappers.java,3,java,False,2021-09-29T06:18:20Z "public static boolean deepEquals(Object a, Object b, Map options) { Set visited = new HashSet<>(); Deque stack = new LinkedList<>(); Set ignoreCustomEquals = (Set) options.get(IGNORE_CUSTOM_EQUALS); final boolean allowStringsToMatchNumbers = convert2boolean(options.get(ALLOW_STRINGS_TO_MATCH_NUMBERS)); stack.addFirst(new ItemsToCompare(a, b)); while (!stack.isEmpty()) { ItemsToCompare itemsToCompare = stack.removeFirst(); visited.add(itemsToCompare); final Object key1 = itemsToCompare._key1; final Object key2 = itemsToCompare._key2; if (key1 == key2) { // Same instance is always equal to itself. continue; } if (key1 == null || key2 == null) { // If either one is null, they are not equal (both can't be null, due to above comparison). return false; } if (key1 instanceof Number && key2 instanceof Number && compareNumbers((Number)key1, (Number)key2)) { continue; } if (key1 instanceof Number || key2 instanceof Number) { // If one is a Number and the other one is not, then optionally compare them as strings, otherwise return false if (allowStringsToMatchNumbers) { try { if (key1 instanceof String && compareNumbers(convert2BigDecimal(key1), (Number)key2)) { continue; } else if (key2 instanceof String && compareNumbers((Number)key1, convert2BigDecimal(key2))) { continue; } } catch (Exception e) { } } return false; } Class key1Class = key1.getClass(); if (key1Class.isPrimitive() || prims.contains(key1Class) || key1 instanceof String || key1 instanceof Date || key1 instanceof Class) { if (!key1.equals(key2)) { return false; } continue; // Nothing further to push on the stack } if (key1 instanceof Collection) { // If Collections, they both must be Collection if (!(key2 instanceof Collection)) { return false; } } else if (key2 instanceof Collection) { // They both must be Collection return false; } if (key1 instanceof SortedSet) { if (!(key2 instanceof SortedSet)) { return false; } } else if (key2 instanceof SortedSet) { return false; } if (key1 instanceof SortedMap) { if (!(key2 instanceof SortedMap)) { return false; } } else if (key2 instanceof SortedMap) { return false; } if (key1 instanceof Map) { if (!(key2 instanceof Map)) { return false; } } else if (key2 instanceof Map) { return false; } if (!isContainerType(key1) && !isContainerType(key2) && !key1Class.equals(key2.getClass())) { // Must be same class return false; } // Handle all [] types. In order to be equal, the arrays must be the same // length, be of the same type, be in the same order, and all elements within // the array must be deeply equivalent. if (key1Class.isArray()) { if (!compareArrays(key1, key2, stack, visited)) { return false; } continue; } // Special handle SortedSets because they are fast to compare because their // elements must be in the same order to be equivalent Sets. if (key1 instanceof SortedSet) { if (!compareOrderedCollection((Collection) key1, (Collection) key2, stack, visited)) { return false; } continue; } // Handled unordered Sets. This is a slightly more expensive comparison because order cannot // be assumed, a temporary Map must be created, however the comparison still runs in O(N) time. if (key1 instanceof Set) { if (!compareUnorderedCollection((Collection) key1, (Collection) key2, stack, visited)) { return false; } continue; } // Check any Collection that is not a Set. In these cases, element order // matters, therefore this comparison is faster than using unordered comparison. if (key1 instanceof Collection) { if (!compareOrderedCollection((Collection) key1, (Collection) key2, stack, visited)) { return false; } continue; } // Compare two SortedMaps. This takes advantage of the fact that these // Maps can be compared in O(N) time due to their ordering. if (key1 instanceof SortedMap) { if (!compareSortedMap((SortedMap) key1, (SortedMap) key2, stack, visited)) { return false; } continue; } // Compare two Unordered Maps. This is a slightly more expensive comparison because // order cannot be assumed, therefore a temporary Map must be created, however the // comparison still runs in O(N) time. if (key1 instanceof Map) { if (!compareUnorderedMap((Map) key1, (Map) key2, stack, visited)) { return false; } continue; } // If there is a custom equals ... AND // the caller has not specified any classes to skip ... OR // the caller has specified come classes to ignore and this one is not in the list ... THEN // compare using the custom equals. if (hasCustomEquals(key1Class)) { if (ignoreCustomEquals == null || (ignoreCustomEquals.size() > 0 && !ignoreCustomEquals.contains(key1Class))) { if (!key1.equals(key2)) { return false; } continue; } } Collection fields = ReflectionUtils.getDeepDeclaredFields(key1Class); for (Field field : fields) { try { ItemsToCompare dk = new ItemsToCompare(field.get(key1), field.get(key2)); if (!visited.contains(dk)) { stack.addFirst(dk); } } catch (Exception ignored) { } } } return true; }","public static boolean deepEquals(Object a, Object b, Map options) { Set visited = new HashSet<>(); return deepEquals(a, b, options,visited); }","Fixing edge cases for unsorted data structures. When comparing within fastLookup also * use comparison options * pass visited elements in order to prevent StackOverflow",https://github.com/jdereg/java-util/commit/15d5670a38b6929c08ec098763878e5060ccc9f2,,,src/main/java/com/cedarsoftware/util/DeepEquals.java,3,java,False,2021-08-27T14:26:50Z "public Component replaceIn(Component component) { TextComponent.Builder builder = Component.text(); if (component instanceof KeybindComponent) { component = ((KeybindComponent) component).keybind(replaceIn(((KeybindComponent) component).keybind())); } if (component instanceof TextComponent) { String replaced = replaceIn(((TextComponent) component).content()); if (replaced.indexOf('§') != -1) { // replacement contain legacy code, parse to components and append them as children Component replacedComponent = LegacyComponentSerializer.legacySection().deserialize(replaced); component = ((TextComponent) component).content(""""); List children = new ArrayList<>(); children.add(replacedComponent); children.addAll(component.children()); component = component.children(children); } else { component = ((TextComponent) component).content(replaced); } } if (component instanceof TranslatableComponent) { component = ((TranslatableComponent) component).key(replaceIn(((TranslatableComponent) component).key())); component = ((TranslatableComponent) component).args(replaceIn(((TranslatableComponent) component).args())); } if (component.insertion() != null) { component = component.insertion(replaceIn(component.insertion())); } if (component.clickEvent() != null) { component = component.clickEvent(ClickEvent.clickEvent( component.clickEvent().action(), replaceIn(component.clickEvent().value()) )); } if (component.hoverEvent() != null) { if (component.hoverEvent().action() == HoverEvent.Action.SHOW_TEXT) { component = component.hoverEvent(HoverEvent.showText( replaceIn((Component) component.hoverEvent().value()) )); } else if (component.hoverEvent().action() == HoverEvent.Action.SHOW_ENTITY) { HoverEvent.ShowEntity showEntity = (HoverEvent.ShowEntity) component.hoverEvent().value(); component = component.hoverEvent(HoverEvent.showEntity( HoverEvent.ShowEntity.of( Key.key(replaceIn(showEntity.type().asString())), showEntity.id(), replaceIn(showEntity.name()) ) )); } else if (component.hoverEvent().action() == HoverEvent.Action.SHOW_ITEM) { HoverEvent.ShowItem showItem = (HoverEvent.ShowItem) component.hoverEvent().value(); component = component.hoverEvent(HoverEvent.showItem( HoverEvent.ShowItem.of( Key.key(replaceIn(showItem.item().asString())), showItem.count(), showItem.nbt() != null ? BinaryTagHolder.of(replaceIn(showItem.nbt().string())) : null ) )); } } component = component.children(replaceIn(component.children())); // Component replacements List replacedComponents = new ArrayList<>(); replacedComponents.add(component); for (Map.Entry replacement : componentReplacements().entrySet()) { List newReplacedComponents = new ArrayList<>(); for (Component replaceComponent : replacedComponents) { if (replaceComponent instanceof TextComponent) { TextComponent textComponent = (TextComponent) replaceComponent; String placeHolder = placeholderPrefix() + (ignorePlaceholderCase() ? replacement.getKey().toLowerCase(Locale.ROOT) : replacement.getKey()) + placeholderSuffix(); String text = ignorePlaceholderCase() ? textComponent.content().toLowerCase(Locale.ROOT) : textComponent.content(); int index = text.indexOf(placeHolder); if (index > -1) { while (true) { ComponentBuilder startBuilder; if (index > 0) { startBuilder = Component.text().mergeStyle(textComponent); ((TextComponent.Builder) startBuilder).content(textComponent.content().substring(0, index)); startBuilder.append(replacement.getValue()); } else if (replacement.getValue() instanceof BuildableComponent){ startBuilder = ((BuildableComponent) replacement.getValue()).toBuilder(); // Merge replacement style onto the component's to properly apply the replacement styles over the component ones startBuilder.style(Style.style().merge(textComponent.style()).merge(replacement.getValue().style()).build()); } else { startBuilder = Component.text().mergeStyle(textComponent); startBuilder.append(replacement.getValue()); } newReplacedComponents.add(startBuilder.build()); textComponent = textComponent.content(textComponent.content().substring(index + placeHolder.length())); text = ignorePlaceholderCase() ? textComponent.content().toLowerCase(Locale.ROOT) : textComponent.content(); if (text.isEmpty() || (index = text.indexOf(placeHolder)) < 0) { // No further placeholder in text, add rest to newReplacedComponents newReplacedComponents.add(textComponent); break; } } continue; } } // Nothing was replaced, just add it newReplacedComponents.add(replaceComponent); } replacedComponents = newReplacedComponents; } builder.append(replacedComponents); return builder.build(); }","public Component replaceIn(Component component) { TextComponent.Builder builder = Component.text(); if (component instanceof KeybindComponent) { component = ((KeybindComponent) component).keybind(replaceIn(((KeybindComponent) component).keybind())); } if (component instanceof TextComponent) { String replaced = replaceIn(((TextComponent) component).content()); int sectionIndex = replaced.indexOf('§'); if (sectionIndex > -1 && replaced.length() > sectionIndex + 1 && Util.getFormatFromLegacy(replaced.toLowerCase(Locale.ROOT).charAt(sectionIndex + 1)) != null) { // replacement contain legacy code, parse to components and append them as children Component replacedComponent = LegacyComponentSerializer.legacySection().deserialize(replaced); component = ((TextComponent) component).content(""""); List children = new ArrayList<>(); children.add(replacedComponent); children.addAll(component.children()); component = component.children(children); } else { component = ((TextComponent) component).content(replaced); } } if (component instanceof TranslatableComponent) { component = ((TranslatableComponent) component).key(replaceIn(((TranslatableComponent) component).key())); component = ((TranslatableComponent) component).args(replaceIn(((TranslatableComponent) component).args())); } if (component.insertion() != null) { component = component.insertion(replaceIn(component.insertion())); } if (component.clickEvent() != null) { component = component.clickEvent(ClickEvent.clickEvent( component.clickEvent().action(), replaceIn(component.clickEvent().value()) )); } if (component.hoverEvent() != null) { if (component.hoverEvent().action() == HoverEvent.Action.SHOW_TEXT) { component = component.hoverEvent(HoverEvent.showText( replaceIn((Component) component.hoverEvent().value()) )); } else if (component.hoverEvent().action() == HoverEvent.Action.SHOW_ENTITY) { HoverEvent.ShowEntity showEntity = (HoverEvent.ShowEntity) component.hoverEvent().value(); component = component.hoverEvent(HoverEvent.showEntity( HoverEvent.ShowEntity.of( Key.key(replaceIn(showEntity.type().asString())), showEntity.id(), replaceIn(showEntity.name()) ) )); } else if (component.hoverEvent().action() == HoverEvent.Action.SHOW_ITEM) { HoverEvent.ShowItem showItem = (HoverEvent.ShowItem) component.hoverEvent().value(); component = component.hoverEvent(HoverEvent.showItem( HoverEvent.ShowItem.of( Key.key(replaceIn(showItem.item().asString())), showItem.count(), showItem.nbt() != null ? BinaryTagHolder.of(replaceIn(showItem.nbt().string())) : null ) )); } } component = component.children(replaceIn(component.children())); // Component replacements List replacedComponents = new ArrayList<>(); replacedComponents.add(component); for (Map.Entry replacement : componentReplacements().entrySet()) { List newReplacedComponents = new ArrayList<>(); for (Component replaceComponent : replacedComponents) { if (replaceComponent instanceof TextComponent) { TextComponent textComponent = (TextComponent) replaceComponent; String placeHolder = placeholderPrefix() + (ignorePlaceholderCase() ? replacement.getKey().toLowerCase(Locale.ROOT) : replacement.getKey()) + placeholderSuffix(); String text = ignorePlaceholderCase() ? textComponent.content().toLowerCase(Locale.ROOT) : textComponent.content(); int index = text.indexOf(placeHolder); if (index > -1) { while (true) { ComponentBuilder startBuilder; if (index > 0) { startBuilder = Component.text().mergeStyle(textComponent); ((TextComponent.Builder) startBuilder).content(textComponent.content().substring(0, index)); startBuilder.append(replacement.getValue()); } else if (replacement.getValue() instanceof BuildableComponent){ startBuilder = ((BuildableComponent) replacement.getValue()).toBuilder(); // Merge replacement style onto the component's to properly apply the replacement styles over the component ones startBuilder.style(Style.style().merge(textComponent.style()).merge(replacement.getValue().style()).build()); } else { startBuilder = Component.text().mergeStyle(textComponent); startBuilder.append(replacement.getValue()); } newReplacedComponents.add(startBuilder.build()); textComponent = textComponent.content(textComponent.content().substring(index + placeHolder.length())); text = ignorePlaceholderCase() ? textComponent.content().toLowerCase(Locale.ROOT) : textComponent.content(); if (text.isEmpty() || (index = text.indexOf(placeHolder)) < 0) { // No further placeholder in text, add rest to newReplacedComponents newReplacedComponents.add(textComponent); break; } } continue; } } // Nothing was replaced, just add it newReplacedComponents.add(replaceComponent); } replacedComponents = newReplacedComponents; } builder.append(replacedComponents); return builder.build(); }","Fix issues with invalid color codes in replacer Apparently some people include invalid legacy color codes in their components... this would result in a stack overflow as it would append children with section signs again and again. Fix that by checking if it's actually a real formatting.",https://github.com/Phoenix616/MineDown/commit/3605778af2e22e9fc6ddf3cf6680801103f083f0,,,src/main/java/de/themoep/minedown/adventure/Replacer.java,3,java,False,2022-01-12T15:18:11Z "public void addFlush() { // There is no need to process all entries if there was already a flush before and no new messages // where added in the meantime. // // See https://github.com/netty/netty/issues/2577 Entry entry = unflushedEntry; if (entry != null) { if (flushedEntry == null) { // there is no flushedEntry yet, so start with the entry flushedEntry = entry; } do { flushed ++; if (!entry.promise.setUncancellable()) { // Was cancelled so make sure we free up memory and notify about the freed bytes int pending = entry.cancel(); decrementPendingOutboundBytes(pending, false, true); } entry = entry.next; } while (entry != null); // All flushed so reset unflushedEntry unflushedEntry = null; } }","public void addFlush() { // There is no need to process all entries if there was already a flush before and no new messages // where added in the meantime. // // See https://github.com/netty/netty/issues/2577 Entry entry = unflushedEntry; if (entry != null) { if (flushedEntry == null) { // there is no flushedEntry yet, so start with the entry flushedEntry = entry; } Entry prev = null; do { if (!entry.promise.setUncancellable()) { // Was cancelled so make sure we free up memory, unlink and notify about the freed bytes int pending = entry.cancel(); if (prev == null) { // It's the first entry, drop it flushedEntry = entry.next; } else { // Remove te entry from the linked list. prev.next = entry.next; } Entry next = entry.next; entry.recycle(); entry = next; decrementPendingOutboundBytes(pending, false, true); } else { flushed ++; prev = entry; entry = entry.next; } } while (entry != null); // All flushed so reset unflushedEntry unflushedEntry = null; } }","Fix handling of cancelled writes after changes introduced in e286b24e803e645449a10894a706be242388b092 (#12545) Motivation: e286b24e803e645449a10894a706be242388b092 changed how Promise.setUncancellabe() behaves but did not take this into acount in the ChannelOutboundBuffer. This could lead to the situation that the internal datastructure of ChannelOutboundBuffer became inconsistent. Modifications: - Only increment flushed count if the promise was not cancelled before and correctly unlink if it was. - Add unit tests Result: No more infinite loop possible while in the write loop and a cancel happens in between.",https://github.com/netty/netty/commit/57e922fd3a96f81855523ec7c57362e2d31b5587,,,transport/src/main/java/io/netty5/channel/ChannelOutboundBuffer.java,3,java,False,2022-07-01T10:24:23Z "private IntentSender getCommitCallback(final String packageName, final int sessionId, final InstallListener callback) { // Create a single-use broadcast receiver BroadcastReceiver broadcastReceiver = new BroadcastReceiver() { @Override public void onReceive(Context context, Intent intent) { mContext.unregisterReceiver(this); handleCommitCallback(intent, packageName, sessionId, callback); } }; // Create a matching intent-filter and register the receiver String action = ACTION_INSTALL_COMMIT + ""."" + packageName; IntentFilter intentFilter = new IntentFilter(); intentFilter.addAction(action); mContext.registerReceiver(broadcastReceiver, intentFilter); // Create a matching PendingIntent and use it to generate the IntentSender Intent broadcastIntent = new Intent(action); PendingIntent pendingIntent = PendingIntent.getBroadcast(mContext, packageName.hashCode(), broadcastIntent, PendingIntent.FLAG_ONE_SHOT | PendingIntent.FLAG_UPDATE_CURRENT | PendingIntent.FLAG_MUTABLE); return pendingIntent.getIntentSender(); }","private IntentSender getCommitCallback(final String packageName, final int sessionId, final InstallListener callback) { // Create a single-use broadcast receiver BroadcastReceiver broadcastReceiver = new BroadcastReceiver() { @Override public void onReceive(Context context, Intent intent) { mContext.unregisterReceiver(this); handleCommitCallback(intent, packageName, sessionId, callback); } }; // Create a matching intent-filter and register the receiver String action = ACTION_INSTALL_COMMIT + ""."" + packageName; IntentFilter intentFilter = new IntentFilter(); intentFilter.addAction(action); mContext.registerReceiver(broadcastReceiver, intentFilter, Context.RECEIVER_EXPORTED_UNAUDITED); // Create a matching PendingIntent and use it to generate the IntentSender Intent broadcastIntent = new Intent(action); PendingIntent pendingIntent = PendingIntent.getBroadcast(mContext, packageName.hashCode(), broadcastIntent, PendingIntent.FLAG_ONE_SHOT | PendingIntent.FLAG_UPDATE_CURRENT | PendingIntent.FLAG_MUTABLE); return pendingIntent.getIntentSender(); }","Add unaudited exported flag to exposed runtime receivers Android T allows apps to declare a runtime receiver as not exported by invoking registerReceiver with a new RECEIVER_NOT_EXPORTED flag; receivers registered with this flag will only receive broadcasts from the platform and the app itself. However to ensure developers can properly protect their receivers, all apps targeting T or later registering a receiver for non-system broadcasts must specify either the exported or not exported flag when invoking #registerReceiver; if one of these flags is not provided, the platform will throw a SecurityException. This commit updates all the exposed receivers with a new RECEIVER_EXPORTED_UNAUDITED flag to maintain the existing behavior of exporting the receiver while also flagging the receiver for audit before the T release. Bug: 161145287 Test: Build Change-Id: I165dbff34a03180a770d7cd621464f3d832b8095",https://github.com/PixelExperience/frameworks_base/commit/de5d7fb28152bacb6781dbdebed95e3ecc48d431,,,packages/PackageInstaller/src/com/android/packageinstaller/wear/PackageInstallerImpl.java,3,java,False,2021-12-29T22:21:35Z "public static boolean closeIfEmpty(Cursor cursor) { if (cursor != null && cursor.moveToFirst()) { return false; } if (cursor != null) { cursor.close(); } return true; }","public static boolean closeIfEmpty(Cursor cursor) { try { if (cursor != null && cursor.moveToFirst()) { return false; } } catch (SQLException e) { // Cursor.moveToFirst() may throw an exception when // the row is too big to fit into CursorWindow. // Catch this exception but still try to close the // Cursor object to free its resources. } if (cursor != null) { cursor.close(); } return true; }","Catch SQLException from too big textures Cursor.moveToFirst() may throw an exception when the row is too big to fit into CursorWindow. Catch this exception to keep the app from crashing.",https://github.com/markusfisch/ShaderEditor/commit/5d4875f5ebe5cebb3cf47d1d2d6970a452c8edd7,,,app/src/main/java/de/markusfisch/android/shadereditor/database/Database.java,3,java,False,2023-02-14T18:07:01Z "private static @NonNull UpdatedBodyAndMentions update(@Nullable CharSequence body, @NonNull List mentions, @NonNull Function replacementTextGenerator) { if (body == null || mentions.isEmpty()) { return new UpdatedBodyAndMentions(body, mentions); } SortedSet sortedMentions = new TreeSet<>(mentions); SpannableStringBuilder updatedBody = new SpannableStringBuilder(); List updatedMentions = new ArrayList<>(); int bodyIndex = 0; for (Mention mention : sortedMentions) { if (invalidMention(body, mention)) { continue; } updatedBody.append(body.subSequence(bodyIndex, mention.getStart())); CharSequence replaceWith = replacementTextGenerator.apply(mention); Mention updatedMention = new Mention(mention.getRecipientId(), updatedBody.length(), replaceWith.length()); updatedBody.append(replaceWith); updatedMentions.add(updatedMention); bodyIndex = mention.getStart() + mention.getLength(); } if (bodyIndex < body.length()) { updatedBody.append(body.subSequence(bodyIndex, body.length())); } return new UpdatedBodyAndMentions(updatedBody.toString(), updatedMentions); }","@VisibleForTesting static @NonNull UpdatedBodyAndMentions update(@Nullable CharSequence body, @NonNull List mentions, @NonNull Function replacementTextGenerator) { if (body == null || mentions.isEmpty()) { return new UpdatedBodyAndMentions(body, mentions); } SortedSet sortedMentions = new TreeSet<>(mentions); SpannableStringBuilder updatedBody = new SpannableStringBuilder(); List updatedMentions = new ArrayList<>(); int bodyIndex = 0; for (Mention mention : sortedMentions) { if (invalidMention(body, mention) || bodyIndex > mention.getStart()) { continue; } updatedBody.append(body.subSequence(bodyIndex, mention.getStart())); CharSequence replaceWith = replacementTextGenerator.apply(mention); Mention updatedMention = new Mention(mention.getRecipientId(), updatedBody.length(), replaceWith.length()); updatedBody.append(replaceWith); updatedMentions.add(updatedMention); bodyIndex = mention.getStart() + mention.getLength(); } if (bodyIndex < body.length()) { updatedBody.append(body.subSequence(bodyIndex, body.length())); } return new UpdatedBodyAndMentions(updatedBody.toString(), updatedMentions); }",Fix mention crash with overlapping ranges.,https://github.com/signalapp/Signal-Android/commit/45a1c5c369dc982139bcd376a9f0202572b4da1d,,,app/src/main/java/org/thoughtcrime/securesms/database/MentionUtil.java,3,java,False,2022-12-07T18:53:03Z "private void algAttackChanged() { JComboBox jCB = jwtST.getNoneAttackComboBox(); switch (jCB.getSelectedIndex()) { default: case 0: algAttackMode = null; break; case 1: algAttackMode = ""none""; break; case 2: algAttackMode = ""None""; break; case 3: algAttackMode = ""nOnE""; break; case 4: algAttackMode = ""NONE""; break; } }","private void algAttackChanged() { JComboBox jCB = jwtST.getNoneAttackComboBox(); switch (jCB.getSelectedIndex()) { default: case 0: algAttackMode = null; break; case 1: algAttackMode = ""none""; break; case 2: algAttackMode = ""None""; break; case 3: algAttackMode = ""nOnE""; break; case 4: algAttackMode = ""NONE""; break; } edited = true; CustomJWToken token = null; try { token = ReadableTokenFormat.getTokenFromReadableFormat(jwtIM.getJWTJSON()); } catch (InvalidTokenFormat e) { // TODO display message to users Output.outputError(""Failed to get token in readable format: ""+e.getMessage()); } String header = token.getHeaderJson(); if (algAttackMode != null) { edited = true; token.setSignature(""""); token.setHeaderJson(header.replace(token.getAlgorithm(), algAttackMode)); }else{ token.setHeaderJson(header.replace(token.getAlgorithm(), originalToken.getAlgorithm())); token.setSignature(originalSignature); } jwtIM.setJWTJSON(ReadableTokenFormat.getReadableFormat(token)); jwtIM.setSignature(token.getSignature()); jwtST.updateSetView(false); }",WIP - CVE attack realtime,https://github.com/ozzi-/JWT4B/commit/75021e5c5dba0f09cac0e82d153116b7e2249d58,,,src/app/controllers/JWTInterceptTabController.java,3,java,False,2021-11-23T16:43:26Z "private String generateAndStoreToken(RoutingContext ctx) { byte[] salt = new byte[32]; random.nextBytes(salt); String saltPlusToken = base64UrlEncode(salt) + ""."" + System.currentTimeMillis(); String signature = base64UrlEncode(mac.doFinal(saltPlusToken.getBytes(StandardCharsets.US_ASCII))); final String token = saltPlusToken + ""."" + signature; // a new token was generated add it to the cookie ctx.response() .addCookie( Cookie.cookie(cookieName, token) .setPath(cookiePath) .setHttpOnly(httpOnly) // it's not an option to change the same site policy .setSameSite(CookieSameSite.STRICT)); Session session = ctx.session(); if (session != null) { // storing will include the session id too. The reason is that if a session is upgraded // we don't want to allow the token to be valid anymore session.put(headerName, session.id() + ""/"" + token); } return token; }","private String generateAndStoreToken(RoutingContext ctx) { byte[] salt = new byte[32]; random.nextBytes(salt); String saltPlusToken = base64UrlEncode(salt) + ""."" + System.currentTimeMillis(); String signature = base64UrlEncode(mac.doFinal(saltPlusToken.getBytes(StandardCharsets.US_ASCII))); final String token = saltPlusToken + ""."" + signature; // a new token was generated add it to the cookie ctx.response() .addCookie( Cookie.cookie(cookieName, token) .setPath(cookiePath) .setHttpOnly(httpOnly) .setSecure(cookieSecure) // it's not an option to change the same site policy .setSameSite(CookieSameSite.STRICT)); Session session = ctx.session(); if (session != null) { // storing will include the session id too. The reason is that if a session is upgraded // we don't want to allow the token to be valid anymore session.put(headerName, session.id() + ""/"" + token); } return token; }","allow setting 'Secure' flag on XSRF Token cookie Signed-off-by: Milan Kotykov ",https://github.com/vert-x3/vertx-web/commit/9ac93316a749e3fbfeb9c5eba25d6f0d5dfc2edb,,,vertx-web/src/main/java/io/vertx/ext/web/handler/impl/CSRFHandlerImpl.java,3,java,False,2022-05-12T13:50:13Z "@Override public void reloadChanges() { ApplicationCore.WEB_API.changeHost(URI.create(props.getProperty(""de.unijena.bioinf.fingerid.web.host""))); ProxyManager.reconnect(); MF.CONNECTION_MONITOR().checkConnectionInBackground(); }","@Override public void reloadChanges() { ProxyManager.reconnect(); ApplicationCore.WEB_API.getAuthService().reconnectService(ProxyManager.getSirirusHttpAsyncClient()); //load new proxy data from service. ProxyManager.enforceGlobalProxySetting(); //update global proxy stuff for Webview. ApplicationCore.WEB_API.changeHost(URI.create(props.getProperty(""de.unijena.bioinf.fingerid.web.host""))); MF.CONNECTION_MONITOR().checkConnectionInBackground(); }",Fixed missing proxy usage for WebView and AuthService,https://github.com/boecker-lab/sirius/commit/43746f8e339484cad07c054fb6e2a8d1cb091f2e,,,sirius_gui/src/main/java/de/unijena/bioinf/ms/gui/settings/NetworkSettingsPanel.java,3,java,False,2021-10-13T15:18:26Z "[AllowAnonymous] [HttpPost(""confirm-password-reset"")] public async Task> ConfirmForgotPassword(ConfirmPasswordResetDto dto) { try { var user = await _unitOfWork.UserRepository.GetUserByEmailAsync(dto.Email); if (user == null) { return BadRequest(""Invalid Details""); } var result = await _userManager.VerifyUserTokenAsync(user, TokenOptions.DefaultProvider, ""ResetPassword"", dto.Token); if (!result) return BadRequest(""Unable to reset password, your email token is not correct.""); var errors = await _accountService.ChangeUserPassword(user, dto.Password); return errors.Any() ? BadRequest(errors) : Ok(""Password updated""); } catch (Exception ex) { _logger.LogError(ex, ""There was an unexpected error when confirming new password""); return BadRequest(""There was an unexpected error when confirming new password""); } }","[AllowAnonymous] [HttpPost(""confirm-password-reset"")] public async Task> ConfirmForgotPassword(ConfirmPasswordResetDto dto) { try { var user = await _unitOfWork.UserRepository.GetUserByEmailAsync(dto.Email); if (user == null) { return BadRequest(""Invalid credentials""); } var result = await _userManager.VerifyUserTokenAsync(user, TokenOptions.DefaultProvider, ""ResetPassword"", dto.Token); if (!result) { _logger.LogInformation(""Unable to reset password, your email token is not correct: {@Dto}"", dto); return BadRequest(""Invalid credentials""); } var errors = await _accountService.ChangeUserPassword(user, dto.Password); return errors.Any() ? BadRequest(errors) : Ok(""Password updated""); } catch (Exception ex) { _logger.LogError(ex, ""There was an unexpected error when confirming new password""); return BadRequest(""There was an unexpected error when confirming new password""); } }","Security Patches (#1624) * Fixed an issue where migrate-email could be called when an admin already existed * When logging in, ensure there is no bias towards username or password when rejecting * Cleaned up some messaging around anonymous apis to ensure there are no attack vectors.",https://github.com/kareadita/kavita/commit/f8db37d3f9aa42d47e7c4f4ca839e892d3f97afb,,,API/Controllers/AccountController.cs,3,cs,False,2022-10-31T13:07:55Z "private static void gameLoop() { float elapsedTime; float accumulator = 0f; float updateInterval = 1f / targetUPS; while (display.getWindow().isVisible()) { elapsedTime = timer.getElapsedTime(); accumulator += elapsedTime; while (accumulator >= updateInterval) { gameManager.update(canvas); gameManager.updateBehaviors(); if (!AfterUpdateList.isEmpty()) { for (Runnable action : AfterUpdateList) { action.run(); } AfterUpdateList.clear(); } accumulator -= updateInterval; } gameManager.processInputEvents(); gameManager.processKeysDown(); gameManager.render(canvas); if (!AfterRenderList.isEmpty()) { for (Runnable action : AfterRenderList) { action.run(); } AfterRenderList.clear(); } drawFrames++; if (display.getDisplayState() != DisplayState.FullScreen) { sync(); } } exit(); }","private static void gameLoop() { float elapsedTime; float accumulator = 0f; float updateInterval = 1f / targetUPS; while (display.getWindow().isVisible()) { elapsedTime = timer.getElapsedTime(); accumulator += elapsedTime; while (accumulator >= updateInterval) { gameManager.update(canvas); gameManager.updateBehaviors(); if (!AfterUpdateList.isEmpty()) { AfterUpdateList.run(list -> { for (Runnable action : list) { action.run(); } }); AfterUpdateList.clear(); } accumulator -= updateInterval; } gameManager.processInputEvents(); gameManager.processKeysDown(); gameManager.render(canvas); if (!AfterRenderList.isEmpty()) { AfterRenderList.run(list -> { for (Runnable action : list) { action.run(); } }); AfterRenderList.clear(); } drawFrames++; if (display.getDisplayState() != DisplayState.FullScreen) { sync(); } } exit(); }","fixed a ton of concurrency issues New Additions - `Drawable#isDestroyed` -- boolean for checking if a given `Drawable` has been destroyed - This boolean also effects the outcome of `Drawable#shouldRender` -- if the `Drawable` is destroyed, then it will not be rendered - `ManagedList` -- a type of `List` with convenient managed actions via a `ScheduledExecutorService`, providing a safe and manageable way to start and stop important list actions at a moment's notice Bug Fixes - Fixed occasional crashes on null pointers with enemies in `GameScene` - Fixed occasional concurrent modification exceptions on `AfterUpdateList` and `AfterRenderList` in `FastJEngine` - Fixed double-`exit` situation on closing `SimpleDisplay` - Fixed occasional concurrenct modification exceptions on `behavior` lists from `GameObject` - Sensibly removed as many `null` values as possible from `Model2D/Polygon2D/Sprite2D/Text2D` - Fixed buggy threading code/occasional concurrent modification exceptions in `InputManager` Breaking Changes - `BehaviorManager#reset` now destroys all the behaviors in each of its behavior lists Other Changes - Moved transform resetting on `destroyTheRest` up from `GameObject` to `Drawable` - Changed `GameObjectTests#tryUpdateBehaviorWithoutInitializing_shouldThrowNullPointerException`'s exception throwing to match the underlying `behaviors` list's exception - added trace-level logging to unit tests",https://github.com/fastjengine/FastJ/commit/3cf252b71786d782a98fdfb976eba13154e57757,,,src/main/java/tech/fastj/engine/FastJEngine.java,3,java,False,2021-12-20T17:24:53Z "@Nullable InputStream getBlobStream(final long blobHandle) throws IOException { final LongHashMap blobStreams = this.blobStreams; if (blobStreams != null) { final InputStream stream = blobStreams.get(blobHandle); if (stream != null) { stream.reset(); return stream; } } final LongHashMap blobFiles = this.blobFiles; if (blobFiles != null) { final File file = blobFiles.get(blobHandle); if (file != null) { return store.getBlobVault().cloneFile(file); } } return null; }","@Nullable InputStream getBlobStream(final long blobHandle) throws IOException { final LongHashMap blobStreams = this.blobStreams; if (blobStreams != null) { final InputStream stream = blobStreams.get(blobHandle); if (stream != null) { stream.reset(); return new InputStreamCloseGuard(stream); } } final LongHashMap blobFiles = this.blobFiles; if (blobFiles != null) { final File file = blobFiles.get(blobHandle); if (file != null) { return store.getBlobVault().getFileStream(file); } } return null; }","Issue XD-908 was fixed. (#44) Issue XD-908 was fixed. 1. Callback which allows executing version post-validation actions before data flush was added. 2. BufferedInputStreams are used instead of ByteArray streams to fall back to the stored position during the processing of stream inside EntityStore. Which should decrease the risk of OOM. 3. All streams are stored in the temporary directory before transaction flush (after validation of the transaction version) and then moved to the BlobVault location after a successful commit. That is done gracefully handling situations when streams generate errors while storing the data. 4. Passed-in streams are automatically closed during commit/flush and abort/revert of transaction.",https://github.com/JetBrains/xodus/commit/9b7d0e6387d80b3e30abb48cad5a064f12cf8b38,,,entity-store/src/main/java/jetbrains/exodus/entitystore/PersistentStoreTransaction.java,3,java,False,2023-01-24T09:44:19Z "function configure(config, layouts) { let layout = layouts.basicLayout; if (config.layout) { layout = layouts.layout(config.layout.type, config.layout); } if (!config.alwaysIncludePattern) { config.alwaysIncludePattern = false; } return appender( config.filename, config.pattern, layout, config, config.timezoneOffset ); }","function configure(config, layouts) { let layout = layouts.basicLayout; if (config.layout) { layout = layouts.layout(config.layout.type, config.layout); } if (!config.alwaysIncludePattern) { config.alwaysIncludePattern = false; } // security default (instead of relying on streamroller default) config.mode = config.mode || 0o600; return appender( config.filename, config.pattern, layout, config, config.timezoneOffset ); }",Changed default file modes from 0o644 to 0o600 for better security,https://github.com/log4js-node/log4js-node/commit/8042252861a1b65adb66931fdf702ead34fa9b76,CVE-2022-21704,['CWE-276'],lib/appenders/dateFile.js,3,js,False,2022-01-16T14:09:32Z "@NonNull public static long[] getSongListForAlbum(Context context, long id) { String[] projection = new String[]{BaseColumns._ID}; String selection = AudioColumns.ALBUM_ID + ""="" + id + "" AND "" + AudioColumns.IS_MUSIC + ""=1""; Cursor cursor = context.getContentResolver().query( MediaStore.Audio.Media.EXTERNAL_CONTENT_URI, projection, selection, null, AudioColumns.TRACK + "", "" + MediaStore.Audio.Media.DEFAULT_SORT_ORDER); if (cursor != null) { long[] mList = getSongListForCursor(cursor); cursor.close(); return mList; } return EMPTY_LIST; }","@NonNull public static long[] getSongListForAlbum(Context context, long id) { Cursor cursor = CursorCreator.makeAlbumSongCursor(context, id); long[] result = EMPTY_LIST; if (cursor != null) { if (cursor.moveToFirst()) { int index = 0; result = new long[cursor.getCount()]; do { result[index++] = cursor.getLong(0); } while (cursor.moveToNext()); } cursor.close(); } return result; }","restructured media access, fixed crash Signed-off-by: nuclearfog ",https://github.com/nuclearfog/Apollo-Music/commit/e77d9b46f869a2eb6f55c0938ee565dd49d101ba,,,app/src/main/java/com/andrew/apollo/utils/MusicUtils.java,3,java,False,2021-04-27T01:27:38Z "private void handlePlace(InventoryClickEvent e, StackedSpawner stackedSpawner){ Integer depositAmount = depositSpawners.get(e.getRawSlot()); if (depositAmount == null) return; int limit = stackedSpawner.getStackLimit(); if(stackedSpawner.getStackAmount() + depositAmount > limit) depositAmount = limit - stackedSpawner.getStackAmount(); Map itemsToRemove = new HashMap<>(); Inventory inventory = e.getWhoClicked().getInventory(); if(e.getWhoClicked().getGameMode() != GameMode.CREATIVE) { int amount = 0; for (int i = 0; i < inventory.getSize(); i++) { ItemStack itemStack = inventory.getItem(i); if (itemStack == null || itemStack.getType() != Materials.SPAWNER.toBukkitType() || plugin.getProviders().getSpawnerType(itemStack) != stackedSpawner.getSpawnedType() || ItemUtils.getSpawnerUpgrade(itemStack) != ((WStackedSpawner) stackedSpawner).getUpgradeId()) continue; int itemAmount = ItemUtils.getSpawnerItemAmount(itemStack); int itemsToAdd = itemStack.getAmount(); if((itemAmount * itemsToAdd) + amount > depositAmount){ itemsToAdd = (depositAmount - amount) / itemAmount; if(itemsToAdd <= 0) continue; } itemsToRemove.put(i, itemsToAdd); amount += (itemAmount * itemsToAdd); if (amount >= depositAmount) break; } depositAmount = Math.min(depositAmount, amount); } if(depositAmount <= 0){ if(failureSound != null) failureSound.playSound(e.getWhoClicked()); return; } if(!EventsCaller.callSpawnerPlaceInventoryEvent((Player) e.getWhoClicked(), stackedSpawner, depositAmount)){ if(failureSound != null) failureSound.playSound(e.getWhoClicked()); return; } stackedSpawner.setStackAmount(stackedSpawner.getStackAmount() + depositAmount, true); Locale.SPAWNER_UPDATE.send(e.getWhoClicked(), stackedSpawner.getStackAmount()); if(successSound != null) successSound.playSound(e.getWhoClicked()); // Remove items from inventory for(Map.Entry entry : itemsToRemove.entrySet()){ ItemStack currentItem = inventory.getItem(entry.getKey()); if(currentItem.getAmount() == entry.getValue()) inventory.setItem(entry.getKey(), new ItemStack(Material.AIR)); else currentItem.setAmount(currentItem.getAmount() - entry.getValue()); } }","private void handlePlace(InventoryClickEvent e, StackedSpawner stackedSpawner){ Integer depositAmount = depositSpawners.get(e.getRawSlot()); if (depositAmount == null) return; if(!stackedSpawner.isCached()){ if(failureSound != null) failureSound.playSound(e.getWhoClicked()); return; } int limit = stackedSpawner.getStackLimit(); if(stackedSpawner.getStackAmount() + depositAmount > limit) depositAmount = limit - stackedSpawner.getStackAmount(); Map itemsToRemove = new HashMap<>(); Inventory inventory = e.getWhoClicked().getInventory(); if(e.getWhoClicked().getGameMode() != GameMode.CREATIVE) { int amount = 0; for (int i = 0; i < inventory.getSize(); i++) { ItemStack itemStack = inventory.getItem(i); if (itemStack == null || itemStack.getType() != Materials.SPAWNER.toBukkitType() || plugin.getProviders().getSpawnerType(itemStack) != stackedSpawner.getSpawnedType() || ItemUtils.getSpawnerUpgrade(itemStack) != ((WStackedSpawner) stackedSpawner).getUpgradeId()) continue; int itemAmount = ItemUtils.getSpawnerItemAmount(itemStack); int itemsToAdd = itemStack.getAmount(); if((itemAmount * itemsToAdd) + amount > depositAmount){ itemsToAdd = (depositAmount - amount) / itemAmount; if(itemsToAdd <= 0) continue; } itemsToRemove.put(i, itemsToAdd); amount += (itemAmount * itemsToAdd); if (amount >= depositAmount) break; } depositAmount = Math.min(depositAmount, amount); } if(depositAmount <= 0){ if(failureSound != null) failureSound.playSound(e.getWhoClicked()); return; } if(!EventsCaller.callSpawnerPlaceInventoryEvent((Player) e.getWhoClicked(), stackedSpawner, depositAmount)){ if(failureSound != null) failureSound.playSound(e.getWhoClicked()); return; } stackedSpawner.setStackAmount(stackedSpawner.getStackAmount() + depositAmount, true); Locale.SPAWNER_UPDATE.send(e.getWhoClicked(), stackedSpawner.getStackAmount()); if(successSound != null) successSound.playSound(e.getWhoClicked()); // Remove items from inventory for(Map.Entry entry : itemsToRemove.entrySet()){ ItemStack currentItem = inventory.getItem(entry.getKey()); if(currentItem.getAmount() == entry.getValue()) inventory.setItem(entry.getKey(), new ItemStack(Material.AIR)); else currentItem.setAmount(currentItem.getAmount() - entry.getValue()); } }",Fix the ability to bypass blacklisted spawners using the amounts menu (#200),https://github.com/BG-Software-LLC/WildStacker/commit/3826c1201863484bbde41d30b9abc85887f999a8,,,src/main/java/com/bgsoftware/wildstacker/menu/SpawnerAmountsMenu.java,3,java,False,2021-06-25T11:36:48Z "private User fromDto(UserDto source, boolean checkChangeDate) { User target = DtoHelper.fillOrBuildEntity(source, userService.getByUuid(source.getUuid()), userService::createUser, checkChangeDate); target.setActive(source.isActive()); target.setFirstName(source.getFirstName()); target.setLastName(source.getLastName()); target.setPhone(source.getPhone()); target.setAddress(locationFacade.fromDto(source.getAddress(), checkChangeDate)); target.setUserName(source.getUserName()); target.setUserEmail(source.getUserEmail()); target.setRegion(regionService.getByReferenceDto(source.getRegion())); target.setDistrict(districtService.getByReferenceDto(source.getDistrict())); target.setCommunity(communityService.getByReferenceDto(source.getCommunity())); target.setHealthFacility(facilityService.getByReferenceDto(source.getHealthFacility())); target.setAssociatedOfficer(userService.getByReferenceDto(source.getAssociatedOfficer())); target.setLaboratory(facilityService.getByReferenceDto(source.getLaboratory())); target.setPointOfEntry(pointOfEntryService.getByReferenceDto(source.getPointOfEntry())); target.setLimitedDisease(source.getLimitedDisease()); target.setLanguage(source.getLanguage()); target.setHasConsentedToGdpr(source.isHasConsentedToGdpr()); Set userRoles = Optional.of(target).map(User::getUserRoles).orElseGet(HashSet::new); target.setUserRoles(userRoles); userRoles.clear(); source.getUserRoles().stream().map(userRoleReferenceDto -> userRoleService.getByReferenceDto(userRoleReferenceDto)).forEach(userRoles::add); target.updateJurisdictionLevel(); return target; }","private User fromDto(UserDto source, boolean checkChangeDate) { User target = DtoHelper.fillOrBuildEntity(source, userService.getByUuid(source.getUuid()), userService::createUser, checkChangeDate); target.setActive(source.isActive()); target.setFirstName(source.getFirstName()); target.setLastName(source.getLastName()); target.setPhone(source.getPhone()); target.setAddress(locationFacade.fromDto(source.getAddress(), checkChangeDate)); target.setUserName(source.getUserName()); target.setUserEmail(source.getUserEmail()); target.setRegion(regionService.getByReferenceDto(source.getRegion())); target.setDistrict(districtService.getByReferenceDto(source.getDistrict())); target.setCommunity(communityService.getByReferenceDto(source.getCommunity())); target.setHealthFacility(facilityService.getByReferenceDto(source.getHealthFacility())); target.setAssociatedOfficer(userService.getByReferenceDto(source.getAssociatedOfficer())); target.setLaboratory(facilityService.getByReferenceDto(source.getLaboratory())); target.setPointOfEntry(pointOfEntryService.getByReferenceDto(source.getPointOfEntry())); target.setLimitedDisease(source.getLimitedDisease()); target.setLanguage(source.getLanguage()); target.setHasConsentedToGdpr(source.isHasConsentedToGdpr()); //Make sure userroles of target are attached Set userRoles = Optional.of(target).map(User::getUserRoles).orElseGet(HashSet::new); target.setUserRoles(userRoles); //Preparation Set targetUserRoleUuids = target.getUserRoles().stream().map(UserRole::getUuid).collect(Collectors.toSet()); Set sourceUserRoleUuids = source.getUserRoles().stream().map(UserRoleReferenceDto::getUuid).collect(Collectors.toSet()); List newUserRoles = source.getUserRoles() .stream() .filter(userRoleReferenceDto -> !targetUserRoleUuids.contains(userRoleReferenceDto.getUuid())) .map(userRoleReferenceDto -> userRoleService.getByReferenceDto(userRoleReferenceDto)) .collect(Collectors.toList()); //Add new userroles target.getUserRoles().addAll(newUserRoles); //Remove userroles that were removed target.getUserRoles().removeIf(userRole -> !sourceUserRoleUuids.contains(userRole.getUuid())); target.updateJurisdictionLevel(); return target; }","#4461: Fixed stackoverflow issue (#9329) * #4461: Fixed stackoverflow issue * #4461: Added comments",https://github.com/SORMAS-Foundation/SORMAS-Project/commit/7bff1b79c7f8b3b30e505bda3f76ae381ef9113f,,,sormas-backend/src/main/java/de/symeda/sormas/backend/user/UserFacadeEjb.java,3,java,False,2022-05-26T07:59:53Z "Mono install(ServerRequest request) { return request.bodyToMono(new ParameterizedTypeReference>() { }) .flatMap(this::getZipFilePart) .flatMap(file -> file.content() .map(DataBuffer::asInputStream) .reduce(SequenceInputStream::new) .map(inputStream -> ThemeUtils.unzipThemeTo(inputStream, getThemeWorkDir()))) .flatMap(this::persistent) .flatMap(theme -> ServerResponse.ok() .contentType(MediaType.APPLICATION_JSON) .bodyValue(theme)); }","Mono install(ServerRequest request) { return request.body(BodyExtractors.toMultipartData()) .flatMap(this::getZipFilePart) .map(file -> { try { var is = DataBufferUtils.toInputStream(file.content()); var themeWorkDir = getThemeWorkDir(); if (log.isDebugEnabled()) { log.debug(""Transferring {} into {}"", file.filename(), themeWorkDir); } return ThemeUtils.unzipThemeTo(is, themeWorkDir); } catch (IOException e) { throw Exceptions.propagate(e); } }) .subscribeOn(Schedulers.boundedElastic()) .flatMap(this::persistent) .flatMap(theme -> ServerResponse.ok() .contentType(MediaType.APPLICATION_JSON) .bodyValue(theme)); }","Fix stackoverflow error when installing big theme (#2399) #### What type of PR is this? /kind bug /area core /milestone 2.0 #### What this PR does / why we need it: We will encounter a stackoverflow error when installing theme with large size. Please see the following screenshot: ![a8a3fadd7b06a071e80d4dd1899a244](https://user-images.githubusercontent.com/16865714/189171274-1940634e-a984-4ca6-857f-f8232f6a6ad3.jpg) #### Special notes for your reviewer: How to test? 1. Create a big theme installation package 2. Install it and see the result #### Does this PR introduce a user-facing change? ```release-note None ```",https://github.com/halo-dev/halo/commit/9331f31d58081d002e53de2d7bb4db0dc56dbc88,,,src/main/java/run/halo/app/core/extension/endpoint/ThemeEndpoint.java,3,java,False,2022-09-08T17:04:11Z "private void executeOperation(Context context, Handler> operation, Promise operationResult, CircuitBreakerMetrics.Operation call) { // Execute the operation if (options.getTimeout() != -1) { vertx.setTimer(options.getTimeout(), (l) -> { context.runOnContext(v -> { // Check if the operation has not already been completed if (!operationResult.future().isComplete()) { if (call != null) { call.timeout(); } operationResult.fail(TimeoutException.INSTANCE); } // Else Operation has completed }); }); } try { // We use an intermediate future to avoid the passed future to complete or fail after a timeout. Promise passedFuture = Promise.promise(); passedFuture.future().onComplete(ar -> { context.runOnContext(v -> { if (ar.failed()) { if (!operationResult.future().isComplete()) { operationResult.fail(ar.cause()); } } else { if (!operationResult.future().isComplete()) { operationResult.complete(ar.result()); } } }); }); operation.handle(passedFuture); } catch (Throwable e) { context.runOnContext(v -> { if (!operationResult.future().isComplete()) { if (call != null) { call.error(); } operationResult.fail(e); } }); } }","private void executeOperation(Context context, Handler> operation, Promise operationResult, CircuitBreakerMetrics.Operation call) { // We use an intermediate future to avoid the passed future to complete or fail after a timeout. Promise passedFuture = Promise.promise(); // Execute the operation if (options.getTimeout() != -1) { long timerId = vertx.setTimer(options.getTimeout(), (l) -> { context.runOnContext(v -> { // Check if the operation has not already been completed if (!operationResult.future().isComplete()) { if (call != null) { call.timeout(); } operationResult.fail(TimeoutException.INSTANCE); } // Else Operation has completed }); }); passedFuture.future().onComplete(v -> vertx.cancelTimer(timerId)); } try { passedFuture.future().onComplete(ar -> { context.runOnContext(v -> { if (ar.failed()) { if (!operationResult.future().isComplete()) { operationResult.fail(ar.cause()); } } else { if (!operationResult.future().isComplete()) { operationResult.complete(ar.result()); } } }); }); operation.handle(passedFuture); } catch (Throwable e) { context.runOnContext(v -> { if (!operationResult.future().isComplete()) { if (call != null) { call.error(); } operationResult.fail(e); } }); } }","Operation timers should be removed when operation completes. (#62) Otherwise, the application might throw an OOM. This would happen with a big enough circuit breaker timeout and a result value that retains a relatively large amount of memory. Signed-off-by: Thomas Segismont Signed-off-by: Thomas Segismont ",https://github.com/vert-x3/vertx-circuit-breaker/commit/3249386c0e2397fdca54af1684821b564a62c7f7,,,src/main/java/io/vertx/circuitbreaker/impl/CircuitBreakerImpl.java,3,java,False,2022-09-16T15:09:03Z "public static MaterialNBT readFromNBT(@Nullable INBT nbt) { if (nbt == null || nbt.getId() != Constants.NBT.TAG_LIST) { return EMPTY; } ListNBT listNBT = (ListNBT) nbt; if (listNBT.getTagType() != Constants.NBT.TAG_STRING) { return EMPTY; } List materials = listNBT.stream() .map(INBT::getString) .map(MaterialId::new) .map(MaterialRegistry::getMaterial) .collect(Collectors.toList()); return new MaterialNBT(materials); }","public static MaterialNBT readFromNBT(@Nullable INBT nbt) { if (nbt == null || nbt.getId() != Constants.NBT.TAG_LIST) { return EMPTY; } ListNBT listNBT = (ListNBT) nbt; if (listNBT.getTagType() != Constants.NBT.TAG_STRING) { return EMPTY; } List materials = listNBT.stream() .map(INBT::getString) .map(MaterialId::tryCreate) .filter(Objects::nonNull) .map(MaterialRegistry::getMaterial) .collect(Collectors.toList()); return new MaterialNBT(materials); }",Fix potential crash deserializing bad material NBT,https://github.com/SlimeKnights/TinkersConstruct/commit/72db8fa78c073cf8edd48e18c08abeb3aba29bf8,,,src/main/java/slimeknights/tconstruct/library/tools/nbt/MaterialNBT.java,3,java,False,2021-01-31T05:58:52Z "public Value handleCommand(ServerCommandSource source, FunctionValue function, List args) { try { return call(source, function, args); } catch (CarpetExpressionException exc) { handleErrorWithStack(""Error while running custom command"", exc); return Value.NULL; } catch (ArithmeticException ae) { handleErrorWithStack(""Math doesn't compute"", ae); return Value.NULL; } }","public Value handleCommand(ServerCommandSource source, FunctionValue function, List args) { try { return call(source, function, args); } catch (CarpetExpressionException exc) { handleErrorWithStack(""Error while running custom command"", exc); } catch (ArithmeticException ae) { handleErrorWithStack(""Math doesn't compute"", ae); } catch (StackOverflowError soe) { handleErrorWithStack(""Your thoughts are too deep"", soe); } return Value.NULL; }","stack overflow in scripts shouldn't crash the game, fixes #934",https://github.com/gnembon/fabric-carpet/commit/8fa54c81463af091847f4a989f11b6c5ede1ffd0,,,src/main/java/carpet/script/CarpetScriptHost.java,3,java,False,2021-06-26T02:31:46Z "@Inject(method = ""broadcastSystemMessage(Lnet/minecraft/network/chat/Component;Ljava/util/function/Function;Z)V"", at = @At(""HEAD""), cancellable = true) private void impl$onBroadcastSystemMessage(final net.minecraft.network.chat.Component $$0, final Function $$1, final boolean $$2, final CallbackInfo ci) { ci.cancel(); final Audience originalAudience = (Audience) this.server; final Component originalMessage = SpongeAdventure.asAdventure($$0); final SystemMessageEvent event = SpongeEventFactory.createSystemMessageEvent(Sponge.server().causeStackManager().currentCause(), originalAudience, Optional.of(originalAudience), originalMessage, originalMessage); if (SpongeCommon.post(event)) { ci.cancel(); return; } event.audience().ifPresent(audience -> audience.sendMessage(event.message())); }","@Inject(method = ""broadcastSystemMessage(Lnet/minecraft/network/chat/Component;Ljava/util/function/Function;Z)V"", at = @At(""HEAD""), cancellable = true) private void impl$onBroadcastSystemMessage(final net.minecraft.network.chat.Component $$0, final Function $$1, final boolean $$2, final CallbackInfo ci) { if (this.impl$isDuringSystemMessageEvent) { return; } ci.cancel(); final Audience originalAudience = (Audience) this.server; final Component originalMessage = SpongeAdventure.asAdventure($$0); final SystemMessageEvent event = SpongeEventFactory.createSystemMessageEvent(Sponge.server().causeStackManager().currentCause(), originalAudience, Optional.of(originalAudience), originalMessage, originalMessage); if (SpongeCommon.post(event)) { ci.cancel(); return; } this.impl$isDuringSystemMessageEvent = true; event.audience().ifPresent(audience -> audience.sendMessage(event.message())); this.impl$isDuringSystemMessageEvent = false; }","Fix Stackoverflow when sending system message to server fixes #3773",https://github.com/SpongePowered/Sponge/commit/2733338f978e86a25da3b8d6a53827a5f68641c2,,,src/mixins/java/org/spongepowered/common/mixin/core/server/players/PlayerListMixin.java,3,java,False,2022-10-13T15:29:52Z "public static long getIdForAlbum(Context context, String albumName, String artistName) { Cursor cursor = context.getContentResolver().query( MediaStore.Audio.Albums.EXTERNAL_CONTENT_URI, new String[]{BaseColumns._ID}, AlbumColumns.ALBUM + ""=? AND "" + AlbumColumns.ARTIST + ""=?"", new String[]{ albumName, artistName}, AlbumColumns.ALBUM); int id = -1; if (cursor != null) { cursor.moveToFirst(); if (!cursor.isAfterLast()) { id = cursor.getInt(0); } cursor.close(); } return id; }","public static long getIdForAlbum(Context context, String albumName, String artistName) { Cursor cursor = CursorCreator.makeAlbumCursor(context, albumName, artistName); int id = -1; if (cursor != null) { if (cursor.moveToFirst()) { id = cursor.getInt(0); } cursor.close(); } return id; }","restructured media access, fixed crash Signed-off-by: nuclearfog ",https://github.com/nuclearfog/Apollo-Music/commit/e77d9b46f869a2eb6f55c0938ee565dd49d101ba,,,app/src/main/java/com/andrew/apollo/utils/MusicUtils.java,3,java,False,2021-04-27T01:27:38Z "[System.Diagnostics.CodeAnalysis.SuppressMessage(""Microsoft.Naming"", ""CA2204:Literals should be spelled correctly"", MessageId = ""HttpStatusCode"")] public static void Apply(this CommandResult commandResult, HttpResponseBase response, bool emitSameSiteNone) { if (commandResult == null) { throw new ArgumentNullException(nameof(commandResult)); } if (response == null) { throw new ArgumentNullException(nameof(response)); } response.Cache.SetCacheability((HttpCacheability)commandResult.Cacheability); ApplyCookies(commandResult, response, emitSameSiteNone); if (commandResult.HttpStatusCode == HttpStatusCode.SeeOther || commandResult.Location != null) { if (commandResult.Location == null) { throw new InvalidOperationException(""Missing Location on redirect.""); } if (commandResult.HttpStatusCode != HttpStatusCode.SeeOther) { throw new InvalidOperationException(""Invalid HttpStatusCode for redirect, but Location is specified""); } response.Redirect(commandResult.Location.OriginalString); } else { response.StatusCode = (int)commandResult.HttpStatusCode; response.ContentType = commandResult.ContentType; response.Write(commandResult.Content); response.End(); } }","[System.Diagnostics.CodeAnalysis.SuppressMessage(""Microsoft.Naming"", ""CA2204:Literals should be spelled correctly"", MessageId = ""HttpStatusCode"")] public static void Apply( this CommandResult commandResult, HttpResponseBase response, bool emitSameSiteNone, string modulePath) { if (commandResult == null) { throw new ArgumentNullException(nameof(commandResult)); } if (response == null) { throw new ArgumentNullException(nameof(response)); } response.Cache.SetCacheability((HttpCacheability)commandResult.Cacheability); ApplyCookies(commandResult, response, emitSameSiteNone, modulePath); if (commandResult.HttpStatusCode == HttpStatusCode.SeeOther || commandResult.Location != null) { if (commandResult.Location == null) { throw new InvalidOperationException(""Missing Location on redirect.""); } if (commandResult.HttpStatusCode != HttpStatusCode.SeeOther) { throw new InvalidOperationException(""Invalid HttpStatusCode for redirect, but Location is specified""); } response.Redirect(commandResult.Location.OriginalString); } else { response.StatusCode = (int)commandResult.HttpStatusCode; response.ContentType = commandResult.ContentType; response.Write(commandResult.Content); response.End(); } }","Use modulepath in data protection purpose - Prevents reuse of protected data across instances/schemes/modules - Fixes #713",https://github.com/Sustainsys/Saml2/commit/2cacdc3a912109d46395eed89e6c28f5a65ebe7e,,,Sustainsys.Saml2.HttpModule/CommandResultHttpExtensions.cs,3,cs,False,2023-09-19T07:25:15Z "@Override public void onPause() { mParent.getLoaderManager().destroyLoader( AppInfoDashboardFragment.LOADER_BATTERY_USAGE_STATS); }","@Override public void onPause() { mParent.getLoaderManager().destroyLoader( AppInfoDashboardFragment.LOADER_BATTERY_USAGE_STATS); closeBatteryUsageStats(); }","Invoke close() method for BatteryUsageStats to close cursor window - Invoke close() method for BatteryUsageStats to close cursor window, avoid OOM. Bug: 245385410 Test: make SettingsRoboTests Change-Id: I68f36a42a33d2546cb191cec88f5431e24dd5b84 (cherry picked from commit f164be387e8e64fc97997dfa352aeaba0da83b55)",https://github.com/LineageOS/android_packages_apps_Settings/commit/9a539a46d1f388e857c1ced7251975693d8fe530,,,src/com/android/settings/applications/appinfo/AppBatteryPreferenceController.java,3,java,False,2022-11-10T06:54:17Z "protected boolean exec() throws SQLException { if (sql == null) throw new SQLException(""SQLiteJDBC internal error: sql==null""); if (rs.isOpen()) throw new SQLException(""SQLite JDBC internal error: rs.isOpen() on exec.""); boolean success = false; boolean rc = false; try { rc = conn.getDatabase().execute(this, null); success = true; } finally { resultsWaiting = rc; if (!success) conn.getDatabase().finalize(this); } return conn.getDatabase().column_count(pointer) != 0; }","protected boolean exec() throws SQLException { if (sql == null) throw new SQLException(""SQLiteJDBC internal error: sql==null""); if (rs.isOpen()) throw new SQLException(""SQLite JDBC internal error: rs.isOpen() on exec.""); boolean success = false; boolean rc = false; try { rc = conn.getDatabase().execute(this, null); success = true; } finally { resultsWaiting = rc; if (!success) { this.pointer.close(); } } return pointer.safeRunInt(DB::column_count) != 0; }",Wrap Statement Pointers to prevent use after free race,https://github.com/xerial/sqlite-jdbc/commit/e1d282cb2887ef427c7ad93d4fe7dd05a6c11473,,,src/main/java/org/sqlite/core/CoreStatement.java,3,java,False,2022-07-29T03:54:01Z "public AuthInfo getParsedClaims(String token) { Claims claims = Jwts.parserBuilder() .setSigningKey(signingKey) .build() .parseClaimsJws(token) .getBody(); Long id = claims.get(""id"", Long.class); String role = claims.get(""role"", String.class); String nickname = claims.get(""nickname"", String.class); return new AuthInfo(id, role, nickname); }","public AuthInfo getParsedClaims(String token) { Claims claims; try { claims = Jwts.parserBuilder() .setSigningKey(signingKey) .build() .parseClaimsJws(token) .getBody(); } catch (ExpiredJwtException ex) { Long id = ex.getClaims().get(""id"", Long.class); String role = ex.getClaims().get(""role"", String.class); String nickname = ex.getClaims().get(""nickname"", String.class); return new AuthInfo(id, role, nickname); } Long id = claims.get(""id"", Long.class); String role = claims.get(""role"", String.class); String nickname = claims.get(""nickname"", String.class); return new AuthInfo(id, role, nickname); }",fix: 만료된 토큰일 때 authinfo 객체를 생성하지 않던 문제 해결,https://github.com/woowacourse-teams/2022-sokdak/commit/f7cbb7eaf61c73d3a3d635d7e682cf5292014478,,,backend/sokdak/src/main/java/com/wooteco/sokdak/support/token/JwtTokenProvider.java,3,java,False,2022-08-02T08:38:03Z "private void initializeMulticastSocket() { try { int port = getOrDefault(MulticastProperties.PORT, DEFAULT_MULTICAST_PORT); PortValueValidator validator = new PortValueValidator(); validator.validate(port); String group = getOrDefault(MulticastProperties.GROUP, DEFAULT_MULTICAST_GROUP); multicastSocket = new MulticastSocket(null); multicastSocket.bind(new InetSocketAddress(port)); if (discoveryNode != null) { // See MulticastService.createMulticastService(...) InetAddress inetAddress = discoveryNode.getPrivateAddress().getInetAddress(); if (!inetAddress.isLoopbackAddress()) { multicastSocket.setInterface(inetAddress); } } multicastSocket.setReuseAddress(true); multicastSocket.setTimeToLive(SOCKET_TIME_TO_LIVE); multicastSocket.setReceiveBufferSize(DATA_OUTPUT_BUFFER_SIZE); multicastSocket.setSendBufferSize(DATA_OUTPUT_BUFFER_SIZE); multicastSocket.setSoTimeout(SOCKET_TIMEOUT); multicastSocket.joinGroup(InetAddress.getByName(group)); multicastDiscoverySender = new MulticastDiscoverySender(discoveryNode, multicastSocket, logger, group, port); multicastDiscoveryReceiver = new MulticastDiscoveryReceiver(multicastSocket, logger); if (discoveryNode == null) { isClient = true; } } catch (Exception e) { logger.finest(e.getMessage()); rethrow(e); } }","private void initializeMulticastSocket() { try { int port = getOrDefault(MulticastProperties.PORT, DEFAULT_MULTICAST_PORT); PortValueValidator validator = new PortValueValidator(); validator.validate(port); String group = getOrDefault(MulticastProperties.GROUP, DEFAULT_MULTICAST_GROUP); boolean safeSerialization = getOrDefault(MulticastProperties.SAFE_SERIALIZATION, DEFAULT_SAFE_SERIALIZATION); if (!safeSerialization) { String prop = MulticastProperties.SAFE_SERIALIZATION.key(); logger.warning(""The "" + getClass().getSimpleName() + "" Hazelcast member discovery strategy is configured without the "" + prop + "" parameter enabled."" + "" Set the "" + prop + "" property to 'true' in the strategy configuration to protect the cluster"" + "" against untrusted deserialization attacks.""); } MulticastDiscoverySerializationHelper serializationHelper = new MulticastDiscoverySerializationHelper( safeSerialization); multicastSocket = new MulticastSocket(null); multicastSocket.bind(new InetSocketAddress(port)); if (discoveryNode != null) { // See MulticastService.createMulticastService(...) InetAddress inetAddress = discoveryNode.getPrivateAddress().getInetAddress(); if (!inetAddress.isLoopbackAddress()) { multicastSocket.setInterface(inetAddress); } } multicastSocket.setReuseAddress(true); multicastSocket.setTimeToLive(SOCKET_TIME_TO_LIVE); multicastSocket.setReceiveBufferSize(DATA_OUTPUT_BUFFER_SIZE); multicastSocket.setSendBufferSize(DATA_OUTPUT_BUFFER_SIZE); multicastSocket.setSoTimeout(SOCKET_TIMEOUT); multicastSocket.joinGroup(InetAddress.getByName(group)); multicastDiscoverySender = new MulticastDiscoverySender(discoveryNode, multicastSocket, logger, group, port, serializationHelper); multicastDiscoveryReceiver = new MulticastDiscoveryReceiver(multicastSocket, logger, serializationHelper); if (discoveryNode == null) { isClient = true; } } catch (Exception e) { logger.finest(e.getMessage()); rethrow(e); } }",Initialize list structures in config objects (#20744),https://github.com/hazelcast/hazelcast/commit/9ce46b8344b8cebbb9b5bf226a264dfe5a7fc75c,,,hazelcast/src/main/java/com/hazelcast/spi/discovery/multicast/MulticastDiscoveryStrategy.java,3,java,False,2022-02-18T10:22:27Z "def login(): callback = url_for("".callback"", _external=True) next_path = request.args.get( ""next"", url_for(""redash.index"", org_slug=session.get(""org_slug"")) ) logger.debug(""Callback url: %s"", callback) logger.debug(""Next is: %s"", next_path) return google_remote_app().authorize(callback=callback, state=next_path)","def login(): redirect_uri = url_for("".callback"", _external=True) next_path = request.args.get( ""next"", url_for(""redash.index"", org_slug=session.get(""org_slug"")) ) logger.debug(""Callback url: %s"", redirect_uri) logger.debug(""Next is: %s"", next_path) session[""next_url""] = next_path return oauth.google.authorize_redirect(redirect_uri)","Merge pull request from GHSA-vhc7-w7r8-8m34 * WIP: break the flask_oauthlib behavior * Refactor google-oauth to use cryptographic state. * Clean up comments * Fix: tests didn't pass because of the scope issues. Moved outside the create_blueprint method because this does not depend on the Authlib object. * Apply Arik's fixes. Tests pass.",https://github.com/getredash/redash/commit/da696ff7f84787cbf85967460fac52886cbe063e,,,redash/authentication/google_oauth.py,3,py,False,2021-11-23T22:22:02Z "@Override public void onNext(ServiceBusReceiveLink next) { Objects.requireNonNull(next, ""'next' cannot be null.""); if (isTerminated()) { logger.atWarning() .addKeyValue(LINK_NAME_KEY, next.getLinkName()) .addKeyValue(ENTITY_PATH_KEY, next.getEntityPath()) .log(""Got another link when we have already terminated processor.""); Operators.onNextDropped(next, currentContext()); return; } final String linkName = next.getLinkName(); final String entityPath = next.getEntityPath(); logger.atInfo() .addKeyValue(LINK_NAME_KEY, linkName) .addKeyValue(ENTITY_PATH_KEY, entityPath) .log(""Setting next AMQP receive link.""); final AmqpReceiveLink oldChannel; final Disposable oldSubscription; synchronized (lock) { oldChannel = currentLink; oldSubscription = currentLinkSubscriptions; currentLink = next; next.setEmptyCreditListener(() -> 0); currentLinkSubscriptions = Disposables.composite( next.receive().publishOn(Schedulers.boundedElastic()).subscribe(message -> { synchronized (queueLock) { messageQueue.add(message); pendingMessages.incrementAndGet(); } drain(); }), next.getEndpointStates().subscribeOn(Schedulers.boundedElastic()).subscribe( state -> { // Connection was successfully opened, we can reset the retry interval. if (state == AmqpEndpointState.ACTIVE) { retryAttempts.set(0); } }, error -> { currentLink = null; onError(error); }, () -> { if (isTerminated()) { logger.info(""Processor is terminated. Disposing of link processor.""); dispose(); } else if (upstream == Operators.cancelledSubscription()) { logger.info(""Upstream has completed. Disposing of link processor.""); dispose(); } else { logger.info(""Receive link endpoint states are closed. Requesting another.""); final AmqpReceiveLink existing = currentLink; currentLink = null; disposeReceiver(existing); requestUpstream(); } })); } checkAndAddCredits(next); disposeReceiver(oldChannel); if (oldSubscription != null) { oldSubscription.dispose(); } }","@Override public void onNext(ServiceBusReceiveLink next) { Objects.requireNonNull(next, ""'next' cannot be null.""); if (isTerminated()) { logger.atWarning() .addKeyValue(LINK_NAME_KEY, next.getLinkName()) .addKeyValue(ENTITY_PATH_KEY, next.getEntityPath()) .log(""Got another link when we have already terminated processor.""); Operators.onNextDropped(next, currentContext()); return; } final String linkName = next.getLinkName(); final String entityPath = next.getEntityPath(); logger.atInfo() .addKeyValue(LINK_NAME_KEY, linkName) .addKeyValue(ENTITY_PATH_KEY, entityPath) .log(""Setting next AMQP receive link.""); final AmqpReceiveLink oldChannel; final Disposable oldSubscription; synchronized (lock) { oldChannel = currentLink; oldSubscription = currentLinkSubscriptions; currentLink = next; next.setEmptyCreditListener(() -> 0); currentLinkSubscriptions = Disposables.composite( next.receive().publishOn(Schedulers.boundedElastic()).subscribe( message -> { synchronized (queueLock) { messageQueue.add(message); pendingMessages.incrementAndGet(); } drain(); }, error -> { // When the receive on AmqpReceiveLink (e.g., ServiceBusReactorReceiver) terminates // with an error, we expect the recovery to happen in response to the terminal events // in link EndpointState Flux. logger.atVerbose() .addKeyValue(LINK_NAME_KEY, linkName) .addKeyValue(ENTITY_PATH_KEY, entityPath) .log(""Receiver is terminated."", error); }), next.getEndpointStates().subscribeOn(Schedulers.boundedElastic()).subscribe( state -> { // Connection was successfully opened, we can reset the retry interval. if (state == AmqpEndpointState.ACTIVE) { retryAttempts.set(0); } }, error -> { currentLink = null; onError(error); }, () -> { if (isTerminated()) { logger.info(""Processor is terminated. Disposing of link processor.""); dispose(); } else if (upstream == Operators.cancelledSubscription()) { logger.info(""Upstream has completed. Disposing of link processor.""); dispose(); } else { logger.info(""Receive link endpoint states are closed. Requesting another.""); final AmqpReceiveLink existing = currentLink; currentLink = null; disposeReceiver(existing); requestUpstream(); } })); } checkAndAddCredits(next); disposeReceiver(oldChannel); if (oldSubscription != null) { oldSubscription.dispose(); } }","Avoid error in one faulty receiver bypassing to parent connection hosting other healthy receivers, ensure ExceutionRejectedException is handled in all places that uses Dispatcher.invoke (#27839)",https://github.com/Azure/azure-sdk-for-java/commit/6d827ec4869bb797a858eaed855290d5926a080a,,,sdk/servicebus/azure-messaging-servicebus/src/main/java/com/azure/messaging/servicebus/implementation/ServiceBusReceiveLinkProcessor.java,3,java,False,2022-03-31T17:00:52Z "@ExceptionHandler({MemberException.class, MapException.class, SpaceException.class, ReservationException.class}) public ResponseEntity zzimkkongExceptionHandler(final ZzimkkongException exception) { logger.warn(exception.getMessage()); return ResponseEntity .status(exception.getStatus()) .body(ErrorResponse.of(exception)); }","@ExceptionHandler({MemberException.class, MapException.class, SpaceException.class, ReservationException.class, AuthorizationException.class}) public ResponseEntity zzimkkongExceptionHandler(final ZzimkkongException exception) { logger.warn(exception.getMessage()); return ResponseEntity .status(exception.getStatus()) .body(ErrorResponse.of(exception)); }","feat: 토큰 검증 (#80) * feat: 토큰 유효성 검사 * refactor: JwtUtils 테스트를 위한 값 상수로 추출 * refactor: JwtUtils가 Constructor Injection을 사용하도록 변경 * refactor: JwtUtilsTest 테스트 메소드 접근제어자 default로 변경 * test: JwtUtilsTest 조작된 토큰에 대한 테스트케이스 작성 * feat: LoginInterceptor 생성 및 등록 * refactor: JwtUtilsTest 테스팅에 필요한 일부 값 상수로 추출 * style: 코드 포매팅 * fix: Authorization이 ControllerAdvice에 없는 문제 해결 * refactor: 테스팅시 malfunction을 방지하기 위한 인터셉터 적용 URL path 설정 * feat: 토큰 유효성 검사 * refactor: JwtUtils 테스트를 위한 값 상수로 추출 * refactor: JwtUtils가 Constructor Injection을 사용하도록 변경 * refactor: JwtUtilsTest 테스트 메소드 접근제어자 default로 변경 * test: JwtUtilsTest 조작된 토큰에 대한 테스트케이스 작성 * feat: LoginInterceptor 생성 및 등록 * refactor: JwtUtilsTest 테스팅에 필요한 일부 값 상수로 추출 * style: 코드 포매팅 * fix: Authorization이 ControllerAdvice에 없는 문제 해결 * refactor: 테스팅시 malfunction을 방지하기 위한 인터셉터 적용 URL path 설정 * refactor: AuthorizationHeaderUninvolvedException 예외 메세지 변경 * refactor: TokenExpiredException(유효기간 만료)의 예외 메세지 변경 * refactor: LocinInterceptor 설정 코드 삭제 - 추후 인터셉터가 필요할 때 다시 설정합니다. * refactor: 인증 관련 패키지 구조 변경, ControllerAdvice 핸들링 코드 통합",https://github.com/woowacourse-teams/2021-zzimkkong/commit/3befc6dc61191ad65577aace67fdb5f12ef02dfc,,,backend/src/main/java/com/woowacourse/zzimkkong/controller/ControllerAdvice.java,3,java,False,2021-07-13T09:40:08Z "private static String extract(Enumeration headers) { while (headers.hasMoreElements()) { String value = headers.nextElement(); if ((value.toLowerCase().startsWith(BEARER_TYPE.toLowerCase()))) { return value.substring(BEARER_TYPE.length()).trim(); } } return null; }","private static String extract(Enumeration headers) { while (headers.hasMoreElements()) { String value = headers.nextElement(); if ((value.toLowerCase().startsWith(BEARER_TYPE.toLowerCase()))) { String authHeaderValue = value.substring(BEARER_TYPE.length()).trim(); int commaIndex = authHeaderValue.indexOf(','); if (commaIndex > 0) { authHeaderValue = authHeaderValue.substring(0, commaIndex); } return authHeaderValue; } } return null; }",fix: 만료된 토큰일 때 authinfo 객체를 생성하지 않던 문제 해결,https://github.com/woowacourse-teams/2022-sokdak/commit/f7cbb7eaf61c73d3a3d635d7e682cf5292014478,,,backend/sokdak/src/main/java/com/wooteco/sokdak/support/token/AuthorizationExtractor.java,3,java,False,2022-08-02T08:38:03Z "private void addSecurityFilter(final ExpressionBuilder builder, RepositoryContext context) { final User user = context.service(User.class); if (user.isAdministrator() || user.hasPermission(Permission.requireAll(Permission.OPERATION_BROWSE, Permission.ALL))) { return; } final List readPermissions = user.getPermissions().stream() .filter(p -> Permission.ALL.equals(p.getOperation()) || Permission.OPERATION_BROWSE.equals(p.getOperation())) .collect(Collectors.toList()); final Set exactResourceIds = readPermissions.stream() .flatMap(p -> p.getResources().stream()) .filter(resource -> !resource.endsWith(""*"")) .collect(Collectors.toSet()); final Set resourceIdPrefixes = readPermissions.stream() .flatMap(p -> p.getResources().stream()) .filter(resource -> isWildCardResource(resource)) .map(resource -> resource.substring(0, resource.length() - 1)) .collect(Collectors.toSet()); SetView resourceIds = Sets.union(exactResourceIds, resourceIdPrefixes); ExpressionBuilder branchFilter = Expressions.builder(); ResourceRequests.prepareSearch() .filterByIds(resourceIds) .setLimit(resourceIds.size()) .setFields(ResourceDocument.Fields.ID, ResourceDocument.Fields.BRANCH_PATH, ResourceDocument.Fields.RESOURCE_TYPE) .buildAsync() .getRequest() .execute(context) .stream() .filter(TerminologyResource.class::isInstance) .map(TerminologyResource.class::cast) .forEach(r -> { if (resourceIdPrefixes.contains(r.getId())) { final String branchPattern = String.format(""%s(/[a-zA-Z0-9.~_\\-]{1,%d})?"", r.getBranchPath(), DEFAULT_MAXIMUM_BRANCH_NAME_LENGTH); branchFilter.should(regexp(BRANCH, branchPattern)); } }); builder.filter(branchFilter.build()); }","private void addSecurityFilter(final ExpressionBuilder builder, RepositoryContext context) { final User user = context.service(User.class); if (user.isAdministrator() || user.hasPermission(Permission.requireAll(Permission.OPERATION_BROWSE, Permission.ALL))) { return; } final List readPermissions = user.getPermissions().stream() .filter(p -> Permission.ALL.equals(p.getOperation()) || Permission.OPERATION_BROWSE.equals(p.getOperation())) .collect(Collectors.toList()); final Set exactResourceIds = Sets.newHashSet(); final Set wildResourceIds = Sets.newHashSet(); final Multimap branchesByResourceId = HashMultimap.create(); readPermissions.stream() .flatMap(p -> p.getResources().stream()) .forEach(resource -> { if (resource.endsWith(""*"")) { if (resource.endsWith(""/*"")) { // wild only match wildResourceIds.add(resource.replace(""/*"", """")); } else { // append to both exact and wild match String resourceToAdd = resource.replace(""*"", """"); wildResourceIds.add(resourceToAdd); exactResourceIds.add(resourceToAdd); } } else if (resource.contains(Branch.SEPARATOR)) { branchesByResourceId.put(resource.substring(0, resource.indexOf(Branch.SEPARATOR)), resource.substring(resource.indexOf(Branch.SEPARATOR) + 1, resource.length())); } else { exactResourceIds.add(resource); } }); Set resourceIdsToSearchFor = ImmutableSet.builder() .addAll(exactResourceIds) .addAll(wildResourceIds) .addAll(branchesByResourceId.keySet()) .build(); ExpressionBuilder branchFilter = Expressions.bool(); ResourceRequests.prepareSearch() .filterByIds(resourceIdsToSearchFor) .setLimit(resourceIdsToSearchFor.size()) .setFields(ResourceDocument.Fields.ID, ResourceDocument.Fields.BRANCH_PATH, ResourceDocument.Fields.RESOURCE_TYPE) .buildAsync() .getRequest() .execute(context) .stream() .filter(TerminologyResource.class::isInstance) .map(TerminologyResource.class::cast) .forEach(res -> { // if present as prefix query, append the branch regex filter if (wildResourceIds.contains(res.getId())) { final String branchPattern = String.format(""%s/[a-zA-Z0-9.~_\\-]{1,%d}"", res.getBranchPath(), DEFAULT_MAXIMUM_BRANCH_NAME_LENGTH); branchFilter.should(regexp(BRANCH, branchPattern)); } // if present as exact query, append exact match if (exactResourceIds.contains(res.getId())) { branchFilter.should(exactMatch(BRANCH, res.getBranchPath())); } // if present as exact branch match, then append a terms filter final Collection exactBranchesToMatch = branchesByResourceId.removeAll(res.getId()); if (!exactBranchesToMatch.isEmpty()) { branchFilter.should(Commit.Expressions.branches(exactBranchesToMatch.stream().map(res::getRelativeBranchPath).collect(Collectors.toSet()))); } }); // if the built expression does not have any clauses Expression authorizationClause = branchFilter.build(); if (authorizationClause instanceof MatchAll) { // then match no documents instead throw new NoResultException(); } builder.filter(authorizationClause); }","fix(api): commits endpoint authorization now correctly restricts... ...the responses based on the incoming access token permission list (user info). If resources are not available to the user, then commit endpoints will return empty results. If a resource is available to the user, then it always returns the main commits of that resource and depending on additional permissions it can be return commits made on child branches. Supported permission formats: * RESOURCE_ID * RESOURCE_ID* * RESOURCE_ID/* * RESOURCE_ID/RELATIVE_BRANCH",https://github.com/b2ihealthcare/snow-owl/commit/75d4662fbac5a6be7d2e036220259717bc73f964,,,core/com.b2international.snowowl.core/src/com/b2international/snowowl/core/commit/CommitInfoSearchRequest.java,3,java,False,2022-04-05T14:37:10Z "private static void removeObjective(Objective objective) { String goalToRemove = objective.getGoal(); for (int i = 0; i < objectives.length; i++) { if (objectives[i] != null && objectives[i].getGoal().equals(goalToRemove)) { objectives[i] = null; } } }","private static void removeObjective(Objective objective) { String goalToRemove = objective.getGoal(); if (guildObjectives != null && guildObjectives.getGoal().equals(goalToRemove)) { guildObjectives = null; return; } for (int i = 0; i < objectives.length; i++) { if (objectives[i] != null && objectives[i].getGoal().equals(goalToRemove)) { objectives[i] = null; return; } } }","Fix 14 issues found in ticket backlog (#502) * Fix IndexOutOfBoundsException in QuestBookListPage Signed-off-by: kristofbolyai * Fix crash if OverlayConfig.GameUpdate.INSTANCE.messageMaxLength is 1 Signed-off-by: kristofbolyai * Fix crash related to deleting chat tabs and ChatGUI not updating Signed-off-by: kristofbolyai * Fix crash related to deleting chat tabs and ChatGUI not updating Signed-off-by: kristofbolyai * Fix translation cache becoming null Signed-off-by: kristofbolyai * Fix objective parsing if player is in party Signed-off-by: kristofbolyai * Fix guild objective not being removed upon completion Signed-off-by: kristofbolyai * Fix race condition in ServerEvents Signed-off-by: kristofbolyai * Fix race condition in ClientEvents Signed-off-by: kristofbolyai * Fix NPE in ServerEvents Signed-off-by: kristofbolyai * Fix AreaDPS value not being correct Signed-off-by: kristofbolyai * Fix NPE in fix :) Signed-off-by: kristofbolyai * Fix quest dialogue spoofing Signed-off-by: kristofbolyai * Fix Keyholder related crash Signed-off-by: kristofbolyai * Fix totem tracking Signed-off-by: kristofbolyai * Dialogue Page gets updated correctly Signed-off-by: kristofbolyai * Register ChatGUI correctly Signed-off-by: kristofbolyai * Use MC's GameSettings to check for isKeyDown Signed-off-by: kristofbolyai * Make multi line if have braces Signed-off-by: kristofbolyai ",https://github.com/Wynntils/Wynntils/commit/c8f6effe187ff68f17bcff809d2bc440ec07128d,,,src/main/java/com/wynntils/modules/utilities/overlays/hud/ObjectivesOverlay.java,3,java,False,2022-04-15T17:16:00Z "@EventHandler(priority = EventPriority.MONITOR) public void onForge(InventoryClickEvent event) { if (OptionL.isEnabled(Skills.FORGING)) { //Check cancelled if (OptionL.getBoolean(Option.FORGING_CHECK_CANCELLED)) { if (event.isCancelled()) { return; } } Inventory inventory = event.getClickedInventory(); if (inventory != null) { if (!(event.getWhoClicked() instanceof Player)) return; Player player = (Player) event.getWhoClicked(); ClickType click = event.getClick(); // Only allow right and left clicks if inventory full if (click != ClickType.LEFT && click != ClickType.RIGHT && ItemUtils.isInventoryFull(player)) return; if (event.getResult() != Event.Result.ALLOW) return; // Make sure the click was successful InventoryAction action = event.getAction(); // Only give if item was picked up if (action != InventoryAction.PICKUP_ALL && action != InventoryAction.MOVE_TO_OTHER_INVENTORY && action != InventoryAction.PICKUP_HALF && action != InventoryAction.DROP_ALL_SLOT && action != InventoryAction.DROP_ONE_SLOT && action != InventoryAction.HOTBAR_SWAP) { return; } if (inventory.getType().equals(InventoryType.ANVIL)) { if (event.getSlot() == 2) { ItemStack addedItem = inventory.getItem(1); ItemStack baseItem = inventory.getItem(0); if (inventory.getLocation() != null) { if (blockXpGainLocation(inventory.getLocation(), player)) return; } else { if (blockXpGainLocation(event.getWhoClicked().getLocation(), player)) return; } if (blockXpGainPlayer(player)) return; Skill s = Skills.FORGING; AnvilInventory anvil = (AnvilInventory) inventory; if (addedItem != null && baseItem != null) { if (addedItem.getType().equals(Material.ENCHANTED_BOOK)) { if (ItemUtils.isArmor(baseItem.getType())) { plugin.getLeveler().addXp(player, s, anvil.getRepairCost() * getXp(player, ForgingSource.COMBINE_ARMOR_PER_LEVEL)); } else if (ItemUtils.isWeapon(baseItem.getType())) { plugin.getLeveler().addXp(player, s, anvil.getRepairCost() * getXp(player, ForgingSource.COMBINE_WEAPON_PER_LEVEL)); } else if (baseItem.getType().equals(Material.ENCHANTED_BOOK)) { plugin.getLeveler().addXp(player, s, anvil.getRepairCost() * getXp(player, ForgingSource.COMBINE_BOOKS_PER_LEVEL)); } else { plugin.getLeveler().addXp(player, s, anvil.getRepairCost() * getXp(player, ForgingSource.COMBINE_TOOL_PER_LEVEL)); } } } } } else if (inventory.getType().toString().equals(""GRINDSTONE"")) { if (event.getSlotType() != InventoryType.SlotType.RESULT) return; if (inventory.getLocation() != null) { if (blockXpGainLocation(inventory.getLocation(), player)) return; } else { if (blockXpGainLocation(event.getWhoClicked().getLocation(), player)) return; } if (blockXpGainPlayer(player)) return; // Calculate total level int totalLevel = 0; ItemStack topItem = inventory.getItem(0); // Get item in top slot totalLevel += getTotalLevel(topItem); ItemStack bottomItem = inventory.getItem(1); // Get item in bottom slot totalLevel += getTotalLevel(bottomItem); plugin.getLeveler().addXp(player, Skills.FORGING, totalLevel * getXp(player, ForgingSource.GRINDSTONE_PER_LEVEL)); } } } }","@EventHandler(priority = EventPriority.MONITOR) public void onForge(InventoryClickEvent event) { if (OptionL.isEnabled(Skills.FORGING)) { //Check cancelled if (OptionL.getBoolean(Option.FORGING_CHECK_CANCELLED)) { if (event.isCancelled()) { return; } } Inventory inventory = event.getClickedInventory(); if (inventory != null) { if (!(event.getWhoClicked() instanceof Player)) return; Player player = (Player) event.getWhoClicked(); ClickType click = event.getClick(); // Only allow right and left clicks if inventory full if (click != ClickType.LEFT && click != ClickType.RIGHT && ItemUtils.isInventoryFull(player)) return; if (event.getResult() != Event.Result.ALLOW) return; // Make sure the click was successful if (player.getItemOnCursor().getType() != Material.AIR) return; // Make sure cursor is empty InventoryAction action = event.getAction(); // Only give if item was picked up if (action != InventoryAction.PICKUP_ALL && action != InventoryAction.MOVE_TO_OTHER_INVENTORY && action != InventoryAction.PICKUP_HALF && action != InventoryAction.DROP_ALL_SLOT && action != InventoryAction.DROP_ONE_SLOT && action != InventoryAction.HOTBAR_SWAP) { return; } if (inventory.getType().equals(InventoryType.ANVIL)) { if (event.getSlot() == 2) { ItemStack addedItem = inventory.getItem(1); ItemStack baseItem = inventory.getItem(0); if (inventory.getLocation() != null) { if (blockXpGainLocation(inventory.getLocation(), player)) return; } else { if (blockXpGainLocation(event.getWhoClicked().getLocation(), player)) return; } if (blockXpGainPlayer(player)) return; Skill s = Skills.FORGING; AnvilInventory anvil = (AnvilInventory) inventory; if (addedItem != null && baseItem != null) { if (addedItem.getType().equals(Material.ENCHANTED_BOOK)) { if (ItemUtils.isArmor(baseItem.getType())) { plugin.getLeveler().addXp(player, s, anvil.getRepairCost() * getXp(player, ForgingSource.COMBINE_ARMOR_PER_LEVEL)); } else if (ItemUtils.isWeapon(baseItem.getType())) { plugin.getLeveler().addXp(player, s, anvil.getRepairCost() * getXp(player, ForgingSource.COMBINE_WEAPON_PER_LEVEL)); } else if (baseItem.getType().equals(Material.ENCHANTED_BOOK)) { plugin.getLeveler().addXp(player, s, anvil.getRepairCost() * getXp(player, ForgingSource.COMBINE_BOOKS_PER_LEVEL)); } else { plugin.getLeveler().addXp(player, s, anvil.getRepairCost() * getXp(player, ForgingSource.COMBINE_TOOL_PER_LEVEL)); } } } } } else if (inventory.getType().toString().equals(""GRINDSTONE"")) { if (event.getSlotType() != InventoryType.SlotType.RESULT) return; if (inventory.getLocation() != null) { if (blockXpGainLocation(inventory.getLocation(), player)) return; } else { if (blockXpGainLocation(event.getWhoClicked().getLocation(), player)) return; } if (blockXpGainPlayer(player)) return; // Calculate total level int totalLevel = 0; ItemStack topItem = inventory.getItem(0); // Get item in top slot totalLevel += getTotalLevel(topItem); ItemStack bottomItem = inventory.getItem(1); // Get item in bottom slot totalLevel += getTotalLevel(bottomItem); plugin.getLeveler().addXp(player, Skills.FORGING, totalLevel * getXp(player, ForgingSource.GRINDSTONE_PER_LEVEL)); } } } }",Fix Forging XP exploit,https://github.com/Archy-X/AuraSkills/commit/4eb3444924b1a52e6406ee5513ea8534807ecd71,,,src/main/java/com/archyx/aureliumskills/skills/forging/ForgingLeveler.java,3,java,False,2021-12-31T06:13:05Z "@Override public void contextInitialized(ServletContextEvent sce) { try { ServletContext context = sce.getServletContext(); // Initialize logging String log4jPath = null; try { URL configFile = null; try { configFile = LoggingConfigurator.class.getClassLoader().getResource(""/log.xml""); } catch (Throwable t) { // Nothing to do } if (configFile == null) configFile = LoggingConfigurator.class.getClassLoader().getResource(""log.xml""); log4jPath = URLDecoder.decode(configFile.getPath(), ""UTF-8""); // Setup the correct logs folder ContextProperties config = new ContextProperties(); LoggingConfigurator lconf = new LoggingConfigurator(); lconf.setLogsRoot(config.getProperty(""conf.logdir"")); lconf.write(); // Init the logs System.out.println(String.format(""Taking log configuration from %s"", log4jPath)); Configurator.initialize(null, log4jPath); } catch (Throwable e) { System.err.println(String.format(""Cannot initialize the log: %s"", e.getMessage())); } // Update the web descriptor with the correct transport guarantee try { ContextProperties conf = new ContextProperties(); String policy = ""true"".equals(conf.getProperty(""ssl.required"")) ? ""CONFIDENTIAL"" : ""NONE""; WebConfigurator configurator = new WebConfigurator(context.getRealPath(""/WEB-INF/web.xml"")); if (configurator.setTransportGuarantee(policy)) { PluginRegistry.getInstance().setRestartRequired(); } } catch (Throwable e) { log.error(e.getMessage(), e); } // Prepare the plugins dir String pluginsDir = context.getRealPath(""/WEB-INF/lib""); // Initialize plugins PluginRegistry.getInstance().init(pluginsDir); // Reinitialize logging because some plugins may have added new // categories try { final LoggerContextFactory factory = LogManager.getFactory(); if (factory instanceof Log4jContextFactory) { Log4jContextFactory contextFactory = (Log4jContextFactory) factory; ((DefaultShutdownCallbackRegistry) contextFactory.getShutdownCallbackRegistry()).stop(); } } catch (Throwable e) { log.error(e.getMessage(), e); } // Clean some temporary folders File tempDirToDelete = new File(context.getRealPath(""upload"")); try { if (tempDirToDelete.exists()) FileUtils.forceDelete(tempDirToDelete); } catch (IOException e) { log.warn(e.getMessage()); } tempDirToDelete = new File(System.getProperty(""java.io.tmpdir"") + ""/upload""); try { if (tempDirToDelete.exists()) FileUtils.forceDelete(tempDirToDelete); } catch (IOException e) { log.warn(e.getMessage()); } tempDirToDelete = new File(System.getProperty(""java.io.tmpdir"") + ""/convertjpg""); try { if (tempDirToDelete.exists()) FileUtils.forceDelete(tempDirToDelete); } catch (IOException e) { log.warn(e.getMessage()); } // Initialize the Automation Automation.initialize(); // Try to unpack new plugins try { unpackPlugins(context); } catch (IOException e) { log.warn(e.getMessage()); } if (PluginRegistry.getInstance().isRestartRequired()) { restartRequired(); log.warn(""The application has to be restarted""); System.out.println(""The application has to be restarted""); } } finally { writePidFile(); } }","@Override public void contextInitialized(ServletContextEvent sce) { try { ServletContext context = sce.getServletContext(); log.warn(""AA1""); // Initialize logging initializeLogging(); log.warn(""AA2""); // Update the web descriptor with the correct transport guarantee try { ContextProperties conf = new ContextProperties(); String policy = ""true"".equals(conf.getProperty(""ssl.required"")) ? ""CONFIDENTIAL"" : ""NONE""; WebConfigurator configurator = new WebConfigurator(context.getRealPath(""/WEB-INF/web.xml"")); if (configurator.setTransportGuarantee(policy)) { PluginRegistry.getInstance().setRestartRequired(); } } catch (Throwable e) { log.error(e.getMessage(), e); } log.warn(""AA3""); // Prepare the plugins dir String pluginsDir = context.getRealPath(""/WEB-INF/lib""); // Initialize plugins PluginRegistry.getInstance().init(pluginsDir); log.warn(""AA4""); // // Reinitialize logging because some plugins may have added new // // categories // try { // final LoggerContextFactory factory = LogManager.getFactory(); // // if (factory instanceof Log4jContextFactory) { // Log4jContextFactory contextFactory = (Log4jContextFactory) factory; // ((DefaultShutdownCallbackRegistry) contextFactory.getShutdownCallbackRegistry()).stop(); // } // } catch (Throwable e) { // log.error(e.getMessage(), e); // } // Clean some temporary folders cleanTemporaryFolders(context); log.warn(""AA5""); initializeLogging(); log.warn(""AA6""); // Initialize the Automation Automation.initialize(); log.warn(""AA7""); // Try to unpack new plugins try { unpackPlugins(context); } catch (IOException e) { log.warn(e.getMessage()); } log.warn(""AA8""); if (PluginRegistry.getInstance().isRestartRequired()) { restartRequired(); log.warn(""The application has to be restarted""); System.out.println(""The application has to be restarted""); } log.warn(""AA9""); } finally { writePidFile(); } }",Fixed vulnerability CVE-2022-47417,https://github.com/logicaldoc/community/commit/68ffab5ae75c4c50849848be6216a62bb83a152f,,,logicaldoc-webapp/src/main/java/com/logicaldoc/web/listener/ApplicationListener.java,3,java,False,2023-02-10T07:28:47Z "def create_new_client_event(self, builder, requester=None, prev_events_and_hashes=None): """"""Create a new event for a local client Args: builder (EventBuilder): requester (synapse.types.Requester|None): prev_events_and_hashes (list[(str, dict[str, str], int)]|None): the forward extremities to use as the prev_events for the new event. For each event, a tuple of (event_id, hashes, depth) where *hashes* is a map from algorithm to hash. If None, they will be requested from the database. Returns: Deferred[(synapse.events.EventBase, synapse.events.snapshot.EventContext)] """""" if prev_events_and_hashes is not None: assert len(prev_events_and_hashes) <= 10, \ ""Attempting to create an event with %i prev_events"" % ( len(prev_events_and_hashes), ) else: prev_events_and_hashes = \ yield self.store.get_prev_events_for_room(builder.room_id) if prev_events_and_hashes: depth = max([d for _, _, d in prev_events_and_hashes]) + 1 else: depth = 1 prev_events = [ (event_id, prev_hashes) for event_id, prev_hashes, _ in prev_events_and_hashes ] builder.prev_events = prev_events builder.depth = depth context = yield self.state.compute_event_context(builder) if requester: context.app_service = requester.app_service if builder.is_state(): builder.prev_state = yield self.store.add_event_hashes( context.prev_state_events ) yield self.auth.add_auth_events(builder, context) signing_key = self.hs.config.signing_key[0] add_hashes_and_signatures( builder, self.server_name, signing_key ) event = builder.build() logger.debug( ""Created event %s with state: %s"", event.event_id, context.prev_state_ids, ) defer.returnValue( (event, context,) )","def create_new_client_event(self, builder, requester=None, prev_events_and_hashes=None): """"""Create a new event for a local client Args: builder (EventBuilder): requester (synapse.types.Requester|None): prev_events_and_hashes (list[(str, dict[str, str], int)]|None): the forward extremities to use as the prev_events for the new event. For each event, a tuple of (event_id, hashes, depth) where *hashes* is a map from algorithm to hash. If None, they will be requested from the database. Returns: Deferred[(synapse.events.EventBase, synapse.events.snapshot.EventContext)] """""" if prev_events_and_hashes is not None: assert len(prev_events_and_hashes) <= 10, \ ""Attempting to create an event with %i prev_events"" % ( len(prev_events_and_hashes), ) else: prev_events_and_hashes = \ yield self.store.get_prev_events_for_room(builder.room_id) if prev_events_and_hashes: depth = max([d for _, _, d in prev_events_and_hashes]) + 1 # we cap depth of generated events, to ensure that they are not # rejected by other servers (and so that they can be persisted in # the db) depth = min(depth, MAX_DEPTH) else: depth = 1 prev_events = [ (event_id, prev_hashes) for event_id, prev_hashes, _ in prev_events_and_hashes ] builder.prev_events = prev_events builder.depth = depth context = yield self.state.compute_event_context(builder) if requester: context.app_service = requester.app_service if builder.is_state(): builder.prev_state = yield self.store.add_event_hashes( context.prev_state_events ) yield self.auth.add_auth_events(builder, context) signing_key = self.hs.config.signing_key[0] add_hashes_and_signatures( builder, self.server_name, signing_key ) event = builder.build() logger.debug( ""Created event %s with state: %s"", event.event_id, context.prev_state_ids, ) defer.returnValue( (event, context,) )","Apply some limits to depth to counter abuse * When creating a new event, cap its depth to 2^63 - 1 * When receiving events, reject any without a sensible depth As per https://docs.google.com/document/d/1I3fi2S-XnpO45qrpCsowZv8P8dHcNZ4fsBsbOW7KABI",https://github.com/matrix-org/synapse/commit/33f469ba19586bbafa0cf2c7d7c35463bdab87eb,,,synapse/handlers/message.py,3,py,False,2018-05-01T15:19:39Z "@Override public void execute() { if (!sender().hasPermission(""libertybans."" + type() + "".undo"")) { sender().sendMessage(section.permissionCommand()); return; } String additionalPermission = getAdditionalPermission(type()); if (!additionalPermission.isEmpty() && !sender().hasPermission(additionalPermission)) { sender().sendMessage(section.permissionIpAddress()); return; } if (!command().hasNext()) { sender().sendMessage(section.usage()); return; } execute0(); }","@Override public void execute() { if (!sender().hasPermission(""libertybans."" + type() + "".undo"")) { sender().sendMessage(section.permissionCommand()); return; } if (!command().hasNext()) { sender().sendMessage(section.usage()); return; } execute0(); }","Fix bug allowing staff members to IP-ban without permission * This is a privilege escalation bug whereby a staff member with the permission to use /ban or /unban would also be able to IP-ban and undo IP-bans. * This would only be possible by using an IP address literal in the /ban or /unban command. For example, '/ban 127.0.0.1' would enact an IP ban despite the staff member not having permission to issue IP-bans. * Due to the last point, it would be necessary for a staff member exploiting this vulnerability to know the IP address of the player they wish to IP ban. However, it is not far-fetched for a staff member to be unable to issue IP bans but still be able to view other players' IP addresses, in which case this bug presents a real vulnerability.",https://github.com/A248/LibertyBans/commit/4db08c254b47920b3158519513c513b50693380a,,,bans-core/src/main/java/space/arim/libertybans/core/commands/UnpunishCommands.java,3,java,False,2021-11-16T19:52:29Z "public void trackRequest(String requestDescriptor, long requestId) { Preconditions.checkNotNull(requestDescriptor, ""Attempting to track a null request descriptor.""); if (!tracingEnabled) { return; } synchronized (lock) { List requestIds = ongoingRequests.getIfPresent(requestDescriptor); if (requestIds == null) { requestIds = Collections.synchronizedList(new ArrayList<>()); } requestIds.add(requestId); ongoingRequests.put(requestDescriptor, requestIds); } log.debug(""Tracking request {} with id {}."", requestDescriptor, requestId); }","public void trackRequest(String requestDescriptor, long requestId) { Preconditions.checkNotNull(requestDescriptor, ""Attempting to track a null request descriptor.""); if (!tracingEnabled) { return; } synchronized (lock) { List requestIds = ongoingRequests.getIfPresent(requestDescriptor); if (requestIds == null) { requestIds = Collections.synchronizedList(new ArrayList<>()); ongoingRequests.put(requestDescriptor, requestIds); } requestIds.add(requestId); if (requestIds.size() > MAX_PARALLEL_REQUESTS) { // Delete the oldest parallel that is not the primary (first) one request id to bound the size of this list. requestIds.remove(1); } } log.debug(""Tracking request {} with id {}."", requestDescriptor, requestId); }","Issue 6664: Caching of Request Ids for Request Tracker causes OOM on Controller (#6665) Limit max number of parallel request ids for a given request descriptor in RequestTracker. Reduced max number of entries in RequestTracker cache from 1M to 100K. Signed-off-by: Raúl Gracia ",https://github.com/pravega/pravega/commit/d9bb37df9c8e6381eff3326681cf351b83fbf477,,,common/src/main/java/io/pravega/common/tracing/RequestTracker.java,3,java,False,2022-05-16T13:06:25Z "void nw_buf_free(nw_buf_pool *pool, nw_buf *buf) { if (pool->free < pool->free_total) { pool->free_arr[pool->free++] = buf; } else { uint32_t new_free_total = pool->free_total * 2; void *new_arr = realloc(pool->free_arr, new_free_total * sizeof(nw_buf *)); if (new_arr) { pool->free_total = new_free_total; pool->free_arr = new_arr; pool->free_arr[pool->free++] = buf; } else { free(buf); } } }","void nw_buf_free(nw_buf_pool *pool, nw_buf *buf) { if (pool->free < pool->free_total) { pool->free_arr[pool->free++] = buf; } else if (pool->free_total < NW_BUF_POOL_MAX_SIZE) { uint32_t new_free_total = pool->free_total * 2; void *new_arr = realloc(pool->free_arr, new_free_total * sizeof(nw_buf *)); if (new_arr) { pool->free_total = new_free_total; pool->free_arr = new_arr; pool->free_arr[pool->free++] = buf; } else { free(buf); } } else { free(buf); } }","Merge pull request #131 from benjaminchodroff/master fix memory corruption and other 32bit overflows",https://github.com/viabtc/viabtc_exchange_server/commit/4a7c27bfe98f409623d4d857894d017ff0672cc9,,,network/nw_buf.c,3,c,False,2018-08-21T06:50:19Z "private ImmutableMap batchPrefetch(boolean throwIfPreviouslyRequestedDepsUndone) throws InterruptedException, UndonePreviouslyRequestedDep { ImmutableSet excludedKeys = evaluatorContext.getGraph().prefetchDeps(skyKey, oldDeps, previouslyRequestedDeps); Collection keysToPrefetch = excludedKeys != null ? excludedKeys : previouslyRequestedDeps.getAllElementsAsIterable(); NodeBatch batch = evaluatorContext.getGraph().getBatch(skyKey, Reason.PREFETCH, keysToPrefetch); ImmutableMap.Builder depValuesBuilder = ImmutableMap.builderWithExpectedSize(keysToPrefetch.size()); for (SkyKey depKey : keysToPrefetch) { NodeEntry entry = checkNotNull( batch.get(depKey), ""Missing previously requested dep %s (parent=%s)"", depKey, skyKey); SkyValue valueMaybeWithMetadata = entry.getValueMaybeWithMetadata(); boolean depDone = valueMaybeWithMetadata != null; if (throwIfPreviouslyRequestedDepsUndone && !depDone) { // A previously requested dep may have transitioned from done to dirty between when the node // was read during a previous attempt to build this node and now. Notify the graph // inconsistency receiver so that we can crash if that's unexpected. evaluatorContext .getGraphInconsistencyReceiver() .noteInconsistencyAndMaybeThrow( skyKey, ImmutableList.of(depKey), Inconsistency.BUILDING_PARENT_FOUND_UNDONE_CHILD); throw new UndonePreviouslyRequestedDep(depKey); } depValuesBuilder.put(depKey, !depDone ? NULL_MARKER : valueMaybeWithMetadata); if (depDone) { maybeUpdateMaxTransitiveSourceVersion(entry); } } return depValuesBuilder.buildOrThrow(); }","private ImmutableMap batchPrefetch(boolean throwIfPreviouslyRequestedDepsUndone) throws InterruptedException, UndonePreviouslyRequestedDeps { ImmutableSet excludedKeys = evaluatorContext.getGraph().prefetchDeps(skyKey, oldDeps, previouslyRequestedDeps); Collection keysToPrefetch = excludedKeys != null ? excludedKeys : previouslyRequestedDeps.getAllElementsAsIterable(); NodeBatch batch = evaluatorContext.getGraph().getBatch(skyKey, Reason.PREFETCH, keysToPrefetch); ImmutableMap.Builder depValuesBuilder = ImmutableMap.builderWithExpectedSize(keysToPrefetch.size()); List missingRequestedDeps = null; for (SkyKey depKey : keysToPrefetch) { NodeEntry entry = batch.get(depKey); if (entry == null) { if (missingRequestedDeps == null) { missingRequestedDeps = new ArrayList<>(); } missingRequestedDeps.add(depKey); continue; } SkyValue valueMaybeWithMetadata = entry.getValueMaybeWithMetadata(); boolean depDone = valueMaybeWithMetadata != null; if (throwIfPreviouslyRequestedDepsUndone && !depDone) { // A previously requested dep may have transitioned from done to dirty between when the node // was read during a previous attempt to build this node and now. Notify the graph // inconsistency receiver so that we can crash if that's unexpected. evaluatorContext .getGraphInconsistencyReceiver() .noteInconsistencyAndMaybeThrow( skyKey, ImmutableList.of(depKey), Inconsistency.BUILDING_PARENT_FOUND_UNDONE_CHILD); throw new UndonePreviouslyRequestedDeps(ImmutableList.of(depKey)); } depValuesBuilder.put(depKey, !depDone ? NULL_MARKER : valueMaybeWithMetadata); if (depDone) { maybeUpdateMaxTransitiveSourceVersion(entry); } } if (missingRequestedDeps != null && !missingRequestedDeps.isEmpty()) { // Notify `GraphInconsistencyReceiver` when there are some dependencies missing from the graph // to check whether this is expected. evaluatorContext .getGraphInconsistencyReceiver() .noteInconsistencyAndMaybeThrow( skyKey, missingRequestedDeps, Inconsistency.ALREADY_DECLARED_CHILD_MISSING); throw new UndonePreviouslyRequestedDeps(null); // TODO(b/261019506): Please investigate whether it is possible // `throwIfPreviouslyRequestedDepsUndone` is false and how to prevent blaze from crashing if // possible. } return depValuesBuilder.buildOrThrow(); }","Handle crashes when `SkyFunctionEnvironment#batchPrefetch()` cannot find dependency for the given `SkyKey` https://github.com/bazelbuild/bazel/commit/658ba15d9f37969edfaae507d267ee3aaba8b44e introduced flag `--experimental_heuristically_drop_nodes` and started to drop `FILE_STATE` or `DIRECTORY_LISTING_STATE` node after the corresponding `FILE` or `DIRECTORY_LISTING` node is evaluated. However, this causes blaze crash due to `SkyFunctionEnvironment#batchPrefetch()` method currently has a hard `checkNotNull` check on node dependency. In order to gracefully avoid crash, this CL implements the following features: * Enhance `GraphInconsistencyReceiver` to tolerate inconsistency caused by heuristically dropping state nodes: * Implement `isExpectedInconsistency` static method which checks the input inconsistency is caused by heuristically dropping state nodes; * Create a new `NodeDroppingInconsistencyReceiver` to replace `GraphInconsistencyReceiver.THROWING` when `--experimental_heuristically_drop_nodes` is enabled; * Enhance `RewindableGraphInconsistencyReceiver` to reflect additional tolerance in case `--experimental_heuristically_drop_nodes` is enabled; * Update `SkyFunctionEnvironment#batchPrefetch()` method so as not to crash blaze by utilizing the updated `GraphInconsistencyReceiver` Integration tests are added to both `SkyframeIntegrationTest` and `SkybuildV2NoBuildIntegrationTest` to verify that blaze will not crash when needed file state file is missing. PiperOrigin-RevId: 498178625 Change-Id: I76ed00a1b03e90193c1484b79e6651a3980d64b6",https://github.com/bazelbuild/bazel/commit/abb402e82fa680f5b22fdf54e978bc6a644209e4,,,src/main/java/com/google/devtools/build/skyframe/SkyFunctionEnvironment.java,3,java,False,2022-12-28T15:27:30Z "public static ForeignException forThrowable(Throwable exception, BinaryMarshaller marshaller) { ByteArrayBinaryOutput out = ByteArrayBinaryOutput.create(marshaller.inferSize(exception)); marshaller.write(out, exception); return new ForeignException(out.getArray(), UNDEFINED, false); }","public static ForeignException forThrowable(Throwable exception, BinaryMarshaller marshaller) { try { ByteArrayBinaryOutput out = ByteArrayBinaryOutput.create(marshaller.inferSize(exception)); marshaller.write(out, exception); return new ForeignException(out.getArray(), UNDEFINED, false); } catch (ThreadDeath td) { throw td; } catch (Throwable t) { // Exception marshalling failed, prevent exception propagation from CEntryPoint that // may cause process crash. JNIUtil.trace(2, t); return MARSHALLING_FAILED; } }","Removed suppport for exception of the same type from JNIExceptionWrapper. Removed non needed call to createString when JNI tracing is disabled. Prevent process crash in case of throwable marshaller failure.",https://github.com/oracle/graal/commit/89d0be2502461cfb7c31f3bc0602c3c776c9b540,,,compiler/src/org.graalvm.nativebridge/src/org/graalvm/nativebridge/ForeignException.java,3,java,False,2022-04-07T13:02:28Z "@CEntryPoint @CEntryPointOptions(prologue = AgentIsolate.Prologue.class) private static void onBreakpoint(@SuppressWarnings(""unused"") JvmtiEnv jvmti, JNIEnvironment jni, JNIObjectHandle thread, JNIMethodId method, @SuppressWarnings(""unused"") long location) { if (recursive.get()) { return; } recursive.set(true); try { JNIObjectHandle rectifiedThread = rectifyCurrentThread(thread); Breakpoint bp = installedBreakpoints.get(method.rawValue()); InterceptedState state = interceptedStateSupplier.get(); if (bp.specification.handler.dispatch(jni, rectifiedThread, bp, state)) { guarantee(!testException(jni)); } } catch (Throwable t) { VMError.shouldNotReachHere(t); } finally { recursive.set(false); } }","@CEntryPoint @CEntryPointOptions(prologue = AgentIsolate.Prologue.class) private static void onBreakpoint(@SuppressWarnings(""unused"") JvmtiEnv jvmti, JNIEnvironment jni, JNIObjectHandle thread, JNIMethodId method, @SuppressWarnings(""unused"") long location) { if (recursive.get()) { return; } recursive.set(true); try { JNIObjectHandle rectifiedThread = rectifyCurrentThread(thread); if (rectifiedThread.equal(nullHandle())) { return; } Breakpoint bp = installedBreakpoints.get(method.rawValue()); InterceptedState state = interceptedStateSupplier.get(); if (bp.specification.handler.dispatch(jni, rectifiedThread, bp, state)) { guarantee(!testException(jni)); } } catch (Throwable t) { VMError.shouldNotReachHere(t); } finally { recursive.set(false); } }",Avoid crashing the JVM if getCurrentThread is called in the wrong phase during a breakpoint,https://github.com/oracle/graal/commit/b9388019bcc46eaa24ccd6638f5a80e66b9ebdb5,,,substratevm/src/com.oracle.svm.agent/src/com/oracle/svm/agent/BreakpointInterceptor.java,3,java,False,2022-10-19T11:14:29Z "private void initOriginalAppComponentFactory(ApplicationInfo aInfo) { final String originPath = aInfo.dataDir + ""/cache/lspatch/origin/""; final String originalAppComponentFactoryClass = FileUtils.readTextFromInputStream(baseClassLoader.getResourceAsStream(ORIGINAL_APP_COMPONENT_FACTORY_ASSET_PATH)); try { String cacheApkPath; try (ZipFile sourceFile = new ZipFile(aInfo.sourceDir)) { cacheApkPath = originPath + sourceFile.getEntry(ORIGINAL_APK_ASSET_PATH).getCrc(); } if (!Files.exists(Paths.get(cacheApkPath))) { Log.i(TAG, ""extract original apk""); FileUtils.deleteFolderIfExists(Paths.get(originPath)); Files.createDirectories(Paths.get(originPath)); try (InputStream is = baseClassLoader.getResourceAsStream(ORIGINAL_APK_ASSET_PATH)) { Files.copy(is, Paths.get(cacheApkPath)); } } appClassLoader = new PathClassLoader(cacheApkPath, aInfo.nativeLibraryDir, baseClassLoader.getParent()); try { originalAppComponentFactory = (AppComponentFactory) appClassLoader.loadClass(originalAppComponentFactoryClass).newInstance(); } catch (ClassNotFoundException | NullPointerException ignored) { if (originalAppComponentFactoryClass != null && !originalAppComponentFactoryClass.isEmpty()) Log.w(TAG, ""original AppComponentFactory not found""); originalAppComponentFactory = new AppComponentFactory(); } Log.d(TAG, ""instantiate original AppComponentFactory: "" + originalAppComponentFactory); } catch (Throwable e) { Log.e(TAG, ""initOriginalAppComponentFactory"", e); } }","private void initOriginalAppComponentFactory(ApplicationInfo aInfo) { final String originPath = aInfo.dataDir + ""/cache/lspatch/origin/""; final String originalAppComponentFactoryClass = FileUtils.readTextFromInputStream(baseClassLoader.getResourceAsStream(ORIGINAL_APP_COMPONENT_FACTORY_ASSET_PATH)); try { String cacheApkPath; try (ZipFile sourceFile = new ZipFile(aInfo.sourceDir)) { cacheApkPath = originPath + sourceFile.getEntry(ORIGINAL_APK_ASSET_PATH).getCrc(); } if (!Files.exists(Paths.get(cacheApkPath))) { Log.i(TAG, ""extract original apk""); FileUtils.deleteFolderIfExists(Paths.get(originPath)); Files.createDirectories(Paths.get(originPath)); try (InputStream is = baseClassLoader.getResourceAsStream(ORIGINAL_APK_ASSET_PATH)) { Files.copy(is, Paths.get(cacheApkPath)); } } appClassLoader = new DelegateLastClassLoader(cacheApkPath, aInfo.nativeLibraryDir, baseClassLoader); try { originalAppComponentFactory = (AppComponentFactory) appClassLoader.loadClass(originalAppComponentFactoryClass).newInstance(); } catch (ClassNotFoundException | NullPointerException ignored) { if (originalAppComponentFactoryClass != null && !originalAppComponentFactoryClass.isEmpty()) Log.w(TAG, ""original AppComponentFactory not found""); originalAppComponentFactory = new AppComponentFactory(); } Log.d(TAG, ""instantiate original AppComponentFactory: "" + originalAppComponentFactory); } catch (Throwable e) { Log.e(TAG, ""initOriginalAppComponentFactory"", e); } }",Fix signature bypass,https://github.com/LSPosed/LSPatch/commit/fa4f4cecffce0475b81071bc34a6aa35bd2a9261,,,appstub/src/main/java/org/lsposed/lspatch/appstub/LSPAppComponentFactoryStub.java,3,java,False,2021-09-11T18:57:03Z "@Override public void handle(Data data) { OkHttpClient client = new OkHttpClient.Builder().build(); try { Response request = client.newCall( new Request.Builder() .url(""https://authserver.mojang.com/authenticate"") .post(RequestBody.create(new Gson().toJson(new RequestData(data.username, data.password, data.clientToken)), MediaType.parse(""application/json""))) .addHeader(""Content-Type"", ""application/json"") .addHeader(""User-Agent"", ""FTB App Subprocess/1.0"") .addHeader(""Accept"", ""application/json"") .build() ).execute(); ResponseBody body = request.body(); if (body != null) { String response = body.string(); if (response.contains(""error"")) { Settings.webSocketAPI.sendMessage(new Reply(data, false, response)); return; } Settings.webSocketAPI.sendMessage(new Reply(data, true, response)); return; } } catch (IOException e) { e.printStackTrace(); Settings.webSocketAPI.sendMessage(new Reply(data, false, """")); } Settings.webSocketAPI.sendMessage(new Reply(data, false, """")); }","@Override public void handle(Data data) { OkHttpClient client = new OkHttpClient.Builder().build(); try { Response request = client.newCall( new Request.Builder() .url(""https://authserver.mojang.com/authenticate"") .post(RequestBody.create(new Gson().toJson(new RequestData(data.username, data.password, UUID.randomUUID().toString())), MediaType.parse(""application/json""))) .addHeader(""Content-Type"", ""application/json"") .addHeader(""User-Agent"", ""FTB App Subprocess/1.0"") .addHeader(""Accept"", ""application/json"") .build() ).execute(); ResponseBody body = request.body(); if (body != null) { String response = body.string(); if (response.contains(""error"")) { Settings.webSocketAPI.sendMessage(new Reply(data, false, response)); return; } Settings.webSocketAPI.sendMessage(new Reply(data, true, response)); return; } } catch (IOException e) { e.printStackTrace(); Settings.webSocketAPI.sendMessage(new Reply(data, false, """")); } Settings.webSocketAPI.sendMessage(new Reply(data, false, """")); }","fix: Mojang auth clientToken, resolved issue with refresh check",https://github.com/FTBTeam/FTB-App/commit/c52e11dc88332a9b61a2890e889f949bd4bd2a4d,,,subprocess/src/main/java/net/creeperhost/creeperlauncher/api/handlers/profiles/AuthenticateMcProfileHandler.java,3,java,False,2021-12-11T19:01:46Z "@RequiresPermission(android.Manifest.permission.SET_WALLPAPER) public int setResource(@RawRes int resid, @SetWallpaperFlags int which) throws IOException { if (sGlobals.mService == null) { Log.w(TAG, ""WallpaperService not running""); throw new RuntimeException(new DeadSystemException()); } final Bundle result = new Bundle(); final WallpaperSetCompletion completion = new WallpaperSetCompletion(); try { Resources resources = mContext.getResources(); /* Set the wallpaper to the default values */ ParcelFileDescriptor fd = sGlobals.mService.setWallpaper( ""res:"" + resources.getResourceName(resid), mContext.getOpPackageName(), null, false, result, which, completion, mContext.getUserId()); if (fd != null) { FileOutputStream fos = null; boolean ok = false; try { fos = new ParcelFileDescriptor.AutoCloseOutputStream(fd); copyStreamToWallpaperFile(resources.openRawResource(resid), fos); // The 'close()' is the trigger for any server-side image manipulation, // so we must do that before waiting for completion. fos.close(); completion.waitForCompletion(); } finally { // Might be redundant but completion shouldn't wait unless the write // succeeded; this is a fallback if it threw past the close+wait. IoUtils.closeQuietly(fos); } } } catch (RemoteException e) { throw e.rethrowFromSystemServer(); } return result.getInt(EXTRA_NEW_WALLPAPER_ID, 0); }","@RequiresPermission(android.Manifest.permission.SET_WALLPAPER) public int setResource(@RawRes int resid, @SetWallpaperFlags int which) throws IOException { if (sGlobals.mService == null) { Log.w(TAG, ""WallpaperService not running""); throw new RuntimeException(new DeadSystemException()); } final Bundle result = new Bundle(); final WallpaperSetCompletion completion = new WallpaperSetCompletion(); try { Resources resources = mContext.getResources(); /* Set the wallpaper to the default values */ ParcelFileDescriptor fd = sGlobals.mService.setWallpaper( ""res:"" + resources.getResourceName(resid), mContext.getOpPackageName(), null, false, result, which, completion, mContext.getUserId()); if (fd != null) { FileOutputStream fos = null; final Bitmap tmp = BitmapFactory.decodeStream(resources.openRawResource(resid)); try { // If the stream can't be decoded, treat it as an invalid input. if (tmp != null) { fos = new ParcelFileDescriptor.AutoCloseOutputStream(fd); tmp.compress(Bitmap.CompressFormat.PNG, 100, fos); // The 'close()' is the trigger for any server-side image manipulation, // so we must do that before waiting for completion. fos.close(); completion.waitForCompletion(); } else { throw new IllegalArgumentException( ""Resource 0x"" + Integer.toHexString(resid) + "" is invalid""); } } finally { // Might be redundant but completion shouldn't wait unless the write // succeeded; this is a fallback if it threw past the close+wait. IoUtils.closeQuietly(fos); if (tmp != null) { tmp.recycle(); } } } } catch (RemoteException e) { throw e.rethrowFromSystemServer(); } return result.getInt(EXTRA_NEW_WALLPAPER_ID, 0); }","DO NOT MERGE: Decode the input of both setStream and setResource calls first The size of the input of both setStream and setResource may very big that system server got oom while handling it, so we try to decode it first before copying it to the wallpaper path, if the decoding fails, we treat the input as an invalid input. Bug: 204087139 Test: Manually set wallpaper, no PDoS observed. Change-Id: I014cf461954992782b3dfa0dde67c98a572cc770 (cherry picked from commit 51b874f628dc45d99d10ce84694277e33a736894) Merged-In:I014cf461954992782b3dfa0dde67c98a572cc770",https://github.com/PixelExperience/frameworks_base/commit/d4e49cbca57e2f4f2dee74138b56fe3fbcaf0261,,,core/java/android/app/WallpaperManager.java,3,java,False,2021-12-02T08:23:26Z "@Override public String getParameter(String parameter) { String value = super.getParameter(parameter); if (parameter.startsWith(NOFILTER)) return value; String rv = stripXSS(value, parameterValuePattern); if (value != null && rv == null) { Log log = I2PAppContext.getGlobalContext().logManager().getLog(XSSRequestWrapper.class); log.logAlways(Log.WARN, ""URL \"""" + getServletPath() + ""\"" Stripped param \"""" + parameter + ""\"" : \"""" + value + '""'); } return rv; }","@Override public String getParameter(String parameter) { String value = super.getParameter(parameter); if (parameter.startsWith(NOFILTER) || parameter.startsWith(NOFILTER2)) return value; String rv = stripXSS(value, parameterValuePattern); if (value != null && rv == null) { Log log = I2PAppContext.getGlobalContext().logManager().getLog(XSSRequestWrapper.class); log.logAlways(Log.WARN, ""URL \"""" + getServletPath() + ""\"" Stripped param \"""" + parameter + ""\"" : \"""" + value + '""'); } return rv; }","i2psnark: Rename search param to bypass the XSS filter Fix encode/decode search param Copy CSS to non-default themes, not tweaked yet Add support for shorter nf_ prefix to XSS filter Remove unneeded float_right, reported by drzed",https://github.com/i2p/i2p.i2p/commit/0cbbe6297e2f2079fcb33b7b1da23b94c8f83f4f,,,apps/jetty/java/src/net/i2p/servlet/filters/XSSRequestWrapper.java,3,java,False,2023-01-18T17:21:29Z "public static int deleteTab(int id) { if (id >= availableTabs.size()) return 0; availableTabs.remove(id); saveConfigs(); return id == 0 ? 0 : id - 1; }","public static int deleteTab(int id) { if (id >= availableTabs.size()) return 0; ChatTab removed = availableTabs.get(id); availableTabs.remove(id); FrameworkManager.getEventBus().post(new ChatTabsUpdatedEvent.TabAdded(removed)); saveConfigs(); return id == 0 ? 0 : id - 1; }","Fix 14 issues found in ticket backlog (#502) * Fix IndexOutOfBoundsException in QuestBookListPage Signed-off-by: kristofbolyai * Fix crash if OverlayConfig.GameUpdate.INSTANCE.messageMaxLength is 1 Signed-off-by: kristofbolyai * Fix crash related to deleting chat tabs and ChatGUI not updating Signed-off-by: kristofbolyai * Fix crash related to deleting chat tabs and ChatGUI not updating Signed-off-by: kristofbolyai * Fix translation cache becoming null Signed-off-by: kristofbolyai * Fix objective parsing if player is in party Signed-off-by: kristofbolyai * Fix guild objective not being removed upon completion Signed-off-by: kristofbolyai * Fix race condition in ServerEvents Signed-off-by: kristofbolyai * Fix race condition in ClientEvents Signed-off-by: kristofbolyai * Fix NPE in ServerEvents Signed-off-by: kristofbolyai * Fix AreaDPS value not being correct Signed-off-by: kristofbolyai * Fix NPE in fix :) Signed-off-by: kristofbolyai * Fix quest dialogue spoofing Signed-off-by: kristofbolyai * Fix Keyholder related crash Signed-off-by: kristofbolyai * Fix totem tracking Signed-off-by: kristofbolyai * Dialogue Page gets updated correctly Signed-off-by: kristofbolyai * Register ChatGUI correctly Signed-off-by: kristofbolyai * Use MC's GameSettings to check for isKeyDown Signed-off-by: kristofbolyai * Make multi line if have braces Signed-off-by: kristofbolyai ",https://github.com/Wynntils/Wynntils/commit/c8f6effe187ff68f17bcff809d2bc440ec07128d,,,src/main/java/com/wynntils/modules/chat/managers/TabManager.java,3,java,False,2022-04-15T17:16:00Z "@Override public void confirmUserAttribute( @NonNull AuthUserAttributeKey attributeKey, @NonNull String confirmationCode, @NonNull Action onSuccess, @NonNull Consumer onError ) { awsMobileClient.confirmUpdateUserAttribute( attributeKey.getKeyString(), confirmationCode, new Callback() { @Override public void onResult(Void result) { onSuccess.call(); } @Override public void onError(Exception error) { onError.accept(new AuthException( ""An error occurred confirming user attribute"", error, ""See attached exception for more details"" )); } }); }","@Override public void confirmUserAttribute( @NonNull AuthUserAttributeKey attributeKey, @NonNull String confirmationCode, @NonNull Action onSuccess, @NonNull Consumer onError ) { awsMobileClient.confirmUpdateUserAttribute( attributeKey.getKeyString(), confirmationCode, new Callback() { @Override public void onResult(Void result) { onSuccess.call(); } @Override public void onError(Exception error) { onError.accept(CognitoAuthExceptionConverter.lookup( error, ""Confirming user attributes failed."")); } }); }","fix(auth): throw correct auth exception for code mismatch (#1370) * fix(auth): #1102 throw correct auth exception for code mismatch * Add multifactor not found auth exception with detailed messaging * Update aws-auth-cognito/src/main/java/com/amplifyframework/auth/cognito/util/CognitoAuthExceptionConverter.java Co-authored-by: Chang Xu <42978935+changxu0306@users.noreply.github.com> * move to fit import rule * float all generic errors to exception mapper * add software token mfa exception * add more missing exceptions * reorder imports as per checkstyle * Update core/src/main/java/com/amplifyframework/auth/AuthException.java Co-authored-by: Chang Xu <42978935+changxu0306@users.noreply.github.com> * Update core/src/main/java/com/amplifyframework/auth/AuthException.java Co-authored-by: Chang Xu <42978935+changxu0306@users.noreply.github.com> * fix documentation description * fix checkstyle errors Co-authored-by: Chang Xu <42978935+changxu0306@users.noreply.github.com>",https://github.com/aws-amplify/amplify-android/commit/4cd7cfee41bac3635974149b4ca6dd269e0cc19b,,,aws-auth-cognito/src/main/java/com/amplifyframework/auth/cognito/AWSCognitoAuthPlugin.java,3,java,False,2021-06-11T21:51:07Z "@UserFunction(""apoc.convert.toJson"") @Description(""apoc.convert.toJson([1,2,3]) or toJson({a:42,b:\""foo\"",c:[1,2,3]})"") public String toJson(@Name(""value"") Object value) { try { return JsonUtil.OBJECT_MAPPER.writeValueAsString(value); } catch (IOException e) { throw new RuntimeException(""Can't convert "" + value + "" to json"", e); } }","@UserFunction(""apoc.convert.toJson"") @Description(""apoc.convert.toJson([1,2,3]) or toJson({a:42,b:\""foo\"",c:[1,2,3]}) or toJson(NODE/REL/PATH)"") public String toJson(@Name(""value"") Object value) { try { return JsonUtil.OBJECT_MAPPER.writeValueAsString(writeJsonResult(value)); } catch (IOException e) { throw new RuntimeException(""Can't convert "" + value + "" to json"", e); } }",Fixes #1711: Invoking apoc.convert.toJson with a Node causes StackOverflow (#1795),https://github.com/neo4j/apoc/commit/65ba809404c3ff29058cc3f90e6c367ebe25bcef,,,core/src/main/java/apoc/convert/Json.java,3,java,False,2021-02-19T14:35:25Z "public void launchSideTaskInLiveTileModeForRestartedApp(int taskId) { int runningTaskViewId = getTaskViewIdFromTaskId(taskId); if (mRunningTaskViewId != -1 && mRunningTaskViewId == runningTaskViewId) { TransformParams params = mRemoteTargetHandles[0].getTransformParams(); RemoteAnimationTargets targets = params.getTargetSet(); if (targets != null && targets.findTask(taskId) != null) { launchSideTaskInLiveTileMode(taskId, targets.apps, targets.wallpapers, targets.nonApps); } } }","public void launchSideTaskInLiveTileModeForRestartedApp(int taskId) { int runningTaskViewId = getTaskViewIdFromTaskId(taskId); if (mRunningTaskViewId == -1 || mRunningTaskViewId != runningTaskViewId || mRemoteTargetHandles == null) { return; } TransformParams params = mRemoteTargetHandles[0].getTransformParams(); RemoteAnimationTargets targets = params.getTargetSet(); if (targets != null && targets.findTask(taskId) != null) { launchSideTaskInLiveTileMode(taskId, targets.apps, targets.wallpapers, targets.nonApps); } }","Add null check for mRemoteTargetHandles for side task launch * Other checks haven't changed, only pulled them out into separate block Fixes: 215699962 Test: Unable to repro the crash, I tried ending the activity and starting via adb shell, but I was never able to get into the original if-block that triggered the NPE Change-Id: I83320634f1d059de610176f9031682ca287bd589",https://github.com/LineageOS/android_packages_apps_Trebuchet/commit/90e0fe39237b57d6d61715db00d27e09db186e7e,,,quickstep/src/com/android/quickstep/views/RecentsView.java,3,java,False,2022-02-09T23:30:19Z "private void checkAuthorizedScripts(List scripts) { updateAuthorizedScriptsSignatures(); if (authorizedSelectionScripts == null || scripts == null) return; for (SelectionScript script : scripts) { checkContentAuthorization(script.fetchScript()); } }","private boolean checkAuthorizedScripts(List scripts) { updateAuthorizedScriptsSignatures(); if (authorizedSelectionScripts == null || scripts == null) return true; boolean allAuthorized = true; for (SelectionScript script : scripts) { allAuthorized = allAuthorized && checkContentAuthorization(script.fetchScript()); } return allAuthorized; }",Merge branch '10.0.X' of https://github.com/ow2-proactive/scheduling into 10.0.X,https://github.com/ow2-proactive/scheduling/commit/ee168dafd02ba77e873ddb98a9e9d563901f630f,,,rm/rm-server/src/main/java/org/ow2/proactive/resourcemanager/selection/SelectionManager.java,3,java,False,2021-01-15T12:20:47Z "protected Beacon fromScanData(byte[] bytesToProcess, int rssi, BluetoothDevice device, long timestampMs, Beacon beacon) { BleAdvertisement advert = new BleAdvertisement(bytesToProcess); boolean parseSucceeded = false; ArrayList pdusToParse = new ArrayList(); int startByte = 0; ArrayList identifiers = new ArrayList(); ArrayList dataFields = new ArrayList(); int txPower = 0; for (Pdu pdu: advert.getPdus()) { if ((pdu.getType() == Pdu.GATT_SERVICE_UUID_PDU_TYPE && mServiceUuid != null) || (pdu.getType() == Pdu.GATT_SERVICE_UUID_128_BIT_PDU_TYPE && mServiceUuid128Bit.length != 0) || pdu.getType() == Pdu.MANUFACTURER_DATA_PDU_TYPE) { pdusToParse.add(pdu); if (LogManager.isVerboseLoggingEnabled()) { LogManager.d(TAG, ""Processing pdu type %02X: %s with startIndex: %d, endIndex: %d"", pdu.getType(), bytesToHex(bytesToProcess), pdu.getStartIndex(), pdu.getEndIndex()); } } else { if (LogManager.isVerboseLoggingEnabled()) { LogManager.d(TAG, ""Ignoring pdu type %02X"", pdu.getType()); } } } if (pdusToParse.size() == 0) { if (LogManager.isVerboseLoggingEnabled()) { LogManager.d(TAG, ""No PDUs to process in this packet.""); } } else { boolean parseFailed = false; for (Pdu pduToParse : pdusToParse) { byte[] serviceUuidBytes = null; byte[] typeCodeBytes = {}; if (mMatchingBeaconTypeCodeEndOffset != null && mMatchingBeaconTypeCodeStartOffset >= 0) { typeCodeBytes = longToByteArray(getMatchingBeaconTypeCode(), mMatchingBeaconTypeCodeEndOffset - mMatchingBeaconTypeCodeStartOffset + 1); } serviceUuidBytes = getServiceUuid128Bit(); if (getServiceUuid() != null) { serviceUuidBytes = longToByteArray(getServiceUuid(), mServiceUuidEndOffset - mServiceUuidStartOffset + 1, false); } startByte = pduToParse.getStartIndex(); boolean patternFound = false; if (serviceUuidBytes.length == 0) { if (mMatchingBeaconTypeCodeEndOffset != null) { if (byteArraysMatch(bytesToProcess, startByte + mMatchingBeaconTypeCodeStartOffset, typeCodeBytes)) { patternFound = true; } } } else { boolean lengthIsExpected = false; if (pduToParse.getType() == Pdu.GATT_SERVICE_UUID_128_BIT_PDU_TYPE) { if (serviceUuidBytes.length == 16) { lengthIsExpected = true; } } if (pduToParse.getType() == Pdu.GATT_SERVICE_UUID_PDU_TYPE) { if (serviceUuidBytes.length == 2) { lengthIsExpected = true; } } if (lengthIsExpected) { if (byteArraysMatch(bytesToProcess, startByte + mServiceUuidStartOffset, serviceUuidBytes)) { if (mMatchingBeaconTypeCodeEndOffset != null) { if (byteArraysMatch(bytesToProcess, startByte + mMatchingBeaconTypeCodeStartOffset, typeCodeBytes)) { patternFound = true; } } else { if (pduToParse.getType() == Pdu.GATT_SERVICE_UUID_PDU_TYPE || pduToParse.getType() == Pdu.GATT_SERVICE_UUID_128_BIT_PDU_TYPE) { patternFound = true; } } } } } if (patternFound == false) { // This is not a beacon if (getServiceUuid() != null || getServiceUuid128Bit().length != 0) { if (LogManager.isVerboseLoggingEnabled()) { int offset = 0; if (mMatchingBeaconTypeCodeStartOffset != null) { offset = mMatchingBeaconTypeCodeStartOffset; } LogManager.d(TAG, ""This is not a matching Beacon advertisement. Was expecting %s at offset %d and %s at offset %d. "" + ""The bytes I see are: %s"", byteArrayToString(serviceUuidBytes), startByte + mServiceUuidStartOffset, byteArrayToString(typeCodeBytes), startByte + offset, bytesToHex(bytesToProcess)); } } else { if (LogManager.isVerboseLoggingEnabled()) { LogManager.d(TAG, ""This is not a matching Beacon advertisement. (Was expecting %s. "" + ""The bytes I see are: %s"", byteArrayToString(typeCodeBytes), bytesToHex(bytesToProcess)); } } } else { if (LogManager.isVerboseLoggingEnabled()) { LogManager.d(TAG, ""This is a recognized beacon advertisement -- %s seen"", byteArrayToString(typeCodeBytes)); LogManager.d(TAG, ""Bytes are: %s"", bytesToHex(bytesToProcess)); } } if (patternFound) { if (bytesToProcess.length <= startByte+mLayoutSize && mAllowPduOverflow) { // If the layout size is bigger than this PDU, and we allow overflow. Make sure // the byte buffer is big enough by zero padding the end so we don't try to read // outside the byte array of the advertisement if (LogManager.isVerboseLoggingEnabled()) { LogManager.d(TAG, ""Expanding buffer because it is too short to parse: ""+bytesToProcess.length+"", needed: ""+(startByte+mLayoutSize)); } bytesToProcess = ensureMaxSize(bytesToProcess, startByte+mLayoutSize); } for (int i = 0; i < mIdentifierEndOffsets.size(); i++) { int endIndex = mIdentifierEndOffsets.get(i) + startByte; if (endIndex > pduToParse.getEndIndex() && mIdentifierVariableLengthFlags.get(i)) { if (LogManager.isVerboseLoggingEnabled()) { LogManager.d(TAG, ""Need to truncate identifier by ""+(endIndex-pduToParse.getEndIndex())); } // If this is a variable length identifier, we truncate it to the size that // is available in the packet int start = mIdentifierStartOffsets.get(i) + startByte; int end = pduToParse.getEndIndex()+1; if (end <= start) { LogManager.d(TAG, ""PDU is too short for identifer. Packet is malformed""); return null; } Identifier identifier = Identifier.fromBytes(bytesToProcess, start, end, mIdentifierLittleEndianFlags.get(i)); identifiers.add(identifier); } else if (endIndex > pduToParse.getEndIndex() && !mAllowPduOverflow) { parseFailed = true; if (LogManager.isVerboseLoggingEnabled()) { LogManager.d(TAG, ""Cannot parse identifier ""+i+"" because PDU is too short. endIndex: "" + endIndex + "" PDU endIndex: "" + pduToParse.getEndIndex()); } } else { Identifier identifier = Identifier.fromBytes(bytesToProcess, mIdentifierStartOffsets.get(i) + startByte, endIndex+1, mIdentifierLittleEndianFlags.get(i)); identifiers.add(identifier); } } for (int i = 0; i < mDataEndOffsets.size(); i++) { int endIndex = mDataEndOffsets.get(i) + startByte; if (endIndex > pduToParse.getEndIndex() && !mAllowPduOverflow) { if (LogManager.isVerboseLoggingEnabled()) { LogManager.d(TAG, ""Cannot parse data field ""+i+"" because PDU is too short. endIndex: "" + endIndex + "" PDU endIndex: "" + pduToParse.getEndIndex()+"". Setting value to 0""); } dataFields.add(new Long(0l)); } else { String dataString = byteArrayToFormattedString(bytesToProcess, mDataStartOffsets.get(i) + startByte, endIndex, mDataLittleEndianFlags.get(i)); dataFields.add(Long.decode(dataString)); } } if (mPowerStartOffset != null) { int endIndex = mPowerEndOffset + startByte; try { if (endIndex > pduToParse.getEndIndex() && !mAllowPduOverflow) { parseFailed = true; if (LogManager.isVerboseLoggingEnabled()) { LogManager.d(TAG, ""Cannot parse power field because PDU is too short. endIndex: "" + endIndex + "" PDU endIndex: "" + pduToParse.getEndIndex()); } } else { String powerString = byteArrayToFormattedString(bytesToProcess, mPowerStartOffset + startByte, mPowerEndOffset + startByte, false); txPower = Integer.parseInt(powerString)+mDBmCorrection; // make sure it is a signed integer if (txPower > 127) { txPower -= 256; } } } catch (NumberFormatException e1) { // keep default value } catch (NullPointerException e2) { // keep default value } } else { if (mDBmCorrection != null) { txPower = mDBmCorrection; } } if (!parseFailed) { parseSucceeded = true; // exit processing PDUs on the first beacon we find. Only one beacon per advertisement! break; } } } } if (parseSucceeded) { int beaconTypeCode = -1; if (mMatchingBeaconTypeCodeEndOffset != null) { String beaconTypeString = byteArrayToFormattedString(bytesToProcess, mMatchingBeaconTypeCodeStartOffset+startByte, mMatchingBeaconTypeCodeEndOffset+startByte, false); beaconTypeCode = Integer.parseInt(beaconTypeString); } int manufacturer = 0; String manufacturerString = byteArrayToFormattedString(bytesToProcess, startByte, startByte+1, true); manufacturer = Integer.parseInt(manufacturerString); String macAddress = null; String name = null; if (device != null) { macAddress = device.getAddress(); name = device.getName(); } beacon.mIdentifiers = identifiers; beacon.mDataFields = dataFields; beacon.mRssi = rssi; beacon.mBeaconTypeCode = beaconTypeCode; if (mServiceUuid != null) { beacon.mServiceUuid = (int) mServiceUuid.longValue(); } else { beacon.mServiceUuid = -1; } beacon.mBluetoothAddress = macAddress; beacon.mBluetoothName= name; beacon.mManufacturer = manufacturer; beacon.mParserIdentifier = mIdentifier; beacon.mMultiFrameBeacon = extraParsers.size() > 0 || mExtraFrame; beacon.mFirstCycleDetectionTimestamp = timestampMs; beacon.mLastCycleDetectionTimestamp = timestampMs; beacon.mTxPower = txPower; return beacon; } else { return null; } }","protected Beacon fromScanData(byte[] bytesToProcess, int rssi, BluetoothDevice device, long timestampMs, Beacon beacon) { BleAdvertisement advert = new BleAdvertisement(bytesToProcess); boolean parseSucceeded = false; ArrayList pdusToParse = new ArrayList(); int startByte = 0; ArrayList identifiers = new ArrayList(); ArrayList dataFields = new ArrayList(); int txPower = 0; for (Pdu pdu: advert.getPdus()) { if ((pdu.getType() == Pdu.GATT_SERVICE_UUID_PDU_TYPE && mServiceUuid != null) || (pdu.getType() == Pdu.GATT_SERVICE_UUID_128_BIT_PDU_TYPE && mServiceUuid128Bit.length != 0) || pdu.getType() == Pdu.MANUFACTURER_DATA_PDU_TYPE) { pdusToParse.add(pdu); if (LogManager.isVerboseLoggingEnabled()) { LogManager.d(TAG, ""Processing pdu type %02X: %s with startIndex: %d, endIndex: %d"", pdu.getType(), bytesToHex(bytesToProcess), pdu.getStartIndex(), pdu.getEndIndex()); } } else { if (LogManager.isVerboseLoggingEnabled()) { LogManager.d(TAG, ""Ignoring pdu type %02X"", pdu.getType()); } } } if (pdusToParse.size() == 0) { if (LogManager.isVerboseLoggingEnabled()) { LogManager.d(TAG, ""No PDUs to process in this packet.""); } } else { boolean parseFailed = false; for (Pdu pduToParse : pdusToParse) { byte[] serviceUuidBytes = null; byte[] typeCodeBytes = {}; if (mMatchingBeaconTypeCodeEndOffset != null && mMatchingBeaconTypeCodeStartOffset >= 0) { typeCodeBytes = longToByteArray(getMatchingBeaconTypeCode(), mMatchingBeaconTypeCodeEndOffset - mMatchingBeaconTypeCodeStartOffset + 1); } serviceUuidBytes = getServiceUuid128Bit(); if (getServiceUuid() != null) { serviceUuidBytes = longToByteArray(getServiceUuid(), mServiceUuidEndOffset - mServiceUuidStartOffset + 1, false); } startByte = pduToParse.getStartIndex(); boolean patternFound = false; if (serviceUuidBytes.length == 0) { if (mMatchingBeaconTypeCodeEndOffset != null) { if (byteArraysMatch(bytesToProcess, startByte + mMatchingBeaconTypeCodeStartOffset, typeCodeBytes)) { patternFound = true; } } } else { boolean lengthIsExpected = false; if (pduToParse.getType() == Pdu.GATT_SERVICE_UUID_128_BIT_PDU_TYPE) { if (serviceUuidBytes.length == 16) { lengthIsExpected = true; } } if (pduToParse.getType() == Pdu.GATT_SERVICE_UUID_PDU_TYPE) { if (serviceUuidBytes.length == 2) { lengthIsExpected = true; } } if (lengthIsExpected) { if (byteArraysMatch(bytesToProcess, startByte + mServiceUuidStartOffset, serviceUuidBytes)) { if (mMatchingBeaconTypeCodeEndOffset != null) { if (byteArraysMatch(bytesToProcess, startByte + mMatchingBeaconTypeCodeStartOffset, typeCodeBytes)) { patternFound = true; } } else { if (pduToParse.getType() == Pdu.GATT_SERVICE_UUID_PDU_TYPE || pduToParse.getType() == Pdu.GATT_SERVICE_UUID_128_BIT_PDU_TYPE) { patternFound = true; } } } } } if (patternFound == false) { // This is not a beacon if (getServiceUuid() != null || getServiceUuid128Bit().length != 0) { if (LogManager.isVerboseLoggingEnabled()) { int offset = 0; if (mMatchingBeaconTypeCodeStartOffset != null) { offset = mMatchingBeaconTypeCodeStartOffset; } LogManager.d(TAG, ""This is not a matching Beacon advertisement. Was expecting %s at offset %d and %s at offset %d. "" + ""The bytes I see are: %s"", byteArrayToString(serviceUuidBytes), startByte + mServiceUuidStartOffset, byteArrayToString(typeCodeBytes), startByte + offset, bytesToHex(bytesToProcess)); } } else { if (LogManager.isVerboseLoggingEnabled()) { LogManager.d(TAG, ""This is not a matching Beacon advertisement. (Was expecting %s. "" + ""The bytes I see are: %s"", byteArrayToString(typeCodeBytes), bytesToHex(bytesToProcess)); } } } else { if (LogManager.isVerboseLoggingEnabled()) { LogManager.d(TAG, ""This is a recognized beacon advertisement -- %s seen"", byteArrayToString(typeCodeBytes)); LogManager.d(TAG, ""Bytes are: %s"", bytesToHex(bytesToProcess)); } } if (patternFound) { if (bytesToProcess.length <= startByte+mLayoutSize && mAllowPduOverflow) { // If the layout size is bigger than this PDU, and we allow overflow. Make sure // the byte buffer is big enough by zero padding the end so we don't try to read // outside the byte array of the advertisement if (LogManager.isVerboseLoggingEnabled()) { LogManager.d(TAG, ""Expanding buffer because it is too short to parse: ""+bytesToProcess.length+"", needed: ""+(startByte+mLayoutSize)); } bytesToProcess = ensureMaxSize(bytesToProcess, startByte+mLayoutSize); } for (int i = 0; i < mIdentifierEndOffsets.size(); i++) { int endIndex = mIdentifierEndOffsets.get(i) + startByte; if (endIndex > pduToParse.getEndIndex() && mIdentifierVariableLengthFlags.get(i)) { if (LogManager.isVerboseLoggingEnabled()) { LogManager.d(TAG, ""Need to truncate identifier by ""+(endIndex-pduToParse.getEndIndex())); } // If this is a variable length identifier, we truncate it to the size that // is available in the packet int start = mIdentifierStartOffsets.get(i) + startByte; int end = pduToParse.getEndIndex()+1; if (end <= start) { LogManager.d(TAG, ""PDU is too short for identifer. Packet is malformed""); return null; } Identifier identifier = Identifier.fromBytes(bytesToProcess, start, end, mIdentifierLittleEndianFlags.get(i)); identifiers.add(identifier); } else if (endIndex > pduToParse.getEndIndex() && !mAllowPduOverflow) { parseFailed = true; if (LogManager.isVerboseLoggingEnabled()) { LogManager.d(TAG, ""Cannot parse identifier ""+i+"" because PDU is too short. endIndex: "" + endIndex + "" PDU endIndex: "" + pduToParse.getEndIndex()); } } else { Identifier identifier = Identifier.fromBytes(bytesToProcess, mIdentifierStartOffsets.get(i) + startByte, endIndex+1, mIdentifierLittleEndianFlags.get(i)); identifiers.add(identifier); } } for (int i = 0; i < mDataEndOffsets.size(); i++) { int endIndex = mDataEndOffsets.get(i) + startByte; if (endIndex > pduToParse.getEndIndex() && !mAllowPduOverflow) { if (LogManager.isVerboseLoggingEnabled()) { LogManager.d(TAG, ""Cannot parse data field ""+i+"" because PDU is too short. endIndex: "" + endIndex + "" PDU endIndex: "" + pduToParse.getEndIndex()+"". Setting value to 0""); } dataFields.add(new Long(0l)); } else { String dataString = byteArrayToFormattedString(bytesToProcess, mDataStartOffsets.get(i) + startByte, endIndex, mDataLittleEndianFlags.get(i)); dataFields.add(Long.decode(dataString)); } } if (mPowerStartOffset != null) { int endIndex = mPowerEndOffset + startByte; try { if (endIndex > pduToParse.getEndIndex() && !mAllowPduOverflow) { parseFailed = true; if (LogManager.isVerboseLoggingEnabled()) { LogManager.d(TAG, ""Cannot parse power field because PDU is too short. endIndex: "" + endIndex + "" PDU endIndex: "" + pduToParse.getEndIndex()); } } else { String powerString = byteArrayToFormattedString(bytesToProcess, mPowerStartOffset + startByte, mPowerEndOffset + startByte, false); txPower = Integer.parseInt(powerString)+mDBmCorrection; // make sure it is a signed integer if (txPower > 127) { txPower -= 256; } } } catch (NumberFormatException e1) { // keep default value } catch (NullPointerException e2) { // keep default value } } else { if (mDBmCorrection != null) { txPower = mDBmCorrection; } } if (!parseFailed) { parseSucceeded = true; // exit processing PDUs on the first beacon we find. Only one beacon per advertisement! break; } } } } if (parseSucceeded) { int beaconTypeCode = -1; if (mMatchingBeaconTypeCodeEndOffset != null) { String beaconTypeString = byteArrayToFormattedString(bytesToProcess, mMatchingBeaconTypeCodeStartOffset+startByte, mMatchingBeaconTypeCodeEndOffset+startByte, false); beaconTypeCode = Integer.parseInt(beaconTypeString); } int manufacturer = 0; String manufacturerString = byteArrayToFormattedString(bytesToProcess, startByte, startByte+1, true); manufacturer = Integer.parseInt(manufacturerString); String macAddress = null; String name = null; if (device != null) { macAddress = device.getAddress(); try { name = device.getName(); } catch (SecurityException e) { Log.d(TAG,""Cannot read device name without Manifest.permission.BLUETOOTH_CONNECT""); } } beacon.mIdentifiers = identifiers; beacon.mDataFields = dataFields; beacon.mRssi = rssi; beacon.mBeaconTypeCode = beaconTypeCode; if (mServiceUuid != null) { beacon.mServiceUuid = (int) mServiceUuid.longValue(); } else { beacon.mServiceUuid = -1; } beacon.mBluetoothAddress = macAddress; beacon.mBluetoothName= name; beacon.mManufacturer = manufacturer; beacon.mParserIdentifier = mIdentifier; beacon.mMultiFrameBeacon = extraParsers.size() > 0 || mExtraFrame; beacon.mFirstCycleDetectionTimestamp = timestampMs; beacon.mLastCycleDetectionTimestamp = timestampMs; beacon.mTxPower = txPower; return beacon; } else { return null; } }","Prevent Android 12 crashes by adding exported=""false"" on broadcast receiver, catching SecurityException on reading bluetooth name.",https://github.com/AltBeacon/android-beacon-library/commit/a61d049d05fb425a1078646221aa6b619aa80350,,,lib/src/main/java/org/altbeacon/beacon/BeaconParser.java,3,java,False,2021-08-01T22:45:01Z "private static void show(Context context, ViewGroup parent, VideoType video, ResultListener listener) { final View view = (View) LayoutInflater.from(context).inflate(R.layout.main_dialogs_add_video, parent, false); final TextInputEditText title = (TextInputEditText) view.findViewById(R.id.video_title); final TextInputEditText URL_low_res = (TextInputEditText) view.findViewById(R.id.video_url_low_res); final TextInputEditText URL_high_res = (TextInputEditText) view.findViewById(R.id.video_url_high_res); final CheckBox is_enabled = (CheckBox) view.findViewById(R.id.video_is_enabled); if (video != null) { title.setText( video.title, TextView.BufferType.EDITABLE); URL_low_res.setText( video.URL_low_res, TextView.BufferType.EDITABLE); URL_high_res.setText( video.URL_high_res, TextView.BufferType.EDITABLE); is_enabled.setChecked(video.is_enabled); } final AlertDialog alertDialog = new AlertDialog.Builder(context) .setTitle( (video == null) ? R.string.dialog_title_add_video : R.string.dialog_title_edit_video ) .setView(view) .setNegativeButton(""CANCEL"", new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialogInterface, int i) { Utils.hideKeyboard(context, view); dialogInterface.dismiss(); listener.onResult((VideoType) null); } }) .setPositiveButton(""SAVE"", new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialogInterface, int i) { Utils.hideKeyboard(context, view); dialogInterface.dismiss(); VideoType result = new VideoType( String.valueOf(title.getText()), String.valueOf(URL_low_res.getText()), String.valueOf(URL_high_res.getText()), is_enabled.isChecked() ); listener.onResult(result); } }) .show(); }","private static void show(Context context, ViewGroup parent, VideoType video, ResultListener listener) { final View view = (View) LayoutInflater.from(context).inflate(R.layout.main_dialogs_add_video, parent, false); final TextInputEditText title = (TextInputEditText) view.findViewById(R.id.video_title); final TextInputEditText URL_low_res = (TextInputEditText) view.findViewById(R.id.video_url_low_res); final TextInputEditText URL_high_res = (TextInputEditText) view.findViewById(R.id.video_url_high_res); final CheckBox is_enabled = (CheckBox) view.findViewById(R.id.video_is_enabled); if (video != null) { title.setText( video.title, TextView.BufferType.EDITABLE); URL_low_res.setText( video.URL_low_res, TextView.BufferType.EDITABLE); URL_high_res.setText( video.URL_high_res, TextView.BufferType.EDITABLE); is_enabled.setChecked(video.is_enabled); } final AlertDialog alertDialog = new AlertDialog.Builder(context) .setTitle( (video == null) ? R.string.dialog_title_add_video : R.string.dialog_title_edit_video ) .setView(view) .setNegativeButton(""CANCEL"", new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialogInterface, int i) { Utils.hideKeyboard(context, view); dialogInterface.dismiss(); listener.onResult((VideoType) null); } }) .setPositiveButton(""SAVE"", new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialogInterface, int i) { // normalize user input String video_title = normalize_string(String.valueOf(title.getText())); String video_URL_low_res = normalize_string(String.valueOf(URL_low_res.getText())); String video_URL_high_res = normalize_string(String.valueOf(URL_high_res.getText())); boolean video_is_enabled = is_enabled.isChecked(); if ((video_URL_low_res == null) && (video_URL_high_res != null)) { video_URL_low_res = video_URL_high_res; video_URL_high_res = null; } if ((video_URL_low_res != null) && (video_URL_high_res != null) && video_URL_low_res.equals(video_URL_high_res)) { video_URL_high_res = null; } // validate user input if ((video_title == null) || (video_URL_low_res == null)) return; Utils.hideKeyboard(context, view); dialogInterface.dismiss(); VideoType result = new VideoType(video_title, video_URL_low_res, video_URL_high_res, video_is_enabled); listener.onResult(result); } private String normalize_string(String val) { if (val == null) return null; val = val.trim(); if (val.isEmpty()) return null; return val; } }) .show(); }","normalize and validate user input when adding new video sources to prevent the app from crashing, when opening fullscreen view for a video with no high-res URL.",https://github.com/warren-bank/Android-RTSP-IPCam-Viewer/commit/2a48a015d6ddb6a08b853f915f4d90e6dd972d79,,,android-studio-project/RTSP-IPCam-Viewer/src/main/java/com/github/warren_bank/rtsp_ipcam_viewer/main/dialogs/add_video/VideoDialog.java,3,java,False,2022-05-18T17:54:50Z "@Override public Optional> deserialize(PersistedData data) { if (!data.isArray()) { return Optional.empty(); } Map result = Maps.newLinkedHashMap(); for (PersistedData entry : data.getAsArray()) { PersistedDataMap kvEntry = entry.getAsValueMap(); final Optional key = keyHandler.deserialize(kvEntry.get(KEY)); if (key.isPresent()) { final Optional value = valueHandler.deserialize(kvEntry.get(VALUE)); if (value.isPresent()) { result.put(key.get(), value.get()); } else { logger.warn(""Missing value for key '{}' with {} given entry '{}'"", key.get(), valueHandler, kvEntry.get(VALUE)); } } else { logger.warn(""Missing field '{}' for entry '{}'"", KEY, kvEntry); } } return Optional.of(result); }","@Override public Optional> deserialize(PersistedData data) { if (!data.isArray() || data.isValueMap()) { logger.warn(""Incorrect map format detected: object instead of array.\n"" + getUsageInfo(data)); return Optional.empty(); } Map result = Maps.newLinkedHashMap(); for (PersistedData entry : data.getAsArray()) { PersistedDataMap kvEntry = entry.getAsValueMap(); PersistedData rawKey = kvEntry.get(KEY); PersistedData rawValue = kvEntry.get(VALUE); if (rawKey == null || rawValue == null) { logger.warn(""Incorrect map format detected: missing map entry with \""key\"" or \""value\"" key.\n"" + getUsageInfo(data)); return Optional.empty(); } final Optional key = keyHandler.deserialize(rawKey); if (key.isEmpty()) { logger.warn(""Could not deserialize key '{}' as '{}'"", rawKey, keyHandler.getClass().getSimpleName()); return Optional.empty(); } final Optional value = valueHandler.deserialize(kvEntry.get(VALUE)); if (value.isEmpty()) { logger.warn(""Could not deserialize value '{}' as '{}'"", rawValue, valueHandler.getClass().getSimpleName()); return Optional.empty(); } result.put(key.get(), value.get()); } return Optional.of(result); }","fix: do not crash on unexpected map format in GenericMapTypeHandler (#5062) Co-authored-by: Tobias Nett ",https://github.com/MovingBlocks/Terasology/commit/f3f9d9280dca2e030bdcc286f336f0536223a9b3,,,subsystems/TypeHandlerLibrary/src/main/java/org/terasology/persistence/typeHandling/coreTypes/GenericMapTypeHandler.java,3,java,False,2022-08-22T22:10:43Z "public List addRecord(int partitionId, Object key, Object value) { final long start = System.currentTimeMillis(); arrayOutputStream.reset(); serializeStream.writeKey(key, ClassTag$.MODULE$.apply(key.getClass())); serializeStream.writeValue(value, ClassTag$.MODULE$.apply(value.getClass())); serializeStream.flush(); serializeTime += System.currentTimeMillis() - start; byte[] serializedData = arrayOutputStream.getBuf(); int serializedDataLength = arrayOutputStream.size(); if (serializedDataLength == 0) { return null; } List result = Lists.newArrayList(); if (buffers.containsKey(partitionId)) { WriterBuffer wb = buffers.get(partitionId); if (wb.askForMemory(serializedDataLength)) { if (serializedDataLength > bufferSegmentSize) { requestMemory(serializedDataLength); } else { requestMemory(bufferSegmentSize); } } wb.addRecord(serializedData, serializedDataLength); if (wb.getMemoryUsed() > bufferSize) { result.add(createShuffleBlock(partitionId, wb)); copyTime += wb.getCopyTime(); buffers.remove(partitionId); LOG.debug(""Single buffer is full for shuffleId["" + shuffleId + ""] partition["" + partitionId + ""] with memoryUsed["" + wb.getMemoryUsed() + ""], dataLength["" + wb.getDataLength() + ""]""); } } else { requestMemory(bufferSegmentSize); WriterBuffer wb = new WriterBuffer(bufferSegmentSize); wb.addRecord(serializedData, serializedDataLength); buffers.put(partitionId, wb); } shuffleWriteMetrics.incRecordsWritten(1L); // check buffer size > spill threshold if (usedBytes.get() - inSendListBytes.get() > spillSize) { result.addAll(clear()); } writeTime += System.currentTimeMillis() - start; return result; }","public List addRecord(int partitionId, Object key, Object value) { final long start = System.currentTimeMillis(); arrayOutputStream.reset(); serializeStream.writeKey(key, ClassTag$.MODULE$.apply(key.getClass())); serializeStream.writeValue(value, ClassTag$.MODULE$.apply(value.getClass())); serializeStream.flush(); serializeTime += System.currentTimeMillis() - start; byte[] serializedData = arrayOutputStream.getBuf(); int serializedDataLength = arrayOutputStream.size(); if (serializedDataLength == 0) { return null; } List result = Lists.newArrayList(); if (buffers.containsKey(partitionId)) { WriterBuffer wb = buffers.get(partitionId); if (wb.askForMemory(serializedDataLength)) { requestMemory(Math.max(bufferSegmentSize, serializedDataLength)); } wb.addRecord(serializedData, serializedDataLength); if (wb.getMemoryUsed() > bufferSize) { result.add(createShuffleBlock(partitionId, wb)); copyTime += wb.getCopyTime(); buffers.remove(partitionId); LOG.debug(""Single buffer is full for shuffleId["" + shuffleId + ""] partition["" + partitionId + ""] with memoryUsed["" + wb.getMemoryUsed() + ""], dataLength["" + wb.getDataLength() + ""]""); } } else { requestMemory(Math.max(bufferSegmentSize, serializedDataLength)); WriterBuffer wb = new WriterBuffer(bufferSegmentSize); wb.addRecord(serializedData, serializedDataLength); buffers.put(partitionId, wb); } shuffleWriteMetrics.incRecordsWritten(1L); // check buffer size > spill threshold if (usedBytes.get() - inSendListBytes.get() > spillSize) { result.addAll(clear()); } writeTime += System.currentTimeMillis() - start; return result; }","[BUGFIX] Fix memory leak which cause oom (#145) ### What changes were proposed in this pull request? the behavior of buffer management and memory allocate when adding a huge record to a partition where the buffer is not initialized, we only allocate bufferSegmentSize memory, however release the real huge size memory after the buffer is sent. this will easily cause OOM. ### Why are the changes needed? better manage memory ### Does this PR introduce _any_ user-facing change? no ### How was this patch tested? pass testing",https://github.com/apache/incubator-uniffle/commit/b3c075294eb4017f2de5309dabfc679914b8a22e,,,client-spark/common/src/main/java/org/apache/spark/shuffle/writer/WriteBufferManager.java,3,java,False,2022-08-10T03:08:47Z "@EventHandler (priority = EventPriority.MONITOR) public void onCraft(CraftItemEvent e){ Player p = (Player) e.getView().getPlayer(); PlayerAccount acc = PlayersManager.getPlayerAccount(p); ItemStack item = e.getRecipe().getResult(); if (item.getType() == Material.AIR && e.getRecipe() instanceof ComplexRecipe) { String key = ((ComplexRecipe) e.getRecipe()).getKey().toString(); if (key.equals(""minecraft:suspicious_stew"")) { item = XMaterial.SUSPICIOUS_STEW.parseItem(); } } if (branch.hasStageLaunched(acc, this) && canUpdate(p)) { if (comparisons.isSimilar(result, item)) { int recipeAmount = item.getAmount(); switch (e.getClick()) { case NUMBER_KEY: // If hotbar slot selected is full, crafting fails (vanilla behavior, even when items match) if (e.getWhoClicked().getInventory().getItem(e.getHotbarButton()) != null) recipeAmount = 0; break; case DROP: case CONTROL_DROP: // If we are holding items, craft-via-drop fails (vanilla behavior) ItemStack cursor = e.getCursor(); if (cursor != null && cursor.getType() != Material.AIR) recipeAmount = 0; break; case SHIFT_RIGHT: case SHIFT_LEFT: if (recipeAmount == 0) break; int maxCraftable = getMaxCraftAmount(e.getInventory()); int capacity = fits(item, e.getView().getBottomInventory()); // If we can't fit everything, increase ""space"" to include the items dropped by crafting // (Think: Uncrafting 8 iron blocks into 1 slot) if (capacity < maxCraftable) maxCraftable = ((capacity + recipeAmount - 1) / recipeAmount) * recipeAmount; recipeAmount = maxCraftable; break; default: cursor = e.getCursor(); if (cursor != null && cursor.getType() != Material.AIR && !cursor.isSimilar(item)) recipeAmount = 0; break; } // No use continuing if we haven't actually crafted a thing if (recipeAmount == 0) return; int amount = getPlayerAmount(acc) - recipeAmount; if (amount <= 0) { finishStage(p); }else { updateObjective(acc, p, ""amount"", amount); } } } }","@EventHandler (priority = EventPriority.MONITOR) public void onCraft(CraftItemEvent e){ Player p = (Player) e.getView().getPlayer(); PlayerAccount acc = PlayersManager.getPlayerAccount(p); ItemStack item = e.getRecipe().getResult(); if (item.getType() == Material.AIR && e.getRecipe() instanceof ComplexRecipe) { String key = ((ComplexRecipe) e.getRecipe()).getKey().toString(); if (key.equals(""minecraft:suspicious_stew"")) { item = XMaterial.SUSPICIOUS_STEW.parseItem(); } } if (branch.hasStageLaunched(acc, this) && canUpdate(p)) { if (comparisons.isSimilar(result, item)) { int recipeAmount = item.getAmount(); switch (e.getClick()) { case NUMBER_KEY: // If hotbar slot selected is full, crafting fails (vanilla behavior, even when items match) if (e.getWhoClicked().getInventory().getItem(e.getHotbarButton()) != null) recipeAmount = 0; break; case DROP: case CONTROL_DROP: // If we are holding items, craft-via-drop fails (vanilla behavior) ItemStack cursor = e.getCursor(); if (cursor != null && cursor.getType() != Material.AIR) recipeAmount = 0; break; case SHIFT_RIGHT: case SHIFT_LEFT: if (recipeAmount == 0) break; int maxCraftable = getMaxCraftAmount(e.getInventory()); int capacity = fits(item, e.getView().getBottomInventory()); // If we can't fit everything, increase ""space"" to include the items dropped by crafting // (Think: Uncrafting 8 iron blocks into 1 slot) if (capacity < maxCraftable) maxCraftable = ((capacity + recipeAmount - 1) / recipeAmount) * recipeAmount; recipeAmount = maxCraftable; break; default: cursor = e.getCursor(); if (cursor != null && cursor.getType() != Material.AIR) { if (cursor.isSimilar(item)) { if (cursor.getAmount() + item.getAmount() > cursor.getMaxStackSize()) recipeAmount = 0; }else { recipeAmount = 0; } } break; } // No use continuing if we haven't actually crafted a thing if (recipeAmount == 0) return; int amount = getPlayerAmount(acc) - recipeAmount; if (amount <= 0) { finishStage(p); }else { updateObjective(acc, p, ""amount"", amount); } } } }",":bug: Fixed craft exploit * closes 236",https://github.com/SkytAsul/BeautyQuests/commit/8e4d2c9edfd08382efaa66620b988fad4c08e0ba,,,core/src/main/java/fr/skytasul/quests/stages/StageCraft.java,3,java,False,2022-08-08T16:44:35Z "public static Optional checkCookie(String cookie) { return Optional.ofNullable(USERS_BY_COOKIE.getIfPresent(cookie)); }","public Optional checkCookie(String cookie) { return Optional.ofNullable(USERS_BY_COOKIE.get(cookie)); }","Implemented persistent cookies Fixed security vulnerability with cookies not being invalidated properly Request headers were not properly set for the Request object, leading to the Cookie header missing when logging out, which then left the cookie in memory. Rogue actor who gained access to the cookie could then use the cookie to access the panel. Made cookie expiry configurable with 'Webserver.Security.Cookie_expires_after' Due to cookie persistence there is no way to log everyone out of the panel. This will be addressed in a future commit with addition of a command. Affects issues: - Close #1740",https://github.com/plan-player-analytics/Plan/commit/fb4b272844263d33f5a6e85af29ac7e6e25ff80a,,,Plan/common/src/main/java/com/djrapitops/plan/delivery/webserver/auth/ActiveCookieStore.java,3,java,False,2021-03-20T10:02:02Z "loadEditor(element, customConfig) { this.setElement(element); const instance = this.getEditorInstanceFromName(), self = this; let config = { language: CONFIG.langKey, allowedContent: true, disableNativeSpellChecker: false, extraAllowedContent: 'div{page-break-after*}', format_tags: 'p;h1;h2;h3;h4;h5;h6;pre;address;div', removeButtons: '', enterMode: CKEDITOR.ENTER_BR, shiftEnterMode: CKEDITOR.ENTER_P, emojiEnabled: false, mentionsEnabled: false, on: { instanceReady: function (evt) { evt.editor.on('blur', function () { evt.editor.updateElement(); }); if (self.isModal && self.progressInstance) { self.progressInstance.progressIndicator({ mode: 'hide' }); } } }, removePlugins: 'scayt', extraPlugins: 'colorbutton,pagebreak,colordialog,find,selectall,showblocks,div,print,font,justify,bidi,ckeditor-image-to-base', toolbar: 'Full', toolbar_Full: [ { name: 'clipboard', items: ['Cut', 'Copy', 'Paste', 'PasteText', 'PasteFromWord', '-', 'Undo', 'Redo'] }, { name: 'editing', items: ['Find', 'Replace', '-', 'SelectAll'] }, { name: 'links', items: ['Link', 'Unlink'] }, { name: 'insert', items: ['ckeditor-image-to-base', 'Table', 'HorizontalRule', 'SpecialChar', 'PageBreak'] }, { name: 'tools', items: ['Maximize', 'ShowBlocks'] }, { name: 'paragraph', items: ['Outdent', 'Indent', '-', 'Blockquote', 'CreateDiv'] }, { name: 'document', items: ['Source', 'Print'] }, '/', { name: 'styles', items: ['Styles', 'Format', 'Font', 'FontSize'] }, { name: 'basicstyles', items: ['Bold', 'Italic', 'Underline', 'Strike', 'Subscript', 'Superscript'] }, { name: 'colors', items: ['TextColor', 'BGColor'] }, { name: 'paragraph', items: [ 'NumberedList', 'BulletedList', '-', 'JustifyLeft', 'JustifyCenter', 'JustifyRight', 'JustifyBlock', '-', 'BidiLtr', 'BidiRtl' ] }, { name: 'basicstyles', items: ['CopyFormatting', 'RemoveFormat'] } ], toolbar_Min: [ { name: 'basicstyles', items: ['Bold', 'Italic', 'Underline', 'Strike'] }, { name: 'colors', items: ['TextColor', 'BGColor'] }, { name: 'tools', items: ['Maximize'] }, { name: 'paragraph', items: [ 'NumberedList', 'BulletedList', '-', 'JustifyLeft', 'JustifyCenter', 'JustifyRight', 'JustifyBlock', '-', 'BidiLtr', 'BidiRtl' ] }, { name: 'basicstyles', items: ['CopyFormatting', 'RemoveFormat', 'Source'] } ], toolbar_Micro: [ { name: 'basicstyles', items: ['Bold', 'Italic', 'Underline', 'Strike'] }, { name: 'colors', items: ['TextColor', 'BGColor'] }, { name: 'paragraph', items: ['NumberedList', 'BulletedList', 'JustifyLeft', 'JustifyCenter', 'JustifyRight', 'JustifyBlock'] }, { name: 'basicstyles', items: ['CopyFormatting', 'RemoveFormat'] } ], toolbar_Clipboard: [ { name: 'document', items: ['Print'] }, { name: 'basicstyles', items: ['CopyFormatting', 'RemoveFormat'] }, { name: 'clipboard', items: ['Cut', 'Copy', 'Paste', 'PasteText', 'PasteFromWord', '-', 'Undo', 'Redo'] } ], toolbar_PDF: [ { name: 'clipboard', items: ['Cut', 'Copy', 'Paste', 'PasteText', 'PasteFromWord', '-', 'Undo', 'Redo'] }, { name: 'editing', items: ['Find', 'Replace', '-', 'SelectAll', '-'] }, { name: 'links', items: ['Link', 'Unlink'] }, { name: 'insert', items: ['ckeditor-image-to-base', 'Table', 'HorizontalRule', 'PageBreak'] }, { name: 'tools', items: ['Maximize', 'ShowBlocks'] }, { name: 'document', items: ['Source'] }, '/', { name: 'styles', items: ['Styles', 'Format', 'Font', 'FontSize'] }, { name: 'basicstyles', items: ['Bold', 'Italic', 'Underline', 'Strike'] }, { name: 'colors', items: ['TextColor', 'BGColor'] }, { name: 'paragraph', items: ['JustifyLeft', 'JustifyCenter', 'JustifyRight'] }, { name: 'basicstyles', items: ['CopyFormatting', 'RemoveFormat'] } ] }; if (typeof customConfig !== 'undefined') { config = $.extend(config, customConfig); } config = Object.assign(config, element.data()); if (config.emojiEnabled) { let emojiToolbar = { name: 'links', items: ['EmojiPanel'] }; if (typeof config.toolbar === 'string') { config[`toolbar_${config.toolbar}`].push(emojiToolbar); } else if (Array.isArray(config.toolbar)) { config.toolbar.push(emojiToolbar); } config.extraPlugins = config.extraPlugins + ',emoji'; config.outputTemplate = '{id}'; } if (config.mentionsEnabled) { config.extraPlugins = config.extraPlugins + ',mentions'; config.mentions = this.registerMentions(); } if (instance) { CKEDITOR.remove(instance); } element.ckeditor(config); }","loadEditor(element, customConfig) { this.setElement(element); const instance = this.getEditorInstanceFromName(); let config = { language: CONFIG.langKey, allowedContent: true, disableNativeSpellChecker: false, extraAllowedContent: 'div{page-break-after*}', format_tags: 'p;h1;h2;h3;h4;h5;h6;pre;address;div', removeButtons: '', enterMode: CKEDITOR.ENTER_BR, shiftEnterMode: CKEDITOR.ENTER_P, emojiEnabled: false, mentionsEnabled: false, on: { instanceReady: (evt) => { evt.editor.on('blur', function () { evt.editor.updateElement(); }); if (this.isModal && this.progressInstance) { this.progressInstance.progressIndicator({ mode: 'hide' }); } }, beforeCommandExec: (e) => { if (e.editor.mode === 'source') { return this.validate(element, e); } } }, removePlugins: 'scayt', extraPlugins: 'colorbutton,pagebreak,colordialog,find,selectall,showblocks,div,print,font,justify,bidi,ckeditor-image-to-base', toolbar: 'Full', toolbar_Full: [ { name: 'clipboard', items: ['Cut', 'Copy', 'Paste', 'PasteText', 'PasteFromWord', '-', 'Undo', 'Redo'] }, { name: 'editing', items: ['Find', 'Replace', '-', 'SelectAll'] }, { name: 'links', items: ['Link', 'Unlink'] }, { name: 'insert', items: ['ckeditor-image-to-base', 'Table', 'HorizontalRule', 'SpecialChar', 'PageBreak'] }, { name: 'tools', items: ['Maximize', 'ShowBlocks'] }, { name: 'paragraph', items: ['Outdent', 'Indent', '-', 'Blockquote', 'CreateDiv'] }, { name: 'document', items: ['Source', 'Print'] }, '/', { name: 'styles', items: ['Styles', 'Format', 'Font', 'FontSize'] }, { name: 'basicstyles', items: ['Bold', 'Italic', 'Underline', 'Strike', 'Subscript', 'Superscript'] }, { name: 'colors', items: ['TextColor', 'BGColor'] }, { name: 'paragraph', items: [ 'NumberedList', 'BulletedList', '-', 'JustifyLeft', 'JustifyCenter', 'JustifyRight', 'JustifyBlock', '-', 'BidiLtr', 'BidiRtl' ] }, { name: 'basicstyles', items: ['CopyFormatting', 'RemoveFormat'] } ], toolbar_Min: [ { name: 'basicstyles', items: ['Bold', 'Italic', 'Underline', 'Strike'] }, { name: 'colors', items: ['TextColor', 'BGColor'] }, { name: 'tools', items: ['Maximize'] }, { name: 'paragraph', items: [ 'NumberedList', 'BulletedList', '-', 'JustifyLeft', 'JustifyCenter', 'JustifyRight', 'JustifyBlock', '-', 'BidiLtr', 'BidiRtl' ] }, { name: 'basicstyles', items: ['CopyFormatting', 'RemoveFormat', 'Source'] } ], toolbar_Micro: [ { name: 'basicstyles', items: ['Bold', 'Italic', 'Underline', 'Strike'] }, { name: 'colors', items: ['TextColor', 'BGColor'] }, { name: 'paragraph', items: ['NumberedList', 'BulletedList', 'JustifyLeft', 'JustifyCenter', 'JustifyRight', 'JustifyBlock'] }, { name: 'basicstyles', items: ['CopyFormatting', 'RemoveFormat'] } ], toolbar_Clipboard: [ { name: 'document', items: ['Print'] }, { name: 'basicstyles', items: ['CopyFormatting', 'RemoveFormat'] }, { name: 'clipboard', items: ['Cut', 'Copy', 'Paste', 'PasteText', 'PasteFromWord', '-', 'Undo', 'Redo'] } ], toolbar_PDF: [ { name: 'clipboard', items: ['Cut', 'Copy', 'Paste', 'PasteText', 'PasteFromWord', '-', 'Undo', 'Redo'] }, { name: 'editing', items: ['Find', 'Replace', '-', 'SelectAll', '-'] }, { name: 'links', items: ['Link', 'Unlink'] }, { name: 'insert', items: ['ckeditor-image-to-base', 'Table', 'HorizontalRule', 'PageBreak'] }, { name: 'tools', items: ['Maximize', 'ShowBlocks'] }, { name: 'document', items: ['Source'] }, '/', { name: 'styles', items: ['Styles', 'Format', 'Font', 'FontSize'] }, { name: 'basicstyles', items: ['Bold', 'Italic', 'Underline', 'Strike'] }, { name: 'colors', items: ['TextColor', 'BGColor'] }, { name: 'paragraph', items: ['JustifyLeft', 'JustifyCenter', 'JustifyRight'] }, { name: 'basicstyles', items: ['CopyFormatting', 'RemoveFormat'] } ] }; if (typeof customConfig !== 'undefined') { config = $.extend(config, customConfig); } config = Object.assign(config, element.data()); if (config.emojiEnabled) { let emojiToolbar = { name: 'links', items: ['EmojiPanel'] }; if (typeof config.toolbar === 'string') { config[`toolbar_${config.toolbar}`].push(emojiToolbar); } else if (Array.isArray(config.toolbar)) { config.toolbar.push(emojiToolbar); } config.extraPlugins = config.extraPlugins + ',emoji'; config.outputTemplate = '{id}'; } if (config.mentionsEnabled) { config.extraPlugins = config.extraPlugins + ',mentions'; config.mentions = this.registerMentions(); } if (instance) { CKEDITOR.remove(instance); } element.ckeditor(config); }",Added additional data validation in the wysiwyg editor when inputting data in the source.,https://github.com/yetiforcecompany/yetiforcecrm/commit/a062d3d5fecb000db207a2ad8a446db97ad96b89,CVE-2021-4107,['CWE-79'],public_html/layouts/resources/Fields.js,3,js,False,2021-12-13T14:18:13Z "public int addWindow(Session session, IWindow client, int seq, LayoutParams attrs, int viewVisibility, int displayId, Rect outFrame, Rect outContentInsets, Rect outStableInsets, DisplayCutout.ParcelableWrapper outDisplayCutout, InputChannel outInputChannel, InsetsState outInsetsState, InsetsSourceControl[] outActiveControls, int requestUserId) { Arrays.fill(outActiveControls, null); int[] appOp = new int[1]; final boolean isRoundedCornerOverlay = (attrs.privateFlags & PRIVATE_FLAG_IS_ROUNDED_CORNERS_OVERLAY) != 0; int res = mPolicy.checkAddPermission(attrs.type, isRoundedCornerOverlay, attrs.packageName, appOp); if (res != WindowManagerGlobal.ADD_OKAY) { return res; } WindowState parentWindow = null; final int callingUid = Binder.getCallingUid(); final int callingPid = Binder.getCallingPid(); final long origId = Binder.clearCallingIdentity(); final int type = attrs.type; synchronized (mGlobalLock) { if (!mDisplayReady) { throw new IllegalStateException(""Display has not been initialialized""); } final DisplayContent displayContent = getDisplayContentOrCreate(displayId, attrs.token); if (displayContent == null) { ProtoLog.w(WM_ERROR, ""Attempted to add window to a display that does "" + ""not exist: %d. Aborting."", displayId); return WindowManagerGlobal.ADD_INVALID_DISPLAY; } if (!displayContent.hasAccess(session.mUid)) { ProtoLog.w(WM_ERROR, ""Attempted to add window to a display for which the application "" + ""does not have access: %d. Aborting."", displayId); return WindowManagerGlobal.ADD_INVALID_DISPLAY; } if (mWindowMap.containsKey(client.asBinder())) { ProtoLog.w(WM_ERROR, ""Window %s is already added"", client); return WindowManagerGlobal.ADD_DUPLICATE_ADD; } if (type >= FIRST_SUB_WINDOW && type <= LAST_SUB_WINDOW) { parentWindow = windowForClientLocked(null, attrs.token, false); if (parentWindow == null) { ProtoLog.w(WM_ERROR, ""Attempted to add window with token that is not a window: "" + ""%s. Aborting."", attrs.token); return WindowManagerGlobal.ADD_BAD_SUBWINDOW_TOKEN; } if (parentWindow.mAttrs.type >= FIRST_SUB_WINDOW && parentWindow.mAttrs.type <= LAST_SUB_WINDOW) { ProtoLog.w(WM_ERROR, ""Attempted to add window with token that is a sub-window: "" + ""%s. Aborting."", attrs.token); return WindowManagerGlobal.ADD_BAD_SUBWINDOW_TOKEN; } } if (type == TYPE_PRIVATE_PRESENTATION && !displayContent.isPrivate()) { ProtoLog.w(WM_ERROR, ""Attempted to add private presentation window to a non-private display. "" + ""Aborting.""); return WindowManagerGlobal.ADD_PERMISSION_DENIED; } if (type == TYPE_PRESENTATION && !displayContent.getDisplay().isPublicPresentation()) { ProtoLog.w(WM_ERROR, ""Attempted to add presentation window to a non-suitable display. "" + ""Aborting.""); return WindowManagerGlobal.ADD_INVALID_DISPLAY; } int userId = UserHandle.getUserId(session.mUid); if (requestUserId != userId) { try { mAmInternal.handleIncomingUser(callingPid, callingUid, requestUserId, false /*allowAll*/, ALLOW_NON_FULL, null, null); } catch (Exception exp) { ProtoLog.w(WM_ERROR, ""Trying to add window with invalid user=%d"", requestUserId); return WindowManagerGlobal.ADD_INVALID_USER; } // It's fine to use this userId userId = requestUserId; } ActivityRecord activity = null; final boolean hasParent = parentWindow != null; // Use existing parent window token for child windows since they go in the same token // as there parent window so we can apply the same policy on them. WindowToken token = displayContent.getWindowToken( hasParent ? parentWindow.mAttrs.token : attrs.token); // If this is a child window, we want to apply the same type checking rules as the // parent window type. final int rootType = hasParent ? parentWindow.mAttrs.type : type; boolean addToastWindowRequiresToken = false; if (token == null) { if (!unprivilegedAppCanCreateTokenWith(parentWindow, callingUid, type, rootType, attrs.token, attrs.packageName)) { return WindowManagerGlobal.ADD_BAD_APP_TOKEN; } final IBinder binder = attrs.token != null ? attrs.token : client.asBinder(); token = new WindowToken(this, binder, type, false, displayContent, session.mCanAddInternalSystemWindow, isRoundedCornerOverlay); } else if (rootType >= FIRST_APPLICATION_WINDOW && rootType <= LAST_APPLICATION_WINDOW) { activity = token.asActivityRecord(); if (activity == null) { ProtoLog.w(WM_ERROR, ""Attempted to add window with non-application token "" + "".%s Aborting."", token); return WindowManagerGlobal.ADD_NOT_APP_TOKEN; } else if (activity.getParent() == null) { ProtoLog.w(WM_ERROR, ""Attempted to add window with exiting application token "" + "".%s Aborting."", token); return WindowManagerGlobal.ADD_APP_EXITING; } else if (type == TYPE_APPLICATION_STARTING && activity.startingWindow != null) { ProtoLog.w(WM_ERROR, ""Attempted to add starting window to token with already existing"" + "" starting window""); return WindowManagerGlobal.ADD_DUPLICATE_ADD; } } else if (rootType == TYPE_INPUT_METHOD) { if (token.windowType != TYPE_INPUT_METHOD) { ProtoLog.w(WM_ERROR, ""Attempted to add input method window with bad token "" + ""%s. Aborting."", attrs.token); return WindowManagerGlobal.ADD_BAD_APP_TOKEN; } } else if (rootType == TYPE_VOICE_INTERACTION) { if (token.windowType != TYPE_VOICE_INTERACTION) { ProtoLog.w(WM_ERROR, ""Attempted to add voice interaction window with bad token "" + ""%s. Aborting."", attrs.token); return WindowManagerGlobal.ADD_BAD_APP_TOKEN; } } else if (rootType == TYPE_WALLPAPER) { if (token.windowType != TYPE_WALLPAPER) { ProtoLog.w(WM_ERROR, ""Attempted to add wallpaper window with bad token "" + ""%s. Aborting."", attrs.token); return WindowManagerGlobal.ADD_BAD_APP_TOKEN; } } else if (rootType == TYPE_ACCESSIBILITY_OVERLAY) { if (token.windowType != TYPE_ACCESSIBILITY_OVERLAY) { ProtoLog.w(WM_ERROR, ""Attempted to add Accessibility overlay window with bad token "" + ""%s. Aborting."", attrs.token); return WindowManagerGlobal.ADD_BAD_APP_TOKEN; } } else if (type == TYPE_TOAST) { // Apps targeting SDK above N MR1 cannot arbitrary add toast windows. addToastWindowRequiresToken = doesAddToastWindowRequireToken(attrs.packageName, callingUid, parentWindow); if (addToastWindowRequiresToken && token.windowType != TYPE_TOAST) { ProtoLog.w(WM_ERROR, ""Attempted to add a toast window with bad token "" + ""%s. Aborting."", attrs.token); return WindowManagerGlobal.ADD_BAD_APP_TOKEN; } } else if (type == TYPE_QS_DIALOG) { if (token.windowType != TYPE_QS_DIALOG) { ProtoLog.w(WM_ERROR, ""Attempted to add QS dialog window with bad token "" + ""%s. Aborting."", attrs.token); return WindowManagerGlobal.ADD_BAD_APP_TOKEN; } } else if (token.asActivityRecord() != null) { ProtoLog.w(WM_ERROR, ""Non-null activity for system window of rootType=%d"", rootType); // It is not valid to use an app token with other system types; we will // instead make a new token for it (as if null had been passed in for the token). attrs.token = null; token = new WindowToken(this, client.asBinder(), type, false, displayContent, session.mCanAddInternalSystemWindow); } final WindowState win = new WindowState(this, session, client, token, parentWindow, appOp[0], seq, attrs, viewVisibility, session.mUid, userId, session.mCanAddInternalSystemWindow); if (win.mDeathRecipient == null) { // Client has apparently died, so there is no reason to // continue. ProtoLog.w(WM_ERROR, ""Adding window client %s"" + "" that is dead, aborting."", client.asBinder()); return WindowManagerGlobal.ADD_APP_EXITING; } if (win.getDisplayContent() == null) { ProtoLog.w(WM_ERROR, ""Adding window to Display that has been removed.""); return WindowManagerGlobal.ADD_INVALID_DISPLAY; } final DisplayPolicy displayPolicy = displayContent.getDisplayPolicy(); displayPolicy.adjustWindowParamsLw(win, win.mAttrs, callingPid, callingUid); attrs.flags = sanitizeFlagSlippery(attrs.flags, win.getName(), callingUid, callingPid); res = displayPolicy.validateAddingWindowLw(attrs, callingPid, callingUid); if (res != WindowManagerGlobal.ADD_OKAY) { return res; } final boolean openInputChannels = (outInputChannel != null && (attrs.inputFeatures & INPUT_FEATURE_NO_INPUT_CHANNEL) == 0); if (openInputChannels) { win.openInputChannel(outInputChannel); } // If adding a toast requires a token for this app we always schedule hiding // toast windows to make sure they don't stick around longer then necessary. // We hide instead of remove such windows as apps aren't prepared to handle // windows being removed under them. // // If the app is older it can add toasts without a token and hence overlay // other apps. To be maximally compatible with these apps we will hide the // window after the toast timeout only if the focused window is from another // UID, otherwise we allow unlimited duration. When a UID looses focus we // schedule hiding all of its toast windows. if (type == TYPE_TOAST) { if (!displayContent.canAddToastWindowForUid(callingUid)) { ProtoLog.w(WM_ERROR, ""Adding more than one toast window for UID at a time.""); return WindowManagerGlobal.ADD_DUPLICATE_ADD; } // Make sure this happens before we moved focus as one can make the // toast focusable to force it not being hidden after the timeout. // Focusable toasts are always timed out to prevent a focused app to // show a focusable toasts while it has focus which will be kept on // the screen after the activity goes away. if (addToastWindowRequiresToken || (attrs.flags & LayoutParams.FLAG_NOT_FOCUSABLE) == 0 || displayContent.mCurrentFocus == null || displayContent.mCurrentFocus.mOwnerUid != callingUid) { mH.sendMessageDelayed( mH.obtainMessage(H.WINDOW_HIDE_TIMEOUT, win), win.mAttrs.hideTimeoutMilliseconds); } } // From now on, no exceptions or errors allowed! res = WindowManagerGlobal.ADD_OKAY; if (mUseBLAST) { res |= WindowManagerGlobal.ADD_FLAG_USE_BLAST; } if (sEnableTripleBuffering) { res |= WindowManagerGlobal.ADD_FLAG_USE_TRIPLE_BUFFERING; } if (displayContent.mCurrentFocus == null) { displayContent.mWinAddedSinceNullFocus.add(win); } if (excludeWindowTypeFromTapOutTask(type)) { displayContent.mTapExcludedWindows.add(win); } win.attach(); mWindowMap.put(client.asBinder(), win); win.initAppOpsState(); final boolean suspended = mPmInternal.isPackageSuspended(win.getOwningPackage(), UserHandle.getUserId(win.getOwningUid())); win.setHiddenWhileSuspended(suspended); final boolean hideSystemAlertWindows = !mHidingNonSystemOverlayWindows.isEmpty(); win.setForceHideNonSystemOverlayWindowIfNeeded(hideSystemAlertWindows); final ActivityRecord tokenActivity = token.asActivityRecord(); if (type == TYPE_APPLICATION_STARTING && tokenActivity != null) { tokenActivity.startingWindow = win; ProtoLog.v(WM_DEBUG_STARTING_WINDOW, ""addWindow: %s startingWindow=%s"", activity, win); } boolean imMayMove = true; win.mToken.addWindow(win); displayPolicy.addWindowLw(win, attrs); if (type == TYPE_INPUT_METHOD) { displayContent.setInputMethodWindowLocked(win); imMayMove = false; } else if (type == TYPE_INPUT_METHOD_DIALOG) { displayContent.computeImeTarget(true /* updateImeTarget */); imMayMove = false; } else { if (type == TYPE_WALLPAPER) { displayContent.mWallpaperController.clearLastWallpaperTimeoutTime(); displayContent.pendingLayoutChanges |= FINISH_LAYOUT_REDO_WALLPAPER; } else if ((attrs.flags & FLAG_SHOW_WALLPAPER) != 0) { displayContent.pendingLayoutChanges |= FINISH_LAYOUT_REDO_WALLPAPER; } else if (displayContent.mWallpaperController.isBelowWallpaperTarget(win)) { // If there is currently a wallpaper being shown, and // the base layer of the new window is below the current // layer of the target window, then adjust the wallpaper. // This is to avoid a new window being placed between the // wallpaper and its target. displayContent.pendingLayoutChanges |= FINISH_LAYOUT_REDO_WALLPAPER; } } final WindowStateAnimator winAnimator = win.mWinAnimator; winAnimator.mEnterAnimationPending = true; winAnimator.mEnteringAnimation = true; // Check if we need to prepare a transition for replacing window first. if (activity != null && activity.isVisible() && !prepareWindowReplacementTransition(activity)) { // If not, check if need to set up a dummy transition during display freeze // so that the unfreeze wait for the apps to draw. This might be needed if // the app is relaunching. prepareNoneTransitionForRelaunching(activity); } if (displayPolicy.getLayoutHint(win.mAttrs, token, outFrame, outContentInsets, outStableInsets, outDisplayCutout)) { res |= WindowManagerGlobal.ADD_FLAG_ALWAYS_CONSUME_SYSTEM_BARS; } outInsetsState.set(win.getInsetsState(), win.isClientLocal()); if (mInTouchMode) { res |= WindowManagerGlobal.ADD_FLAG_IN_TOUCH_MODE; } if (win.mActivityRecord == null || win.mActivityRecord.isClientVisible()) { res |= WindowManagerGlobal.ADD_FLAG_APP_VISIBLE; } displayContent.getInputMonitor().setUpdateInputWindowsNeededLw(); boolean focusChanged = false; if (win.canReceiveKeys()) { focusChanged = updateFocusedWindowLocked(UPDATE_FOCUS_WILL_ASSIGN_LAYERS, false /*updateInputWindows*/); if (focusChanged) { imMayMove = false; } } if (imMayMove) { displayContent.computeImeTarget(true /* updateImeTarget */); } // Don't do layout here, the window must call // relayout to be displayed, so we'll do it there. win.getParent().assignChildLayers(); if (focusChanged) { displayContent.getInputMonitor().setInputFocusLw(displayContent.mCurrentFocus, false /*updateInputWindows*/); } displayContent.getInputMonitor().updateInputWindowsLw(false /*force*/); ProtoLog.v(WM_DEBUG_ADD_REMOVE, ""addWindow: New client %s"" + "": window=%s Callers=%s"", client.asBinder(), win, Debug.getCallers(5)); if (win.isVisibleOrAdding() && displayContent.updateOrientation()) { displayContent.sendNewConfiguration(); } getInsetsSourceControls(win, outActiveControls); } Binder.restoreCallingIdentity(origId); return res; }","public int addWindow(Session session, IWindow client, int seq, LayoutParams attrs, int viewVisibility, int displayId, Rect outFrame, Rect outContentInsets, Rect outStableInsets, DisplayCutout.ParcelableWrapper outDisplayCutout, InputChannel outInputChannel, InsetsState outInsetsState, InsetsSourceControl[] outActiveControls, int requestUserId) { Arrays.fill(outActiveControls, null); int[] appOp = new int[1]; final boolean isRoundedCornerOverlay = (attrs.privateFlags & PRIVATE_FLAG_IS_ROUNDED_CORNERS_OVERLAY) != 0; int res = mPolicy.checkAddPermission(attrs.type, isRoundedCornerOverlay, attrs.packageName, appOp); if (res != WindowManagerGlobal.ADD_OKAY) { return res; } WindowState parentWindow = null; final int callingUid = Binder.getCallingUid(); final int callingPid = Binder.getCallingPid(); final long origId = Binder.clearCallingIdentity(); final int type = attrs.type; synchronized (mGlobalLock) { if (!mDisplayReady) { throw new IllegalStateException(""Display has not been initialialized""); } final DisplayContent displayContent = getDisplayContentOrCreate(displayId, attrs.token); if (displayContent == null) { ProtoLog.w(WM_ERROR, ""Attempted to add window to a display that does "" + ""not exist: %d. Aborting."", displayId); return WindowManagerGlobal.ADD_INVALID_DISPLAY; } if (!displayContent.hasAccess(session.mUid)) { ProtoLog.w(WM_ERROR, ""Attempted to add window to a display for which the application "" + ""does not have access: %d. Aborting."", displayId); return WindowManagerGlobal.ADD_INVALID_DISPLAY; } if (mWindowMap.containsKey(client.asBinder())) { ProtoLog.w(WM_ERROR, ""Window %s is already added"", client); return WindowManagerGlobal.ADD_DUPLICATE_ADD; } if (type >= FIRST_SUB_WINDOW && type <= LAST_SUB_WINDOW) { parentWindow = windowForClientLocked(null, attrs.token, false); if (parentWindow == null) { ProtoLog.w(WM_ERROR, ""Attempted to add window with token that is not a window: "" + ""%s. Aborting."", attrs.token); return WindowManagerGlobal.ADD_BAD_SUBWINDOW_TOKEN; } if (parentWindow.mAttrs.type >= FIRST_SUB_WINDOW && parentWindow.mAttrs.type <= LAST_SUB_WINDOW) { ProtoLog.w(WM_ERROR, ""Attempted to add window with token that is a sub-window: "" + ""%s. Aborting."", attrs.token); return WindowManagerGlobal.ADD_BAD_SUBWINDOW_TOKEN; } } if (type == TYPE_PRIVATE_PRESENTATION && !displayContent.isPrivate()) { ProtoLog.w(WM_ERROR, ""Attempted to add private presentation window to a non-private display. "" + ""Aborting.""); return WindowManagerGlobal.ADD_PERMISSION_DENIED; } if (type == TYPE_PRESENTATION && !displayContent.getDisplay().isPublicPresentation()) { ProtoLog.w(WM_ERROR, ""Attempted to add presentation window to a non-suitable display. "" + ""Aborting.""); return WindowManagerGlobal.ADD_INVALID_DISPLAY; } int userId = UserHandle.getUserId(session.mUid); if (requestUserId != userId) { try { mAmInternal.handleIncomingUser(callingPid, callingUid, requestUserId, false /*allowAll*/, ALLOW_NON_FULL, null, null); } catch (Exception exp) { ProtoLog.w(WM_ERROR, ""Trying to add window with invalid user=%d"", requestUserId); return WindowManagerGlobal.ADD_INVALID_USER; } // It's fine to use this userId userId = requestUserId; } ActivityRecord activity = null; final boolean hasParent = parentWindow != null; // Use existing parent window token for child windows since they go in the same token // as there parent window so we can apply the same policy on them. WindowToken token = displayContent.getWindowToken( hasParent ? parentWindow.mAttrs.token : attrs.token); // If this is a child window, we want to apply the same type checking rules as the // parent window type. final int rootType = hasParent ? parentWindow.mAttrs.type : type; boolean addToastWindowRequiresToken = false; if (token == null) { if (!unprivilegedAppCanCreateTokenWith(parentWindow, callingUid, type, rootType, attrs.token, attrs.packageName)) { return WindowManagerGlobal.ADD_BAD_APP_TOKEN; } final IBinder binder = attrs.token != null ? attrs.token : client.asBinder(); token = new WindowToken(this, binder, type, false, displayContent, session.mCanAddInternalSystemWindow, isRoundedCornerOverlay); } else if (rootType >= FIRST_APPLICATION_WINDOW && rootType <= LAST_APPLICATION_WINDOW) { activity = token.asActivityRecord(); if (activity == null) { ProtoLog.w(WM_ERROR, ""Attempted to add window with non-application token "" + "".%s Aborting."", token); return WindowManagerGlobal.ADD_NOT_APP_TOKEN; } else if (activity.getParent() == null) { ProtoLog.w(WM_ERROR, ""Attempted to add window with exiting application token "" + "".%s Aborting."", token); return WindowManagerGlobal.ADD_APP_EXITING; } else if (type == TYPE_APPLICATION_STARTING && activity.startingWindow != null) { ProtoLog.w(WM_ERROR, ""Attempted to add starting window to token with already existing"" + "" starting window""); return WindowManagerGlobal.ADD_DUPLICATE_ADD; } } else if (rootType == TYPE_INPUT_METHOD) { if (token.windowType != TYPE_INPUT_METHOD) { ProtoLog.w(WM_ERROR, ""Attempted to add input method window with bad token "" + ""%s. Aborting."", attrs.token); return WindowManagerGlobal.ADD_BAD_APP_TOKEN; } } else if (rootType == TYPE_VOICE_INTERACTION) { if (token.windowType != TYPE_VOICE_INTERACTION) { ProtoLog.w(WM_ERROR, ""Attempted to add voice interaction window with bad token "" + ""%s. Aborting."", attrs.token); return WindowManagerGlobal.ADD_BAD_APP_TOKEN; } } else if (rootType == TYPE_WALLPAPER) { if (token.windowType != TYPE_WALLPAPER) { ProtoLog.w(WM_ERROR, ""Attempted to add wallpaper window with bad token "" + ""%s. Aborting."", attrs.token); return WindowManagerGlobal.ADD_BAD_APP_TOKEN; } } else if (rootType == TYPE_ACCESSIBILITY_OVERLAY) { if (token.windowType != TYPE_ACCESSIBILITY_OVERLAY) { ProtoLog.w(WM_ERROR, ""Attempted to add Accessibility overlay window with bad token "" + ""%s. Aborting."", attrs.token); return WindowManagerGlobal.ADD_BAD_APP_TOKEN; } } else if (type == TYPE_TOAST) { // Apps targeting SDK above N MR1 cannot arbitrary add toast windows. addToastWindowRequiresToken = doesAddToastWindowRequireToken(attrs.packageName, callingUid, parentWindow); if (addToastWindowRequiresToken && token.windowType != TYPE_TOAST) { ProtoLog.w(WM_ERROR, ""Attempted to add a toast window with bad token "" + ""%s. Aborting."", attrs.token); return WindowManagerGlobal.ADD_BAD_APP_TOKEN; } } else if (type == TYPE_QS_DIALOG) { if (token.windowType != TYPE_QS_DIALOG) { ProtoLog.w(WM_ERROR, ""Attempted to add QS dialog window with bad token "" + ""%s. Aborting."", attrs.token); return WindowManagerGlobal.ADD_BAD_APP_TOKEN; } } else if (token.asActivityRecord() != null) { ProtoLog.w(WM_ERROR, ""Non-null activity for system window of rootType=%d"", rootType); // It is not valid to use an app token with other system types; we will // instead make a new token for it (as if null had been passed in for the token). attrs.token = null; token = new WindowToken(this, client.asBinder(), type, false, displayContent, session.mCanAddInternalSystemWindow); } final WindowState win = new WindowState(this, session, client, token, parentWindow, appOp[0], seq, attrs, viewVisibility, session.mUid, userId, session.mCanAddInternalSystemWindow); if (win.mDeathRecipient == null) { // Client has apparently died, so there is no reason to // continue. ProtoLog.w(WM_ERROR, ""Adding window client %s"" + "" that is dead, aborting."", client.asBinder()); return WindowManagerGlobal.ADD_APP_EXITING; } if (win.getDisplayContent() == null) { ProtoLog.w(WM_ERROR, ""Adding window to Display that has been removed.""); return WindowManagerGlobal.ADD_INVALID_DISPLAY; } final DisplayPolicy displayPolicy = displayContent.getDisplayPolicy(); displayPolicy.adjustWindowParamsLw(win, win.mAttrs, callingPid, callingUid); attrs.flags = sanitizeFlagSlippery(attrs.flags, win.getName(), callingUid, callingPid); res = displayPolicy.validateAddingWindowLw(attrs, callingPid, callingUid); if (res != WindowManagerGlobal.ADD_OKAY) { return res; } final boolean openInputChannels = (outInputChannel != null && (attrs.inputFeatures & INPUT_FEATURE_NO_INPUT_CHANNEL) == 0); if (openInputChannels) { win.openInputChannel(outInputChannel); } // If adding a toast requires a token for this app we always schedule hiding // toast windows to make sure they don't stick around longer then necessary. // We hide instead of remove such windows as apps aren't prepared to handle // windows being removed under them. // // If the app is older it can add toasts without a token and hence overlay // other apps. To be maximally compatible with these apps we will hide the // window after the toast timeout only if the focused window is from another // UID, otherwise we allow unlimited duration. When a UID looses focus we // schedule hiding all of its toast windows. if (type == TYPE_TOAST) { if (!displayContent.canAddToastWindowForUid(callingUid)) { ProtoLog.w(WM_ERROR, ""Adding more than one toast window for UID at a time.""); return WindowManagerGlobal.ADD_DUPLICATE_ADD; } // Make sure this happens before we moved focus as one can make the // toast focusable to force it not being hidden after the timeout. // Focusable toasts are always timed out to prevent a focused app to // show a focusable toasts while it has focus which will be kept on // the screen after the activity goes away. if (addToastWindowRequiresToken || (attrs.flags & LayoutParams.FLAG_NOT_FOCUSABLE) == 0 || displayContent.mCurrentFocus == null || displayContent.mCurrentFocus.mOwnerUid != callingUid) { mH.sendMessageDelayed( mH.obtainMessage(H.WINDOW_HIDE_TIMEOUT, win), win.mAttrs.hideTimeoutMilliseconds); } } // From now on, no exceptions or errors allowed! res = WindowManagerGlobal.ADD_OKAY; if (mUseBLAST) { res |= WindowManagerGlobal.ADD_FLAG_USE_BLAST; } if (sEnableTripleBuffering) { res |= WindowManagerGlobal.ADD_FLAG_USE_TRIPLE_BUFFERING; } if (displayContent.mCurrentFocus == null) { displayContent.mWinAddedSinceNullFocus.add(win); } if (excludeWindowTypeFromTapOutTask(type)) { displayContent.mTapExcludedWindows.add(win); } win.attach(); mWindowMap.put(client.asBinder(), win); win.initAppOpsState(); final boolean suspended = mPmInternal.isPackageSuspended(win.getOwningPackage(), UserHandle.getUserId(win.getOwningUid())); win.setHiddenWhileSuspended(suspended); final boolean hideSystemAlertWindows = !mHidingNonSystemOverlayWindows.isEmpty(); win.setForceHideNonSystemOverlayWindowIfNeeded(hideSystemAlertWindows); final ActivityRecord tokenActivity = token.asActivityRecord(); if (type == TYPE_APPLICATION_STARTING && tokenActivity != null) { tokenActivity.startingWindow = win; ProtoLog.v(WM_DEBUG_STARTING_WINDOW, ""addWindow: %s startingWindow=%s"", activity, win); } boolean imMayMove = true; win.mToken.addWindow(win); displayPolicy.addWindowLw(win, attrs); displayPolicy.setDropInputModePolicy(win, win.mAttrs); if (type == TYPE_INPUT_METHOD) { displayContent.setInputMethodWindowLocked(win); imMayMove = false; } else if (type == TYPE_INPUT_METHOD_DIALOG) { displayContent.computeImeTarget(true /* updateImeTarget */); imMayMove = false; } else { if (type == TYPE_WALLPAPER) { displayContent.mWallpaperController.clearLastWallpaperTimeoutTime(); displayContent.pendingLayoutChanges |= FINISH_LAYOUT_REDO_WALLPAPER; } else if ((attrs.flags & FLAG_SHOW_WALLPAPER) != 0) { displayContent.pendingLayoutChanges |= FINISH_LAYOUT_REDO_WALLPAPER; } else if (displayContent.mWallpaperController.isBelowWallpaperTarget(win)) { // If there is currently a wallpaper being shown, and // the base layer of the new window is below the current // layer of the target window, then adjust the wallpaper. // This is to avoid a new window being placed between the // wallpaper and its target. displayContent.pendingLayoutChanges |= FINISH_LAYOUT_REDO_WALLPAPER; } } final WindowStateAnimator winAnimator = win.mWinAnimator; winAnimator.mEnterAnimationPending = true; winAnimator.mEnteringAnimation = true; // Check if we need to prepare a transition for replacing window first. if (activity != null && activity.isVisible() && !prepareWindowReplacementTransition(activity)) { // If not, check if need to set up a dummy transition during display freeze // so that the unfreeze wait for the apps to draw. This might be needed if // the app is relaunching. prepareNoneTransitionForRelaunching(activity); } if (displayPolicy.getLayoutHint(win.mAttrs, token, outFrame, outContentInsets, outStableInsets, outDisplayCutout)) { res |= WindowManagerGlobal.ADD_FLAG_ALWAYS_CONSUME_SYSTEM_BARS; } outInsetsState.set(win.getInsetsState(), win.isClientLocal()); if (mInTouchMode) { res |= WindowManagerGlobal.ADD_FLAG_IN_TOUCH_MODE; } if (win.mActivityRecord == null || win.mActivityRecord.isClientVisible()) { res |= WindowManagerGlobal.ADD_FLAG_APP_VISIBLE; } displayContent.getInputMonitor().setUpdateInputWindowsNeededLw(); boolean focusChanged = false; if (win.canReceiveKeys()) { focusChanged = updateFocusedWindowLocked(UPDATE_FOCUS_WILL_ASSIGN_LAYERS, false /*updateInputWindows*/); if (focusChanged) { imMayMove = false; } } if (imMayMove) { displayContent.computeImeTarget(true /* updateImeTarget */); } // Don't do layout here, the window must call // relayout to be displayed, so we'll do it there. win.getParent().assignChildLayers(); if (focusChanged) { displayContent.getInputMonitor().setInputFocusLw(displayContent.mCurrentFocus, false /*updateInputWindows*/); } displayContent.getInputMonitor().updateInputWindowsLw(false /*force*/); ProtoLog.v(WM_DEBUG_ADD_REMOVE, ""addWindow: New client %s"" + "": window=%s Callers=%s"", client.asBinder(), win, Debug.getCallers(5)); if (win.isVisibleOrAdding() && displayContent.updateOrientation()) { displayContent.sendNewConfiguration(); } getInsetsSourceControls(win, outActiveControls); } Binder.restoreCallingIdentity(origId); return res; }","Drop input for toast and child surfaces Toasts that do not have the trustedOverlay flag should not receive input. These windows should not have any children, so force this hierarchy of windows to drop all input by setting a flag on the toast window state which will apply the DROP_INPUT flag on all windows with an input channel. This is to prevent malicious apps from parenting surfaces with input channels to the toast window. Test: show toast and check if input feature flag DROP_INPUT id set via dumpsys Bug: b/197296414 Change-Id: I316b76b685ca5030fd8aa91283555efcce4d6994 Merged-In: I316b76b685ca5030fd8aa91283555efcce4d6994",https://github.com/LineageOS/android_frameworks_base/commit/55c1473bf2fedaacf7bb8ac068e6f9b1a625b5e0,,,services/core/java/com/android/server/wm/WindowManagerService.java,3,java,False,2022-02-02T17:13:21Z "@Override protected void assertCredentialsMatch(AuthenticationToken authcToken, AuthenticationInfo info) throws AuthenticationException { LoginAuthenticationInfo kapuaInfo = (LoginAuthenticationInfo) info; CredentialService credentialService = LOCATOR.getService(CredentialService.class); MfaOptionService mfaOptionService = LOCATOR.getService(MfaOptionService.class); KapuaId userId = kapuaInfo.getUser().getId(); KapuaId scopeId = kapuaInfo.getUser().getScopeId(); boolean hasMfa = false; boolean checkedUsernameAndPasswordMatch = false; boolean userPasswordMatch = true; try { if (KapuaSecurityUtils.doPrivileged(() -> mfaOptionService.findByUserId(userId, scopeId) != null)) { hasMfa = true; } } catch (KapuaException e) { logger.warn(""Error while finding User. Error: {}"", e.getMessage()); throw new ShiroException(""Error while finding user!"", e); } try { if (hasMfa) { super.assertCredentialsMatch(authcToken, info); } else { userPasswordMatch = ((UserPassCredentialsMatcher) getCredentialsMatcher()).doUsernameAndPasswordMatch(authcToken, info); checkedUsernameAndPasswordMatch = true; if (!userPasswordMatch) { String msg = ""Submitted credentials for token ["" + authcToken + ""] did not match the expected credentials.""; throw new IncorrectCredentialsException(msg); } } } catch (AuthenticationException authenticationEx) { try { Credential failedCredential = (Credential) kapuaInfo.getCredentials(); userPasswordMatch = checkedUsernameAndPasswordMatch ? userPasswordMatch : ((UserPassCredentialsMatcher) getCredentialsMatcher()).doUsernameAndPasswordMatch(authcToken, info); final boolean hasMfaAndUserPasswordMatch = hasMfa && userPasswordMatch; KapuaSecurityUtils.doPrivileged(() -> { Map credentialServiceConfig = kapuaInfo.getCredentialServiceConfig(); boolean lockoutPolicyEnabled = (boolean) credentialServiceConfig.get(""lockoutPolicy.enabled""); if (lockoutPolicyEnabled) { Date now = new Date(); int resetAfterSeconds = (int)credentialServiceConfig.get(""lockoutPolicy.resetAfter""); Date firstLoginFailure; boolean resetAttempts = failedCredential.getFirstLoginFailure() == null || now.after(failedCredential.getLoginFailuresReset()) || hasMfaAndUserPasswordMatch; if (resetAttempts) { firstLoginFailure = now; failedCredential.setLoginFailures(1); } else { firstLoginFailure = failedCredential.getFirstLoginFailure(); failedCredential.setLoginFailures(failedCredential.getLoginFailures() + 1); } Date loginFailureWindowExpiration = new Date(firstLoginFailure.getTime() + (resetAfterSeconds * 1000)); failedCredential.setFirstLoginFailure(firstLoginFailure); failedCredential.setLoginFailuresReset(loginFailureWindowExpiration); int maxLoginFailures = (int)credentialServiceConfig.get(""lockoutPolicy.maxFailures""); if (failedCredential.getLoginFailures() >= maxLoginFailures) { long lockoutDuration = (int)credentialServiceConfig.get(""lockoutPolicy.lockDuration""); Date resetDate = new Date(now.getTime() + (lockoutDuration * 1000)); failedCredential.setLockoutReset(resetDate); } } credentialService.update(failedCredential); }); } catch (KapuaException kex) { throw new ShiroException(""Error while updating lockout policy"", kex); } throw authenticationEx; } Credential credential = (Credential) kapuaInfo.getCredentials(); credential.setFirstLoginFailure(null); credential.setLoginFailuresReset(null); credential.setLockoutReset(null); credential.setLoginFailures(0); try { KapuaSecurityUtils.doPrivileged(() -> credentialService.update(credential)); } catch (KapuaException kex) { throw new ShiroException(""Error while updating lockout policy"", kex); } Subject currentSubject = SecurityUtils.getSubject(); Session session = currentSubject.getSession(); session.setAttribute(""scopeId"", scopeId); session.setAttribute(""userId"", userId); }","@Override protected void assertCredentialsMatch(AuthenticationToken authcToken, AuthenticationInfo info) throws AuthenticationException { LoginAuthenticationInfo kapuaInfo = (LoginAuthenticationInfo) info; CredentialService credentialService = LOCATOR.getService(CredentialService.class); MfaOptionService mfaOptionService = LOCATOR.getService(MfaOptionService.class); KapuaId userId = kapuaInfo.getUser().getId(); KapuaId scopeId = kapuaInfo.getUser().getScopeId(); boolean hasMfa = false; boolean checkedUsernameAndPasswordMatch = false; boolean userPasswordMatch = true; try { if (KapuaSecurityUtils.doPrivileged(() -> mfaOptionService.findByUserId(scopeId, userId) != null)) { hasMfa = true; } } catch (KapuaException e) { logger.warn(""Error while finding User. Error: {}"", e.getMessage()); throw new ShiroException(""Error while finding user!"", e); } try { if (hasMfa) { super.assertCredentialsMatch(authcToken, info); } else { userPasswordMatch = ((UserPassCredentialsMatcher) getCredentialsMatcher()).doUsernameAndPasswordMatch(authcToken, info); checkedUsernameAndPasswordMatch = true; if (!userPasswordMatch) { String msg = ""Submitted credentials for token ["" + authcToken + ""] did not match the expected credentials.""; throw new IncorrectCredentialsException(msg); } } } catch (AuthenticationException authenticationEx) { try { Credential failedCredential = (Credential) kapuaInfo.getCredentials(); userPasswordMatch = checkedUsernameAndPasswordMatch ? userPasswordMatch : ((UserPassCredentialsMatcher) getCredentialsMatcher()).doUsernameAndPasswordMatch(authcToken, info); final boolean hasMfaAndUserPasswordMatch = hasMfa && userPasswordMatch; KapuaSecurityUtils.doPrivileged(() -> { Map credentialServiceConfig = kapuaInfo.getCredentialServiceConfig(); boolean lockoutPolicyEnabled = (boolean) credentialServiceConfig.get(""lockoutPolicy.enabled""); if (lockoutPolicyEnabled) { Date now = new Date(); int resetAfterSeconds = (int)credentialServiceConfig.get(""lockoutPolicy.resetAfter""); Date firstLoginFailure; boolean resetAttempts = failedCredential.getFirstLoginFailure() == null || now.after(failedCredential.getLoginFailuresReset()) || hasMfaAndUserPasswordMatch; if (resetAttempts) { firstLoginFailure = now; failedCredential.setLoginFailures(1); } else { firstLoginFailure = failedCredential.getFirstLoginFailure(); failedCredential.setLoginFailures(failedCredential.getLoginFailures() + 1); } Date loginFailureWindowExpiration = new Date(firstLoginFailure.getTime() + (resetAfterSeconds * 1000)); failedCredential.setFirstLoginFailure(firstLoginFailure); failedCredential.setLoginFailuresReset(loginFailureWindowExpiration); int maxLoginFailures = (int)credentialServiceConfig.get(""lockoutPolicy.maxFailures""); if (failedCredential.getLoginFailures() >= maxLoginFailures) { long lockoutDuration = (int)credentialServiceConfig.get(""lockoutPolicy.lockDuration""); Date resetDate = new Date(now.getTime() + (lockoutDuration * 1000)); failedCredential.setLockoutReset(resetDate); } } credentialService.update(failedCredential); }); } catch (KapuaException kex) { throw new ShiroException(""Error while updating lockout policy"", kex); } throw authenticationEx; } Credential credential = (Credential) kapuaInfo.getCredentials(); credential.setFirstLoginFailure(null); credential.setLoginFailuresReset(null); credential.setLockoutReset(null); credential.setLoginFailures(0); try { KapuaSecurityUtils.doPrivileged(() -> credentialService.update(credential)); } catch (KapuaException kex) { throw new ShiroException(""Error while updating lockout policy"", kex); } Subject currentSubject = SecurityUtils.getSubject(); Session session = currentSubject.getSession(); session.setAttribute(""scopeId"", scopeId); session.setAttribute(""userId"", userId); }","Fix MfaOption search when authenticating Signed-off-by: Claudio Mezzasalma ",https://github.com/eclipse/kapua/commit/dcad9561ba3fa00c7674ac92f0f3b530df735e20,,,service/security/shiro/src/main/java/org/eclipse/kapua/service/authentication/shiro/realm/UserPassAuthenticatingRealm.java,3,java,False,2021-08-27T16:17:18Z "short select(byte[] buffer, short offset) { // // PRE-CONDITIONS // // NONE // // EXECUTION STEPS // // STEP 1 - Return the APT Util.arrayCopyNonAtomic( Config.TEMPLATE_APT, ZERO, buffer, offset, (short) Config.TEMPLATE_APT.length); return (short) Config.TEMPLATE_APT.length; }","short select(byte[] buffer, short offset) { // // PRE-CONDITIONS // // NONE // // EXECUTION STEPS // // STEP 1 - Evaluate whether any PIV state needs to be updated as a result of // configuration changes // STEP 1a) Local PIN try limit PIVPIN localPin = cspPIV.getPIN(PIV.ID_CVM_LOCAL_PIN); if (config.readValue(Config.CONFIG_PIN_RETRIES_CONTACT) != localPin.getTryLimit()) { localPin.setTryLimit(config.readValue(Config.CONFIG_PIN_RETRIES_CONTACT)); } // STEP 1b) PUK try limit PIVPIN puk = cspPIV.getPIN(PIV.ID_CVM_PUK); if (config.readValue(Config.CONFIG_PUK_RETRIES_CONTACT) != puk.getTryLimit()) { puk.setTryLimit(config.readValue(Config.CONFIG_PUK_RETRIES_CONTACT)); } // STEP 2 - Return the APT Util.arrayCopyNonAtomic( Config.TEMPLATE_APT, ZERO, buffer, offset, (short) Config.TEMPLATE_APT.length); return (short) Config.TEMPLATE_APT.length; }",Merge branch 'master' of https://github.com/makinako/OpenFIPS201,https://github.com/makinako/OpenFIPS201/commit/e8dfba3a0fdeda6eb6f63d6d28bf5ed44b086ecf,,,src/com/makina/security/openfips201/PIV.java,3,java,False,2022-08-31T13:37:50Z "private OAuth2AccessTokenWithAdditionalInfo generateOauthToken(String authorizationHeaderValue) { String[] tokenStringElements = authorizationHeaderValue.split(""\\s""); TokenGenerator tokenGenerator = tokenGeneratorFactory.createGenerator(tokenStringElements[0]); return tokenGenerator.generate(tokenStringElements[1]); }","private OAuth2AccessTokenWithAdditionalInfo generateOauthToken(String authorizationHeaderValue) { String[] tokenStringElements = authorizationHeaderValue.split(""\\s""); if (tokenStringElements.length != 2) { failWithUnauthorized(Messages.INVALID_AUTHORIZATION_HEADER_WAS_PROVIDED); } TokenGenerator tokenGenerator = tokenGeneratorFactory.createGenerator(tokenStringElements[0]); return tokenGenerator.generate(tokenStringElements[1]); }",Verify user password on basic auth call,https://github.com/cloudfoundry/multiapps-controller/commit/219181265bdfca0058b81679c29a94bac98c4017,,,multiapps-controller-web/src/main/java/org/cloudfoundry/multiapps/controller/web/security/AuthenticationLoaderFilter.java,3,java,False,2021-10-29T12:52:17Z "protected SavingsAccountTransactionData findInterestPostingTransactionFor(final LocalDate postingDate, final SavingsAccountData savingsAccountData) { SavingsAccountTransactionData postingTransation = null; List trans = savingsAccountData.getSavingsAccountTransactionData(); for (final SavingsAccountTransactionData transaction : trans) { if ((transaction.isInterestPostingAndNotReversed() || transaction.isOverdraftInterestAndNotReversed()) && transaction.occursOn(postingDate)) { postingTransation = transaction; break; } } return postingTransation; }","protected SavingsAccountTransactionData findInterestPostingTransactionFor(final LocalDate postingDate, final SavingsAccountData savingsAccountData) { SavingsAccountTransactionData postingTransation = null; List trans = savingsAccountData.getSavingsAccountTransactionData(); for (final SavingsAccountTransactionData transaction : trans) { if ((transaction.isInterestPostingAndNotReversed() || transaction.isOverdraftInterestAndNotReversed()) && transaction.occursOn(postingDate) && !transaction.isReversalTransaction()) { postingTransation = transaction; break; } } return postingTransation; }","fineract-1646 and fineract-1638 combined fix (#2457) authored-by: Dhaval Maniyar ",https://github.com/apache/fineract/commit/a80f589ad4ad91a7b1c8abbd864e6a5129e8e2cf,,,fineract-provider/src/main/java/org/apache/fineract/portfolio/savings/service/SavingsAccountInterestPostingServiceImpl.java,3,java,False,2022-07-28T08:30:15Z "protected Void saveBlock(final Block block) { traceLambda(LOG, ""Going to validate block {}"", block::toLogString); var optResult = this.getBlockValidatorForBlock(block) .validateAndProcessBlock( this.getProtocolContext(), block, HeaderValidationMode.FULL, HeaderValidationMode.NONE); if (optResult.blockProcessingOutputs.isPresent()) { traceLambda(LOG, ""Block {} was validated, going to import it"", block::toLogString); optResult.blockProcessingOutputs.get().worldState.persist(block.getHeader()); this.getProtocolContext() .getBlockchain() .appendBlock(block, optResult.blockProcessingOutputs.get().receipts); possiblyMoveHead(block); } else { final BadBlockManager badBlocksManager = protocolSchedule .getByBlockNumber(getProtocolContext().getBlockchain().getChainHeadBlockNumber()) .getBadBlocksManager(); badBlocksManager.addBadBlock(block); getBackwardChain().addBadChainToManager(badBlocksManager, block.getHash()); throw new BackwardSyncException( ""Cannot save block "" + block.toLogString() + "" because of "" + optResult.errorMessage.orElseThrow()); } return null; }","protected Void saveBlock(final Block block) { traceLambda(LOG, ""Going to validate block {}"", block::toLogString); var optResult = this.getBlockValidatorForBlock(block) .validateAndProcessBlock( this.getProtocolContext(), block, HeaderValidationMode.FULL, HeaderValidationMode.NONE); if (optResult.blockProcessingOutputs.isPresent()) { traceLambda(LOG, ""Block {} was validated, going to import it"", block::toLogString); optResult.blockProcessingOutputs.get().worldState.persist(block.getHeader()); this.getProtocolContext() .getBlockchain() .appendBlock(block, optResult.blockProcessingOutputs.get().receipts); possiblyMoveHead(block); } else { emitBadChainEvent(block); throw new BackwardSyncException( ""Cannot save block "" + block.toLogString() + "" because of "" + optResult.errorMessage.orElseThrow()); } return null; }","Fix post merge chain reog with invalid block (#4131) * fix infinite loop if a reorg contain a bad block * add cache for latest valid ancestors for bad blocks Signed-off-by: Daniel Lehrner ",https://github.com/hyperledger/besu/commit/979988707baa7ba43e3ccd420f016637096109c6,,,ethereum/eth/src/main/java/org/hyperledger/besu/ethereum/eth/sync/backwardsync/BackwardSyncContext.java,3,java,False,2022-07-26T09:26:28Z "private void doFreshBinaryMeasurements() { PackageManager pm = mContext.getPackageManager(); Slog.d(TAG, ""Obtained package manager""); // In general, we care about all APEXs, *and* all Modules, which may include some APKs. // First, we deal with all installed APEXs. for (PackageInfo packageInfo : getInstalledApexs()) { ApplicationInfo appInfo = packageInfo.applicationInfo; // compute SHA256 for these APEXs String sha256digest = computeSha256DigestOfFile(appInfo.sourceDir); if (sha256digest == null) { Slog.e(TAG, String.format(""Failed to compute SHA256 digest for %s"", packageInfo.packageName)); mBinaryHashes.put(packageInfo.packageName, BINARY_HASH_ERROR); } else { mBinaryHashes.put(packageInfo.packageName, sha256digest); } FrameworkStatsLog.write(FrameworkStatsLog.APEX_INFO_GATHERED, packageInfo.packageName, packageInfo.getLongVersionCode(), mBinaryHashes.get(packageInfo.packageName)); Slog.d(TAG, String.format(""Last update time for %s: %d"", packageInfo.packageName, packageInfo.lastUpdateTime)); mBinaryLastUpdateTimes.put(packageInfo.packageName, packageInfo.lastUpdateTime); } // Next, get all installed modules from PackageManager - skip over those APEXs we've // processed above for (ModuleInfo module : pm.getInstalledModules(PackageManager.MATCH_ALL)) { String packageName = module.getPackageName(); if (packageName == null) { Slog.e(TAG, ""ERROR: Encountered null package name for module "" + module.getApexModuleName()); continue; } if (mBinaryHashes.containsKey(module.getPackageName())) { continue; } // get PackageInfo for this module try { PackageInfo packageInfo = pm.getPackageInfo(packageName, PackageManager.PackageInfoFlags.of(PackageManager.MATCH_APEX)); ApplicationInfo appInfo = packageInfo.applicationInfo; // compute SHA256 digest for these modules String sha256digest = computeSha256DigestOfFile(appInfo.sourceDir); if (sha256digest == null) { Slog.e(TAG, String.format(""Failed to compute SHA256 digest for %s"", packageName)); mBinaryHashes.put(packageName, BINARY_HASH_ERROR); } else { mBinaryHashes.put(packageName, sha256digest); } Slog.d(TAG, String.format(""Last update time for %s: %d"", packageName, packageInfo.lastUpdateTime)); mBinaryLastUpdateTimes.put(packageName, packageInfo.lastUpdateTime); } catch (PackageManager.NameNotFoundException e) { Slog.e(TAG, ""ERROR: Could not obtain PackageInfo for package name: "" + packageName); continue; } } }","private void doFreshBinaryMeasurements() { PackageManager pm = mContext.getPackageManager(); Slog.d(TAG, ""Obtained package manager""); // In general, we care about all APEXs, *and* all Modules, which may include some APKs. // First, we deal with all installed APEXs. for (PackageInfo packageInfo : getInstalledApexs()) { ApplicationInfo appInfo = packageInfo.applicationInfo; // compute SHA256 for these APEXs String sha256digest = PackageUtils.computeSha256DigestForLargeFile(appInfo.sourceDir); if (sha256digest == null) { Slog.e(TAG, String.format(""Failed to compute SHA256 digest for %s"", packageInfo.packageName)); mBinaryHashes.put(packageInfo.packageName, BINARY_HASH_ERROR); } else { mBinaryHashes.put(packageInfo.packageName, sha256digest); } FrameworkStatsLog.write(FrameworkStatsLog.APEX_INFO_GATHERED, packageInfo.packageName, packageInfo.getLongVersionCode(), mBinaryHashes.get(packageInfo.packageName)); Slog.d(TAG, String.format(""Last update time for %s: %d"", packageInfo.packageName, packageInfo.lastUpdateTime)); mBinaryLastUpdateTimes.put(packageInfo.packageName, packageInfo.lastUpdateTime); } // Next, get all installed modules from PackageManager - skip over those APEXs we've // processed above for (ModuleInfo module : pm.getInstalledModules(PackageManager.MATCH_ALL)) { String packageName = module.getPackageName(); if (packageName == null) { Slog.e(TAG, ""ERROR: Encountered null package name for module "" + module.getApexModuleName()); continue; } if (mBinaryHashes.containsKey(module.getPackageName())) { continue; } // get PackageInfo for this module try { PackageInfo packageInfo = pm.getPackageInfo(packageName, PackageManager.PackageInfoFlags.of(PackageManager.MATCH_APEX)); ApplicationInfo appInfo = packageInfo.applicationInfo; // compute SHA256 digest for these modules String sha256digest = PackageUtils.computeSha256DigestForLargeFile( appInfo.sourceDir); if (sha256digest == null) { Slog.e(TAG, String.format(""Failed to compute SHA256 digest for %s"", packageName)); mBinaryHashes.put(packageName, BINARY_HASH_ERROR); } else { mBinaryHashes.put(packageName, sha256digest); } Slog.d(TAG, String.format(""Last update time for %s: %d"", packageName, packageInfo.lastUpdateTime)); mBinaryLastUpdateTimes.put(packageName, packageInfo.lastUpdateTime); } catch (PackageManager.NameNotFoundException e) { Slog.e(TAG, ""ERROR: Could not obtain PackageInfo for package name: "" + packageName); continue; } } }","Fix potential OOM issues when APEXs are too large. On low RAM devices, there can be potentially OOM issues when APEXs are too large, causing large buffers to be allocated when computing the SHA256 digest of those APEX packages. This change introduces the usage of DigestInputStream with different buffer sizes according to the state of device (whether it is a low ram device or not) to cap the memory usage. Buffer size is currently derived experimentally at either 1kB or 1MB. Bug: 217596264 Test: Manual. Change-Id: I1964ef9d7047496a758c7f427910f116be89fc51",https://github.com/LineageOS/android_frameworks_base/commit/74b4af53ca57a1dc5a94b1da895c8ab681ec6ecd,,,services/core/java/com/android/server/BinaryTransparencyService.java,3,java,False,2022-02-16T03:32:27Z "private void load(File folder) { this.folder = folder; this.userService = loadUsers(folder); System.out.println(Constants.baseFolder$ + "" set to "" + folder); if (userService == null) { JOptionPane.showMessageDialog(this, MessageFormat.format(""Sorry, {0} doesn't look like a Gitblit GO installation."", folder)); } else { // build empty certificate model for all users Map map = new HashMap(); for (String user : userService.getAllUsernames()) { UserModel model = userService.getUserModel(user); UserCertificateModel ucm = new UserCertificateModel(model); map.put(user, ucm); } File certificatesConfigFile = new File(folder, X509Utils.CA_CONFIG); FileBasedConfig config = new FileBasedConfig(certificatesConfigFile, FS.detect()); if (certificatesConfigFile.exists()) { try { config.load(); // replace user certificate model with actual data List list = UserCertificateConfig.KEY.parse(config).list; for (UserCertificateModel ucm : list) { ucm.user = userService.getUserModel(ucm.user.username); map.put(ucm.user.username, ucm); } } catch (IOException e) { e.printStackTrace(); } catch (ConfigInvalidException e) { e.printStackTrace(); } } tableModel.list = new ArrayList(map.values()); Collections.sort(tableModel.list); tableModel.fireTableDataChanged(); Utils.packColumns(table, Utils.MARGIN); File caKeystore = new File(folder, X509Utils.CA_KEY_STORE); if (!caKeystore.exists()) { if (!X509Utils.unlimitedStrength) { // prompt to confirm user understands JCE Standard Strength encryption int res = JOptionPane.showConfirmDialog(GitblitAuthority.this, Translation.get(""gb.jceWarning""), Translation.get(""gb.warning""), JOptionPane.YES_NO_OPTION, JOptionPane.WARNING_MESSAGE); if (res != JOptionPane.YES_OPTION) { if (Desktop.isDesktopSupported()) { if (Desktop.getDesktop().isSupported(Desktop.Action.BROWSE)) { try { Desktop.getDesktop().browse(URI.create(""http://www.oracle.com/technetwork/java/javase/downloads/index.html"")); } catch (IOException e) { } } } System.exit(1); } } // show certificate defaults dialog certificateDefaultsButton.doClick(); // create ""localhost"" ssl certificate prepareX509Infrastructure(); } } }","private void load(File folder) { this.folder = folder; this.userService = loadUsers(folder); System.out.println(Constants.baseFolder$ + "" set to "" + folder); if (userService == null) { JOptionPane.showMessageDialog(this, MessageFormat.format(""Sorry, {0} doesn't look like a Gitblit GO installation."", folder)); } else { // build empty certificate model for all users Map map = new HashMap(); for (String user : userService.getAllUsernames()) { UserModel model = userService.getUserModel(user); UserCertificateModel ucm = new UserCertificateModel(model); map.put(user, ucm); } File certificatesConfigFile = new File(folder, X509Utils.CA_CONFIG); FileBasedConfig config = new FileBasedConfig(certificatesConfigFile, FS.detect()); if (certificatesConfigFile.exists()) { try { config.load(); // replace user certificate model with actual data List list = UserCertificateConfig.KEY.parse(config).list; for (UserCertificateModel ucm : list) { ucm.user = userService.getUserModel(ucm.user.username); // Users may have been deleted, but are still present in authority.conf. // TODO: Currently this only keeps the app from crashing. It should provide means to show obsolete user entries and delete them. if (ucm.user != null) { map.put(ucm.user.username, ucm); } } } catch (IOException e) { e.printStackTrace(); } catch (ConfigInvalidException e) { e.printStackTrace(); } } tableModel.list = new ArrayList(map.values()); Collections.sort(tableModel.list); tableModel.fireTableDataChanged(); Utils.packColumns(table, Utils.MARGIN); File caKeystore = new File(folder, X509Utils.CA_KEY_STORE); if (!caKeystore.exists()) { if (!X509Utils.unlimitedStrength) { // prompt to confirm user understands JCE Standard Strength encryption int res = JOptionPane.showConfirmDialog(GitblitAuthority.this, Translation.get(""gb.jceWarning""), Translation.get(""gb.warning""), JOptionPane.YES_NO_OPTION, JOptionPane.WARNING_MESSAGE); if (res != JOptionPane.YES_OPTION) { if (Desktop.isDesktopSupported()) { if (Desktop.getDesktop().isSupported(Desktop.Action.BROWSE)) { try { Desktop.getDesktop().browse(URI.create(""http://www.oracle.com/technetwork/java/javase/downloads/index.html"")); } catch (IOException e) { } } } System.exit(1); } } // show certificate defaults dialog certificateDefaultsButton.doClick(); // create ""localhost"" ssl certificate prepareX509Infrastructure(); } } }","authority: Fix null pointer crash for deleted users When a user had a certificate, i.e. an entry in the Gitblit Authority database, but the user was deleted from the Gitblit database, then the Authority application crashes upon loading. This patch prevents the crash. The deleted user is no longer shown in the Authority. But the database entry still is kept. This should be improved to show deleted users and give the possibility to delete them from the Authority's database. This fixes #1359",https://github.com/gitblit-org/gitblit/commit/1c86273edb63f641064bca3a7d40f425e0da09ec,,,src/main/java/com/gitblit/authority/GitblitAuthority.java,3,java,False,2022-10-31T23:50:14Z "private void uploadFile(HttpServletRequest request, ViewEditForm form) throws Exception { if (WebUtils.hasSubmitParameter(request, SUBMIT_UPLOAD)) { if (form.getBackgroundImageMP() != null) { byte[] bytes = form.getBackgroundImageMP().getBytes(); if (bytes != null && bytes.length > 0) { // Create the path to the upload directory. String path = request.getSession().getServletContext().getRealPath(uploadDirectory); LOG.info(""ViewEditController:uploadFile: realpath=""+path); // Make sure the directory exists. File dir = new File(path); dir.mkdirs(); MultipartFile file = form.getBackgroundImageMP(); String fileName = file.getOriginalFilename(); if(fileName != null) { Stream.of(SUPPORTED_EXTENSIONS) .filter(fileName::endsWith) .findFirst() .ifPresent(ext -> { // Valid image! Add it to uploads int imageId = getNextImageId(dir); // Get an image id. String filename = imageId + ext; // Create the image file name. File image = new File(dir, filename); if(saveFile(bytes, image)) { // Save the file. form.getView().setBackgroundFilename(uploadDirectory + filename); LOG.info(""Image file has been successfully uploaded: "" + image.getName()); } else { LOG.warn(""Failed to save image file: "" + image.getName()); } }); } else { LOG.warn(""Image file is damaged!""); } } } } }","private void uploadFile(HttpServletRequest request, ViewEditForm form) throws Exception { if (WebUtils.hasSubmitParameter(request, SUBMIT_UPLOAD)) { MultipartFile file = form.getBackgroundImageMP(); if (file != null) { upload(request, form, file); } else { LOG.warn(""Image file is not attached.""); } } }",#1734 Vulnerabilities from ScadaBR - refactor,https://github.com/SCADA-LTS/Scada-LTS/commit/c0a7965f66458263346cec4bc00fb1f635b36f81,,,src/org/scada_lts/web/mvc/controller/ViewEditContorller.java,3,java,False,2022-02-16T08:07:59Z "def call(__self, __context, __obj, *args, **kwargs): """"""Call an object from sandboxed code."""""" # the double prefixes are to avoid double keyword argument # errors when proxying the call. if not __self.is_safe_callable(__obj): raise SecurityError('%r is not safely callable' % (__obj,)) return __context.call(__obj, *args, **kwargs)","def call(__self, __context, __obj, *args, **kwargs): """"""Call an object from sandboxed code."""""" fmt = inspect_format_method(__obj) if fmt is not None: return __self.format_string(fmt, args, kwargs) # the double prefixes are to avoid double keyword argument # errors when proxying the call. if not __self.is_safe_callable(__obj): raise SecurityError('%r is not safely callable' % (__obj,)) return __context.call(__obj, *args, **kwargs)",SECURITY: support sandboxing in format expressions,https://github.com/pallets/jinja/commit/9b53045c34e61013dc8f09b7e52a555fa16bed16,,,jinja2/sandbox.py,3,py,False,2016-12-29T13:13:38Z "@Override public void handleClick(Screen screen, int guiX, int guiY, double mouseX, double mouseY, int button) { if (!Minecraft.getInstance().player.inventory.getItemStack().isEmpty() && Minecraft.getInstance().player.inventory.getItemStack().getCapability(CapabilityFluidHandler.FLUID_HANDLER_ITEM_CAPABILITY).isPresent()){ Minecraft.getInstance().getSoundHandler().play(new SimpleSound(SoundEvents.UI_BUTTON_CLICK, SoundCategory.PLAYERS, 1f, 1f, Minecraft.getInstance().player.getPosition())); //getPosition if (screen instanceof ContainerScreen && ((ContainerScreen) screen).getContainer() instanceof ILocatable) { ILocatable locatable = (ILocatable) ((ContainerScreen) screen).getContainer(); CompoundNBT compoundNBT = new CompoundNBT(); if (tank instanceof FluidTankComponent){ compoundNBT.putString(""Name"",((FluidTankComponent) tank).getName()); } else { compoundNBT.putBoolean(""Invalid"", true); } Minecraft.getInstance().player.inventory.getItemStack().getCapability(CapabilityFluidHandler.FLUID_HANDLER_ITEM_CAPABILITY).ifPresent(iFluidHandlerItem -> { boolean canFillFromItem = tank.fill(iFluidHandlerItem.drain(Integer.MAX_VALUE, IFluidHandler.FluidAction.SIMULATE), IFluidHandler.FluidAction.SIMULATE) > 0; boolean canDrainFromItem = iFluidHandlerItem.fill(tank.drain(Integer.MAX_VALUE, IFluidHandler.FluidAction.SIMULATE), IFluidHandler.FluidAction.SIMULATE) > 0; if (canFillFromItem && button == 0) compoundNBT.putBoolean(""Fill"", true); if (canDrainFromItem && button == 1) compoundNBT.putBoolean(""Fill"", false); }); Titanium.NETWORK.get().sendToServer(new ButtonClickNetworkMessage(locatable.getLocatorInstance(), -3, compoundNBT)); } } }","@Override public void handleClick(Screen screen, int guiX, int guiY, double mouseX, double mouseY, int button) { if (!Minecraft.getInstance().player.inventory.getItemStack().isEmpty() && Minecraft.getInstance().player.inventory.getItemStack().getCapability(CapabilityFluidHandler.FLUID_HANDLER_ITEM_CAPABILITY).isPresent()){ Minecraft.getInstance().getSoundHandler().play(new SimpleSound(SoundEvents.UI_BUTTON_CLICK, SoundCategory.PLAYERS, 1f, 1f, Minecraft.getInstance().player.getPosition())); //getPosition if (screen instanceof ContainerScreen && ((ContainerScreen) screen).getContainer() instanceof ILocatable) { ILocatable locatable = (ILocatable) ((ContainerScreen) screen).getContainer(); CompoundNBT compoundNBT = new CompoundNBT(); if (tank instanceof FluidTankComponent){ compoundNBT.putString(""Name"",((FluidTankComponent) tank).getName()); } else { compoundNBT.putBoolean(""Invalid"", true); } Minecraft.getInstance().player.inventory.getItemStack().getCapability(CapabilityFluidHandler.FLUID_HANDLER_ITEM_CAPABILITY).ifPresent(iFluidHandlerItem -> { boolean isBucket = Minecraft.getInstance().player.inventory.getItemStack().getItem() instanceof BucketItem; int amount = isBucket ? FluidAttributes.BUCKET_VOLUME : Integer.MAX_VALUE; boolean canFillFromItem = false; boolean canDrainFromItem = false; if (isBucket) { canFillFromItem = tank.fill(iFluidHandlerItem.drain(amount, IFluidHandler.FluidAction.SIMULATE), IFluidHandler.FluidAction.SIMULATE) == FluidAttributes.BUCKET_VOLUME; canDrainFromItem = iFluidHandlerItem.fill(tank.drain(amount, IFluidHandler.FluidAction.SIMULATE), IFluidHandler.FluidAction.SIMULATE) == FluidAttributes.BUCKET_VOLUME; } else { canFillFromItem = tank.fill(iFluidHandlerItem.drain(amount, IFluidHandler.FluidAction.SIMULATE), IFluidHandler.FluidAction.SIMULATE) > 0; canDrainFromItem = iFluidHandlerItem.fill(tank.drain(amount, IFluidHandler.FluidAction.SIMULATE), IFluidHandler.FluidAction.SIMULATE) > 0; } if (canFillFromItem && button == 0) compoundNBT.putBoolean(""Fill"", true); if (canDrainFromItem && button == 1) compoundNBT.putBoolean(""Fill"", false); }); Titanium.NETWORK.get().sendToServer(new ButtonClickNetworkMessage(locatable.getLocatorInstance(), -3, compoundNBT)); } } }",Fixed Tank GUI interaction bypassing bucket limits,https://github.com/InnovativeOnlineIndustries/Industrial-Foregoing/commit/4a6391d80a381ec1a808492f82a5f78e3538e4b9,,,src/main/java/com/buuz135/industrial/gui/component/ItemStackTankScreenAddon.java,3,java,False,2021-05-29T20:42:17Z "public static boolean isSpellEnabled(String tag){ return enabledSpells.get(tag).get(); }","public static boolean isSpellEnabled(String tag){ return enabledSpells.containsKey(tag) ? enabledSpells.get(tag).get() : true; }","Default to true if a spellPart isn't found Changing this line'll default to true whenever a glyph is added by an addon that *isn't* in the default Config, preventing an NPE crash for addons that add new glpyhs and spell parts.",https://github.com/baileyholl/Ars-Nouveau/commit/93ce14df571fa978047965cc2fdc9be57976ae2f,,,src/main/java/com/hollingsworth/arsnouveau/setup/Config.java,3,java,False,2021-04-07T19:44:58Z "public String addAutomaticZenRule(String pkg, AutomaticZenRule automaticZenRule, String reason) { if (!isSystemRule(automaticZenRule)) { PackageItemInfo component = getServiceInfo(automaticZenRule.getOwner()); if (component == null) { component = getActivityInfo(automaticZenRule.getConfigurationActivity()); } if (component == null) { throw new IllegalArgumentException(""Lacking enabled CPS or config activity""); } int ruleInstanceLimit = -1; if (component.metaData != null) { ruleInstanceLimit = component.metaData.getInt( ConditionProviderService.META_DATA_RULE_INSTANCE_LIMIT, -1); } int newRuleInstanceCount = getCurrentInstanceCount(automaticZenRule.getOwner()) + getCurrentInstanceCount(automaticZenRule.getConfigurationActivity()) + 1; int newPackageRuleCount = getPackageRuleCount(pkg) + 1; if (newPackageRuleCount > RULE_LIMIT_PER_PACKAGE || (ruleInstanceLimit > 0 && ruleInstanceLimit < newRuleInstanceCount)) { throw new IllegalArgumentException(""Rule instance limit exceeded""); } } ZenModeConfig newConfig; synchronized (mConfig) { if (mConfig == null) { throw new AndroidRuntimeException(""Could not create rule""); } if (DEBUG) { Log.d(TAG, ""addAutomaticZenRule rule= "" + automaticZenRule + "" reason="" + reason); } newConfig = mConfig.copy(); ZenRule rule = new ZenRule(); populateZenRule(pkg, automaticZenRule, rule, true); newConfig.automaticRules.put(rule.id, rule); if (setConfigLocked(newConfig, reason, rule.component, true)) { return rule.id; } else { throw new AndroidRuntimeException(""Could not create rule""); } } }","public String addAutomaticZenRule(String pkg, AutomaticZenRule automaticZenRule, String reason) { if (!ZenModeConfig.SYSTEM_AUTHORITY.equals(pkg)) { PackageItemInfo component = getServiceInfo(automaticZenRule.getOwner()); if (component == null) { component = getActivityInfo(automaticZenRule.getConfigurationActivity()); } if (component == null) { throw new IllegalArgumentException(""Lacking enabled CPS or config activity""); } int ruleInstanceLimit = -1; if (component.metaData != null) { ruleInstanceLimit = component.metaData.getInt( ConditionProviderService.META_DATA_RULE_INSTANCE_LIMIT, -1); } int newRuleInstanceCount = getCurrentInstanceCount(automaticZenRule.getOwner()) + getCurrentInstanceCount(automaticZenRule.getConfigurationActivity()) + 1; int newPackageRuleCount = getPackageRuleCount(pkg) + 1; if (newPackageRuleCount > RULE_LIMIT_PER_PACKAGE || (ruleInstanceLimit > 0 && ruleInstanceLimit < newRuleInstanceCount)) { throw new IllegalArgumentException(""Rule instance limit exceeded""); } } ZenModeConfig newConfig; synchronized (mConfig) { if (mConfig == null) { throw new AndroidRuntimeException(""Could not create rule""); } if (DEBUG) { Log.d(TAG, ""addAutomaticZenRule rule= "" + automaticZenRule + "" reason="" + reason); } newConfig = mConfig.copy(); ZenRule rule = new ZenRule(); populateZenRule(pkg, automaticZenRule, rule, true); newConfig.automaticRules.put(rule.id, rule); if (setConfigLocked(newConfig, reason, rule.component, true)) { return rule.id; } else { throw new AndroidRuntimeException(""Could not create rule""); } } }","Check rule package name in ZenModeHelper.addAutomaticRule instead of checking that of the configuration activity, which is potentially spoofable. The package name is verified to be the same app as the caller by NMS. This change removes isSystemRule (called only once) in favor of checking the provided package name directly. Bug: 242537431 Test: ZenModeHelperTest, manual by verifying via provided exploit apk Change-Id: Ic7f350618c26a613df455a4128c9195f4b424a4d Merged-In: Ic7f350618c26a613df455a4128c9195f4b424a4d (cherry picked from commit a826f9bd15d149305814a835fb5d1a3921a085f5) Merged-In: Ic7f350618c26a613df455a4128c9195f4b424a4d",https://github.com/LineageOS/android_frameworks_base/commit/5f2e985bd60223bc6e0a3d160707157c6dcc93d8,,,services/core/java/com/android/server/notification/ZenModeHelper.java,3,java,False,2022-08-25T20:23:12Z "@Override public List lookup(String hostname) throws UnknownHostException { List addressList = null; // 系统 dns try { addressList = systemDns.lookup(hostname); } catch (IOException e) { handleDnsError(e, hostname); } if (addressList != null && addressList.size() > 0) { return addressList; } // http dns try { addressList = httpDns.lookup(hostname); } catch (IOException e) { handleDnsError(e, hostname); } return addressList; }","@Override public List lookup(String hostname) throws UnknownHostException { List addressList = null; int dnsTimeout = GlobalConfiguration.getInstance().dnsResolveTimeout; // 自定义 dns if (customDns != null) { try { addressList = customDns.lookup(hostname); } catch (IOException e) { handleDnsError(e, hostname); } if (addressList != null && addressList.size() > 0) { return addressList; } } // 系统 dns try { addressList = systemDns.lookup(hostname); } catch (IOException e) { handleDnsError(e, hostname); } if (addressList != null && addressList.size() > 0) { return addressList; } // http dns try { HttpDns httpDns = new HttpDns(dnsTimeout); addressList = httpDns.lookup(hostname); } catch (IOException e) { handleDnsError(e, hostname); } if (addressList != null && addressList.size() > 0) { return addressList; } // udp dns try { UdpDns udpDns = new UdpDns(dnsTimeout); addressList = udpDns.lookup(hostname); } catch (IOException e) { handleDnsError(e, hostname); } return addressList; }",handle dns hijacked & dns prefetch add doh,https://github.com/qiniu/android-sdk/commit/ada3c8feb608ed37fe8d64ba2d10ac672a207525,,,library/src/main/java/com/qiniu/android/http/dns/HappyDns.java,3,java,False,2021-08-27T10:02:18Z "public void load() { squashBakedQuads = getBoolean(""squashBakedQuads"", ""bakedquad"", ""Saves RAM by removing BakedQuad instance variables, redirecting BakedQuad creation to specific BakedQuad child classes. This will be forcefully turned off when Optifine is installed as it is incompatible"", true); classesThatCallBakedQuadCtor = getStringArray(""classesThatCallBakedQuadCtor"", ""bakedquad"", ""Classes where BakedQuad::new calls need to be redirected. As of 3.2, this should be done automatically, while the changes will show in the next launch"", ""net.minecraft.client.renderer.block.model.FaceBakery""); classesThatExtendBakedQuad = getStringArray(""classesThatExtendBakedQuad"", ""bakedquad"", ""Classes that extend BakedQuad need to be handled separately. This should be done automatically, while the changes will show in the next launch"", """"); logClassesThatCallBakedQuadCtor = getBoolean(""logClassesThatCallBakedQuadCtor"", ""bakedquad"", ""Log classes that need their BakedQuad::new calls redirected"", true); reuseBucketQuads = getBoolean(""reuseBucketQuads"", ""bakedquad"", ""Allows bucket models to re-use UnpackedBakedQuads"", true); cleanupLaunchClassLoaderEarly = getBoolean(""cleanupLaunchClassLoaderEarly"", ""launchwrapper"", ""Cleanup some redundant data structures in LaunchClassLoader at the earliest point possible (when LoliASM is loaded). Helpful for those that don't have enough RAM to load into the game. This can induce slowdowns while loading the game in exchange for more available RAM"", false); cleanupLaunchClassLoaderLate = getBoolean(""cleanupLaunchClassLoaderLate"", ""launchwrapper"", ""Cleanup some redundant data structures in LaunchClassLoader at the latest point possible (when the game reaches the Main Screen). This is for those that have enough RAM to load the game and do not want any slowdowns while loading. Note: if 'cleanupLaunchClassLoaderEarly' is 'true', this option will be ignored"", true); noResourceCache = getBoolean(""noResourceCache"", ""launchwrapper"", ""Disabling caching of resources (Class Bytes). This will induce slowdowns to game/world loads in exchange for more available RAM"", false); noClassCache = getBoolean(""noClassCache"", ""launchwrapper"", ""Disabling caching of classes. This will induce major slowdowns to game/world loads in exchange for more available RAM"", false); weakResourceCache = getBoolean(""weakResourceCache"", ""launchwrapper"", ""Weaken the caching of resources (Class Bytes). This allows the GC to free up more space when the caches are no longer needed. If 'noResourceCache' is 'true', this option will be ignored. This option coincides with Foamfix's 'weakenResourceCache' option"", true); weakClassCache = getBoolean(""weakClassCache"", ""launchwrapper"", ""Weaken the caching of classes. This allows the GC to free up more space when the caches are no longer needed. If 'noClassCache' is 'true', this option will be ignored"", true); disablePackageManifestMap = getBoolean(""disablePackageManifestMap"", ""launchwrapper"", ""Disable the unusused Package Manifest map. This option coincides with Foamfix's 'removePackageManifestMap' option"", true); cleanCachesOnGameLoad = getBoolean(""cleanCachesOnGameLoad"", ""launchwrapper"", ""Invalidate and clean cache entries when the game finishes loading (onto the main screen). Loading into the first world may take longer. This option wouldn't do anything if 'cleanupLaunchClassLoaderLate' is 'true'"", false); // cleanCachesOnWorldLoad = getBoolean(""cleanCachesOnWorldLoad"", ""launchwrapper"", ""Invalidate and clean cache entries when you load into a world, whether that be loading into a singleplayer world or a multiplayer server."", true); resourceLocationCanonicalization = getBoolean(""resourceLocationCanonicalization"", ""canonicalization"", ""Deduplicate ResourceLocation and ModelResourceLocation instances"", true); modelConditionCanonicalization = getBoolean(""modelConditionCanonicalization"", ""canonicalization"", ""Deduplicate Model Conditions. Enable this if you do not have Foamfix installed"", false); nbtTagStringBackingStringCanonicalization = getBoolean(""nbtTagStringBackingStringCanonicalization"", ""canonicalization"", ""Deduplicate Strings in NBTTagString"", true); nbtBackingMapStringCanonicalization = getBoolean(""nbtBackingMapStringCanonicalization"", ""canonicalization"", ""Deduplicate String keys in NBTTagCompound"", true); packageStringCanonicalization = getBoolean(""packageStringCanonicalization"", ""canonicalization"", ""Deduplicate package strings when Forge gathers them when mod candidates are loaded"", true); lockCodeCanonicalization = getBoolean(""lockCodeCanonicalization"", ""canonicalization"", ""Deduplicate LockCode when reading from NBT"", true); spriteNameCanonicalization = getBoolean(""spriteNameCanonicalization"", ""canonicalization"", ""Deduplicate TextureAtlasSprite's names"", true); asmDataStringCanonicalization = getBoolean(""asmDataStringCanonicalization"", ""canonicalization"", ""Deduplicate ASMData related Strings"", true); vertexDataCanonicalization = getBoolean(""vertexDataCanonicalization"", ""canonicalization"", ""EXPERIMENTAL: Deduplicate BakedQuad's Vertex Data array. If you see any artifacting in-game, turn this off and report it on github"", true); filePermissionsCacheCanonicalization = getBoolean(""filePermissionsCacheCanonicalization"", ""canonicalization"", ""Deduplicate Java's FilePermission cache's names within SecureClassLoader"", true); optimizeFMLRemapper = getBoolean(""optimizeFMLRemapper"", ""remapper"", ""Optimizing Forge's Remapper for not storing redundant entries"", true); // optimizeDataStructures = getBoolean(""optimizeDataStructures"", ""datastructures"", ""Optimizes various data structures around Minecraft"", true); optimizeRegistries = getBoolean(""optimizeRegistries"", ""datastructures"", ""Optimizes registries"", true); optimizeNBTTagCompoundBackingMap = getBoolean(""optimizeNBTTagCompoundBackingMap"", ""datastructures"", ""Optimize NBTTagCompound's backing map structure"", true); optimizeFurnaceRecipeStore = getBoolean(""optimizeFurnaceRecipeStore"", ""datastructures"", ""Optimizing FurnaceRecipes. FastFurnace will see very little benefit when this option is turned on"", true); stripNearUselessItemStackFields = getBoolean(""stripNearUselessItemStackFields"", ""datastructures"", ""EXPERIMENTAL: Strips ItemStack of some of its fields as it stores some near-useless references"", true); moreModelManagerCleanup = getBoolean(""moreModelManagerCleanup"", ""datastructures"", ""Clears and trims ModelManager data structures after models are loaded and baked"", true); efficientHashing = getBoolean(""efficientHashing"", ""datastructures"", ""Improve hashing performances of various objects"", true); releaseSpriteFramesCache = getBoolean(""releaseSpriteFramesCache"", ""textures"", ""Releases TextureAtlasSprite's framesTextureData. Won't touch custom TextureAtlasSprite implementations"", true); optimizeSomeRendering = getBoolean(""optimizeSomeRendering"", ""rendering"", ""Optimizes some rendering features, not game-breaking; however, negligible at times"", true); stripUnnecessaryLocalsInRenderHelper = getBoolean(""stripUnnecessaryLocalsInRenderHelper"", ""rendering"", ""Strip unnecessary locals in RenderHelper::enableStandardItemLighting, no idea why it's there"", true); quickerEnableUniversalBucketCheck = getBoolean(""quickerEnableUniversalBucketCheck"", ""misc"", ""Optimizes FluidRegistry::enableUniversalBucket check"", true); stripInstancedRandomFromSoundEventAccessor = getBoolean(""stripInstancedRandomFromSoundEventAccessor"", ""misc"", ""Strips the boring instanced Random object from SoundEventAccessors and uses ThreadLocalRandom instead"", true); classCaching = getBoolean(""classCaching"", ""misc"", ""[W.I.P] - EXPERIMENTAL: Yet another attempt at caching classes between loads"", false); copyScreenshotToClipboard = getBoolean(""copyScreenshotToClipboard"", ""misc"", ""Copy image after screenshotting to clipboard"", false); releaseScreenshotCache = getBoolean(""releaseScreenshotCache"", ""misc"", ""For some reason Mojang decided to cache int buffers and arrays after a screenshot is taken, this makes sure they're never cached"", true); fixBlockIEBaseArrayIndexOutOfBoundsException = getBoolean(""fixBlockIEBaseArrayIndexOutOfBoundsException"", ""modfixes"", ""When Immersive Engineering is installed, sometimes it or it's addons can induce an ArrayIndexOutOfBoundsException in BlockIEBase#getPushReaction. This option will be ignored when IE isn't installed"", true); cleanupChickenASMClassHierarchyManager = getBoolean(""cleanupChickenASMClassHierarchyManager"", ""modfixes"", ""EXPERIMENTAL: When ChickenASM (Library of CodeChickenLib and co.) is installed, ClassHierarchyManager can cache a lot of Strings and seem to be unused in any transformation purposes. This clears ClassHierarchyManager of those redundant strings. This option will be ignored when ChickenASM isn't installed"", true); optimizeAmuletRelatedFunctions = getBoolean(""optimizeAmuletRelatedFunctions"", ""modfixes"", ""Optimizes Astral Sorcery's Resplendent Prism related functions. This option will be ignored when Astral Sorcery isn't installed"", true); labelCanonicalization = getBoolean(""labelCanonicalization"", ""modfixes"", ""When Just Enough Items is installed, it deduplicates strings in the generated generalized suffix trees' edge labels. This option will be ignored when Just Enough Items isn't installed"", true); skipCraftTweakerRecalculatingSearchTrees = getBoolean(""skipCraftTweakerRecalculatingSearchTrees"", ""modfixes"", ""When CraftTweaker is installed, large modpacks tend to stall in the last stage of loading, when CraftTweaker inexplicably recalculates search trees. This option will be ignored when CraftTweaker isn't installed"", true); bwmBlastingOilOptimization = getBoolean(""bwmBlastingOilOptimization"", ""modfixes"", ""When Better with Mods is installed, optimize Blasting Oil related events. The original implementation harms server performance at any given moment. This option will be ignored when Better with Mods isn't installed"", true); optimizeQMDBeamRenderer = getBoolean(""optimizeQMDBeamRenderer"", ""modfixes"", ""When QMD is installed, optimize its BeamRenderer. The original implementation harms client performance heavily (takes ~5% of each tick time). This option will be ignored when QMD isn't installed"", true); repairEvilCraftEIOCompat = getBoolean(""repairEvilCraftEIOCompat"", ""modfixes"", ""When EvilCraft Compat + EnderIO is installed, repair the compatibility module"", true); optimizeArcaneLockRendering = getBoolean(""optimizeArcaneLockRendering"", ""modfixes"", ""When Electroblob's Wizardry is installed, optimize the search for arcane locked tile entities to render"", true); fixXU2CrafterCrash = getBoolean(""fixXU2CrafterCrash"", ""modfixes"", ""When Extra Utilities 2 is installed, fix and optimize mechanical crafter's rendering"", true); disableXU2CrafterRendering = getBoolean(""disableXU2CrafterRendering"", ""modfixes"", ""When Extra Utilities 2 is installed, disable the crafter's rendering of the item being crafted, this can reduce lag, ignores fixXU2CrafterCrash config option"", false); fixTFCFallingBlockFalseStartingTEPos = getBoolean(""fixTFCFallingBlockFalseStartingTEPos"", ""modfixes"", ""When TerraFirmaCraft is installed, fix the falling block's false starting position "", true); fixAmuletHolderCapability = getBoolean(""fixAmuletHolderCapability"", ""capability"", ""Fixes Astral Sorcery applying AmuletHolderCapability to large amount of ItemStacks when it isn't needed. This option will be ignored when Astral Sorcery isn't installed"", true); delayItemStackCapabilityInit = getBoolean(""delayItemStackCapabilityInit"", ""capability"", ""Delays ItemStack's capabilities from being initialized until they needed to be"", true); fixFillBucketEventNullPointerException = getBoolean(""fixFillBucketEventNullPointerException"", ""forgefixes"", ""Fixes Forge's mistake of annotating FillBucketEvent#getFilledBucket as @Nonnull when the contract isn't fulfilled nor checked. First discovered here: https://github.com/Divine-Journey-2/main/issues/295"", true); fixTileEntityOnLoadCME = getBoolean(""fixTileEntityOnLoadCME"", ""forgefixes"", ""Fixes a vanilla-forge code interaction bug leading to a possible ConcurrentModificationException/StackOverflowError crash. First discovered here: https://github.com/GregTechCE/GregTech/issues/1256"", true); removeForgeSecurityManager = getBoolean(""removeForgeSecurityManager"", ""forgefixes"", ""EXPERIMENTAL: Forcibly remove Forge's FMLSecurityManager that adds very very slight overheads in calls that requires permission checks"", false); fasterEntitySpawnPreparation = getBoolean(""fasterEntitySpawnPreparation"", ""forgefixes"", ""Fixes Forge's EntityEntry calling a slow Constructor::newInstance call every time an entity spawns, it is replaced with a fast Function::get generated from LambdaMetafactory#metafactory"", true); sparkProfileEntireGameLoad = getBoolean(""sparkProfileEntireGameLoad"", ""spark"", ""When Spark is installed, profile the loading of the game in its entirety"", false); sparkProfileEntireWorldLoad = getBoolean(""sparkProfileEntireWorldLoad"", ""spark"", ""When Spark is installed, profile the loading of the world in its entirety"", false); sparkProfileCoreModLoading = getBoolean(""sparkProfileCoreModLoading"", ""spark"", ""When Spark is installed, profile the loading of coremods, but only those that load after LoliASM"", false); sparkProfileConstructionStage = getBoolean(""sparkProfileConstructionStage"", ""spark"", ""When Spark is installed, profile the loading of FMLConstructionEvent stage"", false); sparkProfilePreInitializationStage = getBoolean(""sparkProfilePreInitializationStage"", ""spark"", ""When Spark is installed, profile the loading of FMLPreInitializationEvent stage"", false); sparkProfileInitializationStage = getBoolean(""sparkProfileInitializationStage"", ""spark"", ""When Spark is installed, profile the loading of FMLInitializationEvent stage"", false); sparkProfilePostInitializationStage = getBoolean(""sparkProfilePostInitializationStage"", ""spark"", ""When Spark is installed, profile the loading of FMLPostInitializationEvent stage"", false); sparkProfileLoadCompleteStage = getBoolean(""sparkProfileLoadCompleteStage"", ""spark"", ""When Spark is installed, profile the loading of FMLLoadCompleteEvent stage"", false); sparkProfileFinalizingStage = getBoolean(""sparkProfileFinalizingStage"", ""spark"", ""When Spark is installed, profile the loading of FMLModIdMappingEvent stage, this is the last event fired before the game is finalized"", false); sparkProfileWorldAboutToStartStage = getBoolean(""sparkProfileWorldAboutToStartStage"", ""spark"", ""When Spark is installed, profile the loading of FMLServerAboutToStartEvent stage"", false); sparkProfileWorldStartingStage = getBoolean(""sparkProfileWorldStartingStage"", ""spark"", ""When Spark is installed, profile the loading of FMLServerStartingEvent stage"", false); sparkProfileWorldStartedStage = getBoolean(""sparkProfileWorldStartedStage"", ""spark"", ""When Spark is installed, profile the loading of FMLServerStartedEvent stage"", false); includeAllThreadsWhenProfiling = getBoolean(""includeAllThreadsWhenProfiling"", ""spark"", ""Allow LoliASM's Spark profiling to include all threads that are present"", true); sparkSummarizeHeapSpaceAfterGameLoads = getBoolean(""sparkSummarizeHeapSpaceAfterGameLoads"", ""spark"", ""When Spark is installed, summarize the heap space (/spark heapsummary) when the game finishes loading"", false); sparkSummarizeHeapSpaceAfterWorldLoads = getBoolean(""sparkSummarizeHeapSpaceAfterWorldLoads"", ""spark"", ""When Spark is installed, summarize the heap space (/spark heapsummary) when the world finishes loading"", false); furnaceExperienceFCFS = getBoolean(""furnaceExperienceFCFS"", ""furnace"", ""When optimizeFurnaceRecipeStore is true, experience is determined by who registers the entry first, this is also the fallback option if all three options aren't true"", true); furnaceExperienceVanilla = getBoolean(""furnaceExperienceVanilla"", ""furnace"", ""When optimizeFurnaceRecipeStore is true, experience is determined the vanilla way, this method is the most inefficient and random"", false); furnaceExperienceMost = getBoolean(""furnaceExperienceMost"", ""furnace"", ""When optimizeFurnaceRecipeStore is true, experience is determined by whichever entry gives the most experience"", false); makeEventsSingletons = getBoolean(""makeEventsSingletons"", ""events"", ""[EXPERIMENTAL]: Stops mass object creation when Forge is firing events, this can decrease Garbage Collection pressure"", false); configuration.save(); }","public void load() { squashBakedQuads = getBoolean(""squashBakedQuads"", ""bakedquad"", ""Saves RAM by removing BakedQuad instance variables, redirecting BakedQuad creation to specific BakedQuad child classes. This will be forcefully turned off when Optifine is installed as it is incompatible"", true); classesThatCallBakedQuadCtor = getStringArray(""classesThatCallBakedQuadCtor"", ""bakedquad"", ""Classes where BakedQuad::new calls need to be redirected. As of 3.2, this should be done automatically, while the changes will show in the next launch"", ""net.minecraft.client.renderer.block.model.FaceBakery""); classesThatExtendBakedQuad = getStringArray(""classesThatExtendBakedQuad"", ""bakedquad"", ""Classes that extend BakedQuad need to be handled separately. This should be done automatically, while the changes will show in the next launch"", """"); logClassesThatCallBakedQuadCtor = getBoolean(""logClassesThatCallBakedQuadCtor"", ""bakedquad"", ""Log classes that need their BakedQuad::new calls redirected"", true); reuseBucketQuads = getBoolean(""reuseBucketQuads"", ""bakedquad"", ""Allows bucket models to re-use UnpackedBakedQuads"", true); cleanupLaunchClassLoaderEarly = getBoolean(""cleanupLaunchClassLoaderEarly"", ""launchwrapper"", ""Cleanup some redundant data structures in LaunchClassLoader at the earliest point possible (when LoliASM is loaded). Helpful for those that don't have enough RAM to load into the game. This can induce slowdowns while loading the game in exchange for more available RAM"", false); cleanupLaunchClassLoaderLate = getBoolean(""cleanupLaunchClassLoaderLate"", ""launchwrapper"", ""Cleanup some redundant data structures in LaunchClassLoader at the latest point possible (when the game reaches the Main Screen). This is for those that have enough RAM to load the game and do not want any slowdowns while loading. Note: if 'cleanupLaunchClassLoaderEarly' is 'true', this option will be ignored"", true); noResourceCache = getBoolean(""noResourceCache"", ""launchwrapper"", ""Disabling caching of resources (Class Bytes). This will induce slowdowns to game/world loads in exchange for more available RAM"", false); noClassCache = getBoolean(""noClassCache"", ""launchwrapper"", ""Disabling caching of classes. This will induce major slowdowns to game/world loads in exchange for more available RAM"", false); weakResourceCache = getBoolean(""weakResourceCache"", ""launchwrapper"", ""Weaken the caching of resources (Class Bytes). This allows the GC to free up more space when the caches are no longer needed. If 'noResourceCache' is 'true', this option will be ignored. This option coincides with Foamfix's 'weakenResourceCache' option"", true); weakClassCache = getBoolean(""weakClassCache"", ""launchwrapper"", ""Weaken the caching of classes. This allows the GC to free up more space when the caches are no longer needed. If 'noClassCache' is 'true', this option will be ignored"", true); disablePackageManifestMap = getBoolean(""disablePackageManifestMap"", ""launchwrapper"", ""Disable the unusused Package Manifest map. This option coincides with Foamfix's 'removePackageManifestMap' option"", true); cleanCachesOnGameLoad = getBoolean(""cleanCachesOnGameLoad"", ""launchwrapper"", ""Invalidate and clean cache entries when the game finishes loading (onto the main screen). Loading into the first world may take longer. This option wouldn't do anything if 'cleanupLaunchClassLoaderLate' is 'true'"", false); // cleanCachesOnWorldLoad = getBoolean(""cleanCachesOnWorldLoad"", ""launchwrapper"", ""Invalidate and clean cache entries when you load into a world, whether that be loading into a singleplayer world or a multiplayer server."", true); resourceLocationCanonicalization = getBoolean(""resourceLocationCanonicalization"", ""canonicalization"", ""Deduplicate ResourceLocation and ModelResourceLocation instances"", true); modelConditionCanonicalization = getBoolean(""modelConditionCanonicalization"", ""canonicalization"", ""Deduplicate Model Conditions. Enable this if you do not have Foamfix installed"", false); nbtTagStringBackingStringCanonicalization = getBoolean(""nbtTagStringBackingStringCanonicalization"", ""canonicalization"", ""Deduplicate Strings in NBTTagString"", true); nbtBackingMapStringCanonicalization = getBoolean(""nbtBackingMapStringCanonicalization"", ""canonicalization"", ""Deduplicate String keys in NBTTagCompound"", true); packageStringCanonicalization = getBoolean(""packageStringCanonicalization"", ""canonicalization"", ""Deduplicate package strings when Forge gathers them when mod candidates are loaded"", true); lockCodeCanonicalization = getBoolean(""lockCodeCanonicalization"", ""canonicalization"", ""Deduplicate LockCode when reading from NBT"", true); spriteNameCanonicalization = getBoolean(""spriteNameCanonicalization"", ""canonicalization"", ""Deduplicate TextureAtlasSprite's names"", true); asmDataStringCanonicalization = getBoolean(""asmDataStringCanonicalization"", ""canonicalization"", ""Deduplicate ASMData related Strings"", true); vertexDataCanonicalization = getBoolean(""vertexDataCanonicalization"", ""canonicalization"", ""EXPERIMENTAL: Deduplicate BakedQuad's Vertex Data array. If you see any artifacting in-game, turn this off and report it on github"", true); filePermissionsCacheCanonicalization = getBoolean(""filePermissionsCacheCanonicalization"", ""canonicalization"", ""Deduplicate Java's FilePermission cache's names within SecureClassLoader"", true); optimizeFMLRemapper = getBoolean(""optimizeFMLRemapper"", ""remapper"", ""Optimizing Forge's Remapper for not storing redundant entries"", true); // optimizeDataStructures = getBoolean(""optimizeDataStructures"", ""datastructures"", ""Optimizes various data structures around Minecraft"", true); optimizeRegistries = getBoolean(""optimizeRegistries"", ""datastructures"", ""Optimizes registries"", true); optimizeNBTTagCompoundBackingMap = getBoolean(""optimizeNBTTagCompoundBackingMap"", ""datastructures"", ""Optimize NBTTagCompound's backing map structure"", true); optimizeFurnaceRecipeStore = getBoolean(""optimizeFurnaceRecipeStore"", ""datastructures"", ""Optimizing FurnaceRecipes. FastFurnace will see very little benefit when this option is turned on"", true); stripNearUselessItemStackFields = getBoolean(""stripNearUselessItemStackFields"", ""datastructures"", ""EXPERIMENTAL: Strips ItemStack of some of its fields as it stores some near-useless references"", true); moreModelManagerCleanup = getBoolean(""moreModelManagerCleanup"", ""datastructures"", ""Clears and trims ModelManager data structures after models are loaded and baked"", true); efficientHashing = getBoolean(""efficientHashing"", ""datastructures"", ""Improve hashing performances of various objects"", true); releaseSpriteFramesCache = getBoolean(""releaseSpriteFramesCache"", ""textures"", ""Releases TextureAtlasSprite's framesTextureData. Won't touch custom TextureAtlasSprite implementations"", true); optimizeSomeRendering = getBoolean(""optimizeSomeRendering"", ""rendering"", ""Optimizes some rendering features, not game-breaking; however, negligible at times"", true); stripUnnecessaryLocalsInRenderHelper = getBoolean(""stripUnnecessaryLocalsInRenderHelper"", ""rendering"", ""Strip unnecessary locals in RenderHelper::enableStandardItemLighting, no idea why it's there"", true); quickerEnableUniversalBucketCheck = getBoolean(""quickerEnableUniversalBucketCheck"", ""misc"", ""Optimizes FluidRegistry::enableUniversalBucket check"", true); stripInstancedRandomFromSoundEventAccessor = getBoolean(""stripInstancedRandomFromSoundEventAccessor"", ""misc"", ""Strips the boring instanced Random object from SoundEventAccessors and uses ThreadLocalRandom instead"", true); classCaching = getBoolean(""classCaching"", ""misc"", ""[W.I.P] - EXPERIMENTAL: Yet another attempt at caching classes between loads"", false); copyScreenshotToClipboard = getBoolean(""copyScreenshotToClipboard"", ""misc"", ""Copy image after screenshotting to clipboard"", false); releaseScreenshotCache = getBoolean(""releaseScreenshotCache"", ""misc"", ""For some reason Mojang decided to cache int buffers and arrays after a screenshot is taken, this makes sure they're never cached"", true); fixBlockIEBaseArrayIndexOutOfBoundsException = getBoolean(""fixBlockIEBaseArrayIndexOutOfBoundsException"", ""modfixes"", ""When Immersive Engineering is installed, sometimes it or it's addons can induce an ArrayIndexOutOfBoundsException in BlockIEBase#getPushReaction. This option will be ignored when IE isn't installed"", true); cleanupChickenASMClassHierarchyManager = getBoolean(""cleanupChickenASMClassHierarchyManager"", ""modfixes"", ""EXPERIMENTAL: When ChickenASM (Library of CodeChickenLib and co.) is installed, ClassHierarchyManager can cache a lot of Strings and seem to be unused in any transformation purposes. This clears ClassHierarchyManager of those redundant strings. This option will be ignored when ChickenASM isn't installed"", true); optimizeAmuletRelatedFunctions = getBoolean(""optimizeAmuletRelatedFunctions"", ""modfixes"", ""Optimizes Astral Sorcery's Resplendent Prism related functions. This option will be ignored when Astral Sorcery isn't installed"", true); labelCanonicalization = getBoolean(""labelCanonicalization"", ""modfixes"", ""When Just Enough Items is installed, it deduplicates strings in the generated generalized suffix trees' edge labels. This option will be ignored when Just Enough Items isn't installed"", true); skipCraftTweakerRecalculatingSearchTrees = getBoolean(""skipCraftTweakerRecalculatingSearchTrees"", ""modfixes"", ""When CraftTweaker is installed, large modpacks tend to stall in the last stage of loading, when CraftTweaker inexplicably recalculates search trees. This option will be ignored when CraftTweaker isn't installed"", true); bwmBlastingOilOptimization = getBoolean(""bwmBlastingOilOptimization"", ""modfixes"", ""When Better with Mods is installed, optimize Blasting Oil related events. The original implementation harms server performance at any given moment. This option will be ignored when Better with Mods isn't installed"", true); optimizeQMDBeamRenderer = getBoolean(""optimizeQMDBeamRenderer"", ""modfixes"", ""When QMD is installed, optimize its BeamRenderer. The original implementation harms client performance heavily (takes ~5% of each tick time). This option will be ignored when QMD isn't installed"", true); repairEvilCraftEIOCompat = getBoolean(""repairEvilCraftEIOCompat"", ""modfixes"", ""When EvilCraft Compat + EnderIO is installed, repair the compatibility module"", true); optimizeArcaneLockRendering = getBoolean(""optimizeArcaneLockRendering"", ""modfixes"", ""When Electroblob's Wizardry is installed, optimize the search for arcane locked tile entities to render"", true); fixXU2CrafterCrash = getBoolean(""fixXU2CrafterCrash"", ""modfixes"", ""When Extra Utilities 2 is installed, fix and optimize mechanical crafter's rendering"", true); disableXU2CrafterRendering = getBoolean(""disableXU2CrafterRendering"", ""modfixes"", ""When Extra Utilities 2 is installed, disable the crafter's rendering of the item being crafted, this can reduce lag, ignores fixXU2CrafterCrash config option"", false); fixTFCFallingBlockFalseStartingTEPos = getBoolean(""fixTFCFallingBlockFalseStartingTEPos"", ""modfixes"", ""When TerraFirmaCraft is installed, fix the falling block's false starting position "", true); fixAmuletHolderCapability = getBoolean(""fixAmuletHolderCapability"", ""capability"", ""Fixes Astral Sorcery applying AmuletHolderCapability to large amount of ItemStacks when it isn't needed. This option will be ignored when Astral Sorcery isn't installed"", true); delayItemStackCapabilityInit = getBoolean(""delayItemStackCapabilityInit"", ""capability"", ""Delays ItemStack's capabilities from being initialized until they needed to be"", true); fixFillBucketEventNullPointerException = getBoolean(""fixFillBucketEventNullPointerException"", ""forgefixes"", ""Fixes Forge's mistake of annotating FillBucketEvent#getFilledBucket as @Nonnull when the contract isn't fulfilled nor checked. First discovered here: https://github.com/Divine-Journey-2/main/issues/295"", true); fixTileEntityOnLoadCME = getBoolean(""fixTileEntityOnLoadCME"", ""forgefixes"", ""Fixes a vanilla-forge code interaction bug leading to a possible ConcurrentModificationException/StackOverflowError crash. First discovered here: https://github.com/GregTechCE/GregTech/issues/1256"", true); removeForgeSecurityManager = getBoolean(""removeForgeSecurityManager"", ""forgefixes"", ""EXPERIMENTAL: Forcibly remove Forge's FMLSecurityManager that adds very very slight overheads in calls that requires permission checks"", false); fasterEntitySpawnPreparation = getBoolean(""fasterEntitySpawnPreparation"", ""forgefixes"", ""Fixes Forge's EntityEntry calling a slow Constructor::newInstance call every time an entity spawns, it is replaced with a fast Function::get generated from LambdaMetafactory#metafactory"", true); sparkProfileEntireGameLoad = getBoolean(""sparkProfileEntireGameLoad"", ""spark"", ""When Spark is installed, profile the loading of the game in its entirety"", false); sparkProfileEntireWorldLoad = getBoolean(""sparkProfileEntireWorldLoad"", ""spark"", ""When Spark is installed, profile the loading of the world in its entirety"", false); sparkProfileCoreModLoading = getBoolean(""sparkProfileCoreModLoading"", ""spark"", ""When Spark is installed, profile the loading of coremods, but only those that load after LoliASM"", false); sparkProfileConstructionStage = getBoolean(""sparkProfileConstructionStage"", ""spark"", ""When Spark is installed, profile the loading of FMLConstructionEvent stage"", false); sparkProfilePreInitializationStage = getBoolean(""sparkProfilePreInitializationStage"", ""spark"", ""When Spark is installed, profile the loading of FMLPreInitializationEvent stage"", false); sparkProfileInitializationStage = getBoolean(""sparkProfileInitializationStage"", ""spark"", ""When Spark is installed, profile the loading of FMLInitializationEvent stage"", false); sparkProfilePostInitializationStage = getBoolean(""sparkProfilePostInitializationStage"", ""spark"", ""When Spark is installed, profile the loading of FMLPostInitializationEvent stage"", false); sparkProfileLoadCompleteStage = getBoolean(""sparkProfileLoadCompleteStage"", ""spark"", ""When Spark is installed, profile the loading of FMLLoadCompleteEvent stage"", false); sparkProfileFinalizingStage = getBoolean(""sparkProfileFinalizingStage"", ""spark"", ""When Spark is installed, profile the loading of FMLModIdMappingEvent stage, this is the last event fired before the game is finalized"", false); sparkProfileWorldAboutToStartStage = getBoolean(""sparkProfileWorldAboutToStartStage"", ""spark"", ""When Spark is installed, profile the loading of FMLServerAboutToStartEvent stage"", false); sparkProfileWorldStartingStage = getBoolean(""sparkProfileWorldStartingStage"", ""spark"", ""When Spark is installed, profile the loading of FMLServerStartingEvent stage"", false); sparkProfileWorldStartedStage = getBoolean(""sparkProfileWorldStartedStage"", ""spark"", ""When Spark is installed, profile the loading of FMLServerStartedEvent stage"", false); includeAllThreadsWhenProfiling = getBoolean(""includeAllThreadsWhenProfiling"", ""spark"", ""Allow LoliASM's Spark profiling to include all threads that are present"", true); sparkSummarizeHeapSpaceAfterGameLoads = getBoolean(""sparkSummarizeHeapSpaceAfterGameLoads"", ""spark"", ""When Spark is installed, summarize the heap space (/spark heapsummary) when the game finishes loading"", false); sparkSummarizeHeapSpaceAfterWorldLoads = getBoolean(""sparkSummarizeHeapSpaceAfterWorldLoads"", ""spark"", ""When Spark is installed, summarize the heap space (/spark heapsummary) when the world finishes loading"", false); furnaceExperienceFCFS = getBoolean(""furnaceExperienceFCFS"", ""furnace"", ""When optimizeFurnaceRecipeStore is true, experience is determined by who registers the entry first, this is also the fallback option if all three options aren't true"", true); furnaceExperienceVanilla = getBoolean(""furnaceExperienceVanilla"", ""furnace"", ""When optimizeFurnaceRecipeStore is true, experience is determined the vanilla way, this method is the most inefficient and random"", false); furnaceExperienceMost = getBoolean(""furnaceExperienceMost"", ""furnace"", ""When optimizeFurnaceRecipeStore is true, experience is determined by whichever entry gives the most experience"", false); makeEventsSingletons = getBoolean(""makeEventsSingletons"", ""events"", ""[EXPERIMENTAL]: Stops mass object creation when Forge is firing events, this can decrease Garbage Collection pressure"", false); crashReportImprovements = getBoolean(""crashReportImprovements"", ""crashes"", ""Allow the game to keep running after it crashes and provide deobf crash reports. Thanks to VanillaFix for the original implementation of this, many parts of which are reused."", true); allowMainMenuInCrashes = getBoolean(""allowMainMenu"", ""crashes"", ""Allow the user to return to the main menu and play again when a crash occurs."", true); fixVanillaBugs = getBoolean(""fixVanillaBugs"", ""improvements"", ""Fixes some assorted bugs and memory leaks in vanilla code. Thanks to VanillaFix for this code."", true); configuration.save(); }",Merge VanillaFix crash handler and various bugfixes,https://github.com/LoliKingdom/LoliASM/commit/ce5dc01fb9d772d162dba46942afbcf67af858f0,,,src/main/java/zone/rong/loliasm/config/LoliConfig.java,3,java,False,2022-04-29T14:53:56Z "private static boolean checkIp(String ip) { String regex = ""^\\s*(((([0-9A-Fa-f]{1,4}:){7}(([0-9A-Fa-f]{1,4})|:))|(([0-9A-Fa-f]{1,4}:){6}(:|((25[0-5]|2[0-4]\\d|[01]?\\d{1,2})(\\.(25[0-5]|2[0-4]\\d|[01]?\\d{1,2})){3})|(:[0-9A-Fa-f]{1,4})))|(([0-9A-Fa-f]{1,4}:){5}((:((25[0-5]|2[0-4]\\d|[01]?\\d{1,2})(\\.(25[0-5]|2[0-4]\\d|[01]?\\d{1,2})){3})?)|((:[0-9A-Fa-f]{1,4}){1,2})))|(([0-9A-Fa-f]{1,4}:){4}(:[0-9A-Fa-f]{1,4}){0,1}((:((25[0-5]|2[0-4]\\d|[01]?\\d{1,2})(\\.(25[0-5]|2[0-4]\\d|[01]?\\d{1,2})){3})?)|((:[0-9A-Fa-f]{1,4}){1,2})))|(([0-9A-Fa-f]{1,4}:){3}(:[0-9A-Fa-f]{1,4}){0,2}((:((25[0-5]|2[0-4]\\d|[01]?\\d{1,2})(\\.(25[0-5]|2[0-4]\\d|[01]?\\d{1,2})){3})?)|((:[0-9A-Fa-f]{1,4}){1,2})))|(([0-9A-Fa-f]{1,4}:){2}(:[0-9A-Fa-f]{1,4}){0,3}((:((25[0-5]|2[0-4]\\d|[01]?\\d{1,2})(\\.(25[0-5]|2[0-4]\\d|[01]?\\d{1,2})){3})?)|((:[0-9A-Fa-f]{1,4}){1,2})))|(([0-9A-Fa-f]{1,4}:)(:[0-9A-Fa-f]{1,4}){0,4}((:((25[0-5]|2[0-4]\\d|[01]?\\d{1,2})(\\.(25[0-5]|2[0-4]\\d|[01]?\\d{1,2})){3})?)|((:[0-9A-Fa-f]{1,4}){1,2})))|(:(:[0-9A-Fa-f]{1,4}){0,5}((:((25[0-5]|2[0-4]\\d|[01]?\\d{1,2})(\\.(25[0-5]|2[0-4]\\d|[01]?\\d{1,2})){3})?)|((:[0-9A-Fa-f]{1,4}){1,2})))|(((25[0-5]|2[0-4]\\d|[01]?\\d{1,2})(\\.(25[0-5]|2[0-4]\\d|[01]?\\d{1,2})){3})))\\;?\\s*)*$""; return !StringUtils.isEmpty(ip) && !""unknown"".equalsIgnoreCase(ip) && RegexUtils.checkByRegex(ip, regex); }","private static boolean checkIp(String ip) { return !StringUtils.isEmpty(ip) && !""unknown"".equalsIgnoreCase(ip) && RegexUtils.isIp(ip); }",修复部分 XSS,https://github.com/zhangyd-c/OneBlog/commit/6caba5babb4c1763d78502c062a4860b7414f36b,,,blog-core/src/main/java/com/zyd/blog/util/IpUtil.java,3,java,False,2021-08-07T02:44:58Z "@Override public void preDirty(final InstanceLifecycleEvent event) { log.debug(""preDirty {}"", ()->_Utils.debug(event)); final Persistable pojo = _Utils.persistableFor(event); val entity = adaptEntity(pojo, EntityAdaptingMode.MEMOIZE_BOOKMARK); objectLifecyclePublisher.onPreUpdate(entity, null); }","@Override public void preDirty(final InstanceLifecycleEvent event) { log.debug(""preDirty {}"", ()->_Utils.debug(event)); final Persistable pojo = _Utils.persistableFor(event); final Runnable doPreDirty = ()->doPreDirty(pojo); _Casts.castTo(DnObjectProviderForIsis.class, pojo.dnGetStateManager()) .ifPresentOrElse(stateManager-> stateManager.acquirePreDirtyPropagationLock(pojo.dnGetObjectId()) .ifPresent(lock->{ try { doPreDirty.run(); } finally { lock.release(); } }), doPreDirty); }",ISIS-3126: [JDO] fixes Stack Overflow on TimestampService#onPreStore,https://github.com/apache/causeway/commit/368b46bae724f4621f04ef34ac9fbd7c26f387e8,,,persistence/jdo/datanucleus/src/main/java/org/apache/isis/persistence/jdo/datanucleus/changetracking/JdoLifecycleListener.java,3,java,False,2022-08-19T19:31:20Z "private Pair> killYarnJob(Host host, String logPath, String executePath, String tenantCode) { try (LogClientService logClient = new LogClientService();) { logger.info(""log host : {} , logPath : {} , port : {}"", host.getIp(), logPath, host.getPort()); String log = logClient.viewLog(host.getIp(), host.getPort(), logPath); List appIds = Collections.emptyList(); if (!StringUtils.isEmpty(log)) { appIds = LoggerUtils.getAppIds(log, logger); if (StringUtils.isEmpty(executePath)) { logger.error(""task instance execute path is empty""); throw new RuntimeException(""task instance execute path is empty""); } if (appIds.size() > 0) { ProcessUtils.cancelApplication(appIds, logger, tenantCode, executePath); } } return Pair.of(true, appIds); } catch (Exception e) { logger.error(""kill yarn job error"", e); } return Pair.of(false, Collections.emptyList()); }","private Pair> killYarnJob(@NonNull Host host, String logPath, String executePath, String tenantCode) { if (logPath == null || executePath == null || tenantCode == null) { logger.error(""Kill yarn job error, the input params is illegal, host: {}, logPath: {}, executePath: {}, tenantCode: {}"", host, logPath, executePath, tenantCode); return Pair.of(false, Collections.emptyList()); } try (LogClientService logClient = new LogClientService()) { logger.info(""Get appIds from worker {}:{} taskLogPath: {}"", host.getIp(), host.getPort(), logPath); List appIds = logClient.getAppIds(host.getIp(), host.getPort(), logPath); if (CollectionUtils.isEmpty(appIds)) { return Pair.of(true, Collections.emptyList()); } ProcessUtils.cancelApplication(appIds, logger, tenantCode, executePath); return Pair.of(true, appIds); } catch (InterruptedException e) { Thread.currentThread().interrupt(); logger.error(""kill yarn job error, the current thread has been interrtpted"", e); } catch (Exception e) { logger.error(""kill yarn job error"", e); } return Pair.of(false, Collections.emptyList()); }","[3.0.1-prepare]cherry-pick [Bug] [Worker] Optimize the getAppId method to avoid worker OOM when kill task (#11994) * cherry-pick [Bug] [Worker] Optimize the getAppId method to avoid worker OOM when kill task Co-authored-by: Wenjun Ruan ",https://github.com/apache/dolphinscheduler/commit/c4c943277c82ef944c912d4a0dfc493b42586d25,,,dolphinscheduler-worker/src/main/java/org/apache/dolphinscheduler/server/worker/processor/TaskKillProcessor.java,3,java,False,2022-09-18T06:23:35Z "private void fix() { if (!detector.getVulnerableFiles().isEmpty()) System.out.println(""""); // collect backup files to zip List backupFiles = new ArrayList(); for (VulnerableFile vf : detector.getVulnerableFiles()) { File f = vf.getFile(); File symlinkFile = null; String symlinkMsg = """"; if (FileUtils.isSymlink(f)) { try { symlinkFile = f; f = symlinkFile.getCanonicalFile(); symlinkMsg = "" (from symlink "" + symlinkFile.getAbsolutePath() + "")""; } catch (IOException e) { // unreachable (already known symlink) } } if (config.isTrace()) System.out.printf(""Patching %s%s%n"", f.getAbsolutePath(), symlinkMsg); File backupFile = new File(f.getAbsolutePath() + "".bak""); if (backupFile.exists()) { reportError(f, ""Cannot create backup file. .bak File already exists""); continue; } // do not patch if jar has only CVE-2021-45105 vulnerability String except = """"; boolean needFix = false; // report entries are added by original file. beware of symbolic link case List entries = detector.getReportEntries(vf.getFile()); for (ReportEntry entry : entries) { if (entry.getCve().equals(""CVE-2021-45105"")) except = "" (except CVE-2021-45105)""; else needFix = true; } if (!needFix) { System.out.printf(""Cannot fix CVE-2021-45105, Upgrade it: %s%s%n"", f.getAbsolutePath(), symlinkMsg); continue; } boolean readonlyFile = false; boolean lockError = true; boolean truncateError = true; try { // set writable if file is read-only if (!f.canWrite()) { readonlyFile = true; if (!f.setWritable(true)) { reportError(f, ""No write permission. Cannot remove read-only attribute""); continue; } } // check lock first FileUtils.checkLock(f); lockError = false; FileUtils.copyAsIs(f, backupFile); // keep inode as is for symbolic link FileUtils.truncate(f); truncateError = false; Set removeTargets = detector.getVulnerableEntries(); Set shadePatterns = detector.getShadePatterns(); try { ZipUtils.repackage(backupFile, f, removeTargets, shadePatterns, config.isScanZip(), vf.isNestedJar(), config.isDebug(), vf.getAltCharset()); // update fixed status for (ReportEntry entry : entries) { if (!entry.getCve().equals(""CVE-2021-45105"")) entry.setFixed(true); } metrics.addFixedFileCount(); System.out.printf(""Fixed: %s%s%s%n"", f.getAbsolutePath(), symlinkMsg, except); backupFiles.add(backupFile); } catch (Throwable t) { reportError(f, ""Cannot fix file ("" + t.getMessage() + "")."", t); // rollback operation FileUtils.copyAsIs(backupFile, f); } } catch (Throwable t) { if (lockError) { reportError(f, ""Cannot lock file "" + t.getMessage(), t); } else if (truncateError) { backupFile.delete(); reportError(f, ""Cannot truncate file "" + t.getMessage(), t); } else { reportError(f, ""Cannot backup file "" + t.getMessage(), t); } } finally { // restore read only attribute if (readonlyFile) f.setReadOnly(); } } // archive backup files if (backupFiles.isEmpty()) return; SimpleDateFormat df = new SimpleDateFormat(""yyyyMMdd_HHmmss""); String timestamp = df.format(new Date(metrics.getScanStartTime())); File f = new File(""log4j2_scan_backup_"" + timestamp + ""."" + config.getBackupExtension()); if (config.getBackupPath() != null) f = config.getBackupPath(); ZipOutputStream zos = null; try { zos = new ZipOutputStream(new FileOutputStream(f)); for (File backupFile : backupFiles) { String entryPath = backupFile.getAbsolutePath(); if (isWindows) { entryPath = entryPath.replaceAll(""\\\\"", ""/""); // remove drive colon. e.g. c:/ to c/ entryPath = entryPath.charAt(0) + entryPath.substring(2); } entryPath = entryPath.substring(0, entryPath.length() - "".bak"".length()); zos.putNextEntry(new ZipEntry(entryPath)); FileInputStream is = null; try { is = new FileInputStream(backupFile); FileUtils.transfer(is, zos); } finally { IoUtils.ensureClose(is); } } } catch (IOException e) { throw new IllegalStateException(""Cannot archive backup files to "" + f.getAbsolutePath(), e); } finally { IoUtils.ensureClose(zos); } // delete backup files only if zip file is generated for (File backupFile : backupFiles) backupFile.delete(); }","private void fix() { if (!detector.getVulnerableFiles().isEmpty()) System.out.println(""""); // collect backup files to zip List backupFiles = new ArrayList(); for (VulnerableFile vf : detector.getVulnerableFiles()) { File f = vf.getFile(); File symlinkFile = null; String symlinkMsg = """"; if (FileUtils.isSymlink(f)) { try { symlinkFile = f; f = symlinkFile.getCanonicalFile(); symlinkMsg = "" (from symlink "" + symlinkFile.getAbsolutePath() + "")""; } catch (IOException e) { // unreachable (already known symlink) } } if (config.isTrace()) System.out.printf(""Patching %s%s%n"", f.getAbsolutePath(), symlinkMsg); File backupFile = new File(f.getAbsolutePath() + "".bak""); if (backupFile.exists()) { reportError(f, ""Cannot create backup file. .bak File already exists""); continue; } // do not patch if jar has only CVE-2021-45105 or CVE-2021-44832 vulnerability Set exceptCves = new HashSet(); boolean needFix = false; // report entries are added by original file. beware of symbolic link case List entries = detector.getReportEntries(vf.getFile()); for (ReportEntry entry : entries) { String cve = entry.getCve(); if (cve.equals(""CVE-2021-45105"") || cve.equals(""CVE-2021-44832"")) exceptCves.add(cve); else needFix = true; } String except = "" (except "" + StringUtils.join(exceptCves, "", "") + "")""; if (!needFix) { System.out.printf(""Cannot fix "" + StringUtils.join(exceptCves, "", "") + "", Upgrade it: %s%s%n"", f.getAbsolutePath(), symlinkMsg); continue; } boolean readonlyFile = false; boolean lockError = true; boolean truncateError = true; try { // set writable if file is read-only if (!f.canWrite()) { readonlyFile = true; if (!f.setWritable(true)) { reportError(f, ""No write permission. Cannot remove read-only attribute""); continue; } } // check lock first FileUtils.checkLock(f); lockError = false; FileUtils.copyAsIs(f, backupFile); // keep inode as is for symbolic link FileUtils.truncate(f); truncateError = false; Set removeTargets = detector.getVulnerableEntries(); Set shadePatterns = detector.getShadePatterns(); try { ZipUtils.repackage(backupFile, f, removeTargets, shadePatterns, config.isScanZip(), vf.isNestedJar(), config.isDebug(), vf.getAltCharset()); // update fixed status for (ReportEntry entry : entries) { if (!entry.getCve().equals(""CVE-2021-45105"")) entry.setFixed(true); } metrics.addFixedFileCount(); System.out.printf(""Fixed: %s%s%s%n"", f.getAbsolutePath(), symlinkMsg, except); backupFiles.add(backupFile); } catch (Throwable t) { reportError(f, ""Cannot fix file ("" + t.getMessage() + "")."", t); // rollback operation FileUtils.copyAsIs(backupFile, f); } } catch (Throwable t) { if (lockError) { reportError(f, ""Cannot lock file "" + t.getMessage(), t); } else if (truncateError) { backupFile.delete(); reportError(f, ""Cannot truncate file "" + t.getMessage(), t); } else { reportError(f, ""Cannot backup file "" + t.getMessage(), t); } } finally { // restore read only attribute if (readonlyFile) f.setReadOnly(); } } // archive backup files if (backupFiles.isEmpty()) return; SimpleDateFormat df = new SimpleDateFormat(""yyyyMMdd_HHmmss""); String timestamp = df.format(new Date(metrics.getScanStartTime())); File f = new File(""log4j2_scan_backup_"" + timestamp + ""."" + config.getBackupExtension()); if (config.getBackupPath() != null) f = config.getBackupPath(); ZipOutputStream zos = null; try { zos = new ZipOutputStream(new FileOutputStream(f)); for (File backupFile : backupFiles) { String entryPath = backupFile.getAbsolutePath(); if (isWindows) { entryPath = entryPath.replaceAll(""\\\\"", ""/""); // remove drive colon. e.g. c:/ to c/ entryPath = entryPath.charAt(0) + entryPath.substring(2); } entryPath = entryPath.substring(0, entryPath.length() - "".bak"".length()); zos.putNextEntry(new ZipEntry(entryPath)); FileInputStream is = null; try { is = new FileInputStream(backupFile); FileUtils.transfer(is, zos); } finally { IoUtils.ensureClose(is); } } } catch (IOException e) { throw new IllegalStateException(""Cannot archive backup files to "" + f.getAbsolutePath(), e); } finally { IoUtils.ensureClose(zos); } // delete backup files only if zip file is generated for (File backupFile : backupFiles) backupFile.delete(); }",Do not remove JndiLookup.class for log4j 2.17.0 (CVE-2021-44832),https://github.com/logpresso/CVE-2021-44228-Scanner/commit/c0395e679c5d04963da7e44411996ba955efe2cb,,,src/main/java/com/logpresso/scanner/Log4j2Scanner.java,3,java,False,2021-12-29T01:59:44Z "public final synchronized int executeUpdate(CoreStatement stmt, Object[] vals) throws SQLException { try { if (execute(stmt, vals)) { throw new SQLException(""query returns results""); } } finally { if (stmt.pointer != 0) reset(stmt.pointer); } return changes(); }","public final synchronized int executeUpdate(CoreStatement stmt, Object[] vals) throws SQLException { try { if (execute(stmt, vals)) { throw new SQLException(""query returns results""); } } finally { if (!stmt.pointer.isClosed()) { stmt.pointer.safeRunInt(DB::reset); } } return changes(); }",Wrap Statement Pointers to prevent use after free race,https://github.com/xerial/sqlite-jdbc/commit/e1d282cb2887ef427c7ad93d4fe7dd05a6c11473,,,src/main/java/org/sqlite/core/DB.java,3,java,False,2022-07-29T03:54:01Z "@Override public T getAdapter(Class adapter) { if (adapter == IWorkbenchAdapter.class || adapter == IWorkbenchAdapter2.class || adapter == IWorkbenchAdapter3.class) { return adapter.cast(this); } else if (adapter == IPluginContribution.class) { return adapter.cast(this); } else if (adapter == IConfigurationElement.class) { return adapter.cast(configurationElement); } return Adapters.adapt(this, adapter); }","@Override public T getAdapter(Class adapter) { if (adapter == IWorkbenchAdapter.class || adapter == IWorkbenchAdapter2.class || adapter == IWorkbenchAdapter3.class) { return adapter.cast(this); } else if (adapter == IPluginContribution.class) { return adapter.cast(this); } else if (adapter == IConfigurationElement.class) { return adapter.cast(configurationElement); } return Platform.getAdapterManager().getAdapter(this, adapter); }","Revert ""Bug 567543 - Use Adapters in WorkbenchWizardElement"" This reverts commit 6cc1230c6a2b5fb7674c7b390bde5c78da12394c. Reason for revert: Bug 572904. IAdaptable should never delegate getAdapter() call to Adapters, this can lead to recursion and stack overflow. Change-Id: I3c1ec9b49bb3f0227ffda81f771c27000f4df172 Reviewed-on: https://git.eclipse.org/r/c/platform/eclipse.platform.ui/+/179033 Tested-by: Platform Bot Reviewed-by: Andrey Loskutov ",https://github.com/eclipse-platform/eclipse.platform.ui/commit/f7febcce41da0e07ed2fd6418acd4bd1bad82d2a,,,bundles/org.eclipse.ui.workbench/Eclipse UI/org/eclipse/ui/internal/dialogs/WorkbenchWizardElement.java,3,java,False,2021-04-16T09:27:29Z "public void requestThemeRefresh(boolean designMightHaveChanged) { Intent intent = new Intent(); intent.setAction( designMightHaveChanged ? ACTION.THEME_AND_DESIGN_CHANGED : ACTION.THEME_CHANGED ); sendBroadcast(intent); }","public void requestThemeRefresh(boolean designMightHaveChanged) { Intent intent = new Intent(); intent.setPackage(getPackageName()); intent.setAction( designMightHaveChanged ? ACTION.THEME_AND_DESIGN_CHANGED : ACTION.THEME_CHANGED ); sendBroadcast(intent); }",Fix Implicit Internal Intent Vulnerability and fix crash caused by non-display intent,https://github.com/patzly/doodle-android/commit/b8fb524d6e4ec45857c74065d5ebd134667c9e1f,,,app/src/main/java/xyz/zedler/patrick/doodle/activity/MainActivity.java,3,java,False,2022-08-29T01:15:15Z "METHODDEF(void) post_process_1pass (j_decompress_ptr cinfo, JSAMPIMAGE input_buf, JDIMENSION *in_row_group_ctr, JDIMENSION in_row_groups_avail, JSAMPARRAY output_buf, JDIMENSION *out_row_ctr, JDIMENSION out_rows_avail) { my_post_ptr post = (my_post_ptr) cinfo->post; JDIMENSION num_rows, max_rows; /* Fill the buffer, but not more than what we can dump out in one go. */ /* Note we rely on the upsampler to detect bottom of image. */ max_rows = out_rows_avail - *out_row_ctr; if (max_rows > post->strip_height) max_rows = post->strip_height; num_rows = 0; (*cinfo->upsample->upsample) (cinfo, input_buf, in_row_group_ctr, in_row_groups_avail, post->buffer, &num_rows, max_rows); /* Quantize and emit data. */ (*cinfo->cquantize->color_quantize) (cinfo, post->buffer, output_buf + *out_row_ctr, (int) num_rows); *out_row_ctr += num_rows; }","METHODDEF(void) post_process_1pass (j_decompress_ptr cinfo, JSAMPIMAGE input_buf, JDIMENSION *in_row_group_ctr, JDIMENSION in_row_groups_avail, JSAMPARRAY output_buf, JDIMENSION *out_row_ctr, JDIMENSION out_rows_avail) { my_post_ptr post = (my_post_ptr) cinfo->post; JDIMENSION num_rows, max_rows; /* read_and_discard_scanlines may call it with rows ""available"", but no buffer */ if (output_buf == NULL) { return; } /* Fill the buffer, but not more than what we can dump out in one go. */ /* Note we rely on the upsampler to detect bottom of image. */ max_rows = out_rows_avail - *out_row_ctr; if (max_rows > post->strip_height) max_rows = post->strip_height; num_rows = 0; (*cinfo->upsample->upsample) (cinfo, input_buf, in_row_group_ctr, in_row_groups_avail, post->buffer, &num_rows, max_rows); /* Quantize and emit data. */ (*cinfo->cquantize->color_quantize) (cinfo, post->buffer, output_buf + *out_row_ctr, (int) num_rows); *out_row_ctr += num_rows; }",Handle NULL buffer when discarding rows,https://github.com/libjpeg-turbo/libjpeg-turbo/commit/1ecd9a5729d78518397889a630e3534bd9d963a8,,,jdpostct.c,3,c,False,2017-09-30T11:05:53Z "function internalize (holder, name, reviver) { const value = holder[name] if (value != null && typeof value === 'object') { for (const key in value) { const replacement = internalize(value, key, reviver) if (replacement === undefined) { delete value[key] } else { value[key] = replacement } } } return reviver.call(holder, name, value) }","function internalize (holder, name, reviver) { const value = holder[name] if (value != null && typeof value === 'object') { if (Array.isArray(value)) { for (let i = 0; i < value.length; i++) { const key = String(i) const replacement = internalize(value, key, reviver) if (replacement === undefined) { delete value[key] } else { Object.defineProperty(value, key, { value: replacement, writable: true, enumerable: true, configurable: true, }) } } } else { for (const key in value) { const replacement = internalize(value, key, reviver) if (replacement === undefined) { delete value[key] } else { Object.defineProperty(value, key, { value: replacement, writable: true, enumerable: true, configurable: true, }) } } } } return reviver.call(holder, name, value) }","fix: add __proto__ to objects and arrays backport 7774c1097993bc3ce9f0ac4b722a32bf7d6871c8 to v1.",https://github.com/json5/json5/commit/b7c04ea36b953e1af75ea4ef89339f2d0256dab1,CVE-2022-46175,['CWE-1321'],src/parse.js,3,js,False,2022-12-16T03:16:27Z "private boolean hasCommandInjection(String trimedLowerCasedInput) { List parts = Splitter.on(CharMatcher.anyOf(""\r\n"")).omitEmptyStrings() .splitToList(trimedLowerCasedInput); return hasInvalidStartTlsPart(parts) || multiPartsAndOneStartTls(parts); }","private boolean hasCommandInjection(String trimedLowerCasedInput) { List parts = CRLF_SPLITTER.splitToList(trimedLowerCasedInput); return hasInvalidStartTlsPart(parts) || multiPartsAndOneStartTls(parts); }","JAMES-1862 STARTTLS command injection checks are vulnerable to concurrency man-in-the-middle attacks Attack scenario: - 1. Clients sends frame F1 activating STARTTLS - 2. Framer sees a STARTTLS request alone and thinks ""that's ok"" - 3. Right after attacker sends a second frame (eg NOOP) - 4. Framer sees a NOOP request alone and thinks ""that's ok"" - 5. Processing of STARTTLS requests starts, SSL is negociated - 6. Previously accepted NOOP request then gets processed - 7. The attacker succeeded to execute an injected command! This attack scenario leverages the fact that concurrency is enforced at the netty handler level and not at the pipeline level. This can be mitigated by tracking when a starttls command is received via channel attachments. The scenario then becames: - 1. Clients sends frame F1 activating STARTTLS - 2. Framer sees a STARTTLS request alone and thinks ""Hmm careful we are activating STARTTLS let's turn auto-reads to false so we can't get concurency issues"" - 3. Right after attacker sends a second frame (eg NOOP) - 4. Framer see the noop but knows it already handles a STARTTLS and thus rejects the NOOP command. fixup! JAMES-1862 STARTTLS command injection checks are vulnerable to concurrency man-in-the-middle attacks",https://github.com/apache/james-project/commit/c8afa55e376b582cb119d5aa8ea0efb669bea052,,,protocols/netty/src/main/java/org/apache/james/protocols/netty/AllButStartTlsLineBasedChannelHandler.java,3,java,False,2022-03-15T04:05:02Z "private void moveLocationSelected() { setTitle(); hideMoveBar(); fab.show(); fab.setVisibility(View.VISIBLE); setFabBehaviour(true); setOptionsMenuVisibility(true); recyclerViewAdapter.setMoveMode(false); recyclerViewAdapter.refreshData(); isInMoveMode = false; showNavDrawerButtonInToolbar(); String oldPath = moveList.get(0).getPath(); int index = oldPath.lastIndexOf(moveList.get(0).getName()); String path2; if (index > 0) { path2 = moveList.get(0).getPath().substring(0, index - 1); } else { path2 = ""//"" + remoteName; } for (FileItem moveItem : moveList) { Intent intent = new Intent(context, MoveService.class); intent.putExtra(MoveService.REMOTE_ARG, remote); intent.putExtra(MoveService.MOVE_DEST_PATH, directoryObject.getCurrentPath()); intent.putExtra(MoveService.MOVE_ITEM, moveItem); intent.putExtra(MoveService.PATH, path2); tryStartService(context, intent); } Toasty.info(context, getString(R.string.moving_info), Toast.LENGTH_SHORT, true).show(); moveList.clear(); moveStartPath = null; }","private void moveLocationSelected() { setTitle(); hideMoveBar(); fab.show(); fab.setVisibility(View.VISIBLE); setFabBehaviour(true); setOptionsMenuVisibility(true); recyclerViewAdapter.setMoveMode(false); recyclerViewAdapter.refreshData(); isInMoveMode = false; showNavDrawerButtonInToolbar(); if (moveList.size() < 1) { Toasty.error(context, getString(R.string.error_moving_file), Toast.LENGTH_SHORT, true).show(); moveList.clear(); moveStartPath = null; return; } String oldPath = moveList.get(0).getPath(); int index = oldPath.lastIndexOf(moveList.get(0).getName()); String path2; if (index > 0) { path2 = moveList.get(0).getPath().substring(0, index - 1); } else { path2 = ""//"" + remoteName; } for (FileItem moveItem : moveList) { Intent intent = new Intent(context, MoveService.class); intent.putExtra(MoveService.REMOTE_ARG, remote); intent.putExtra(MoveService.MOVE_DEST_PATH, directoryObject.getCurrentPath()); intent.putExtra(MoveService.MOVE_ITEM, moveItem); intent.putExtra(MoveService.PATH, path2); tryStartService(context, intent); } Toasty.info(context, getString(R.string.moving_info), Toast.LENGTH_SHORT, true).show(); moveList.clear(); moveStartPath = null; }","Fix: crash when moving files In some circumstance, it was not properly checked if the user had actually selected source files to move. References: IndexOutOfBoundsException @ FileExplorerFragment:952 Appcenter #1746750377u #226234893u #15324912u",https://github.com/x0b/rcx/commit/5bffe609000a2f6d1b7d5f0821b9de08ac492144,,,app/src/main/java/ca/pkay/rcloneexplorer/Fragments/FileExplorerFragment.java,3,java,False,2021-06-15T09:02:21Z "private static void equipBackpack(MonsterEntity monster, ItemStack backpack, int difficulty, boolean playMusicDisc) { getSpawnEgg(monster.getType()).ifPresent(egg -> backpack.getCapability(CapabilityBackpackWrapper.getCapabilityInstance()) .ifPresent(w -> { w.setColors(getPrimaryColor(egg), getSecondaryColor(egg)); setLoot(monster, w, difficulty); if (playMusicDisc) { monster.addTag(SPAWNED_WITH_JUKEBOX_UPGRADE); w.getInventoryHandler(); //just to assign uuid and real upgrade handler w.getUpgradeHandler().setStackInSlot(0, new ItemStack(ModItems.JUKEBOX_UPGRADE.get())); Iterator it = w.getUpgradeHandler().getTypeWrappers(JukeboxUpgradeItem.TYPE).iterator(); if (it.hasNext()) { JukeboxUpgradeItem.Wrapper wrapper = it.next(); List musicDiscs = getMusicDiscs(); wrapper.setDisc(new ItemStack(musicDiscs.get(monster.world.rand.nextInt(musicDiscs.size())))); } } })); monster.setItemStackToSlot(EquipmentSlotType.CHEST, backpack); }","private static void equipBackpack(MonsterEntity monster, ItemStack backpack, int difficulty, boolean playMusicDisc) { getSpawnEgg(monster.getType()).ifPresent(egg -> backpack.getCapability(CapabilityBackpackWrapper.getCapabilityInstance()) .ifPresent(w -> { w.setColors(getPrimaryColor(egg), getSecondaryColor(egg)); setLoot(monster, w, difficulty); if (playMusicDisc) { w.getInventoryHandler(); //just to assign uuid and real upgrade handler if (w.getUpgradeHandler().getSlots() > 0) { monster.addTag(SPAWNED_WITH_JUKEBOX_UPGRADE); addJukeboxUpgradeAndRandomDisc(monster, w); } } })); monster.setItemStackToSlot(EquipmentSlotType.CHEST, backpack); }",fix: 🐛 Added an extra check to logic which adds jukebox upgrade to entities with backpacks just to make sure there's at least one upgrade slot in backpack and prevent potential crash if people have any backpack tier set to have 0 upgrade slots.,https://github.com/P3pp3rF1y/SophisticatedBackpacks/commit/36d5d4d785ca7c1678467ff17c825f66ff155ddb,,,src/main/java/net/p3pp3rf1y/sophisticatedbackpacks/common/EntityBackpackAdditionHandler.java,3,java,False,2021-03-24T21:33:08Z "public void stop() { if(getChannelSourceManager() != null) { getChannelSourceManager().stopAllChannels(); getChannelSourceManager().dispose(); mChannelSourceManager = null; } broadcast(new TunerEvent(this, Event.NOTIFICATION_SHUTTING_DOWN)); getTunerController().stop(); getTunerController().dispose(); mTunerEventBroadcaster.clear(); mTunerFrequencyErrorMonitor = null; mTunerErrorListener = null; }","public void stop() { if(mRunning.compareAndSet(true, false)) { broadcast(new TunerEvent(this, Event.NOTIFICATION_SHUTTING_DOWN)); if(getChannelSourceManager() != null) { getChannelSourceManager().stopAllChannels(); getChannelSourceManager().dispose(); mChannelSourceManager = null; } getTunerController().stop(); getTunerController().dispose(); mTunerEventBroadcaster.clear(); mTunerFrequencyErrorMonitor = null; mTunerErrorListener = null; } }","#1243 Updates USB tuner error handling to prevent stack overflow when tuner error occurs while streaming. (#1247) Co-authored-by: Dennis Sheirer ",https://github.com/DSheirer/sdrtrunk/commit/8bfb1d54702ce89f44094a76346e98f4b9f7e255,,,src/main/java/io/github/dsheirer/source/tuner/Tuner.java,3,java,False,2022-05-09T11:16:35Z "@SysLog(""修改个人信息"") @PutMapping(""/edit"") public R updateUserInfo(@Valid @RequestBody UserDTO userDto) { userDto.setUsername(SecurityUtils.getUser().getUsername()); return userService.updateUserInfo(userDto); }","@SysLog(""修改个人信息"") @PutMapping(""/edit"") @XssCleanIgnore({ ""password"", ""newpassword1"" }) public R updateUserInfo(@Valid @RequestBody UserDTO userDto) { userDto.setUsername(SecurityUtils.getUser().getUsername()); return userService.updateUserInfo(userDto); }",:sparkles: Introducing new features. 增加 xss 过滤模块,https://github.com/pig-mesh/pig/commit/297e056df932c56bf259205d47c5560c9098ba0e,,,pig-upms/pig-upms-biz/src/main/java/com/pig4cloud/pig/admin/controller/UserController.java,3,java,False,2022-10-10T07:34:59Z "public void ensureInputsPresent( RemoteActionExecutionContext context, MerkleTree merkleTree, Map additionalInputs, boolean force) throws IOException, InterruptedException { ImmutableSet allDigests = ImmutableSet.builder() .addAll(merkleTree.getAllDigests()) .addAll(additionalInputs.keySet()) .build(); // Collect digests that are not being or already uploaded ConcurrentHashMap> missingDigestSubjects = new ConcurrentHashMap<>(); List> uploadFutures = new ArrayList<>(); for (Digest digest : allDigests) { Completable upload = casUploadCache.execute( digest, Completable.defer( () -> { // The digest hasn't been processed, add it to the collection which will be used // later for findMissingDigests call AsyncSubject missingDigestSubject = AsyncSubject.create(); missingDigestSubjects.put(digest, missingDigestSubject); return missingDigestSubject.flatMapCompletable( missing -> { if (!missing) { return Completable.complete(); } return RxFutures.toCompletable( () -> uploadBlob(context, digest, merkleTree, additionalInputs), MoreExecutors.directExecutor()); }); }), force); uploadFutures.add(RxFutures.toListenableFuture(upload)); } ImmutableSet missingDigests; try { missingDigests = getFromFuture(findMissingDigests(context, missingDigestSubjects.keySet())); } catch (IOException | InterruptedException e) { for (Map.Entry> entry : missingDigestSubjects.entrySet()) { entry.getValue().onError(e); } if (e instanceof InterruptedException) { Thread.currentThread().interrupt(); } throw e; } for (Map.Entry> entry : missingDigestSubjects.entrySet()) { AsyncSubject missingSubject = entry.getValue(); if (missingDigests.contains(entry.getKey())) { missingSubject.onNext(true); } else { // The digest is already existed in the remote cache, skip the upload. missingSubject.onNext(false); } missingSubject.onComplete(); } waitForBulkTransfer(uploadFutures, /* cancelRemainingOnInterrupt=*/ false); }","public void ensureInputsPresent( RemoteActionExecutionContext context, MerkleTree merkleTree, Map additionalInputs, boolean force) throws IOException, InterruptedException { ImmutableSet allDigests = ImmutableSet.builder() .addAll(merkleTree.getAllDigests()) .addAll(additionalInputs.keySet()) .build(); if (allDigests.isEmpty()) { return; } MissingDigestFinder missingDigestFinder = new MissingDigestFinder(context, allDigests.size()); Flowable uploads = Flowable.fromIterable(allDigests) .flatMapSingle( digest -> uploadBlobIfMissing( context, merkleTree, additionalInputs, force, missingDigestFinder, digest)); try { mergeBulkTransfer(uploads).blockingAwait(); } catch (RuntimeException e) { Throwable cause = e.getCause(); if (cause != null) { Throwables.throwIfInstanceOf(cause, InterruptedException.class); Throwables.throwIfInstanceOf(cause, IOException.class); } throw e; } }","Remote: Fix crashes by InterruptedException when dynamic execution is enabled. Fixes #14433. The root cause is, inside `RemoteExecutionCache`, the result of `FindMissingDigests` is shared with other threads without considering error handling. For example, if there are two or more threads uploading the same input and one thread got interrupted when waiting for the result of `FindMissingDigests` call, the call is cancelled and others threads still waiting for the upload will receive upload error due to the cancellation which is wrong. This PR fixes this by effectively applying reference count to the result of `FindMissingDigests` call so that if one thread got interrupted, as long as there are other threads depending on the result, the call won't be cancelled and the upload can continue. Closes #15001. PiperOrigin-RevId: 436180205",https://github.com/bazelbuild/bazel/commit/702df847cf32789ffe6c0a7c7679e92a7ccccb8d,,,src/main/java/com/google/devtools/build/lib/remote/RemoteExecutionCache.java,3,java,False,2022-03-21T12:37:13Z "@Override public void onStart() { super.onStart(); mHandler.sendEmptyMessage(DISABLE_BUTTONS); mHandler.sendMessageDelayed(mHandler.obtainMessage(ENABLE_BUTTONS), 1000); getContext().registerReceiver(mReceiver, new IntentFilter(Intent.ACTION_CLOSE_SYSTEM_DIALOGS), Context.RECEIVER_EXPORTED); }","@Override public void onStart() { super.onStart(); mHandler.sendEmptyMessage(DISABLE_BUTTONS); mHandler.sendMessageDelayed(mHandler.obtainMessage(ENABLE_BUTTONS), 1000); if (mReceiver == null) { mReceiver = new BroadcastReceiver() { @Override public void onReceive(Context context, Intent intent) { if (Intent.ACTION_CLOSE_SYSTEM_DIALOGS.equals(intent.getAction())) { closeDialog(); } } }; getContext().registerReceiver(mReceiver, new IntentFilter(Intent.ACTION_CLOSE_SYSTEM_DIALOGS), RECEIVER_EXPORTED); } }","Prevent crash when unregsiter the broadcast Make sure the receiver could be generated and registered when `onStart` and cleared when `onStop`. Bug: 225214384 Test: Show error dialog, atest WindowInputTests Change-Id: Ib39629180aac1a7aa418e9c7e540922c7f865718",https://github.com/LineageOS/android_frameworks_base/commit/33a01ec1b4a6957a4451a62b6b29b94829c42942,,,services/core/java/com/android/server/am/BaseErrorDialog.java,3,java,False,2022-03-23T14:28:14Z "private String uniqueName() { return RandomStringUtils.randomAlphanumeric(10); }","private String uniqueName() { return RANDOM_STRING_GENERATOR.generate(10); }",Fix security issue reported in Sonar,https://github.com/goldmansachs/jdmn/commit/315951ce6ae12c02be08415c45340d9648844cf1,,,dmn-core/src/main/java/com/gs/dmn/runtime/compiler/JavaxToolsCompiler.java,3,java,False,2021-10-14T10:53:07Z "def download_project_scans(self, project_name,version_name, output_folder=None): version = self.get_project_version_by_name(project_name,version_name) codelocations = self.get_version_codelocations(version) import os if output_folder: if not os.path.exists(output_folder): os.makedirs(output_folder, 0o755, True) result = [] for item in codelocations['items']: links = item['_meta']['links'] matches = [x for x in links if x['rel'] == 'enclosure'] for m in matches: url = m['href'] filename = url.split('/')[6] if output_folder: pathname = os.path.join(output_folder, filename) else: if not os.path.exists(project_name): os.mkdir(project_name) pathname = os.path.join(project_name, filename) responce = requests.get(url, headers=self.get_headers(), stream=True, verify=False) with open(pathname, ""wb"") as f: for data in responce.iter_content(): f.write(data) result.append({filename, pathname}) return result","def download_project_scans(self, project_name,version_name, output_folder=None): version = self.get_project_version_by_name(project_name,version_name) codelocations = self.get_version_codelocations(version) import os if output_folder: if not os.path.exists(output_folder): os.makedirs(output_folder, 0o755, True) result = [] for item in codelocations['items']: links = item['_meta']['links'] matches = [x for x in links if x['rel'] == 'enclosure'] for m in matches: url = m['href'] filename = url.split('/')[6] if output_folder: pathname = os.path.join(output_folder, filename) else: if not os.path.exists(project_name): os.mkdir(project_name) pathname = os.path.join(project_name, filename) responce = requests.get(url, headers=self.get_headers(), stream=True, verify=not self.config['insecure']) with open(pathname, ""wb"") as f: for data in responce.iter_content(): f.write(data) result.append({filename, pathname}) return result",fixed use of hard-coded values for the verify parameter being supplied to the requests module calls,https://github.com/blackducksoftware/hub-rest-api-python/commit/273b27d0de1004389dd8cf43c40b1197c787e7cd,,,blackduck/HubRestApi.py,3,py,False,2020-10-22T18:47:14Z "private void addDefaultPolicies( DeploymentContext context, Service service, Map filterParams, List params, ResourceDescriptor resource) throws URISyntaxException { addWebAppSecFilters(context, service, resource); addAuthenticationFilter(context, service, resource); addRewriteFilter(context, service, filterParams, params, resource); addIdentityAssertionFilter(context, service, resource); addAuthorizationFilter(context, service, resource); }","private void addDefaultPolicies( DeploymentContext context, Service service, Map filterParams, List params, ResourceDescriptor resource) throws URISyntaxException { addDoSFilter(context, service, resource); addWebAppSecFilters(context, service, resource); addAuthenticationFilter(context, service, resource); addRewriteFilter(context, service, filterParams, params, resource); addIdentityAssertionFilter(context, service, resource); addAuthorizationFilter(context, service, resource); }",KNOX-2806 - Implement a new DoS security provider (#634),https://github.com/apache/knox/commit/c47a425a6a70669134716ce552a7cca4abb12dbe,,,gateway-server/src/main/java/org/apache/knox/gateway/deploy/impl/ApplicationDeploymentContributor.java,3,java,False,2022-09-30T09:39:27Z "protected View prepareDecorView(View v) { v = FontLoader.apply(v); if (!mBase.getConfig().isDisableContextMenu()) { v = new ContextMenuDecorView(v, this); } return v; }","protected View prepareDecorView(View v) { v = FontLoader.apply(v); if (!mBase.getConfig().isDisableContextMenu() && v != null) { v = new ContextMenuDecorView(getSupportActivity(), v, this); } return v; }",Fix crashing when content view in activity or fragment cause npe into ContextMenuDecorView,https://github.com/zl-suu/ingrauladolfo/commit/1d5aa50dfda2aedfdb678648dae567df7d068841,,,library/src/com/WazaBe/HoloEverywhere/app/Fragment.java,3,java,False,2022-07-31T08:13:46Z "public bool Exists(string ip, string netmask) { if (String.IsNullOrEmpty(ip)) throw new ArgumentNullException(nameof(ip)); if (String.IsNullOrEmpty(netmask)) throw new ArgumentNullException(nameof(netmask)); lock (_CacheLock) { if (_Cache.ContainsKey(ip)) { Log(ip + "" "" + netmask + "" exists in cache""); return true; } } lock (_AddressLock) { Address curr = _Addresses.Where(d => d.Ip.Equals(ip) && d.Netmask.Equals(netmask)).FirstOrDefault(); if (curr == default(Address)) { Log(ip + "" "" + netmask + "" does not exist in address list""); return false; } else { Log(ip + "" "" + netmask + "" exists in address list""); return true; } } }","public bool Exists(string ip, string netmask) { if (String.IsNullOrEmpty(ip)) throw new ArgumentNullException(nameof(ip)); if (String.IsNullOrEmpty(netmask)) throw new ArgumentNullException(nameof(netmask)); ip = IPAddress.Parse(ip).ToString(); netmask = IPAddress.Parse(netmask).ToString(); lock (_CacheLock) { if (_Cache.ContainsKey(ip)) { Log(ip + "" "" + netmask + "" exists in cache""); return true; } } lock (_AddressLock) { Address curr = _Addresses.Where(d => d.Ip.Equals(ip) && d.Netmask.Equals(netmask)).FirstOrDefault(); if (curr == default(Address)) { Log(ip + "" "" + netmask + "" does not exist in address list""); return false; } else { Log(ip + "" "" + netmask + "" exists in address list""); return true; } } }","NuGet v1.0.4.2, fix for SICK-2021-060",https://github.com/jchristn/IpMatcher/commit/81d77c2f33aa912dbd032b34b9e184fc6e041d89,,,IpMatcher/Matcher.cs,3,cs,False,2021-08-18T20:28:16Z "private void validate(Node copy) throws SAXException, IOException { SchemaFactory schemaFactory = SchemaFactory.newInstance(schemaLanguage); Schema schema = schemaFactory.newSchema(schemaFile); Validator validator = schema.newValidator(); validator.setErrorHandler(new ErrorHandler() { @Override public void warning(SAXParseException exception) throws SAXException { LOG.warn(exception.getMessage()); } @Override public void error(SAXParseException exception) throws SAXException { if(isIgnore(exception.getMessage())) { LOG.warn(exception.getMessage()); return; } throw exception; } @Override public void fatalError(SAXParseException exception) throws SAXException { throw exception; } }); validator.validate(new DOMSource(copy)); }","private void validate(Node copy) throws SAXException, IOException { SchemaFactory schemaFactory = SchemaFactory.newInstance(schemaLanguage); Schema schema = schemaFactory.newSchema(schemaFile); Validator validator = schema.newValidator(); validator.setProperty(XMLConstants.ACCESS_EXTERNAL_DTD, """"); validator.setProperty(XMLConstants.ACCESS_EXTERNAL_SCHEMA, """"); validator.setErrorHandler(new ErrorHandler() { @Override public void warning(SAXParseException exception) throws SAXException { LOG.warn(exception.getMessage()); } @Override public void error(SAXParseException exception) throws SAXException { if(isIgnore(exception.getMessage())) { LOG.warn(exception.getMessage()); return; } throw exception; } @Override public void fatalError(SAXParseException exception) throws SAXException { throw exception; } }); validator.validate(new DOMSource(copy)); }","#2173 Fixed import project - moved SvgUtils.isSvg(document,svgSchema) to SvgSchema.isSvg(document)",https://github.com/SCADA-LTS/Scada-LTS/commit/51d0bacd2fc16706ab149c595fd47c478bae3590,,,src/org/scada_lts/svg/SvgSchema.java,3,java,False,2022-04-18T23:22:19Z "@Override protected Void doInBackground(Void... params) { Uri uri = Uri.parse(this.url); if (uri.getScheme().equalsIgnoreCase(CONTENT)) { return handleContentUri(uri); } URL url; HttpURLConnection connection; try { url = new URL(this.url); String protocol = url.getProtocol(); if (!protocol.equalsIgnoreCase(HTTP) && !protocol.equalsIgnoreCase(HTTPS)) { exception = new IOException(""Protocol \"""" + protocol + ""\"" is not supported""); return null; } connection = (HttpURLConnection) url.openConnection(); enrichWithUrlProps(connection); connection.connect(); } catch (Exception e) { exception = e; return null; } try ( InputStream input = new BufferedInputStream(connection.getInputStream(), BUFF_SIZE); OutputStream output = new FileOutputStream(file) ) { copyAndFlush(input, output); } catch (IOException e) { exception = e; } return null; }","@Override protected Void doInBackground(Void... params) { Uri uri = Uri.parse(this.url); String scheme = uri.getScheme(); if (this.url.equalsIgnoreCase("""") || scheme == null) { exception = new IOException(""Invalid or empty url provided""); return null; } if (scheme.equalsIgnoreCase(CONTENT)) { return handleContentUri(uri); } URL url; HttpURLConnection connection; try { url = new URL(this.url); String protocol = url.getProtocol(); if (!protocol.equalsIgnoreCase(HTTP) && !protocol.equalsIgnoreCase(HTTPS)) { exception = new IOException(""Protocol \"""" + protocol + ""\"" is not supported""); return null; } connection = (HttpURLConnection) url.openConnection(); enrichWithUrlProps(connection); connection.connect(); } catch (Exception e) { exception = e; return null; } try ( InputStream input = new BufferedInputStream(connection.getInputStream(), BUFF_SIZE); OutputStream output = new FileOutputStream(file) ) { copyAndFlush(input, output); } catch (IOException e) { exception = e; } return null; }","fix:android: Handle empty url Fixes crash in case empty url is provided. Returns exception now",https://github.com/rumax/react-native-PDFView/commit/09c6e43583a9915cd4842172fc9df4525ab918bb,,,android/src/main/java/com/rumax/reactnative/pdfviewer/AsyncDownload.java,3,java,False,2022-08-15T17:58:05Z "private void checkForCharsetMismatch() { String characterEncodingValue = this.characterEncoding.getValue(); if (characterEncodingValue != null) { Charset characterEncodingCs = Charset.forName(characterEncodingValue); Charset encodingToCheck = jvmPlatformCharset; if (encodingToCheck == null) { encodingToCheck = Charset.forName(Constants.PLATFORM_ENCODING); } this.platformDbCharsetMatches = encodingToCheck == null ? false : encodingToCheck.equals(characterEncodingCs); } }","private void checkForCharsetMismatch() { String characterEncodingValue = this.characterEncoding.getValue(); if (characterEncodingValue != null) { Charset characterEncodingCs = Charset.forName(characterEncodingValue); Charset encodingToCheck = Charset.defaultCharset(); this.platformDbCharsetMatches = encodingToCheck.equals(characterEncodingCs); } }","Fix for Bug#67828 (Bug#15967406), Crashing applets due to reading file.encoding system property. Change-Id: Ic65898094327acfc4440736a4fa9c3a2aca661de",https://github.com/mysql/mysql-connector-j/commit/83bbcac8272ad4df7f811f33e5ffc7ce36e3e031,,,src/main/core-impl/java/com/mysql/cj/NativeCharsetSettings.java,3,java,False,2022-09-01T11:53:51Z "private void fillCreativeItems() { if(initialCreativeItems == null) { initialCreativeItems = new ArrayList<>(); for (Object o : Item.itemRegistry) { Item item = (Item) o; if (item != null && item.getCreativeTab() != null) { item.getSubItems(item, null, initialCreativeItems); } } for(Enchantment enchantment : Enchantment.enchantmentsList) { if (enchantment != null && enchantment.type != null) { Items.enchanted_book.func_92113_a(enchantment, initialCreativeItems); } } } }","private void fillCreativeItems() { if(initialCreativeItems == null) { initialCreativeItems = new ArrayList<>(); for (Object o : Item.itemRegistry) { Item item = (Item) o; if (item != null && item.getCreativeTab() != null) { try { item.getSubItems(item, null, initialCreativeItems); } catch(Exception e) { ArchaicLogger.LOGGER.error(""Item "" + item + "" threw an error while populating the creative item list!"", e); } } } for(Enchantment enchantment : Enchantment.enchantmentsList) { if (enchantment != null && enchantment.type != null) { Items.enchanted_book.func_92113_a(enchantment, initialCreativeItems); } } } }",Avoid crashing when filling in buggy creative items,https://github.com/embeddedt/ArchaicFix/commit/1d7ef285c44808e27ee5038e163a96f85c3660ae,,,src/main/java/org/embeddedt/archaicfix/proxy/ClientProxy.java,3,java,False,2022-07-16T18:11:21Z "public static List readSignatures(InputStream inputStream, int maxIterations) throws IOException, PGPException { List signatures = new ArrayList<>(); InputStream pgpIn = ArmorUtils.getDecoderStream(inputStream); PGPObjectFactory objectFactory = ImplementationFactory.getInstance().getPGPObjectFactory(pgpIn); int i = 0; Object nextObject; while (i++ < maxIterations && (nextObject = objectFactory.nextObject()) != null) { if (nextObject instanceof PGPCompressedData) { PGPCompressedData compressedData = (PGPCompressedData) nextObject; objectFactory = ImplementationFactory.getInstance().getPGPObjectFactory(compressedData.getDataStream()); } if (nextObject instanceof PGPSignatureList) { PGPSignatureList signatureList = (PGPSignatureList) nextObject; for (PGPSignature s : signatureList) { signatures.add(s); } } if (nextObject instanceof PGPSignature) { signatures.add((PGPSignature) nextObject); } } pgpIn.close(); return signatures; }","public static List readSignatures(InputStream inputStream, int maxIterations) throws IOException, PGPException { List signatures = new ArrayList<>(); InputStream pgpIn = ArmorUtils.getDecoderStream(inputStream); PGPObjectFactory objectFactory = ImplementationFactory.getInstance().getPGPObjectFactory(pgpIn); int i = 0; Object nextObject; while (i++ < maxIterations && (nextObject = objectFactory.nextObject()) != null) { if (nextObject instanceof PGPSignatureList) { PGPSignatureList signatureList = (PGPSignatureList) nextObject; for (PGPSignature s : signatureList) { signatures.add(s); } } if (nextObject instanceof PGPSignature) { signatures.add((PGPSignature) nextObject); } } pgpIn.close(); return signatures; }","Remove support for processing compressed detached signatures Signatures are indistinguishable from randomness, so there is no point in compressing them, apart from attempting to exploit flaws in compression algorithms. Thanks to @DemiMarie for pointing this out Fixes #286",https://github.com/pgpainless/pgpainless/commit/49d65788b48018bf2e194b21ab392b7c7c7c8d55,,,pgpainless-core/src/main/java/org/pgpainless/signature/SignatureUtils.java,3,java,False,2022-05-07T19:46:03Z "int Exiv2::http(Exiv2::Dictionary& request,Exiv2::Dictionary& response,std::string& errors) { if ( !request.count(""verb"") ) request[""verb"" ] = ""GET""; if ( !request.count(""header"") ) request[""header"" ] = """" ; if ( !request.count(""version"")) request[""version""] = ""1.0""; if ( !request.count(""port"") ) request[""port"" ] = """" ; std::string file; errors = """"; int result = 0; //////////////////////////////////// // Windows specific code #ifdef WIN32 WSADATA wsaData; WSAStartup(MAKEWORD(2,2), &wsaData); #endif const char* servername = request[""server"" ].c_str(); const char* page = request[""page"" ].c_str(); const char* verb = request[""verb"" ].c_str(); const char* header = request[""header"" ].c_str(); const char* version = request[""version""].c_str(); const char* port = request[""port"" ].c_str(); const char* servername_p = servername; const char* port_p = port ; std::string url = std::string(""http://"") + request[""server""] + request[""page""]; // parse and change server if using a proxy const char* PROXI = ""HTTP_PROXY""; const char* proxi = ""http_proxy""; const char* PROXY = getenv(PROXI); const char* proxy = getenv(proxi); bool bProx = PROXY || proxy; const char* prox = bProx ? (proxy?proxy:PROXY):""""; Exiv2::Uri Proxy = Exiv2::Uri::Parse(prox); // find the dictionary of no_proxy servers const char* NO_PROXI = ""NO_PROXY""; const char* no_proxi = ""no_proxy""; const char* NO_PROXY = getenv(NO_PROXI); const char* no_proxy = getenv(no_proxi); bool bNoProxy = NO_PROXY||no_proxy; std::string no_prox = std::string(bNoProxy?(no_proxy?no_proxy:NO_PROXY):""""); Exiv2::Dictionary noProxy= stringToDict(no_prox + "",localhost,127.0.0.1""); // if the server is on the no_proxy list ... ignore the proxy! if ( noProxy.count(servername) ) bProx = false; if ( bProx ) { servername_p = Proxy.Host.c_str(); port_p = Proxy.Port.c_str(); page = url.c_str(); std::string p(proxy?proxi:PROXI); // std::cerr << p << '=' << prox << "" page = "" << page << std::endl; } if ( !port [0] ) port = ""80""; if ( !port_p[0] ) port_p = ""80""; //////////////////////////////////// // open the socket int sockfd = (int) socket(AF_INET , SOCK_STREAM,IPPROTO_TCP) ; if ( sockfd < 0 ) return error(errors, ""unable to create socket\n"",NULL,NULL,0) ; // connect the socket to the server int server = -1 ; // fill in the address struct sockaddr_in serv_addr ; int serv_len = sizeof(serv_addr); memset((char *)&serv_addr,0,serv_len); serv_addr.sin_addr.s_addr = inet_addr(servername_p); serv_addr.sin_family = AF_INET ; serv_addr.sin_port = htons(atoi(port_p)); // convert unknown servername into IP address // http://publib.boulder.ibm.com/infocenter/iseries/v5r3/index.jsp?topic=/rzab6/rzab6uafinet.htm if (serv_addr.sin_addr.s_addr == (unsigned long)INADDR_NONE) { struct hostent* host = gethostbyname(servername_p); if ( !host ) return error(errors, ""no such host"", servername_p); memcpy(&serv_addr.sin_addr,host->h_addr,sizeof(serv_addr.sin_addr)); } makeNonBlocking(sockfd) ; //////////////////////////////////// // and connect server = connect(sockfd, (const struct sockaddr *) &serv_addr, serv_len) ; if ( server == SOCKET_ERROR && WSAGetLastError() != WSAEWOULDBLOCK ) return error(errors,""error - unable to connect to server = %s port = %s wsa_error = %d"",servername_p,port_p,WSAGetLastError()); char buffer[32*1024+1]; size_t buff_l= sizeof buffer - 1 ; //////////////////////////////////// // format the request int n = snprintf(buffer,buff_l,httpTemplate,verb,page,version,servername,header) ; buffer[n] = 0 ; response[""requestheaders""]=std::string(buffer,n); //////////////////////////////////// // send the header (we'll have to wait for the connection by the non-blocking socket) while ( sleep_ >= 0 && send(sockfd,buffer,n,0) == SOCKET_ERROR /* && WSAGetLastError() == WSAENOTCONN */ ) { Sleep(snooze) ; sleep_ -= snooze ; } if ( sleep_ < 0 ) return error(errors,""error - timeout connecting to server = %s port = %s wsa_error = %d"",servername,port,WSAGetLastError()); int end = 0 ; // write position in buffer bool bSearching = true ; // looking for headers in the response int status= 200 ; // assume happiness //////////////////////////////////// // read and process the response int err ; n=forgive(recv(sockfd,buffer,(int)buff_l,0),err) ; while ( n >= 0 && OK(status) ) { if ( n ) { end += n ; buffer[end] = 0 ; size_t body = 0 ; // start of body if ( bSearching ) { // search for the body for ( size_t b = 0 ; bSearching && b < lengthof(blankLines) ; b++ ) { if ( strstr(buffer,blankLines[b]) ) { bSearching = false ; body = (int) ( strstr(buffer,blankLines[b]) - buffer ) + strlen(blankLines[b]) ; status = atoi(strchr(buffer,' ')) ; } } // parse response headers char* h = buffer; char C = ':' ; char N = '\n'; int i = 0 ; // initial byte in buffer while(buffer[i] == N ) i++; h = strchr(h+i,N)+1; response[""""]=std::string(buffer+i).substr(0,h-buffer-2); result = atoi(strchr(buffer,' ')); char* c = strchr(h,C); char* first_newline = strchr(h,N); while ( c && first_newline && c < first_newline && h < buffer+body ) { std::string key(h); std::string value(c+1); key = key.substr(0,c-h); value = value.substr(0,first_newline-c-1); response[key]=value; h = first_newline+1; c = strchr(h,C); first_newline = strchr(h,N); } } // if the bufffer's full and we're still searching - give up! // this handles the possibility that there are no headers if ( bSearching && buff_l-end < 10 ) { bSearching = false ; body = 0 ; } if ( !bSearching && OK(status) ) { flushBuffer(buffer,body,end,file); } } n=forgive(recv(sockfd,buffer+end,(int)(buff_l-end),0),err) ; if ( !n ) { Sleep(snooze) ; sleep_ -= snooze ; if ( sleep_ < 0 ) n = FINISH ; } } if ( n != FINISH || !OK(status) ) { snprintf(buffer,sizeof buffer,""wsa_error = %d,n = %d,sleep_ = %d status = %d"" , WSAGetLastError() , n , sleep_ , status ) ; error(errors,buffer,NULL,NULL,0) ; } else if ( bSearching && OK(status) ) { if ( end ) { // we finished OK without finding headers, flush the buffer flushBuffer(buffer,0,end,file) ; } else { return error(errors,""error - no response from server = %s port = %s wsa_error = %d"",servername,port,WSAGetLastError()); } } //////////////////////////////////// // close sockets closesocket(server) ; closesocket(sockfd) ; response[""body""]=file; return result; }","int Exiv2::http(Exiv2::Dictionary& request,Exiv2::Dictionary& response,std::string& errors) { if ( !request.count(""verb"") ) request[""verb"" ] = ""GET""; if ( !request.count(""header"") ) request[""header"" ] = """" ; if ( !request.count(""version"")) request[""version""] = ""1.0""; if ( !request.count(""port"") ) request[""port"" ] = """" ; std::string file; errors = """"; int result = 0; //////////////////////////////////// // Windows specific code #ifdef WIN32 WSADATA wsaData; WSAStartup(MAKEWORD(2,2), &wsaData); #endif const char* servername = request[""server"" ].c_str(); const char* page = request[""page"" ].c_str(); const char* verb = request[""verb"" ].c_str(); const char* header = request[""header"" ].c_str(); const char* version = request[""version""].c_str(); const char* port = request[""port"" ].c_str(); const char* servername_p = servername; const char* port_p = port ; std::string url = std::string(""http://"") + request[""server""] + request[""page""]; // parse and change server if using a proxy const char* PROXI = ""HTTP_PROXY""; const char* proxi = ""http_proxy""; const char* PROXY = getenv(PROXI); const char* proxy = getenv(proxi); bool bProx = PROXY || proxy; const char* prox = bProx ? (proxy?proxy:PROXY):""""; Exiv2::Uri Proxy = Exiv2::Uri::Parse(prox); // find the dictionary of no_proxy servers const char* NO_PROXI = ""NO_PROXY""; const char* no_proxi = ""no_proxy""; const char* NO_PROXY = getenv(NO_PROXI); const char* no_proxy = getenv(no_proxi); bool bNoProxy = NO_PROXY||no_proxy; std::string no_prox = std::string(bNoProxy?(no_proxy?no_proxy:NO_PROXY):""""); Exiv2::Dictionary noProxy= stringToDict(no_prox + "",localhost,127.0.0.1""); // if the server is on the no_proxy list ... ignore the proxy! if ( noProxy.count(servername) ) bProx = false; if ( bProx ) { servername_p = Proxy.Host.c_str(); port_p = Proxy.Port.c_str(); page = url.c_str(); std::string p(proxy?proxi:PROXI); // std::cerr << p << '=' << prox << "" page = "" << page << std::endl; } if ( !port [0] ) port = ""80""; if ( !port_p[0] ) port_p = ""80""; //////////////////////////////////// // open the socket int sockfd = (int) socket(AF_INET , SOCK_STREAM,IPPROTO_TCP) ; if ( sockfd < 0 ) return error(errors, ""unable to create socket\n"",NULL,NULL,0) ; // connect the socket to the server int server = -1 ; // fill in the address struct sockaddr_in serv_addr ; int serv_len = sizeof(serv_addr); memset((char *)&serv_addr,0,serv_len); serv_addr.sin_addr.s_addr = inet_addr(servername_p); serv_addr.sin_family = AF_INET ; serv_addr.sin_port = htons(atoi(port_p)); // convert unknown servername into IP address // http://publib.boulder.ibm.com/infocenter/iseries/v5r3/index.jsp?topic=/rzab6/rzab6uafinet.htm if (serv_addr.sin_addr.s_addr == (unsigned long)INADDR_NONE) { struct hostent* host = gethostbyname(servername_p); if ( !host ) return error(errors, ""no such host"", servername_p); memcpy(&serv_addr.sin_addr,host->h_addr,sizeof(serv_addr.sin_addr)); } makeNonBlocking(sockfd) ; //////////////////////////////////// // and connect server = connect(sockfd, (const struct sockaddr *) &serv_addr, serv_len) ; if ( server == SOCKET_ERROR && WSAGetLastError() != WSAEWOULDBLOCK ) return error(errors,""error - unable to connect to server = %s port = %s wsa_error = %d"",servername_p,port_p,WSAGetLastError()); char buffer[32*1024+1]; size_t buff_l= sizeof buffer - 1 ; //////////////////////////////////// // format the request int n = snprintf(buffer,buff_l,httpTemplate,verb,page,version,servername,header) ; buffer[n] = 0 ; response[""requestheaders""]=std::string(buffer,n); //////////////////////////////////// // send the header (we'll have to wait for the connection by the non-blocking socket) while ( sleep_ >= 0 && send(sockfd,buffer,n,0) == SOCKET_ERROR /* && WSAGetLastError() == WSAENOTCONN */ ) { Sleep(snooze) ; sleep_ -= snooze ; } if ( sleep_ < 0 ) return error(errors,""error - timeout connecting to server = %s port = %s wsa_error = %d"",servername,port,WSAGetLastError()); int end = 0 ; // write position in buffer bool bSearching = true ; // looking for headers in the response int status= 200 ; // assume happiness //////////////////////////////////// // read and process the response int err ; n=forgive(recv(sockfd,buffer,(int)buff_l,0),err) ; while ( n >= 0 && OK(status) ) { if ( n ) { end += n ; buffer[end] = 0 ; size_t body = 0 ; // start of body if ( bSearching ) { // search for the body for ( size_t b = 0 ; bSearching && b < lengthof(blankLines) ; b++ ) { const char* blankLinePos = strstr(buffer,blankLines[b]); if ( blankLinePos ) { bSearching = false ; body = blankLinePos - buffer + strlen(blankLines[b]); const char* firstSpace = strchr(buffer,' '); if (firstSpace) { status = atoi(firstSpace); } } } // parse response headers char* h = buffer; char C = ':' ; char N = '\n'; int i = 0 ; // initial byte in buffer while(buffer[i] == N ) i++; h = strchr(h+i,N); if (!h) { status = 0; break; } h++; response[""""]=std::string(buffer+i).substr(0,h-buffer-2); const char* firstSpace = strchr(buffer,' '); if ( !firstSpace ) { status = 0; break; } result = atoi(firstSpace); char* c = strchr(h,C); char* first_newline = strchr(h,N); while ( c && first_newline && c < first_newline && h < buffer+body ) { std::string key(h); std::string value(c+1); key = key.substr(0,c-h); value = value.substr(0,first_newline-c-1); response[key]=value; h = first_newline+1; c = strchr(h,C); first_newline = strchr(h,N); } } // if the bufffer's full and we're still searching - give up! // this handles the possibility that there are no headers if ( bSearching && buff_l-end < 10 ) { bSearching = false ; body = 0 ; } if ( !bSearching && OK(status) ) { flushBuffer(buffer,body,end,file); } } n=forgive(recv(sockfd,buffer+end,(int)(buff_l-end),0),err) ; if ( !n ) { Sleep(snooze) ; sleep_ -= snooze ; if ( sleep_ < 0 ) n = FINISH ; } } if ( n != FINISH || !OK(status) ) { snprintf(buffer,sizeof buffer,""wsa_error = %d,n = %d,sleep_ = %d status = %d"" , WSAGetLastError() , n , sleep_ , status ) ; error(errors,buffer,NULL,NULL,0) ; } else if ( bSearching && OK(status) ) { if ( end ) { // we finished OK without finding headers, flush the buffer flushBuffer(buffer,0,end,file) ; } else { return error(errors,""error - no response from server = %s port = %s wsa_error = %d"",servername,port,WSAGetLastError()); } } //////////////////////////////////// // close sockets closesocket(server) ; closesocket(sockfd) ; response[""body""]=file; return result; }","Avoid null pointer exception due to NULL return value from strchr. This fixes #793.",https://github.com/Exiv2/exiv2/commit/ae20c30805b330275b2aa0303a42e1f2bbd53661,,,src/http.cpp,3,cpp,False,2019-04-30T10:15:06Z "public void streamContentImpl(WebScriptRequest req, WebScriptResponse res, ContentReader reader, final NodeRef nodeRef, final QName propertyQName, final boolean attach, final Date modified, String eTag, final String attachFileName, Map model) throws IOException { setAttachment(req, res, attach, attachFileName); // establish mimetype String mimetype = reader.getMimetype(); String extensionPath = req.getExtensionPath(); if (mimetype == null || mimetype.length() == 0) { mimetype = MimetypeMap.MIMETYPE_BINARY; int extIndex = extensionPath.lastIndexOf('.'); if (extIndex != -1) { String ext = extensionPath.substring(extIndex + 1); mimetype = mimetypeService.getMimetype(ext); } } res.setHeader(HEADER_ACCEPT_RANGES, ""bytes""); try { boolean processedRange = false; String range = req.getHeader(HEADER_CONTENT_RANGE); final long size = reader.getSize(); final String encoding = reader.getEncoding(); // if (attach) // { // final String finalMimetype = mimetype; // // eventPublisher.publishEvent(new EventPreparator(){ // @Override // public Event prepareEvent(String user, String networkId, String transactionId) // { // String siteId = siteService.getSiteShortName(nodeRef); // // return new ContentEventImpl(ContentEvent.DOWNLOAD, user, networkId, transactionId, // nodeRef.getId(), siteId, propertyQName.toString(), Client.asType(ClientType.webclient), attachFileName, finalMimetype, size, encoding); // } // }); // } if (range == null) { range = req.getHeader(HEADER_RANGE); } if (range != null) { if (logger.isDebugEnabled()) logger.debug(""Found content range header: "" + range); // ensure the range header is starts with ""bytes="" and process the range(s) if (range.length() > 6) { if (range.indexOf(',') != -1 && (nodeRef == null || propertyQName == null)) { if (logger.isInfoEnabled()) logger.info(""Multi-range only supported for nodeRefs""); } else { HttpRangeProcessor rangeProcessor = new HttpRangeProcessor(contentService); processedRange = rangeProcessor.processRange( res, reader, range.substring(6), nodeRef, propertyQName, mimetype, req.getHeader(HEADER_USER_AGENT)); } } } if (processedRange == false) { if (logger.isDebugEnabled()) logger.debug(""Sending complete file content...""); // set mimetype for the content and the character encoding for the stream res.setContentType(mimetype); res.setContentEncoding(encoding); // return the complete entity range res.setHeader(HEADER_CONTENT_RANGE, ""bytes 0-"" + Long.toString(size-1L) + ""/"" + Long.toString(size)); res.setHeader(HEADER_CONTENT_LENGTH, Long.toString(size)); // set caching setResponseCache(res, modified, eTag, model); // get the content and stream directly to the response output stream // assuming the repository is capable of streaming in chunks, this should allow large files // to be streamed directly to the browser response stream. reader.getContent( res.getOutputStream() ); } } catch (SocketException e1) { // the client cut the connection - our mission was accomplished apart from a little error message if (logger.isInfoEnabled()) logger.info(""Client aborted stream read:\n\tcontent: "" + reader); } catch (ContentIOException e2) { if (logger.isInfoEnabled()) logger.info(""Client aborted stream read:\n\tcontent: "" + reader); } }","public void streamContentImpl(WebScriptRequest req, WebScriptResponse res, ContentReader reader, final NodeRef nodeRef, final QName propertyQName, final boolean attach, final Date modified, String eTag, final String attachFileName, Map model) throws IOException { setAttachment(req, res, attach, attachFileName); // establish mimetype String mimetype = MimeTypeUtil.determineMimetype(reader, req, mimetypeService); res.setHeader(HEADER_ACCEPT_RANGES, ""bytes""); try { boolean processedRange = false; String range = req.getHeader(HEADER_CONTENT_RANGE); final long size = reader.getSize(); final String encoding = reader.getEncoding(); // if (attach) // { // final String finalMimetype = mimetype; // // eventPublisher.publishEvent(new EventPreparator(){ // @Override // public Event prepareEvent(String user, String networkId, String transactionId) // { // String siteId = siteService.getSiteShortName(nodeRef); // // return new ContentEventImpl(ContentEvent.DOWNLOAD, user, networkId, transactionId, // nodeRef.getId(), siteId, propertyQName.toString(), Client.asType(ClientType.webclient), attachFileName, finalMimetype, size, encoding); // } // }); // } if (range == null) { range = req.getHeader(HEADER_RANGE); } if (range != null) { if (logger.isDebugEnabled()) logger.debug(""Found content range header: "" + range); // ensure the range header is starts with ""bytes="" and process the range(s) if (range.length() > 6) { if (range.indexOf(',') != -1 && (nodeRef == null || propertyQName == null)) { if (logger.isInfoEnabled()) logger.info(""Multi-range only supported for nodeRefs""); } else { HttpRangeProcessor rangeProcessor = new HttpRangeProcessor(contentService); processedRange = rangeProcessor.processRange( res, reader, range.substring(6), nodeRef, propertyQName, mimetype, req.getHeader(HEADER_USER_AGENT)); } } } if (processedRange == false) { if (logger.isDebugEnabled()) logger.debug(""Sending complete file content...""); // set mimetype for the content and the character encoding for the stream res.setContentType(mimetype); res.setContentEncoding(encoding); // return the complete entity range res.setHeader(HEADER_CONTENT_RANGE, ""bytes 0-"" + Long.toString(size-1L) + ""/"" + Long.toString(size)); res.setHeader(HEADER_CONTENT_LENGTH, Long.toString(size)); // set caching setResponseCache(res, modified, eTag, model); // get the content and stream directly to the response output stream // assuming the repository is capable of streaming in chunks, this should allow large files // to be streamed directly to the browser response stream. reader.getContent( res.getOutputStream() ); } } catch (SocketException e1) { // the client cut the connection - our mission was accomplished apart from a little error message if (logger.isInfoEnabled()) logger.info(""Client aborted stream read:\n\tcontent: "" + reader); } catch (ContentIOException e2) { if (logger.isInfoEnabled()) logger.info(""Client aborted stream read:\n\tcontent: "" + reader); } }","ACS-3316 Fix custom models downloading and XSS (#1304) (#1320) * Revert ""Revert ""ACS-3316 Fix HTML sanitisation bypass (#1266)"" (#1294)"" This reverts commit 6c407b1ef5b9002534b2e114e186a0e273495d5a. * ACS-3316 Set node name for download node * ACS-3316 Update license Co-authored-by: Damian.Ujma@hyland.com (cherry picked from commit cc3f8aaff4b6c3d16473529f97d229a86d241793)",https://github.com/Alfresco/alfresco-community-repo/commit/9bd0c4c699be68ce13a31d5a57771ccb5c66bb16,,,remote-api/src/main/java/org/alfresco/repo/web/scripts/content/ContentStreamer.java,3,java,False,2022-08-22T10:07:30Z "@Override public boolean isValid(String value, ConstraintValidatorContext constraintValidatorContext) { return !containsHtml(value); }","@Override public boolean isValid(String value, ConstraintValidatorContext constraintValidatorContext) { return !ReUtil.contains(HtmlUtil.RE_HTML_MARK, value); }",add 增加 自定义 Xss 校验注解 用户导入增加 Bean 校验,https://github.com/dromara/RuoYi-Vue-Plus/commit/2455d0b859708e39fa9fd5b710bebee45c32b085,,,ruoyi-common/src/main/java/com/ruoyi/common/xss/XssValidator.java,3,java,False,2021-12-15T07:03:44Z "@Override public JSONArray getLessonsForContext(String siteId) { JSONArray jsonLessons = new JSONArray(); jsonLessons = addAllSubpages(simplePageToolDao.findItemsInSite(siteId), null, jsonLessons, ""false""); return jsonLessons; }","@Override public JSONArray getLessonsForContext(String siteId) { JSONArray jsonLessons = new JSONArray(); List processedItemIDs = new ArrayList<>(); jsonLessons = addAllSubpages(simplePageToolDao.findItemsInSite(siteId), null, jsonLessons, ""false"", processedItemIDs); return jsonLessons; }","SAK-46007 stackoverflow caused by DateManagerServiceImpl.addAllSubpages (#9591) (cherry picked from commit f949180908ab973d1724f8b945b7f89146206fb2)",https://github.com/sakaiproject/sakai/commit/49952d7836a1e7b7df14234e4eae6b67ec0ad84c,,,site-manage/datemanager/impl/src/java/org/sakaiproject/datemanager/impl/DateManagerServiceImpl.java,3,java,False,2021-08-18T14:45:46Z "@SysLog(""添加用户"") @PostMapping @PreAuthorize(""@pms.hasPermission('sys_user_add')"") public R user(@RequestBody UserDTO userDto) { return R.ok(userService.saveUser(userDto)); }","@SysLog(""添加用户"") @PostMapping @XssCleanIgnore({ ""password"" }) @PreAuthorize(""@pms.hasPermission('sys_user_add')"") public R user(@RequestBody UserDTO userDto) { return R.ok(userService.saveUser(userDto)); }",:sparkles: Introducing new features. 增加 xss 过滤模块,https://github.com/pig-mesh/pig/commit/297e056df932c56bf259205d47c5560c9098ba0e,,,pig-upms/pig-upms-biz/src/main/java/com/pig4cloud/pig/admin/controller/UserController.java,3,java,False,2022-10-10T07:34:59Z "private File unzip(final String id, final File zipFile, final String dest) throws IOException { final File targetDirectory = new File(this.documentsDir, dest); final ZipInputStream zis = new ZipInputStream(new BufferedInputStream(new FileInputStream(zipFile))); try { int count; final int bufferSize = 8192; final byte[] buffer = new byte[bufferSize]; final long lengthTotal = zipFile.length(); long lengthRead = bufferSize; int percent = 0; this.notifyDownload(id, 75); ZipEntry entry; while ((entry = zis.getNextEntry()) != null) { final File file = new File(targetDirectory, entry.getName()); final String canonicalPath = file.getCanonicalPath(); final String canonicalDir = (new File(String.valueOf(targetDirectory))).getCanonicalPath(); final File dir = entry.isDirectory() ? file : file.getParentFile(); if (!canonicalPath.startsWith(canonicalDir)) { throw new FileNotFoundException( ""SecurityException, Failed to ensure directory is the start path : "" + canonicalDir + "" of "" + canonicalPath ); } if (!dir.isDirectory() && !dir.mkdirs()) { throw new FileNotFoundException(""Failed to ensure directory: "" + dir.getAbsolutePath()); } if (entry.isDirectory()) { continue; } try (final FileOutputStream outputStream = new FileOutputStream(file)) { while ((count = zis.read(buffer)) != -1) outputStream.write(buffer, 0, count); } final int newPercent = (int) ((lengthRead * 100) / lengthTotal); if (lengthTotal > 1 && newPercent != percent) { percent = newPercent; this.notifyDownload(id, this.calcTotalPercent(percent, 75, 90)); } lengthRead += entry.getCompressedSize(); } return targetDirectory; } finally { try { zis.close(); } catch (final IOException e) { Log.e(TAG, ""Failed to close zip input stream"", e); } } }","private File unzip(final String id, final File zipFile, final String dest) throws IOException { final File targetDirectory = new File(this.documentsDir, Paths.get(dest).normalize().toString()); final ZipInputStream zis = new ZipInputStream(new BufferedInputStream(new FileInputStream(zipFile))); try { int count; final int bufferSize = 8192; final byte[] buffer = new byte[bufferSize]; final long lengthTotal = zipFile.length(); long lengthRead = bufferSize; int percent = 0; this.notifyDownload(id, 75); ZipEntry entry; while ((entry = zis.getNextEntry()) != null) { final File file = new File(targetDirectory, Paths.get(entry.getName()).normalize().toString()); final String canonicalPath = file.getCanonicalPath(); final String canonicalDir = (new File(String.valueOf(targetDirectory))).getCanonicalPath(); final File dir = entry.isDirectory() ? file : file.getParentFile(); if (!canonicalPath.startsWith(canonicalDir)) { throw new FileNotFoundException( ""SecurityException, Failed to ensure directory is the start path : "" + canonicalDir + "" of "" + canonicalPath ); } if (!dir.isDirectory() && !dir.mkdirs()) { throw new FileNotFoundException(""Failed to ensure directory: "" + dir.getAbsolutePath()); } if (entry.isDirectory()) { continue; } try (final FileOutputStream outputStream = new FileOutputStream(file)) { while ((count = zis.read(buffer)) != -1) outputStream.write(buffer, 0, count); } final int newPercent = (int) ((lengthRead * 100) / lengthTotal); if (lengthTotal > 1 && newPercent != percent) { percent = newPercent; this.notifyDownload(id, this.calcTotalPercent(percent, 75, 90)); } lengthRead += entry.getCompressedSize(); } return targetDirectory; } finally { try { zis.close(); } catch (final IOException e) { Log.e(TAG, ""Failed to close zip input stream"", e); } } }",fix: vulnerability issue,https://github.com/Cap-go/capacitor-updater/commit/738904f904ea48f24d6b3b14b2b092c46a860ded,,,android/src/main/java/ee/forgr/capacitor_updater/CapacitorUpdater.java,3,java,False,2022-11-17T14:55:10Z "public void exit (InputEvent event, float x, float y, int pointer, @Null Actor toActor) { if (toActor == null || !isAscendantOf(toActor)) list.selection.set(selectBox.getSelected()); }","public void exit (InputEvent event, float x, float y, int pointer, @Null Actor toActor) { if (toActor == null || !isAscendantOf(toActor)) { T selected = selectBox.getSelected(); if (selected != null) list.selection.set(selected); } }","[scene2d.ui] SelectBox, fixed crash if select box items are cleared before the mouse exits.",https://github.com/libgdx/libgdx/commit/4eaee83eb18a8826907fcf678bc428df78bbc7db,,,gdx/src/com/badlogic/gdx/scenes/scene2d/ui/SelectBox.java,3,java,False,2022-09-28T01:08:50Z "@VisibleForTesting void authenticateIfRequired(Connection conn) { cancelCriterion.checkCancelInProgress(null); if (pool.isUsedByGateway() || pool.getMultiuserAuthentication()) { return; } ServerLocation server = conn.getServer(); if (!server.getRequiresCredentials() || server.getUserId() != -1) { return; } Long uniqueID = AuthenticateUserOp.executeOn(conn, pool); server.setUserId(uniqueID); if (logger.isDebugEnabled()) { logger.debug(""CFI.authenticateIfRequired() Completed authentication on {}"", conn); } }","@VisibleForTesting void authenticateIfRequired(Connection conn) { cancelCriterion.checkCancelInProgress(null); if (pool.isUsedByGateway() || pool.getMultiuserAuthentication()) { return; } ServerLocation server = conn.getServer(); if (!server.getRequiresCredentials()) { return; } // make this block synchronized so that when a AuthenticateUserOp is already in progress, // another thread won't try to authenticate again. synchronized (server) { if (server.getUserId() != -1) { return; } Long uniqueID = AuthenticateUserOp.executeOn(conn, pool); server.setUserId(uniqueID); } if (logger.isDebugEnabled()) { logger.debug(""CFI.authenticateIfRequired() Completed authentication on {}"", conn); } }",GEODE-9792: avoid sending in multiple authentication request on the same connection by different threads. (#7067),https://github.com/apache/geode/commit/af79b3ae7a88ecb01f94f4f329e20d1ca9e49b71,,,geode-core/src/main/java/org/apache/geode/cache/client/internal/ConnectionFactoryImpl.java,3,java,False,2021-11-02T20:20:00Z "public Response getResponse(HttpExchange exchange) { if (ipWhitelist == null) { ipWhitelist = config.isTrue(WebserverSettings.IP_WHITELIST) ? config.get(WebserverSettings.WHITELIST) : Collections.emptyList(); } String accessor = getAccessorAddress(exchange); Request request = null; Response response; try { request = buildRequest(exchange); if (bruteForceGuard.shouldPreventRequest(accessor)) { response = responseFactory.failedLoginAttempts403(); } else if (!ipWhitelist.isEmpty() && !ipWhitelist.contains(accessor)) { response = responseFactory.ipWhitelist403(accessor); logger.info(locale.getString(PluginLang.WEB_SERVER_NOTIFY_IP_WHITELIST_BLOCK, accessor, exchange.getRequestURI().toString())); } else { response = responseResolver.getResponse(request); } } catch (WebUserAuthException thrownByAuthentication) { FailReason failReason = thrownByAuthentication.getFailReason(); if (failReason == FailReason.USER_PASS_MISMATCH) { bruteForceGuard.increaseAttemptCountOnFailedLogin(accessor); response = responseFactory.badRequest(failReason.getReason(), ""/auth/login""); } else { String from = exchange.getRequestURI().toASCIIString(); response = Response.builder() .redirectTo(StringUtils.startsWithAny(from, ""/auth/"", ""/login"") ? ""/login"" : ""/login?from=."" + from) .setHeader(""Set-Cookie"", ""auth=expired; Path=/; Max-Age=1; SameSite=Lax; Secure;"") .build(); } } if (bruteForceGuard.shouldPreventRequest(accessor)) { response = responseFactory.failedLoginAttempts403(); } if (response.getCode() != 401 // Not failed && response.getCode() != 403 // Not blocked && (request != null && request.getUser().isPresent()) // Logged in ) { bruteForceGuard.resetAttemptCount(accessor); } return response; }","public Response getResponse(HttpExchange exchange) { if (ipWhitelist == null) { ipWhitelist = config.isTrue(WebserverSettings.IP_WHITELIST) ? config.get(WebserverSettings.WHITELIST) : Collections.emptyList(); } String accessor = getAccessorAddress(exchange); Request request = null; Response response; try { request = buildRequest(exchange); if (bruteForceGuard.shouldPreventRequest(accessor)) { response = responseFactory.failedLoginAttempts403(); } else if (!ipWhitelist.isEmpty() && !ipWhitelist.contains(accessor)) { response = responseFactory.ipWhitelist403(accessor); logger.info(locale.getString(PluginLang.WEB_SERVER_NOTIFY_IP_WHITELIST_BLOCK, accessor, exchange.getRequestURI().toString())); } else { response = responseResolver.getResponse(request); } } catch (WebUserAuthException thrownByAuthentication) { FailReason failReason = thrownByAuthentication.getFailReason(); if (failReason == FailReason.USER_PASS_MISMATCH) { bruteForceGuard.increaseAttemptCountOnFailedLogin(accessor); response = responseFactory.badRequest(failReason.getReason(), ""/auth/login""); } else { String from = exchange.getRequestURI().toASCIIString(); String directTo = StringUtils.startsWithAny(from, ""/auth/"", ""/login"") ? ""/login"" : ""/login?from=."" + from; response = Response.builder() .redirectTo(directTo) .setHeader(""Set-Cookie"", ""auth=expired; Path=/; Max-Age=1; SameSite=Lax; Secure;"") .build(); } } if (bruteForceGuard.shouldPreventRequest(accessor)) { response = responseFactory.failedLoginAttempts403(); } if (response.getCode() != 401 // Not failed && response.getCode() != 403 // Not blocked && (request != null && request.getUser().isPresent()) // Logged in ) { bruteForceGuard.resetAttemptCount(accessor); } return response; }","Implemented persistent cookies Fixed security vulnerability with cookies not being invalidated properly Request headers were not properly set for the Request object, leading to the Cookie header missing when logging out, which then left the cookie in memory. Rogue actor who gained access to the cookie could then use the cookie to access the panel. Made cookie expiry configurable with 'Webserver.Security.Cookie_expires_after' Due to cookie persistence there is no way to log everyone out of the panel. This will be addressed in a future commit with addition of a command. Affects issues: - Close #1740",https://github.com/plan-player-analytics/Plan/commit/fb4b272844263d33f5a6e85af29ac7e6e25ff80a,,,Plan/common/src/main/java/com/djrapitops/plan/delivery/webserver/RequestHandler.java,3,java,False,2021-03-20T10:02:02Z "public static void resetObjectives() { objectivesPosition = 0; objectivesEnd = 0; }","public static void resetObjectives() { objectivesPosition = 0; }","Fix 14 issues found in ticket backlog (#502) * Fix IndexOutOfBoundsException in QuestBookListPage Signed-off-by: kristofbolyai * Fix crash if OverlayConfig.GameUpdate.INSTANCE.messageMaxLength is 1 Signed-off-by: kristofbolyai * Fix crash related to deleting chat tabs and ChatGUI not updating Signed-off-by: kristofbolyai * Fix crash related to deleting chat tabs and ChatGUI not updating Signed-off-by: kristofbolyai * Fix translation cache becoming null Signed-off-by: kristofbolyai * Fix objective parsing if player is in party Signed-off-by: kristofbolyai * Fix guild objective not being removed upon completion Signed-off-by: kristofbolyai * Fix race condition in ServerEvents Signed-off-by: kristofbolyai * Fix race condition in ClientEvents Signed-off-by: kristofbolyai * Fix NPE in ServerEvents Signed-off-by: kristofbolyai * Fix AreaDPS value not being correct Signed-off-by: kristofbolyai * Fix NPE in fix :) Signed-off-by: kristofbolyai * Fix quest dialogue spoofing Signed-off-by: kristofbolyai * Fix Keyholder related crash Signed-off-by: kristofbolyai * Fix totem tracking Signed-off-by: kristofbolyai * Dialogue Page gets updated correctly Signed-off-by: kristofbolyai * Register ChatGUI correctly Signed-off-by: kristofbolyai * Use MC's GameSettings to check for isKeyDown Signed-off-by: kristofbolyai * Make multi line if have braces Signed-off-by: kristofbolyai ",https://github.com/Wynntils/Wynntils/commit/c8f6effe187ff68f17bcff809d2bc440ec07128d,,,src/main/java/com/wynntils/modules/utilities/overlays/hud/ObjectivesOverlay.java,3,java,False,2022-04-15T17:16:00Z "private Ip4Address readFirstIPv4Address() { List assignedIps = getAddresses().stream() .filter(IpAddress::isIpv4) .map(ip -> (Ip4Address) ip) .collect(Collectors.toList()); if (assignedIps.size() > 1) { log.warn(""Could not find primary ip address, candidates: {}"", assignedIps); } return assignedIps.get(0); }","private Ip4Address readFirstIPv4Address() { List assignedIps = getAddresses().stream() .filter(IpAddress::isIpv4) .map(ip -> (Ip4Address) ip) .collect(Collectors.toList()); if (assignedIps.isEmpty()) { log.error(""Could not find primary IPv4 address""); return null; } if (assignedIps.size() > 1) { log.warn(""More than one IPv4 address ({}). Returning the first one."", assignedIps); } return assignedIps.get(0); }",Add unit test for NetworkInterfacWrapper. Bugfix: do not crash if no IPv4 address is assigned to main interface initially.,https://github.com/eblocker/eblocker/commit/d432d69ad8ddbc90cb1372593898c9627099d402,,,eblocker-icapserver/src/main/java/org/eblocker/server/common/network/NetworkInterfaceWrapper.java,3,java,False,2022-08-03T09:05:22Z "@Override protected void handleProducer(final CommandProducer cmdProducer) { checkArgument(state == State.Connected); final long producerId = cmdProducer.getProducerId(); final long requestId = cmdProducer.getRequestId(); // Use producer name provided by client if present final String producerName = cmdProducer.hasProducerName() ? cmdProducer.getProducerName() : service.generateUniqueProducerName(); final long epoch = cmdProducer.getEpoch(); final boolean userProvidedProducerName = cmdProducer.isUserProvidedProducerName(); final boolean isEncrypted = cmdProducer.isEncrypted(); final Map metadata = CommandUtils.metadataFromCommand(cmdProducer); final SchemaData schema = cmdProducer.hasSchema() ? getSchema(cmdProducer.getSchema()) : null; final ProducerAccessMode producerAccessMode = cmdProducer.getProducerAccessMode(); final Optional topicEpoch = cmdProducer.hasTopicEpoch() ? Optional.of(cmdProducer.getTopicEpoch()) : Optional.empty(); final boolean isTxnEnabled = cmdProducer.isTxnEnabled(); final String initialSubscriptionName = cmdProducer.hasInitialSubscriptionName() ? cmdProducer.getInitialSubscriptionName() : null; final boolean supportsPartialProducer = supportsPartialProducer(); TopicName topicName = validateTopicName(cmdProducer.getTopic(), requestId, cmdProducer); if (topicName == null) { return; } if (invalidOriginalPrincipal(originalPrincipal)) { final String msg = ""Valid Proxy Client role should be provided while creating producer ""; log.warn(""[{}] {} with role {} and proxyClientAuthRole {} on topic {}"", remoteAddress, msg, authRole, originalPrincipal, topicName); commandSender.sendErrorResponse(requestId, ServerError.AuthorizationError, msg); return; } CompletableFuture isAuthorizedFuture = isTopicOperationAllowed( topicName, TopicOperation.PRODUCE ); if (!Strings.isNullOrEmpty(initialSubscriptionName)) { isAuthorizedFuture = isAuthorizedFuture.thenCombine(isTopicOperationAllowed(topicName, TopicOperation.SUBSCRIBE), (canProduce, canSubscribe) -> canProduce && canSubscribe); } isAuthorizedFuture.thenApply(isAuthorized -> { if (!isAuthorized) { String msg = ""Client is not authorized to Produce""; log.warn(""[{}] {} with role {}"", remoteAddress, msg, getPrincipal()); ctx.writeAndFlush(Commands.newError(requestId, ServerError.AuthorizationError, msg)); return null; } if (log.isDebugEnabled()) { log.debug(""[{}] Client is authorized to Produce with role {}"", remoteAddress, getPrincipal()); } CompletableFuture producerFuture = new CompletableFuture<>(); CompletableFuture existingProducerFuture = producers.putIfAbsent(producerId, producerFuture); if (existingProducerFuture != null) { if (existingProducerFuture.isDone() && !existingProducerFuture.isCompletedExceptionally()) { Producer producer = existingProducerFuture.getNow(null); log.info(""[{}] Producer with the same id is already created:"" + "" producerId={}, producer={}"", remoteAddress, producerId, producer); commandSender.sendProducerSuccessResponse(requestId, producer.getProducerName(), producer.getSchemaVersion()); return null; } else { // There was an early request to create a producer with same producerId. // This can happen when client timeout is lower than the broker timeouts. // We need to wait until the previous producer creation request // either complete or fails. ServerError error = null; if (!existingProducerFuture.isDone()) { error = ServerError.ServiceNotReady; } else { error = getErrorCode(existingProducerFuture); // remove producer with producerId as it's already completed with exception producers.remove(producerId, existingProducerFuture); } log.warn(""[{}][{}] Producer with id is already present on the connection, producerId={}"", remoteAddress, topicName, producerId); commandSender.sendErrorResponse(requestId, error, ""Producer is already present on the connection""); return null; } } log.info(""[{}][{}] Creating producer. producerId={}"", remoteAddress, topicName, producerId); service.getOrCreateTopic(topicName.toString()).thenCompose((Topic topic) -> { // Before creating producer, check if backlog quota exceeded // on topic for size based limit and time based limit CompletableFuture backlogQuotaCheckFuture = CompletableFuture.allOf( topic.checkBacklogQuotaExceeded(producerName, BacklogQuotaType.destination_storage), topic.checkBacklogQuotaExceeded(producerName, BacklogQuotaType.message_age)); backlogQuotaCheckFuture.thenRun(() -> { // Check whether the producer will publish encrypted messages or not if ((topic.isEncryptionRequired() || encryptionRequireOnProducer) && !isEncrypted) { String msg = String.format(""Encryption is required in %s"", topicName); log.warn(""[{}] {}"", remoteAddress, msg); if (producerFuture.completeExceptionally(new ServerMetadataException(msg))) { commandSender.sendErrorResponse(requestId, ServerError.MetadataError, msg); } producers.remove(producerId, producerFuture); return; } disableTcpNoDelayIfNeeded(topicName.toString(), producerName); CompletableFuture schemaVersionFuture = tryAddSchema(topic, schema); schemaVersionFuture.exceptionally(exception -> { if (producerFuture.completeExceptionally(exception)) { String message = exception.getMessage(); if (exception.getCause() != null) { message += ("" caused by "" + exception.getCause()); } commandSender.sendErrorResponse(requestId, BrokerServiceException.getClientErrorCode(exception), message); } producers.remove(producerId, producerFuture); return null; }); schemaVersionFuture.thenAccept(schemaVersion -> { topic.checkIfTransactionBufferRecoverCompletely(isTxnEnabled).thenAccept(future -> { CompletableFuture createInitSubFuture; if (!Strings.isNullOrEmpty(initialSubscriptionName) && topic.isPersistent() && !topic.getSubscriptions().containsKey(initialSubscriptionName)) { if (!this.getBrokerService().isAllowAutoSubscriptionCreation(topicName)) { String msg = ""Could not create the initial subscription due to the auto subscription "" + ""creation is not allowed.""; if (producerFuture.completeExceptionally( new BrokerServiceException.NotAllowedException(msg))) { log.warn(""[{}] {} initialSubscriptionName: {}, topic: {}"", remoteAddress, msg, initialSubscriptionName, topicName); commandSender.sendErrorResponse(requestId, ServerError.NotAllowedError, msg); } producers.remove(producerId, producerFuture); return; } createInitSubFuture = topic.createSubscription(initialSubscriptionName, InitialPosition.Earliest, false, null); } else { createInitSubFuture = CompletableFuture.completedFuture(null); } createInitSubFuture.whenComplete((sub, ex) -> { if (ex != null) { String msg = ""Failed to create the initial subscription: "" + ex.getCause().getMessage(); log.warn(""[{}] {} initialSubscriptionName: {}, topic: {}"", remoteAddress, msg, initialSubscriptionName, topicName); if (producerFuture.completeExceptionally(ex)) { commandSender.sendErrorResponse(requestId, BrokerServiceException.getClientErrorCode(ex), msg); } producers.remove(producerId, producerFuture); return; } buildProducerAndAddTopic(topic, producerId, producerName, requestId, isEncrypted, metadata, schemaVersion, epoch, userProvidedProducerName, topicName, producerAccessMode, topicEpoch, supportsPartialProducer, producerFuture); }); }).exceptionally(exception -> { Throwable cause = exception.getCause(); log.error(""producerId {}, requestId {} : TransactionBuffer recover failed"", producerId, requestId, exception); if (producerFuture.completeExceptionally(exception)) { commandSender.sendErrorResponse(requestId, ServiceUnitNotReadyException.getClientErrorCode(cause), cause.getMessage()); } producers.remove(producerId, producerFuture); return null; }); }); }); return backlogQuotaCheckFuture; }).exceptionally(exception -> { Throwable cause = exception.getCause(); if (cause instanceof BrokerServiceException.TopicBacklogQuotaExceededException) { BrokerServiceException.TopicBacklogQuotaExceededException tbqe = (BrokerServiceException.TopicBacklogQuotaExceededException) cause; IllegalStateException illegalStateException = new IllegalStateException(tbqe); BacklogQuota.RetentionPolicy retentionPolicy = tbqe.getRetentionPolicy(); if (producerFuture.completeExceptionally(illegalStateException)) { if (retentionPolicy == BacklogQuota.RetentionPolicy.producer_request_hold) { commandSender.sendErrorResponse(requestId, ServerError.ProducerBlockedQuotaExceededError, illegalStateException.getMessage()); } else if (retentionPolicy == BacklogQuota.RetentionPolicy.producer_exception) { commandSender.sendErrorResponse(requestId, ServerError.ProducerBlockedQuotaExceededException, illegalStateException.getMessage()); } } producers.remove(producerId, producerFuture); return null; } // Do not print stack traces for expected exceptions if (cause instanceof NoSuchElementException) { cause = new TopicNotFoundException(""Topic Not Found.""); log.info(""[{}] Failed to load topic {}, producerId={}: Topic not found"", remoteAddress, topicName, producerId); } else if (!Exceptions.areExceptionsPresentInChain(cause, ServiceUnitNotReadyException.class, ManagedLedgerException.class)) { log.error(""[{}] Failed to create topic {}, producerId={}"", remoteAddress, topicName, producerId, exception); } // If client timed out, the future would have been completed // by subsequent close. Send error back to // client, only if not completed already. if (producerFuture.completeExceptionally(exception)) { commandSender.sendErrorResponse(requestId, BrokerServiceException.getClientErrorCode(cause), cause.getMessage()); } producers.remove(producerId, producerFuture); return null; }); return null; }).exceptionally(ex -> { logAuthException(remoteAddress, ""producer"", getPrincipal(), Optional.of(topicName), ex); commandSender.sendErrorResponse(requestId, ServerError.AuthorizationError, ex.getMessage()); return null; }); }","@Override protected void handleProducer(final CommandProducer cmdProducer) { checkArgument(state == State.Connected); final long producerId = cmdProducer.getProducerId(); final long requestId = cmdProducer.getRequestId(); // Use producer name provided by client if present final String producerName = cmdProducer.hasProducerName() ? cmdProducer.getProducerName() : service.generateUniqueProducerName(); final long epoch = cmdProducer.getEpoch(); final boolean userProvidedProducerName = cmdProducer.isUserProvidedProducerName(); final boolean isEncrypted = cmdProducer.isEncrypted(); final Map metadata = CommandUtils.metadataFromCommand(cmdProducer); final SchemaData schema = cmdProducer.hasSchema() ? getSchema(cmdProducer.getSchema()) : null; final ProducerAccessMode producerAccessMode = cmdProducer.getProducerAccessMode(); final Optional topicEpoch = cmdProducer.hasTopicEpoch() ? Optional.of(cmdProducer.getTopicEpoch()) : Optional.empty(); final boolean isTxnEnabled = cmdProducer.isTxnEnabled(); final String initialSubscriptionName = cmdProducer.hasInitialSubscriptionName() ? cmdProducer.getInitialSubscriptionName() : null; final boolean supportsPartialProducer = supportsPartialProducer(); TopicName topicName = validateTopicName(cmdProducer.getTopic(), requestId, cmdProducer); if (topicName == null) { return; } if (invalidOriginalPrincipal(originalPrincipal)) { final String msg = ""Valid Proxy Client role should be provided while creating producer ""; log.warn(""[{}] {} with role {} and proxyClientAuthRole {} on topic {}"", remoteAddress, msg, authRole, originalPrincipal, topicName); commandSender.sendErrorResponse(requestId, ServerError.AuthorizationError, msg); return; } CompletableFuture isAuthorizedFuture = isTopicOperationAllowed( topicName, TopicOperation.PRODUCE, getAuthenticationData() ); if (!Strings.isNullOrEmpty(initialSubscriptionName)) { isAuthorizedFuture = isAuthorizedFuture.thenCombine( isTopicOperationAllowed(topicName, TopicOperation.SUBSCRIBE, getAuthenticationData()), (canProduce, canSubscribe) -> canProduce && canSubscribe); } isAuthorizedFuture.thenApply(isAuthorized -> { if (!isAuthorized) { String msg = ""Client is not authorized to Produce""; log.warn(""[{}] {} with role {}"", remoteAddress, msg, getPrincipal()); ctx.writeAndFlush(Commands.newError(requestId, ServerError.AuthorizationError, msg)); return null; } if (log.isDebugEnabled()) { log.debug(""[{}] Client is authorized to Produce with role {}"", remoteAddress, getPrincipal()); } CompletableFuture producerFuture = new CompletableFuture<>(); CompletableFuture existingProducerFuture = producers.putIfAbsent(producerId, producerFuture); if (existingProducerFuture != null) { if (existingProducerFuture.isDone() && !existingProducerFuture.isCompletedExceptionally()) { Producer producer = existingProducerFuture.getNow(null); log.info(""[{}] Producer with the same id is already created:"" + "" producerId={}, producer={}"", remoteAddress, producerId, producer); commandSender.sendProducerSuccessResponse(requestId, producer.getProducerName(), producer.getSchemaVersion()); return null; } else { // There was an early request to create a producer with same producerId. // This can happen when client timeout is lower than the broker timeouts. // We need to wait until the previous producer creation request // either complete or fails. ServerError error = null; if (!existingProducerFuture.isDone()) { error = ServerError.ServiceNotReady; } else { error = getErrorCode(existingProducerFuture); // remove producer with producerId as it's already completed with exception producers.remove(producerId, existingProducerFuture); } log.warn(""[{}][{}] Producer with id is already present on the connection, producerId={}"", remoteAddress, topicName, producerId); commandSender.sendErrorResponse(requestId, error, ""Producer is already present on the connection""); return null; } } log.info(""[{}][{}] Creating producer. producerId={}"", remoteAddress, topicName, producerId); service.getOrCreateTopic(topicName.toString()).thenCompose((Topic topic) -> { // Before creating producer, check if backlog quota exceeded // on topic for size based limit and time based limit CompletableFuture backlogQuotaCheckFuture = CompletableFuture.allOf( topic.checkBacklogQuotaExceeded(producerName, BacklogQuotaType.destination_storage), topic.checkBacklogQuotaExceeded(producerName, BacklogQuotaType.message_age)); backlogQuotaCheckFuture.thenRun(() -> { // Check whether the producer will publish encrypted messages or not if ((topic.isEncryptionRequired() || encryptionRequireOnProducer) && !isEncrypted) { String msg = String.format(""Encryption is required in %s"", topicName); log.warn(""[{}] {}"", remoteAddress, msg); if (producerFuture.completeExceptionally(new ServerMetadataException(msg))) { commandSender.sendErrorResponse(requestId, ServerError.MetadataError, msg); } producers.remove(producerId, producerFuture); return; } disableTcpNoDelayIfNeeded(topicName.toString(), producerName); CompletableFuture schemaVersionFuture = tryAddSchema(topic, schema); schemaVersionFuture.exceptionally(exception -> { if (producerFuture.completeExceptionally(exception)) { String message = exception.getMessage(); if (exception.getCause() != null) { message += ("" caused by "" + exception.getCause()); } commandSender.sendErrorResponse(requestId, BrokerServiceException.getClientErrorCode(exception), message); } producers.remove(producerId, producerFuture); return null; }); schemaVersionFuture.thenAccept(schemaVersion -> { topic.checkIfTransactionBufferRecoverCompletely(isTxnEnabled).thenAccept(future -> { CompletableFuture createInitSubFuture; if (!Strings.isNullOrEmpty(initialSubscriptionName) && topic.isPersistent() && !topic.getSubscriptions().containsKey(initialSubscriptionName)) { if (!this.getBrokerService().isAllowAutoSubscriptionCreation(topicName)) { String msg = ""Could not create the initial subscription due to the auto subscription "" + ""creation is not allowed.""; if (producerFuture.completeExceptionally( new BrokerServiceException.NotAllowedException(msg))) { log.warn(""[{}] {} initialSubscriptionName: {}, topic: {}"", remoteAddress, msg, initialSubscriptionName, topicName); commandSender.sendErrorResponse(requestId, ServerError.NotAllowedError, msg); } producers.remove(producerId, producerFuture); return; } createInitSubFuture = topic.createSubscription(initialSubscriptionName, InitialPosition.Earliest, false, null); } else { createInitSubFuture = CompletableFuture.completedFuture(null); } createInitSubFuture.whenComplete((sub, ex) -> { if (ex != null) { String msg = ""Failed to create the initial subscription: "" + ex.getCause().getMessage(); log.warn(""[{}] {} initialSubscriptionName: {}, topic: {}"", remoteAddress, msg, initialSubscriptionName, topicName); if (producerFuture.completeExceptionally(ex)) { commandSender.sendErrorResponse(requestId, BrokerServiceException.getClientErrorCode(ex), msg); } producers.remove(producerId, producerFuture); return; } buildProducerAndAddTopic(topic, producerId, producerName, requestId, isEncrypted, metadata, schemaVersion, epoch, userProvidedProducerName, topicName, producerAccessMode, topicEpoch, supportsPartialProducer, producerFuture); }); }).exceptionally(exception -> { Throwable cause = exception.getCause(); log.error(""producerId {}, requestId {} : TransactionBuffer recover failed"", producerId, requestId, exception); if (producerFuture.completeExceptionally(exception)) { commandSender.sendErrorResponse(requestId, ServiceUnitNotReadyException.getClientErrorCode(cause), cause.getMessage()); } producers.remove(producerId, producerFuture); return null; }); }); }); return backlogQuotaCheckFuture; }).exceptionally(exception -> { Throwable cause = exception.getCause(); if (cause instanceof BrokerServiceException.TopicBacklogQuotaExceededException) { BrokerServiceException.TopicBacklogQuotaExceededException tbqe = (BrokerServiceException.TopicBacklogQuotaExceededException) cause; IllegalStateException illegalStateException = new IllegalStateException(tbqe); BacklogQuota.RetentionPolicy retentionPolicy = tbqe.getRetentionPolicy(); if (producerFuture.completeExceptionally(illegalStateException)) { if (retentionPolicy == BacklogQuota.RetentionPolicy.producer_request_hold) { commandSender.sendErrorResponse(requestId, ServerError.ProducerBlockedQuotaExceededError, illegalStateException.getMessage()); } else if (retentionPolicy == BacklogQuota.RetentionPolicy.producer_exception) { commandSender.sendErrorResponse(requestId, ServerError.ProducerBlockedQuotaExceededException, illegalStateException.getMessage()); } } producers.remove(producerId, producerFuture); return null; } // Do not print stack traces for expected exceptions if (cause instanceof NoSuchElementException) { cause = new TopicNotFoundException(""Topic Not Found.""); log.info(""[{}] Failed to load topic {}, producerId={}: Topic not found"", remoteAddress, topicName, producerId); } else if (!Exceptions.areExceptionsPresentInChain(cause, ServiceUnitNotReadyException.class, ManagedLedgerException.class)) { log.error(""[{}] Failed to create topic {}, producerId={}"", remoteAddress, topicName, producerId, exception); } // If client timed out, the future would have been completed // by subsequent close. Send error back to // client, only if not completed already. if (producerFuture.completeExceptionally(exception)) { commandSender.sendErrorResponse(requestId, BrokerServiceException.getClientErrorCode(cause), cause.getMessage()); } producers.remove(producerId, producerFuture); return null; }); return null; }).exceptionally(ex -> { logAuthException(remoteAddress, ""producer"", getPrincipal(), Optional.of(topicName), ex); commandSender.sendErrorResponse(requestId, ServerError.AuthorizationError, ex.getMessage()); return null; }); }","Avoid AuthenticationDataSource mutation for subscription name (#16065) ### Motivation The `authenticationData` field in `ServerCnx` is being mutated to add the `subscription` field that will be passed on to the authorization plugin. The problem is that `authenticationData` is scoped to the whole connection and it should be getting mutated for each consumer that is created on the connection. The current code leads to a race condition where the subscription name used in the authz plugin is already modified while we're looking at it. Instead, we should create a new object and enforce the final modifier. (cherry picked from commit e6b12c64b043903eb5ff2dc5186fe8030f157cfc)",https://github.com/apache/pulsar/commit/5cc3649ecc16c8f62a19de5ee4ed036943f7319d,,,pulsar-broker/src/main/java/org/apache/pulsar/broker/service/ServerCnx.java,3,java,False,2022-06-15T07:00:28Z "public static Event getInstance(Runnable runnable) { RunnableEvent instance = recycled.pop(); if (instance == null) { instance = new RunnableEvent(); } instance.runnable = runnable; return instance; }","public static Event getInstance(Runnable runnable) { RunnableEvent instance = recycled.pop(); if (instance == null) { instance = new RunnableEvent(); if (++instances > 100 && EventQueue.isImmediate()) { EventQueue.setImmediate(false); ViewHandler.postEvent(() -> Toast.makeText(ContextHolder.getAppContext(), ""Immediate mode disabled due to stack overflow"", Toast.LENGTH_SHORT).show()); } } instance.runnable = runnable; return instance; }",Disable immediate mode when RunnableEvent instance > 100 (workaround for StackOverFlow issue),https://github.com/nikita36078/J2ME-Loader/commit/f78c98c8a5cb9639d18e026e476a387ca4c2014e,,,app/src/main/java/javax/microedition/lcdui/event/RunnableEvent.java,3,java,False,2021-08-16T12:54:34Z "public CredentialsProvider getCredentialProvider(SourceControlContext context) throws AuthenticationException { try { return new UsernamePasswordCredentialsProvider(getToken(context), """"); } catch (Exception e) { throw new AuthenticationException(""Failed to get auth token from secure store"", e); } }","public CredentialsProvider getCredentialProvider(SourceControlContext context) throws AuthenticationException { try { return new UsernamePasswordCredentialsProvider(""oauth2"", getToken(context)); } catch (Exception e) { throw new AuthenticationException(""Failed to get auth token from secure store"", e); } }",Fixed auth and local run,https://github.com/cdapio/cdap/commit/e459161fe4154adae7aef5cc40de336d52f2ccda,,,cdap-source-control/src/main/java/io/cdap/cdap/sourcecontrol/GitPATAuthStrategy.java,3,java,False,2023-02-02T10:43:56Z "private void loadDirectory(File dir, String baseId) throws Exception { String id = baseId + dir.getName(); String name = id; String typeStr = ""imageSet""; int width = -1; int height = -1; int textX = 5; int textY = 5; File[] files = dir.listFiles(); Arrays.sort(files); List imageFiles = new ArrayList(); for (File file : files) { if (file.isDirectory()) loadDirectory(file, id + "".""); else if (IGNORE_THUMBS.equalsIgnoreCase(file.getName())) { // no op } else if (INFO_FILE_NAME.equalsIgnoreCase(file.getName())) { // Info file Properties props = new Properties(); try (FileInputStream fileInputStream = new FileInputStream(file)) { props.load(fileInputStream); name = getProperty(props, ""name"", name); typeStr = getProperty(props, ""type"", ""imageSet""); width = getIntProperty(props, ""width"", width); height = getIntProperty(props, ""height"", height); textX = getIntProperty(props, ""text.x"", textX); textY = getIntProperty(props, ""text.y"", textY); } } else if(isGraphic(file)) { // Image file. Subtract the load path from the image path String imagePath = file.getPath().substring(path.length()); if(imagePath.startsWith(""/"") || imagePath.startsWith(""\\"")) { imagePath=imagePath.substring(1); } // Replace Windows-style '\' path separators with '/' imagePath = imagePath.replaceAll(""\\\\"", ""/""); imageFiles.add(imagePath); } else { LOG.warn(""File is not supported type: "" + file); } } if (!imageFiles.isEmpty()) { if (width == -1 || height == -1) { String imagePath = path + File.separator + imageFiles.get(0); Image image = Toolkit.getDefaultToolkit().getImage(imagePath); MediaTracker tracker = new MediaTracker(new Container()); tracker.addImage(image, 0); tracker.waitForID(0); if (width == -1) width = image.getWidth(null); if (height == -1) height = image.getHeight(null); } if (width == -1 || height == -1) throw new Exception(""Unable to derive image dimensions""); String[] imageFileArr = imageFiles.toArray(new String[imageFiles.size()]); ViewGraphic g; if (""imageSet"".equals(typeStr)) g = new ImageSet(id, name, imageFileArr, width, height, textX, textY); else if (""dynamic"".equals(typeStr)) g = new DynamicImage(id, name, imageFileArr[0], width, height, textX, textY); else throw new Exception(""Invalid type: "" + typeStr); viewGraphics.add(g); } }","private void loadDirectory(File dir, String baseId) throws Exception { String id = baseId + dir.getName(); String name = id; String typeStr = ""imageSet""; int width = -1; int height = -1; int textX = 5; int textY = 5; File[] files = dir.listFiles(); Arrays.sort(files); List imageFiles = new ArrayList(); for (File file : files) { if (file.isDirectory()) loadDirectory(file, id + "".""); else if (isThumbsFile(file)) { // no op } else if (isInfoFile(file)) { // Info file Properties props = new Properties(); try (FileInputStream fileInputStream = new FileInputStream(file)) { props.load(fileInputStream); name = getProperty(props, ""name"", name); typeStr = getProperty(props, ""type"", ""imageSet""); width = getIntProperty(props, ""width"", width); height = getIntProperty(props, ""height"", height); textX = getIntProperty(props, ""text.x"", textX); textY = getIntProperty(props, ""text.y"", textY); } } else if(isImageBitmap(file)) { // Image file. Subtract the load path from the image path String imagePath = file.getPath().substring(path.length()); if(imagePath.startsWith(""/"") || imagePath.startsWith(""\\"")) { imagePath=imagePath.substring(1); } // Replace Windows-style '\' path separators with '/' imagePath = imagePath.replaceAll(""\\\\"", ""/""); imageFiles.add(imagePath); } else { LOG.warn(""File is not supported type: "" + file); } } if (!imageFiles.isEmpty()) { if (width == -1 || height == -1) { String imagePath = path + File.separator + imageFiles.get(0); Image image = Toolkit.getDefaultToolkit().getImage(imagePath); MediaTracker tracker = new MediaTracker(new Container()); tracker.addImage(image, 0); tracker.waitForID(0); if (width == -1) width = image.getWidth(null); if (height == -1) height = image.getHeight(null); } if (width == -1 || height == -1) throw new Exception(""Unable to derive image dimensions""); String[] imageFileArr = imageFiles.toArray(new String[imageFiles.size()]); ViewGraphic g; if (""imageSet"".equals(typeStr)) g = new ImageSet(id, name, imageFileArr, width, height, textX, textY); else if (""dynamic"".equals(typeStr)) g = new DynamicImage(id, name, imageFileArr[0], width, height, textX, textY); else throw new Exception(""Invalid type: "" + typeStr); viewGraphics.add(g); } }","#2173 Fixed import project CVE-2021-26828 - added filtering, for graghics only bitmap or info.txt, for uploads bitmap and svg: ZIPProjectManager, ViewEditController; corrected: ViewGraphicLoader; added: UploadFileUtils",https://github.com/SCADA-LTS/Scada-LTS/commit/9dadab1638562102d71ef1e43367c4303124c812,,,src/com/serotonin/mango/view/ViewGraphicLoader.java,3,java,False,2022-04-13T08:18:24Z "@Override protected void handleInnerData(byte[] data) { TraceManager.TraceObject traceObject = TraceManager.serviceTrace(this, ""handle-auth-data""); try { this.setPacketId(data[3]); if (data.length == QuitPacket.QUIT.length && data[4] == MySQLPacket.COM_QUIT) { connection.close(""quit packet""); return; } else if (data.length == PingPacket.PING.length && data[4] == PingPacket.COM_PING) { pingResponse(); return; } if (needAuthSwitched) { handleSwitchResponse(data); } else { handleAuthPacket(data); } } finally { TraceManager.finishSpan(this, traceObject); } }","@Override protected void handleInnerData(byte[] data) { TraceManager.TraceObject traceObject = TraceManager.serviceTrace(this, ""handle-auth-data""); try { this.setPacketId(data[3]); if (data.length == QuitPacket.QUIT.length && data[4] == MySQLPacket.COM_QUIT) { connection.close(""quit packet""); return; } else if (data.length == PingPacket.PING.length && data[4] == PingPacket.COM_PING) { pingResponse(); return; } if (needAuthSwitched) { handleSwitchResponse(data); } else { handleAuthPacket(data); } } catch (Exception e) { LOGGER.error(""illegal auth packet {}"", data, e); writeErrMessage(ErrorCode.ER_ACCESS_DENIED_ERROR, ""illegal auth packet, the detail error message is "" + e.getMessage()); connection.close(""illegal auth packet""); } finally { TraceManager.finishSpan(this, traceObject); } }","inner-1124:prevent illegal auth packet (#2673) (#2704) Signed-off-by: dcy ",https://github.com/actiontech/dble/commit/5a64e4e9527ac97358f4218da9bf75f781adea87,,,src/main/java/com/actiontech/dble/services/mysqlauthenticate/MySQLFrontAuthService.java,3,java,False,2021-05-28T02:36:34Z "@Override protected void configure(final HttpSecurity http) throws Exception { http.csrf().disable() .authorizeRequests() .antMatchers(AUTH_WHITELIST).permitAll() .antMatchers(API, ROOT).authenticated() .and().exceptionHandling() .authenticationEntryPoint(this::failureHandler); }","@Override protected void configure(final HttpSecurity http) throws Exception { http.csrf().disable() .authorizeRequests() .antMatchers(AUTH_WHITELIST).permitAll() .antMatchers(API, PUBLIC_API, ROOT).authenticated() .and().exceptionHandling() .authenticationEntryPoint(this::failureHandler); oAuth2WebConfigurer.configure(http); }","#2586 (fix:sec) Add public API endpoints to authenticated (#2588) * fix(backend): add public API endpoints to authenticated - add oauth configuration Related with #2586 * fix(backend): all urls needs to be authenticated by default for sso-auth Related with #2586 * fix(backend): all urls needs to be authenticated by default for auth and ldap-auth Related with #2586 * fix(backend): all urls needs to be authenticated by default for identity-auth Related with #2586 * fix(backend): add actuator health endpoint to allowed list Related with #2586 * fix(backend): add actuator endpoint to allowed list Related with #2586 * fix(backend): change BaseWebConfigurer authentication urls Related with #2586 * Revert ""fix(backend): change BaseWebConfigurer authentication urls"" This reverts commit ed75decee9e0631c72821dd9fc6df0cadcb2a67d. * Revert ""fix(backend): add actuator endpoint to allowed list"" This reverts commit 5798750fecba5ef4b14ae3df3af10ef8e38b176b. * Revert ""fix(backend): add actuator health endpoint to allowed list"" This reverts commit caec70524250537b13016ce2ab1d5984346cb52a. * Revert ""fix(backend): all urls needs to be authenticated by default for identity-auth"" This reverts commit 1b15c5af2aa5d7a3446825bc0b687b8402768a76. * Revert ""fix(backend): all urls needs to be authenticated by default for auth and ldap-auth"" This reverts commit 58412a8cea3d5ea4ae71e5aac81654015c05aa51. * Revert ""fix(backend): all urls needs to be authenticated by default for sso-auth"" This reverts commit 5ea044eaf4ae3473e99290010befb292cf157e81.",https://github.com/camunda/zeebe/commit/9c687b48b7a37aceaa83e57767a3cd29954bcef7,,,webapp/src/main/java/io/camunda/operate/webapp/security/sso/SSOWebSecurityConfig.java,3,java,False,2022-04-08T07:17:45Z "@Override public List onTabCompleteEssentials(final CommandSender cSender, final Command command, final String commandLabel, final String[] args, final ClassLoader classLoader, final String commandPath, final String permissionPrefix, final IEssentialsModule module) { if (!getSettings().isCommandOverridden(command.getName()) && (!commandLabel.startsWith(""e"") || commandLabel.equalsIgnoreCase(command.getName()))) { final Command pc = alternativeCommandsHandler.getAlternative(commandLabel); if (pc instanceof PluginCommand) { try { final TabCompleter completer = ((PluginCommand) pc).getTabCompleter(); if (completer != null) { return completer.onTabComplete(cSender, command, commandLabel, args); } } catch (final Exception ex) { Bukkit.getLogger().log(Level.SEVERE, ex.getMessage(), ex); } } } try { // Note: The tab completer is always a player, even when tab-completing in a command block User user = null; if (cSender instanceof Player) { user = getUser((Player) cSender); } final CommandSource sender = new CommandSource(cSender); // Check for disabled commands if (getSettings().isCommandDisabled(commandLabel)) { if (getKnownCommandsProvider().getKnownCommands().containsKey(commandLabel)) { return getKnownCommandsProvider().getKnownCommands().get(commandLabel).tabComplete(cSender, commandLabel, args); } return Collections.emptyList(); } final IEssentialsCommand cmd; try { cmd = (IEssentialsCommand) classLoader.loadClass(commandPath + command.getName()).newInstance(); cmd.setEssentials(this); cmd.setEssentialsModule(module); } catch (final Exception ex) { sender.sendMessage(tl(""commandNotLoaded"", commandLabel)); LOGGER.log(Level.SEVERE, tl(""commandNotLoaded"", commandLabel), ex); return Collections.emptyList(); } // Check authorization if (user != null && !user.isAuthorized(cmd, permissionPrefix)) { return Collections.emptyList(); } if (user != null && user.isJailed() && !user.isAuthorized(cmd, ""essentials.jail.allow."")) { return Collections.emptyList(); } // Run the command try { if (user == null) { return cmd.tabComplete(getServer(), sender, commandLabel, command, args); } else { return cmd.tabComplete(getServer(), user, commandLabel, command, args); } } catch (final Exception ex) { showError(sender, ex, commandLabel); // Tab completion shouldn't fail LOGGER.log(Level.SEVERE, tl(""commandFailed"", commandLabel), ex); return Collections.emptyList(); } } catch (final Throwable ex) { LOGGER.log(Level.SEVERE, tl(""commandFailed"", commandLabel), ex); return Collections.emptyList(); } }","@Override public List onTabCompleteEssentials(final CommandSender cSender, final Command command, final String commandLabel, final String[] args, final ClassLoader classLoader, final String commandPath, final String permissionPrefix, final IEssentialsModule module) { if (!getSettings().isCommandOverridden(command.getName()) && (!commandLabel.startsWith(""e"") || commandLabel.equalsIgnoreCase(command.getName()))) { final Command pc = alternativeCommandsHandler.getAlternative(commandLabel); if (pc instanceof PluginCommand) { try { final TabCompleter completer = ((PluginCommand) pc).getTabCompleter(); if (completer != null) { return completer.onTabComplete(cSender, command, commandLabel, args); } } catch (final Exception ex) { Bukkit.getLogger().log(Level.SEVERE, ex.getMessage(), ex); } } } try { // Note: The tab completer is always a player, even when tab-completing in a command block User user = null; if (cSender instanceof Player) { user = getUser((Player) cSender); } final CommandSource sender = new CommandSource(cSender); // Check for disabled commands if (getSettings().isCommandDisabled(commandLabel)) { if (getKnownCommandsProvider().getKnownCommands().containsKey(commandLabel)) { final Command newCmd = getKnownCommandsProvider().getKnownCommands().get(commandLabel); if (!(newCmd instanceof PluginIdentifiableCommand) || ((PluginIdentifiableCommand) newCmd).getPlugin() != this) { return newCmd.tabComplete(cSender, commandLabel, args); } } return Collections.emptyList(); } final IEssentialsCommand cmd; try { cmd = (IEssentialsCommand) classLoader.loadClass(commandPath + command.getName()).newInstance(); cmd.setEssentials(this); cmd.setEssentialsModule(module); } catch (final Exception ex) { sender.sendMessage(tl(""commandNotLoaded"", commandLabel)); LOGGER.log(Level.SEVERE, tl(""commandNotLoaded"", commandLabel), ex); return Collections.emptyList(); } // Check authorization if (user != null && !user.isAuthorized(cmd, permissionPrefix)) { return Collections.emptyList(); } if (user != null && user.isJailed() && !user.isAuthorized(cmd, ""essentials.jail.allow."")) { return Collections.emptyList(); } // Run the command try { if (user == null) { return cmd.tabComplete(getServer(), sender, commandLabel, command, args); } else { return cmd.tabComplete(getServer(), user, commandLabel, command, args); } } catch (final Exception ex) { showError(sender, ex, commandLabel); // Tab completion shouldn't fail LOGGER.log(Level.SEVERE, tl(""commandFailed"", commandLabel), ex); return Collections.emptyList(); } } catch (final Throwable ex) { LOGGER.log(Level.SEVERE, tl(""commandFailed"", commandLabel), ex); return Collections.emptyList(); } }",Prevent stack overflow when finding an EssX cmd as alternative (#4128),https://github.com/EssentialsX/Essentials/commit/83ca7d257476b822fae5df778dad80ecf3ecad72,,,Essentials/src/main/java/com/earth2me/essentials/Essentials.java,3,java,False,2021-05-02T19:08:18Z "@Override protected void rawResponseHandler(String response) { String processed = response; try { boolean verbose = false; if (GrblUtils.isOkResponse(response)) { this.commandComplete(processed); } // Error case. else if (GrblUtils.isOkErrorAlarmResponse(response)) { if (GrblUtils.isAlarmResponse(response)) { //this is not updating the state to Alarm in the GUI, and the alarm is no longer being processed controllerStatus = ControllerStatusBuilder .newInstance(controllerStatus) .setState(ControllerState.ALARM) .build(); Alarm alarm = GrblUtils.parseAlarmResponse(response); dispatchAlarm(alarm); dispatchStatusString(controllerStatus); dispatchStateChange(COMM_IDLE); } // If there is an active command, mark it as completed with error Optional activeCommand = this.getActiveCommand(); if( activeCommand.isPresent() ) { processed = String.format(Localization.getString(""controller.exception.sendError""), activeCommand.get().getCommandString(), lookupCode(response, false)).replaceAll(""\\.\\."", ""\\.""); this.dispatchConsoleMessage(MessageType.ERROR, processed + ""\n""); this.commandComplete(processed); } else { processed = String.format(Localization.getString(""controller.exception.unexpectedError""), lookupCode(response, false)).replaceAll(""\\.\\."", ""\\.""); dispatchConsoleMessage(MessageType.INFO,processed + ""\n""); } checkStreamFinished(); processed = """"; } else if (GrblUtils.isGrblVersionString(response)) { this.isReady = true; resetBuffers(); // When exiting COMM_CHECK mode a soft reset is done, do not clear the // controller status because we need to know the previous state for resetting // single step mode if (getControlState() != COMM_CHECK) { this.controllerStatus = null; } positionPollTimer.stop(); positionPollTimer.start(); // In case a reset occurred while streaming. if (this.isStreaming()) { checkStreamFinished(); } this.grblVersion = GrblUtils.getVersionDouble(response); this.grblVersionLetter = GrblUtils.getVersionLetter(response); this.capabilities = GrblUtils.getGrblStatusCapabilities(this.grblVersion, this.grblVersionLetter); try { this.sendCommandImmediately(createCommand(GrblUtils.GRBL_VIEW_SETTINGS_COMMAND)); this.sendCommandImmediately(createCommand(GrblUtils.GRBL_VIEW_PARSER_STATE_COMMAND)); } catch (Exception e) { throw new RuntimeException(e); } Logger.getLogger(GrblController.class.getName()).log(Level.CONFIG, ""{0} = {1}{2}"", new Object[]{Localization.getString(""controller.log.version""), this.grblVersion, this.grblVersionLetter}); Logger.getLogger(GrblController.class.getName()).log(Level.CONFIG, ""{0} = {1}"", new Object[]{Localization.getString(""controller.log.realtime""), this.capabilities.hasCapability(GrblCapabilitiesConstants.REAL_TIME)}); } else if (GrblUtils.isGrblProbeMessage(response)) { Position p = GrblUtils.parseProbePosition(response, getFirmwareSettings().getReportingUnits()); if (p != null) { dispatchProbeCoordinates(p); } } else if (GrblUtils.isGrblStatusString(response)) { // Only 1 poll is sent at a time so don't decrement, reset to zero. positionPollTimer.receivedStatus(); // Status string goes to verbose console verbose = true; this.handleStatusString(response); this.checkStreamFinished(); } else if (GrblUtils.isGrblFeedbackMessage(response, capabilities)) { GrblFeedbackMessage grblFeedbackMessage = new GrblFeedbackMessage(response); // Convert feedback message to raw commands to update modal state. this.updateParserModalState(new GcodeCommand(GrblUtils.parseFeedbackMessage(response, capabilities))); this.dispatchConsoleMessage(MessageType.VERBOSE, grblFeedbackMessage.toString() + ""\n""); setDistanceModeCode(grblFeedbackMessage.getDistanceMode()); setUnitsCode(grblFeedbackMessage.getUnits()); dispatchStateChange(COMM_IDLE); } else if (GrblUtils.isGrblSettingMessage(response)) { GrblSettingMessage message = new GrblSettingMessage(response); processed = message.toString(); } if (StringUtils.isNotBlank(processed)) { if (verbose) { this.dispatchConsoleMessage(MessageType.VERBOSE,processed + ""\n""); } else { this.dispatchConsoleMessage(MessageType.INFO, processed + ""\n""); } } } catch (Exception e) { String message = """"; if (e.getMessage() != null) { message = "": "" + e.getMessage(); } message = Localization.getString(""controller.error.response"") + "" <"" + processed + "">"" + message; logger.log(Level.SEVERE, message, e); this.dispatchConsoleMessage(MessageType.ERROR,message + ""\n""); } }","@Override protected void rawResponseHandler(String response) { String processed = response; try { boolean verbose = false; if (GrblUtils.isOkResponse(response)) { this.commandComplete(processed); } // Error case. else if (GrblUtils.isOkErrorAlarmResponse(response)) { if (GrblUtils.isAlarmResponse(response)) { //this is not updating the state to Alarm in the GUI, and the alarm is no longer being processed controllerStatus = ControllerStatusBuilder .newInstance(controllerStatus) .setState(ControllerState.ALARM) .build(); Alarm alarm = GrblUtils.parseAlarmResponse(response); dispatchAlarm(alarm); dispatchStatusString(controllerStatus); dispatchStateChange(COMM_IDLE); } // If there is an active command, mark it as completed with error Optional activeCommand = this.getActiveCommand(); if( activeCommand.isPresent() ) { processed = String.format(Localization.getString(""controller.exception.sendError""), activeCommand.get().getCommandString(), lookupCode(response, false)).replaceAll(""\\.\\."", ""\\.""); this.dispatchConsoleMessage(MessageType.ERROR, processed + ""\n""); this.commandComplete(processed); } else { processed = String.format(Localization.getString(""controller.exception.unexpectedError""), lookupCode(response, false)).replaceAll(""\\.\\."", ""\\.""); dispatchConsoleMessage(MessageType.INFO,processed + ""\n""); } checkStreamFinished(); processed = """"; } else if (GrblUtils.isGrblVersionString(response)) { this.isReady = true; resetBuffers(); // When exiting COMM_CHECK mode a soft reset is done, do not clear the // controller status because we need to know the previous state for resetting // single step mode if (getControlState() != COMM_CHECK) { this.controllerStatus = null; } positionPollTimer.stop(); positionPollTimer.start(); // In case a reset occurred while streaming. if (this.isStreaming()) { this.dispatchConsoleMessage(MessageType.INFO, ""\n**** GRBL was reset. Canceling file transfer. ****\n\n""); cancelCommands(); } this.grblVersion = GrblUtils.getVersionDouble(response); this.grblVersionLetter = GrblUtils.getVersionLetter(response); this.capabilities = GrblUtils.getGrblStatusCapabilities(this.grblVersion, this.grblVersionLetter); try { this.sendCommandImmediately(createCommand(GrblUtils.GRBL_VIEW_SETTINGS_COMMAND)); this.sendCommandImmediately(createCommand(GrblUtils.GRBL_VIEW_PARSER_STATE_COMMAND)); } catch (Exception e) { throw new RuntimeException(e); } Logger.getLogger(GrblController.class.getName()).log(Level.CONFIG, ""{0} = {1}{2}"", new Object[]{Localization.getString(""controller.log.version""), this.grblVersion, this.grblVersionLetter}); Logger.getLogger(GrblController.class.getName()).log(Level.CONFIG, ""{0} = {1}"", new Object[]{Localization.getString(""controller.log.realtime""), this.capabilities.hasCapability(GrblCapabilitiesConstants.REAL_TIME)}); } else if (GrblUtils.isGrblProbeMessage(response)) { Position p = GrblUtils.parseProbePosition(response, getFirmwareSettings().getReportingUnits()); if (p != null) { dispatchProbeCoordinates(p); } } else if (GrblUtils.isGrblStatusString(response)) { // Only 1 poll is sent at a time so don't decrement, reset to zero. positionPollTimer.receivedStatus(); // Status string goes to verbose console verbose = true; this.handleStatusString(response); this.checkStreamFinished(); } else if (GrblUtils.isGrblFeedbackMessage(response, capabilities)) { GrblFeedbackMessage grblFeedbackMessage = new GrblFeedbackMessage(response); // Convert feedback message to raw commands to update modal state. this.updateParserModalState(new GcodeCommand(GrblUtils.parseFeedbackMessage(response, capabilities))); this.dispatchConsoleMessage(MessageType.VERBOSE, grblFeedbackMessage.toString() + ""\n""); setDistanceModeCode(grblFeedbackMessage.getDistanceMode()); setUnitsCode(grblFeedbackMessage.getUnits()); dispatchStateChange(COMM_IDLE); } else if (GrblUtils.isGrblSettingMessage(response)) { GrblSettingMessage message = new GrblSettingMessage(response); processed = message.toString(); } if (StringUtils.isNotBlank(processed)) { if (verbose) { this.dispatchConsoleMessage(MessageType.VERBOSE,processed + ""\n""); } else { this.dispatchConsoleMessage(MessageType.INFO, processed + ""\n""); } } } catch (Exception e) { String message = """"; if (e.getMessage() != null) { message = "": "" + e.getMessage(); } message = Localization.getString(""controller.error.response"") + "" <"" + processed + "">"" + message; logger.log(Level.SEVERE, message, e); this.dispatchConsoleMessage(MessageType.ERROR,message + ""\n""); } }","Stops the stream if the physical reset/abort input is pressed If the Grbl controller has a physical button connected to the reset/abort input, and it's pressed while UGS is streaming commands, UGS doesn't properly detect that Grbl has been reset and does not stop streaming, which could lead to a machine crash",https://github.com/winder/Universal-G-Code-Sender/commit/c65d351a0e85f50e569e5d4f2941be480ca5726f,,,ugs-core/src/com/willwinder/universalgcodesender/GrblController.java,3,java,False,2021-11-19T06:27:35Z "public CompiledDescriptor getCompiledDescriptor(World overworld, ResourceLocation id) { if (!compiledDescriptorMap.containsKey(id)) { DimensionId dimworld = DimensionId.fromResourceLocation(id); ServerWorld world = dimworld.loadWorld(overworld); ChunkGenerator generator = world.getChunkProvider().generator; if (generator instanceof BaseChunkGenerator) { CompiledDescriptor compiledDescriptor = ((BaseChunkGenerator) generator).getSettings().getCompiledDescriptor(); compiledDescriptorMap.put(id, compiledDescriptor); } else { RFToolsDim.setup.getLogger().error(id.toString() + "" is not a dimension managed by us!""); return null; } } return compiledDescriptorMap.get(id); }","public CompiledDescriptor getCompiledDescriptor(World overworld, ResourceLocation id) { if (!compiledDescriptorMap.containsKey(id)) { DimensionId dimworld = DimensionId.fromResourceLocation(id); ServerWorld world = dimworld.loadWorld(overworld); if (world == null || world.getChunkProvider() == null) { // No data yet return null; } ChunkGenerator generator = world.getChunkProvider().generator; if (generator instanceof BaseChunkGenerator) { CompiledDescriptor compiledDescriptor = ((BaseChunkGenerator) generator).getSettings().getCompiledDescriptor(); compiledDescriptorMap.put(id, compiledDescriptor); } else { RFToolsDim.setup.getLogger().error(id.toString() + "" is not a dimension managed by us!""); return null; } } return compiledDescriptorMap.get(id); }",Fixed a potential crash bug with dimensions on servers,https://github.com/McJtyMods/RFToolsDimensions/commit/8bec26fe227dbca8cccc97c743a6665e127a1c21,,,src/main/java/mcjty/rftoolsdim/dimension/data/DimensionManager.java,3,java,False,2021-03-10T15:17:25Z "@Override protected synchronized void updateState() { synchronized (BaritoneHelper.MINECRAFT_LOCK) { _itemDropLocations.clear(); _entityMap.clear(); _closeEntities.clear(); _projectiles.clear(); _hostiles.clear(); _playerMap.clear(); if (MinecraftClient.getInstance().world == null) return; // Loop through all entities and track 'em for (Entity entity : MinecraftClient.getInstance().world.getEntities()) { Class type = entity.getClass(); type = squashType(type); // Don't catalogue our own player. if (type == PlayerEntity.class && entity.equals(_mod.getPlayer())) continue; if (!_entityMap.containsKey(type)) { //Debug.logInternal(""NEW TYPE: "" + type); _entityMap.put(type, new ArrayList<>()); } _entityMap.get(type).add(entity); if (_mod.getControllerExtras().inRange(entity)) { _closeEntities.add(entity); } if (entity instanceof ItemEntity) { ItemEntity ientity = (ItemEntity) entity; Item droppedItem = ientity.getStack().getItem(); if (!_itemDropLocations.containsKey(droppedItem)) { _itemDropLocations.put(droppedItem, new ArrayList<>()); } _itemDropLocations.get(droppedItem).add(ientity); } else if (entity instanceof MobEntity) { //MobEntity mob = (MobEntity) entity; if (entity instanceof HostileEntity) { // Only run away if the hostile can see us. HostileEntity hostile = (HostileEntity) entity; if (isHostileToPlayer(_mod, hostile)) { // Check if the mob is facing us or is close enough boolean closeEnough = hostile.isInRange(_mod.getPlayer(), 26); //Debug.logInternal(""TARGET: "" + hostile.is); if (closeEnough) { _hostiles.add(hostile); } } } /* if (mob instanceof HostileEntity) { HostileEntity hostile = (HostileEntity) mob; } */ } else if (entity instanceof ProjectileEntity) { if (!_mod.getConfigState().shouldAvoidDodgingProjectile(entity)) { CachedProjectile proj = new CachedProjectile(); ProjectileEntity projEntity = (ProjectileEntity) entity; boolean inGround = false; // Get projectile ""inGround"" variable if (entity instanceof PersistentProjectileEntity) { inGround = ((PersistentProjectileEntityAccessor) entity).isInGround(); } if (!inGround) { proj.position = projEntity.getPos(); proj.velocity = projEntity.getVelocity(); proj.gravity = ProjectileUtil.hasGravity(projEntity) ? ProjectileUtil.GRAVITY_ACCEL : 0; proj.projectileType = projEntity.getClass(); _projectiles.add(proj); } } } else if (entity instanceof PlayerEntity) { PlayerEntity player = (PlayerEntity) entity; String name = player.getName().getString(); _playerMap.put(name, player); _playerLastCoordinates.put(name, player.getPos()); } } } }","@Override protected synchronized void updateState() { synchronized (BaritoneHelper.MINECRAFT_LOCK) { _itemDropLocations.clear(); _entityMap.clear(); _closeEntities.clear(); _projectiles.clear(); _hostiles.clear(); _playerMap.clear(); if (MinecraftClient.getInstance().world == null) return; // Loop through all entities and track 'em for (Entity entity : MinecraftClient.getInstance().world.getEntities()) { Class type = entity.getClass(); type = squashType(type); if (entity == null || !entity.isAlive()) continue; // Don't catalogue our own player. if (type == PlayerEntity.class && entity.equals(_mod.getPlayer())) continue; if (!_entityMap.containsKey(type)) { //Debug.logInternal(""NEW TYPE: "" + type); _entityMap.put(type, new ArrayList<>()); } _entityMap.get(type).add(entity); if (_mod.getControllerExtras().inRange(entity)) { _closeEntities.add(entity); } if (entity instanceof ItemEntity) { ItemEntity ientity = (ItemEntity) entity; Item droppedItem = ientity.getStack().getItem(); if (!_itemDropLocations.containsKey(droppedItem)) { _itemDropLocations.put(droppedItem, new ArrayList<>()); } _itemDropLocations.get(droppedItem).add(ientity); } else if (entity instanceof MobEntity) { //MobEntity mob = (MobEntity) entity; if (entity instanceof HostileEntity) { // Only run away if the hostile can see us. HostileEntity hostile = (HostileEntity) entity; if (isHostileToPlayer(_mod, hostile)) { // Check if the mob is facing us or is close enough boolean closeEnough = hostile.isInRange(_mod.getPlayer(), 26); //Debug.logInternal(""TARGET: "" + hostile.is); if (closeEnough) { _hostiles.add(hostile); } } } /* if (mob instanceof HostileEntity) { HostileEntity hostile = (HostileEntity) mob; } */ } else if (entity instanceof ProjectileEntity) { if (!_mod.getConfigState().shouldAvoidDodgingProjectile(entity)) { CachedProjectile proj = new CachedProjectile(); ProjectileEntity projEntity = (ProjectileEntity) entity; boolean inGround = false; // Get projectile ""inGround"" variable if (entity instanceof PersistentProjectileEntity) { inGround = ((PersistentProjectileEntityAccessor) entity).isInGround(); } if (!inGround) { proj.position = projEntity.getPos(); proj.velocity = projEntity.getVelocity(); proj.gravity = ProjectileUtil.hasGravity(projEntity) ? ProjectileUtil.GRAVITY_ACCEL : 0; proj.projectileType = projEntity.getClass(); _projectiles.add(proj); } } } else if (entity instanceof PlayerEntity) { PlayerEntity player = (PlayerEntity) entity; String name = player.getName().getString(); _playerMap.put(name, player); _playerLastCoordinates.put(name, player.getPos()); } } } }",Don't track/attack dead entities and prevent nullptrexception caused by this,https://github.com/gaucho-matrero/altoclef/commit/1309fe903bd50f3227cdfeba3138dd9e6151e544,,,src/main/java/adris/altoclef/trackers/EntityTracker.java,3,java,False,2021-05-25T09:03:04Z "@Override public void onRoleHoldersChanged(@NonNull String roleName, @NonNull UserHandle user) { if (!roleName.equals(RoleManager.ROLE_ASSISTANT)) { return; } List roleHolders = mRm.getRoleHoldersAsUser(roleName, user); int userId = user.getIdentifier(); if (roleHolders.isEmpty()) { Settings.Secure.putStringForUser(getContext().getContentResolver(), Settings.Secure.ASSISTANT, """", userId); Settings.Secure.putStringForUser(getContext().getContentResolver(), Settings.Secure.VOICE_INTERACTION_SERVICE, """", userId); } else { // Assistant is singleton role String pkg = roleHolders.get(0); // Try to set role holder as VoiceInteractionService for (ResolveInfo resolveInfo : queryInteractorServices(userId, pkg)) { ServiceInfo serviceInfo = resolveInfo.serviceInfo; VoiceInteractionServiceInfo voiceInteractionServiceInfo = new VoiceInteractionServiceInfo(mPm, serviceInfo); if (!voiceInteractionServiceInfo.getSupportsAssist()) { continue; } String serviceComponentName = serviceInfo.getComponentName() .flattenToShortString(); String serviceRecognizerName = new ComponentName(pkg, voiceInteractionServiceInfo.getRecognitionService()) .flattenToShortString(); Settings.Secure.putStringForUser(getContext().getContentResolver(), Settings.Secure.ASSISTANT, serviceComponentName, userId); Settings.Secure.putStringForUser(getContext().getContentResolver(), Settings.Secure.VOICE_INTERACTION_SERVICE, serviceComponentName, userId); return; } // If no service could be found try to set assist activity final List activities = mPm.queryIntentActivitiesAsUser( new Intent(Intent.ACTION_ASSIST).setPackage(pkg), PackageManager.MATCH_DEFAULT_ONLY | PackageManager.MATCH_DIRECT_BOOT_AWARE | PackageManager.MATCH_DIRECT_BOOT_UNAWARE, userId); for (ResolveInfo resolveInfo : activities) { ActivityInfo activityInfo = resolveInfo.activityInfo; Settings.Secure.putStringForUser(getContext().getContentResolver(), Settings.Secure.ASSISTANT, activityInfo.getComponentName().flattenToShortString(), userId); Settings.Secure.putStringForUser(getContext().getContentResolver(), Settings.Secure.VOICE_INTERACTION_SERVICE, """", userId); return; } } }","@Override public void onRoleHoldersChanged(@NonNull String roleName, @NonNull UserHandle user) { if (!roleName.equals(RoleManager.ROLE_ASSISTANT)) { return; } List roleHolders = mRm.getRoleHoldersAsUser(roleName, user); int userId = user.getIdentifier(); if (roleHolders.isEmpty()) { Settings.Secure.putStringForUser(getContext().getContentResolver(), Settings.Secure.ASSISTANT, """", userId); Settings.Secure.putStringForUser(getContext().getContentResolver(), Settings.Secure.VOICE_INTERACTION_SERVICE, """", userId); } else { // Assistant is singleton role String pkg = roleHolders.get(0); // Try to set role holder as VoiceInteractionService for (ResolveInfo resolveInfo : queryInteractorServices(userId, pkg)) { ServiceInfo serviceInfo = resolveInfo.serviceInfo; VoiceInteractionServiceInfo voiceInteractionServiceInfo = new VoiceInteractionServiceInfo(mPm, serviceInfo); if (!voiceInteractionServiceInfo.getSupportsAssist()) { continue; } String serviceComponentName = serviceInfo.getComponentName() .flattenToShortString(); if (voiceInteractionServiceInfo.getRecognitionService() == null) { Slog.e(TAG, ""The RecognitionService must be set to avoid boot "" + ""loop on earlier platform version. Also make sure that this "" + ""is a valid RecognitionService when running on Android 11 "" + ""or earlier.""); serviceComponentName = """"; } Settings.Secure.putStringForUser(getContext().getContentResolver(), Settings.Secure.ASSISTANT, serviceComponentName, userId); Settings.Secure.putStringForUser(getContext().getContentResolver(), Settings.Secure.VOICE_INTERACTION_SERVICE, serviceComponentName, userId); return; } // If no service could be found try to set assist activity final List activities = mPm.queryIntentActivitiesAsUser( new Intent(Intent.ACTION_ASSIST).setPackage(pkg), PackageManager.MATCH_DEFAULT_ONLY | PackageManager.MATCH_DIRECT_BOOT_AWARE | PackageManager.MATCH_DIRECT_BOOT_UNAWARE, userId); for (ResolveInfo resolveInfo : activities) { ActivityInfo activityInfo = resolveInfo.activityInfo; Settings.Secure.putStringForUser(getContext().getContentResolver(), Settings.Secure.ASSISTANT, activityInfo.getComponentName().flattenToShortString(), userId); Settings.Secure.putStringForUser(getContext().getContentResolver(), Settings.Secure.VOICE_INTERACTION_SERVICE, """", userId); return; } } }","Bug fix: fix System crash due to NullPointerException. If the voice interaction doesn't set RecognitionService, it may cause NPE when it tries to get recognizer name. We don't need recognizer name since Android 12, we delete it directly. To avoid the app does not set RecognitionService then updating the app to earlier platform that may cause boot loop. We add a warning log and set empty service for voiceinteraction to let app aware the problem. Also logging and unset the voiceinteraction service if the app try to update the app without recognition service. Bug: 170742278 Test: Use sample VoiceInteractionService without a RecognitionService The system doesn't crash when choosing the sample app as the default assistant app from Settings. And make sure the VoiceInteractionService is unset. Test: Install sample VoiceInteractionService with a RecognitionService and then update it without a RecognitionService. Make sure the voice interaction service is unset. Change-Id: I79ab3d6449984ead0be28a94adaad57ab24d1fb9",https://github.com/omnirom/android_frameworks_base/commit/223060d6f4bdf0847032a9bea8a12276494ff657,,,services/voiceinteraction/java/com/android/server/voiceinteraction/VoiceInteractionManagerService.java,3,java,False,2021-07-08T13:53:34Z "public static boolean canDragonBreak(Block block) { return block != Blocks.BARRIER && block != Blocks.OBSIDIAN && block != Blocks.CRYING_OBSIDIAN && block != Blocks.END_STONE && block != Blocks.BEDROCK && block != Blocks.END_PORTAL && block != Blocks.END_PORTAL_FRAME && block != Blocks.COMMAND_BLOCK && block != Blocks.REPEATING_COMMAND_BLOCK && block != Blocks.CHAIN_COMMAND_BLOCK && block != Blocks.IRON_BARS && block != Blocks.END_GATEWAY && !isBlacklistedBlock(block); }","public static boolean canDragonBreak(Block block) { if (BLOCK_CACHE.containsKey(block)) return BLOCK_CACHE.get(block); boolean value = block != Blocks.BARRIER && block != Blocks.OBSIDIAN && block != Blocks.CRYING_OBSIDIAN && block != Blocks.END_STONE && block != Blocks.BEDROCK && block != Blocks.END_PORTAL && block != Blocks.END_PORTAL_FRAME && block != Blocks.COMMAND_BLOCK && block != Blocks.REPEATING_COMMAND_BLOCK && block != Blocks.CHAIN_COMMAND_BLOCK && block != Blocks.IRON_BARS && block != Blocks.END_GATEWAY && !isBlacklistedBlock(block); BLOCK_CACHE.put(block, value); return value; }","Updated IafDamageRegistry to use EntityDamageSource. - Attacking someone while riding a dragon now identifies the rider as the source of the damage/attack Cleaned up code related to entity charge attacks. - The various dragon charges now all inherit from the same abstract class - Charge attacks now no longer raytrace twice - Removed duplicate code Cleaned up and improved code regarding dragons breath attacks Dragons don't break blocks anymore that they shouldn't. Fixes #4475",https://github.com/AlexModGuy/Ice_and_Fire/commit/3c52775ad166dd8ee77da768881444db1b89512a,,,src/main/java/com/github/alexthe666/iceandfire/entity/util/DragonUtils.java,3,java,False,2022-05-10T16:42:49Z "private boolean findMember(String host, int port, String dnSearchIn, boolean useSsl, String dnFind, boolean recursiveSearch) throws NamingException { Hashtable env = new Hashtable(); env.put(Context.INITIAL_CONTEXT_FACTORY, ""com.sun.jndi.ldap.LdapCtxFactory""); String provUrl = retrieveUrl(host, port, dnSearchIn, useSsl); env.put(Context.PROVIDER_URL, provUrl); if (StringUtils.isNotEmpty(cf.getUsername())) { env.put(Context.SECURITY_AUTHENTICATION, ""simple""); env.put(Context.SECURITY_PRINCIPAL, cf.getUsername()); env.put(Context.SECURITY_CREDENTIALS, cf.getPassword()); } else { env.put(Context.SECURITY_AUTHENTICATION, ""none""); } DirContext ctx = null; try { try { ctx = new InitialDirContext(env); } catch (CommunicationException e) { log.info(""Cannot create constructor for DirContext [""+ e.getMessage() + ""], will try again with dummy SocketFactory"",e); env.put(""java.naming.ldap.factory.socket"", DummySSLSocketFactory.class.getName()); ctx = new InitialLdapContext(env, null); } Attribute attrs = ctx.getAttributes("""").get(""member""); if (attrs != null) { boolean found = false; for (int i = 0; i < attrs.size() && !found; i++) { String dnFound = (String) attrs.get(i); if (dnFound.equalsIgnoreCase(dnFind)) { found = true; } else { if (recursiveSearch) { found = findMember(host, port, dnFound, useSsl, dnFind, recursiveSearch); } } } return found; } } finally { if (ctx != null) { try { ctx.close(); } catch (NamingException e) { log.warn(""Exception closing DirContext"", e); } } } return false; }","private boolean findMember(String host, int port, String dnSearchIn, boolean useSsl, String dnFind, boolean recursiveSearch) throws NamingException { Hashtable env = new Hashtable(); env.put(Context.INITIAL_CONTEXT_FACTORY, ""com.sun.jndi.ldap.LdapCtxFactory""); String provUrl = retrieveUrl(host, port, dnSearchIn, useSsl); env.put(Context.PROVIDER_URL, provUrl); if (StringUtils.isNotEmpty(cf.getUsername())) { env.put(Context.SECURITY_AUTHENTICATION, ""simple""); env.put(Context.SECURITY_PRINCIPAL, cf.getUsername()); env.put(Context.SECURITY_CREDENTIALS, cf.getPassword()); } else { env.put(Context.SECURITY_AUTHENTICATION, ""none""); } DirContext ctx = null; try { try { ctx = new InitialDirContext(env); } catch (CommunicationException e) { log.info(""Cannot create constructor for DirContext [""+ e.getMessage() + ""], will try again with dummy SocketFactory"",e); ctx = new InitialLdapContext(env, null); //Try again without connection request controls. } Attribute attrs = ctx.getAttributes("""").get(""member""); if (attrs != null) { boolean found = false; for (int i = 0; i < attrs.size() && !found; i++) { String dnFound = (String) attrs.get(i); if (dnFound.equalsIgnoreCase(dnFind)) { found = true; } else { if (recursiveSearch) { found = findMember(host, port, dnFound, useSsl, dnFind, recursiveSearch); } } } return found; } } finally { if (ctx != null) { try { ctx.close(); } catch (NamingException e) { log.warn(""Exception closing DirContext"", e); } } } return false; }",Remove insecure SSLSocketFactory (#4004),https://github.com/frankframework/frankframework/commit/ecb0c74ea75e3c7f13df1dcec2f0b562c0c3a202,,,core/src/main/java/nl/nn/adapterframework/ldap/LdapFindMemberPipe.java,3,java,False,2022-11-16T16:35:25Z "public float convertSpToDp(float sp) { final float spPositive = Math.abs(sp); // TODO(b/247861374): find a match at a higher index? final int spRounded = Math.round(spPositive); final float sign = Math.signum(sp); final int index = Arrays.binarySearch(mFromSpValues, spRounded); if (index >= 0 && Math.abs(spRounded - spPositive) < THRESHOLD_FOR_MATCHING_SP) { // exact match, return the matching dp return sign * mToDpValues[index]; } else { // must be a value in between index and index + 1: interpolate. final int lowerIndex = -(index + 1) - 1; final float startSp; final float endSp; final float startDp; final float endDp; if (lowerIndex >= mFromSpValues.length - 1) { // It's past our lookup table. Determine the last elements' scaling factor and use. startSp = mFromSpValues[mFromSpValues.length - 1]; startDp = mToDpValues[mFromSpValues.length - 1]; if (startSp == 0) return 0; final float scalingFactor = startDp / startSp; return sp * scalingFactor; } else if (lowerIndex == -1) { // It's smaller than the smallest value in our table. Interpolate from 0. startSp = 0; startDp = 0; endSp = mFromSpValues[0]; endDp = mToDpValues[0]; } else { startSp = mFromSpValues[lowerIndex]; endSp = mFromSpValues[lowerIndex + 1]; startDp = mToDpValues[lowerIndex]; endDp = mToDpValues[lowerIndex + 1]; } return sign * MathUtils.constrainedMap(startDp, endDp, startSp, endSp, spPositive); } }","public float convertSpToDp(float sp) { final float spPositive = Math.abs(sp); // TODO(b/247861374): find a match at a higher index? final float sign = Math.signum(sp); // We search for exact matches only, even if it's just a little off. The interpolation will // handle any non-exact matches. final int index = Arrays.binarySearch(mFromSpValues, spPositive); if (index >= 0) { // exact match, return the matching dp return sign * mToDpValues[index]; } else { // must be a value in between index and index + 1: interpolate. final int lowerIndex = -(index + 1) - 1; final float startSp; final float endSp; final float startDp; final float endDp; if (lowerIndex >= mFromSpValues.length - 1) { // It's past our lookup table. Determine the last elements' scaling factor and use. startSp = mFromSpValues[mFromSpValues.length - 1]; startDp = mToDpValues[mFromSpValues.length - 1]; if (startSp == 0) return 0; final float scalingFactor = startDp / startSp; return sp * scalingFactor; } else if (lowerIndex == -1) { // It's smaller than the smallest value in our table. Interpolate from 0. startSp = 0; startDp = 0; endSp = mFromSpValues[0]; endDp = mToDpValues[0]; } else { startSp = mFromSpValues[lowerIndex]; endSp = mFromSpValues[lowerIndex + 1]; startDp = mToDpValues[lowerIndex]; endDp = mToDpValues[lowerIndex + 1]; } return sign * MathUtils.constrainedMap(startDp, endDp, startSp, endSp, spPositive); } }","fix(non linear font scaling): fix crash with certain negative SP values The crash was due to some old logic that was looking for near matches. Now we only return exact matches, and let the interpolation deal with near matches. Add test to make sure it doesn't crash at any value passed in. Test: atest FrameworksCoreTests:android.content.res.FontScaleConverterTest Bug: b/260984829 Change-Id: Ic90d1c5b48862e4f78b90be5926c9ce6d468acf9",https://github.com/aosp-mirror/platform_frameworks_base/commit/bae1102a51a5c4a88bb3edac7c540736b8c7522b,,,core/java/android/content/res/FontScaleConverter.java,3,java,False,2022-12-01T21:29:05Z "@Override protected void configure(HttpSecurity aHttp) throws Exception { // @formatter:off aHttp .antMatcher(""/api/**"") .csrf().disable() // We hard-wire the internal user DB as the authentication provider here because // because the API shouldn't work with external pre-authentication .authenticationProvider(remoteApiAuthenticationProvider()) .authorizeRequests() .anyRequest().access(""hasAnyRole('ROLE_REMOTE')"") .and() .httpBasic() .and() .sessionManagement() .sessionCreationPolicy(SessionCreationPolicy.STATELESS); // @formatter:on }","@Override protected void configure(HttpSecurity aHttp) throws Exception { // @formatter:off aHttp .rememberMe() .and() .csrf().disable() .authorizeRequests() .antMatchers(""/login.html*"").permitAll() // Resources need to be publicly accessible so they don't trigger the login // page. Otherwise it could happen that the user is redirected to a resource // upon login instead of being forwarded to a proper application page. .antMatchers(""/favicon.ico"").permitAll() .antMatchers(""/favicon.png"").permitAll() .antMatchers(""/assets/**"").permitAll() .antMatchers(""/images/**"").permitAll() .antMatchers(""/resources/**"").permitAll() .antMatchers(""/whoops"").permitAll() .antMatchers(""/about/**"").permitAll() .antMatchers(""/wicket/resource/**"").permitAll() .antMatchers(""/"" + NS_PROJECT + ""/*/join-project/**"").permitAll() .antMatchers(""/swagger-ui/**"").access(""hasAnyRole('ROLE_REMOTE')"") .antMatchers(""/swagger-ui.html"").access(""hasAnyRole('ROLE_REMOTE')"") .antMatchers(""/v3/**"").access(""hasAnyRole('ROLE_REMOTE')"") .antMatchers(""/admin/**"").access(""hasAnyRole('ROLE_ADMIN')"") .antMatchers(""/doc/**"").access(""hasAnyRole('ROLE_ADMIN', 'ROLE_USER')"") .antMatchers(""/**"").access(""hasAnyRole('ROLE_ADMIN', 'ROLE_USER')"") .anyRequest().denyAll() .and() .exceptionHandling() .defaultAuthenticationEntryPointFor( new LoginUrlAuthenticationEntryPoint(""/login.html""), new AntPathRequestMatcher(""/**"")) .and() .headers().frameOptions().sameOrigin() .and() .sessionManagement() // Configuring an unlimited session per-user maximum as a side-effect registers // the ConcurrentSessionFilter which checks for valid sessions in the session // registry. This allows us to indirectly invalidate a server session by marking // its Spring-security registration as invalid and have Spring Security in turn // mark the server session as invalid on the next request. This is used e.g. to // force-sign-out users that are being deleted. .maximumSessions(-1) .sessionRegistry(sessionRegistry); // @formatter:on }","#3146 - Bad credentials to remote API redirect to login HTML page - Allow access to error page without login (thus avoiding the redirection to the login page when trying to render the error page to an anonymous user) - Do not render OS, Java, etc. details to unauthorized users on the error page - When the client says to accept JSON or the request URL looks like an API url, return a JSON response instead of rendering the page as HTML",https://github.com/inception-project/inception/commit/ce2bb6b6b81707a272481c350d2d3a7ed2f81967,,,inception/inception-app-webapp/src/main/java/de/tudarmstadt/ukp/inception/app/config/InceptionSecurity.java,3,java,False,2022-06-24T18:53:54Z "public Subject authenticate( HttpServletRequest request, HttpServletResponse response, boolean sendChallenge) throws IOException { String credentials = request.getHeader(""Authorization""); String username = null; String password = null; try { if (credentials != null) { final Base64Decoder dec = new Base64Decoder(); dec.translate(credentials.substring(""Basic "".length())); final byte[] c = dec.getByteArray(); final String s = new String(c); // LOG.debug(""BASIC auth credentials: ""+s); final int p = s.indexOf(':'); username = p < 0 ? s : s.substring(0, p); password = p < 0 ? null : s.substring(p + 1); } } catch(final IllegalArgumentException iae) { LOG.warn(""Invalid BASIC authentication header received: "" + iae.getMessage(), iae); credentials = null; } // get the user from the session if possible final HttpSession session = request.getSession(false); Subject user = null; if (session != null) { user = (Subject) session.getAttribute(XQueryContext.HTTP_SESSIONVAR_XMLDB_USER); if (user != null && (username == null || user.getName().equals(username))) { return user; } } if (user != null) { session.removeAttribute(XQueryContext.HTTP_SESSIONVAR_XMLDB_USER); } // get the credentials if (credentials == null) { // prompt for credentials // LOG.debug(""Sending BASIC auth challenge.""); if (sendChallenge) {sendChallenge(request, response);} return null; } // authenticate the credentials final SecurityManager secman = pool.getSecurityManager(); try { user = secman.authenticate(username, password); } catch (final AuthenticationException e) { // if authentication failed then send a challenge request again if (sendChallenge) {sendChallenge(request, response);} return null; } // store the user in the session if (session != null) { session.setAttribute(XQueryContext.HTTP_SESSIONVAR_XMLDB_USER, user); } // return the authenticated user return user; }","public Subject authenticate( HttpServletRequest request, HttpServletResponse response, boolean sendChallenge) throws IOException { String credentials = request.getHeader(""Authorization""); String username = null; String password = null; try { if (credentials != null && credentials.startsWith(""Basic"")) { final Base64Decoder dec = new Base64Decoder(); dec.translate(credentials.substring(""Basic "".length())); final byte[] c = dec.getByteArray(); final String s = new String(c); // LOG.debug(""BASIC auth credentials: ""+s); final int p = s.indexOf(':'); username = p < 0 ? s : s.substring(0, p); password = p < 0 ? null : s.substring(p + 1); } } catch(final IllegalArgumentException iae) { LOG.warn(""Invalid BASIC authentication header received: "" + iae.getMessage(), iae); credentials = null; } // get the user from the session if possible final HttpSession session = request.getSession(false); Subject user = null; if (session != null) { user = (Subject) session.getAttribute(XQueryContext.HTTP_SESSIONVAR_XMLDB_USER); if (user != null && (username == null || user.getName().equals(username))) { return user; } } if (user != null) { session.removeAttribute(XQueryContext.HTTP_SESSIONVAR_XMLDB_USER); } // get the credentials if (credentials == null) { // prompt for credentials // LOG.debug(""Sending BASIC auth challenge.""); if (sendChallenge) {sendChallenge(request, response);} return null; } // authenticate the credentials final SecurityManager secman = pool.getSecurityManager(); try { user = secman.authenticate(username, password); } catch (final AuthenticationException e) { // if authentication failed then send a challenge request again if (sendChallenge) {sendChallenge(request, response);} return null; } // store the user in the session if (session != null) { session.setAttribute(XQueryContext.HTTP_SESSIONVAR_XMLDB_USER, user); } // return the authenticated user return user; }",[bugfix] Backport of aa975d1; [fix] basic authentication,https://github.com/eXist-db/exist/commit/6896dafd5ef6df6b17225abb2256466280520963,,,exist-core/src/main/java/org/exist/http/servlets/BasicAuthenticator.java,3,java,False,2022-05-02T20:17:38Z "@Override public void initialize() { // Make it easier for subclasses to put their logic in initialize safely. if (!mSource.isInitialized()) { mSource.initialize(); } }","@Override public void initialize() { // Make it easier for subclasses to put their logic in initialize safely. if (!isInitialized()) { if (mSource == null) { throw new NullPointerException(""DataSourceWrapper's source is not set!""); } mSource.initialize(); } }",fix FilePathDataSource crash before initialize. (#160),https://github.com/natario1/Transcoder/commit/8627643e0d7b0864158137010bafdba4840eb9a2,,,lib/src/main/java/com/otaliastudios/transcoder/source/DataSourceWrapper.java,3,java,False,2022-03-12T14:28:43Z "function __processMessage(modules, message) { const { config, crypto } = modules; if (!config.cipherKey) return message; try { return crypto.decrypt(message); } catch (e) { return message; } }","function __processMessage(modules, message) { if (!modules.cryptoModule) return message; try { const decryptedData = modules.cryptoModule.decrypt(message); const decryptedPayload = decryptedData instanceof ArrayBuffer ? JSON.parse(new TextDecoder().decode(decryptedData)) : decryptedData; return decryptedPayload; } catch (e) { if (console && console.log) console.log('decryption error', e.message); return message; } }","feat/CryptoModule (#339) * ref: decoupling cryptor module * cryptoModule * lint * rever cryptors in config * lint fixes * CryptoModule for web and node * step definitions for contract tests * lib files * fix:es-lint * let vs const * and some more ts not wanting me to specific about trivials * access modfiers * refactor-1 * lint, cleanup test * refactor - 2 * code cleanup in stream encryption with new cryptor * fix: lint issue. * refactor: eliminate ts-ignores by defining file reated types * * integration of crypto module * refactoring cryptoModule * lib and dist * support for setCipherKey * fix: setCipherKey() * lib and dist files * fix: staticIV support * lib and dist * refactor: cryptoModule, * added support for PubNub.CryptoModule factory * fix: types * dist and libs * fix: test- customEncrypt function * fix: legacy crypto init, tests * refactor: typecheck on incoming data for aescbc cryptor * code cleanup, * fix: broken file cryptography operations on web * lib and dist directories * refactor: crypto initialiser apis default value initialisation * LICENSE * reverted last commit 11351ec * update LICENSE * PubNub SDK v7.4.0 release. --------- Co-authored-by: PubNub Release Bot <120067856+pubnub-release-bot@users.noreply.github.com>",https://github.com/pubnub/javascript/commit/fb6cd0417cbb4ba87ea2d5d86a9c94774447e119,CVE-2023-26154,['CWE-331'],src/core/endpoints/fetch_messages.js,3,js,False,2023-10-16T11:14:10Z "@EventHandler(priority = EventPriority.HIGHEST, ignoreCancelled = true) public void onInteract(PlayerInteractEvent event) { Action eventAction = event.getAction(); Player player = event.getPlayer(); Block clicked = event.getClickedBlock(); if (eventAction != Action.RIGHT_CLICK_BLOCK && eventAction != Action.LEFT_CLICK_BLOCK) { return; } if (clicked == null) { return; } Option regionOption = this.regionManager.findRegionAtLocation(clicked.getLocation()); if (regionOption.isEmpty()) { return; } Region region = regionOption.get(); boolean returnMethod = region.getHeartBlock() .filter(heart -> heart.equals(clicked)) .peek(heart -> { event.setCancelled(true); Guild guild = region.getGuild(); Option userOption = this.userManager.findByPlayer(player); if (userOption.isEmpty()) { return; } User user = userOption.get(); GuildHeartInteractEvent interactEvent = new GuildHeartInteractEvent(EventCause.USER, user, guild, eventAction == Action.LEFT_CLICK_BLOCK ? Click.LEFT : Click.RIGHT, SecuritySystem.onHitCrystal(player, guild)); SimpleEventHandler.handle(interactEvent); if (interactEvent.isCancelled() || !interactEvent.isSecurityCheckPassed()) { return; } if (eventAction == Action.LEFT_CLICK_BLOCK) { if (!SimpleEventHandler.handle(new GuildHeartAttackEvent(EventCause.USER, user, guild))) { return; } WarSystem.getInstance().attack(player, guild); return; } if (config.informationMessageCooldowns.cooldown(player, config.infoPlayerCooldown)) { return; } try { infoExecutor.execute(player, new String[] {guild.getTag()}); } catch (ValidationException validatorException) { validatorException.getValidationMessage().peek(message -> ChatUtils.sendMessage(player, message)); } }) .isPresent(); if (returnMethod) { return; } if (eventAction == Action.RIGHT_CLICK_BLOCK) { Guild guild = region.getGuild(); this.userManager.findByPlayer(player).peek(user -> { boolean blocked = config.blockedInteract.contains(clicked.getType()); if (guild.isMember(user)) { event.setCancelled(blocked && config.regionExplodeBlockInteractions && !guild.canBuild()); } else { event.setCancelled(blocked && !player.hasPermission(""funnyguilds.admin.interact"")); } }); } }","@EventHandler(priority = EventPriority.HIGHEST, ignoreCancelled = true) public void onInteract(PlayerInteractEvent event) { Action eventAction = event.getAction(); Player player = event.getPlayer(); Block clicked = event.getClickedBlock(); if (eventAction != Action.RIGHT_CLICK_BLOCK && eventAction != Action.LEFT_CLICK_BLOCK) { return; } if (clicked == null) { return; } Option regionOption = this.regionManager.findRegionAtLocation(clicked.getLocation()); if (regionOption.isEmpty()) { return; } Region region = regionOption.get(); boolean returnMethod = region.getHeartBlock() .filter(heart -> heart.equals(clicked)) .peek(heart -> { event.setCancelled(true); Guild guild = region.getGuild(); Option userOption = this.userManager.findByPlayer(player); if (userOption.isEmpty()) { return; } User user = userOption.get(); GuildHeartInteractEvent interactEvent = new GuildHeartInteractEvent(EventCause.USER, user, guild, eventAction == Action.LEFT_CLICK_BLOCK ? Click.LEFT : Click.RIGHT, !SecuritySystem.onHitCrystal(player, guild)); SimpleEventHandler.handle(interactEvent); if (interactEvent.isCancelled() || !interactEvent.isSecurityCheckPassed()) { return; } if (eventAction == Action.LEFT_CLICK_BLOCK) { if (!SimpleEventHandler.handle(new GuildHeartAttackEvent(EventCause.USER, user, guild))) { return; } WarSystem.getInstance().attack(player, guild); return; } if (config.informationMessageCooldowns.cooldown(player, config.infoPlayerCooldown)) { return; } try { infoExecutor.execute(player, new String[] {guild.getTag()}); } catch (ValidationException validatorException) { validatorException.getValidationMessage().peek(message -> ChatUtils.sendMessage(player, message)); } }) .isPresent(); if (returnMethod) { return; } if (eventAction == Action.RIGHT_CLICK_BLOCK) { Guild guild = region.getGuild(); this.userManager.findByPlayer(player).peek(user -> { boolean blocked = config.blockedInteract.contains(clicked.getType()); if (guild.isMember(user)) { event.setCancelled(blocked && config.regionExplodeBlockInteractions && !guild.canBuild()); } else { event.setCancelled(blocked && !player.hasPermission(""funnyguilds.admin.interact"")); } }); } }","GH-1943 Fix guild attack & info (#1943) * Fix * idiot * XD * better",https://github.com/FunnyGuilds/FunnyGuilds/commit/03bc21e5e934c9bd949eff432b4515b7e09b1f0d,,,plugin/src/main/java/net/dzikoysk/funnyguilds/listener/region/PlayerInteract.java,3,java,False,2022-04-25T19:49:24Z "void ensureAuthenticatedUserCanDeleteFromIndex(AsyncExecutionId executionId, ActionListener listener) { GetRequest internalGet = new GetRequest(index).preference(executionId.getEncoded()) .id(executionId.getDocId()) .fetchSourceContext(new FetchSourceContext(true, new String[] { HEADERS_FIELD }, new String[] {})); clientWithOrigin.get(internalGet, ActionListener.wrap(get -> { if (get.isExists() == false) { listener.onFailure(new ResourceNotFoundException(executionId.getEncoded())); return; } // Check authentication for the user @SuppressWarnings(""unchecked"") Map headers = (Map) get.getSource().get(HEADERS_FIELD); if (ensureAuthenticatedUserIsSame(headers, securityContext.getAuthentication())) { listener.onResponse(null); } else { listener.onFailure(new ResourceNotFoundException(executionId.getEncoded())); } }, exc -> listener.onFailure(new ResourceNotFoundException(executionId.getEncoded())))); }","void ensureAuthenticatedUserCanDeleteFromIndex(AsyncExecutionId executionId, ActionListener listener) { GetRequest internalGet = new GetRequest(index).preference(executionId.getEncoded()) .id(executionId.getDocId()) .fetchSourceContext(new FetchSourceContext(true, new String[] { HEADERS_FIELD }, new String[] {})); clientWithOrigin.get(internalGet, ActionListener.wrap(get -> { if (get.isExists() == false) { listener.onFailure(new ResourceNotFoundException(executionId.getEncoded())); return; } // Check authentication for the user @SuppressWarnings(""unchecked"") Map headers = (Map) get.getSource().get(HEADERS_FIELD); if (securityContext.canIAccessResourcesCreatedWithHeaders(headers)) { listener.onResponse(null); } else { listener.onFailure(new ResourceNotFoundException(executionId.getEncoded())); } }, exc -> listener.onFailure(new ResourceNotFoundException(executionId.getEncoded())))); }","Fix can access resource checks for API Keys with run as (#84277) This fixes two things for the ""can access"" authz check: * API Keys running as, have access to the resources created by the effective run as user * tokens created by API Keys (with the client credentials) have access to the API Key's resources In addition, this PR moves some of the authz plumbing code from the Async and Scroll services classes under the Security Context class (as a minor refactoring).",https://github.com/elastic/elasticsearch/commit/2f0733d1b5dc9458ec901efe2f7141742d9dfed8,,,x-pack/plugin/core/src/main/java/org/elasticsearch/xpack/core/async/AsyncTaskIndexService.java,3,java,False,2022-02-28T14:00:54Z "public void readExternal(DataInput in) throws IOException { if (!isEmpty()) { throw new NotActiveException(); } boolean fLite = in.readBoolean(); if (fLite) { int c = ExternalizableHelper.readInt(in); if (c > 0) { Object[] ao = new Object[c <= 1 || c > THRESHOLD ? c : THRESHOLD]; for (int i = 0; i < c; ++i) { ao[i] = ExternalizableHelper.readObject(in); } initFromArray(ao, c); } } else { Object[] ao = (Object[]) ExternalizableHelper.readObject(in); initFromArray(ao, ao.length); } }","public void readExternal(DataInput in) throws IOException { if (!isEmpty()) { throw new NotActiveException(); } boolean fLite = in.readBoolean(); if (fLite) { readAndInitObjectArray(in); } else { Object[] ao = (Object[]) ExternalizableHelper.readObject(in); initFromArray(ao, ao.length); } }","BUG 34248310 - [34211273->21.12.5] DENIAL OF SERVICE (OOM) (merge ce/22.06 -> ce/22.12 @ 94389) [git-p4: depot-paths = ""//dev/coherence-ce/release/coherence-ce-v21.12/"": change = 94953]",https://github.com/oracle/coherence/commit/e0de9b90daee7b58f0a2893db0df1cc1a429c56b,,,prj/coherence-core/src/main/java/com/tangosol/util/LiteSet.java,3,java,False,2022-08-17T19:42:45Z "void server_loop2(struct ssh *ssh, Authctxt *authctxt) { fd_set *readset = NULL, *writeset = NULL; int max_fd; u_int nalloc = 0, connection_in, connection_out; u_int64_t rekey_timeout_ms = 0; debug(""Entering interactive session for SSH2.""); ssh_signal(SIGCHLD, sigchld_handler); child_terminated = 0; connection_in = ssh_packet_get_connection_in(ssh); connection_out = ssh_packet_get_connection_out(ssh); if (!use_privsep) { ssh_signal(SIGTERM, sigterm_handler); ssh_signal(SIGINT, sigterm_handler); ssh_signal(SIGQUIT, sigterm_handler); } notify_setup(); max_fd = MAXIMUM(connection_in, connection_out); max_fd = MAXIMUM(max_fd, notify_pipe[0]); server_init_dispatch(ssh); for (;;) { process_buffered_input_packets(ssh); if (!ssh_packet_is_rekeying(ssh) && ssh_packet_not_very_much_data_to_write(ssh)) channel_output_poll(ssh); if (options.rekey_interval > 0 && !ssh_packet_is_rekeying(ssh)) { rekey_timeout_ms = ssh_packet_get_rekey_timeout(ssh) * 1000; } else { rekey_timeout_ms = 0; } wait_until_can_do_something(ssh, connection_in, connection_out, &readset, &writeset, &max_fd, &nalloc, rekey_timeout_ms); if (received_sigterm) { logit(""Exiting on signal %d"", (int)received_sigterm); /* Clean up sessions, utmp, etc. */ cleanup_exit(255); } collect_children(ssh); if (!ssh_packet_is_rekeying(ssh)) channel_after_select(ssh, readset, writeset); if (process_input(ssh, readset, connection_in) < 0) break; process_output(ssh, writeset, connection_out); } collect_children(ssh); free(readset); free(writeset); /* free all channels, no more reads and writes */ channel_free_all(ssh); /* free remaining sessions, e.g. remove wtmp entries */ session_destroy_all(ssh, NULL); }","void server_loop2(struct ssh *ssh, Authctxt *authctxt) { fd_set *readset = NULL, *writeset = NULL; int r, max_fd; u_int nalloc = 0, connection_in, connection_out; u_int64_t rekey_timeout_ms = 0; sigset_t bsigset, osigset; debug(""Entering interactive session for SSH2.""); if (sigemptyset(&bsigset) == -1 || sigaddset(&bsigset, SIGCHLD) == -1) error_f(""bsigset setup: %s"", strerror(errno)); ssh_signal(SIGCHLD, sigchld_handler); child_terminated = 0; connection_in = ssh_packet_get_connection_in(ssh); connection_out = ssh_packet_get_connection_out(ssh); if (!use_privsep) { ssh_signal(SIGTERM, sigterm_handler); ssh_signal(SIGINT, sigterm_handler); ssh_signal(SIGQUIT, sigterm_handler); } max_fd = MAXIMUM(connection_in, connection_out); server_init_dispatch(ssh); for (;;) { process_buffered_input_packets(ssh); if (!ssh_packet_is_rekeying(ssh) && ssh_packet_not_very_much_data_to_write(ssh)) channel_output_poll(ssh); if (options.rekey_interval > 0 && !ssh_packet_is_rekeying(ssh)) { rekey_timeout_ms = ssh_packet_get_rekey_timeout(ssh) * 1000; } else { rekey_timeout_ms = 0; } /* * Block SIGCHLD while we check for dead children, then pass * the old signal mask through to pselect() so that it'll wake * up immediately if a child exits after we've called waitpid(). */ if (sigprocmask(SIG_BLOCK, &bsigset, &osigset) == -1) error_f(""bsigset sigprocmask: %s"", strerror(errno)); collect_children(ssh); wait_until_can_do_something(ssh, connection_in, connection_out, &readset, &writeset, &max_fd, &nalloc, rekey_timeout_ms, &osigset); if (sigprocmask(SIG_UNBLOCK, &bsigset, &osigset) == -1) error_f(""osigset sigprocmask: %s"", strerror(errno)); if (received_sigterm) { logit(""Exiting on signal %d"", (int)received_sigterm); /* Clean up sessions, utmp, etc. */ cleanup_exit(255); } if (!ssh_packet_is_rekeying(ssh)) channel_after_select(ssh, readset, writeset); if (process_input(ssh, readset, connection_in) < 0) break; /* A timeout may have triggered rekeying */ if ((r = ssh_packet_check_rekey(ssh)) != 0) fatal_fr(r, ""cannot start rekeying""); process_output(ssh, writeset, connection_out); } collect_children(ssh); free(readset); free(writeset); /* free all channels, no more reads and writes */ channel_free_all(ssh); /* free remaining sessions, e.g. remove wtmp entries */ session_destroy_all(ssh, NULL); }",Merge branch 'openssh-master',https://github.com/openssh/openssh-portable/commit/dcdf9749f6682d6f980ea6c956817a9564daaed7,,,serverloop.c,3,c,False,2021-08-18T13:31:52Z "private void reload() { Seed seed = Seeds.get().getSeed(); if (seed == null) return; worldSeed = seed; oreConfig = Ore.getConfig(Seeds.get().getSeed().version); chunkRenderers.clear(); if (mc.world != null && worldSeed != null) { loadVisibleChunks(); } }","private void reload() { Seed seed = Seeds.get().getSeed(); if (seed == null) return; worldSeed = seed; oreConfig = Ore.getConfig(Seeds.get().getSeed().version); if (oreConfig == null) { error(""Ore Sim only works with seeds from version 1.14 or higher. (Current seed is from version "" + Seeds.get().getSeed().version.toString() + "")""); this.toggle(); return; } chunkRenderers.clear(); if (mc.world != null && worldSeed != null) { loadVisibleChunks(); } }","Fix OreSim Crash Fixes a crash when the seed's version is too old (Ore.getConfig() returns null, resulting in a NullPointerException.)",https://github.com/AntiCope/meteor-rejects/commit/e3f61a9931f9f1f975294db2db8060fa97abfc5d,,,src/main/java/anticope/rejects/modules/OreSim.java,3,java,False,2022-02-19T15:51:53Z "@Override public Chunk readChunk(int x, int z) throws IOException { int index = getChunkOffset(x, z); if (index < 0 || index >= 4096) { return null; } this.lastUsed = System.currentTimeMillis(); if (!this.isChunkGenerated(index)) { return null; } try { int[] table = this.primitiveLocationTable.get(index); RandomAccessFile raf = this.getRandomAccessFile(); raf.seek((long) table[0] << 12L); int length = raf.readInt(); byte compression = raf.readByte(); if (length <= 0 || length >= MAX_SECTOR_LENGTH) { if (length >= MAX_SECTOR_LENGTH) { table[0] = ++this.lastSector; table[1] = 1; this.primitiveLocationTable.put(index, table); log.error(""Corrupted chunk header detected""); } return null; } if (length > (table[1] << 12)) { log.error(""Corrupted bigger chunk detected""); table[1] = length >> 12; this.primitiveLocationTable.put(index, table); this.writeLocationIndex(index); } else if (compression != COMPRESSION_ZLIB && compression != COMPRESSION_GZIP) { log.error(""Invalid compression type""); return null; } byte[] data = new byte[length - 1]; raf.readFully(data); Chunk chunk = this.unserializeChunk(data); if (chunk != null) { //更新256世界到384世界 if (levelProvider != null && !chunk.isNew384World && levelProvider.isOverWorld() && levelProvider instanceof Anvil) { //检查重复更新情况 if (chunkUpdated == null) { chunkUpdated = LongSets.synchronize(new LongArraySet()); } final long chunkHash = Level.chunkHash(chunk.getX(), chunk.getZ()); if (!chunkUpdated.contains(chunkHash)) { chunkUpdated.add(chunkHash); chunk.isNew384World = true; //这可以在大部分情况下避免区块重复更新,但是对多线程造成的重复更新仍然无效,所以需要一个set来检查 var bid = Server.getInstance().addBusying(System.currentTimeMillis()); log.info(Server.getInstance().getLanguage().translateString(""nukkit.anvil.converter.update-chunk"", levelProvider.getLevel().getName(), chunk.getX() << 4, chunk.getZ() << 4)); for (int dx = 0; dx < 16; dx++) { for (int dz = 0; dz < 16; dz++) { for (int dy = 255; dy >= -64; --dy) { chunk.setBlockState(dx, dy + 64, dz, chunk.getBlockState(dx, dy, dz)); chunk.setBlockStateAtLayer(dx, dy + 64, dz, 1, chunk.getBlockState(dx, dy, dz, 1)); chunk.setBlockState(dx, dy, dz, BlockState.AIR); chunk.setBlockStateAtLayer(dx, dy, dz, 1, BlockState.AIR); } } } Server.getInstance().removeBusying(bid); } } return chunk; } else { log.error(""Corrupted chunk detected at ({}, {}) in {}"", x, z, levelProvider.getName()); return null; } } catch (EOFException e) { log.error(""Your world is corrupt, because some code is bad and corrupted it. oops. ""); return null; } }","@Override public Chunk readChunk(int x, int z) throws IOException { int index = getChunkOffset(x, z); if (index < 0 || index >= 4096) { return null; } this.lastUsed = System.currentTimeMillis(); if (!this.isChunkGenerated(index)) { return null; } try { int[] table = this.primitiveLocationTable.get(index); RandomAccessFile raf = this.getRandomAccessFile(); raf.seek((long) table[0] << 12L); int length = raf.readInt(); byte compression = raf.readByte(); if (length <= 0 || length >= Server.getInstance().getMaximumSizePerChunk()) { if (length >= Server.getInstance().getMaximumSizePerChunk()) { table[0] = ++this.lastSector; table[1] = 1; this.primitiveLocationTable.put(index, table); log.error(""Corrupted chunk header detected""); } return null; } if (length > (table[1] << 12)) { log.error(""Corrupted bigger chunk detected""); table[1] = length >> 12; this.primitiveLocationTable.put(index, table); this.writeLocationIndex(index); } else if (compression != COMPRESSION_ZLIB && compression != COMPRESSION_GZIP) { log.error(""Invalid compression type""); return null; } byte[] data = new byte[length - 1]; raf.readFully(data); Chunk chunk = this.unserializeChunk(data); if (chunk != null) { //更新256世界到384世界 if (levelProvider != null && !chunk.isNew384World && levelProvider.isOverWorld() && levelProvider instanceof Anvil) { //检查重复更新情况 if (chunkUpdated == null) { chunkUpdated = LongSets.synchronize(new LongArraySet()); } final long chunkHash = Level.chunkHash(chunk.getX(), chunk.getZ()); if (!chunkUpdated.contains(chunkHash)) { chunkUpdated.add(chunkHash); chunk.isNew384World = true; //这可以在大部分情况下避免区块重复更新,但是对多线程造成的重复更新仍然无效,所以需要一个set来检查 var bid = Server.getInstance().addBusying(System.currentTimeMillis()); log.info(Server.getInstance().getLanguage().translateString(""nukkit.anvil.converter.update-chunk"", levelProvider.getLevel().getName(), chunk.getX() << 4, chunk.getZ() << 4)); for (int dx = 0; dx < 16; dx++) { for (int dz = 0; dz < 16; dz++) { for (int dy = 255; dy >= -64; --dy) { chunk.setBlockState(dx, dy + 64, dz, chunk.getBlockState(dx, dy, dz)); chunk.setBlockStateAtLayer(dx, dy + 64, dz, 1, chunk.getBlockState(dx, dy, dz, 1)); chunk.setBlockState(dx, dy, dz, BlockState.AIR); chunk.setBlockStateAtLayer(dx, dy, dz, 1, BlockState.AIR); } } } Server.getInstance().removeBusying(bid); } } return chunk; } else { log.error(""Corrupted chunk detected at ({}, {}) in {}"", x, z, levelProvider.getName()); return null; } } catch (EOFException e) { log.error(""Your world is corrupt, because some code is bad and corrupted it. oops. ""); return null; } }","Add property maximumStaleDatagrams (#698) * add property maximumStaleDatagrams * add property maximumStaleDatagrams * add property maximum-size-per-chunk * CVE-2022-24823 Co-authored-by: CoolLoong <1542536763@qq.com>",https://github.com/PowerNukkitX/PowerNukkitX/commit/36b28081a18bb9e55647eecff89e86fe91d6fb3f,,,src/main/java/cn/nukkit/level/format/anvil/RegionLoader.java,3,java,False,2022-10-06T12:53:03Z "public void finish() throws IOException { if (!def.finished()) { def.finish(); while (!def.finished()) { deflate(); } } }","public void finish() throws IOException { if (!def.finished()) { try{ def.finish(); while (!def.finished()) { deflate(); } } catch(IOException e) { if (usesDefaultDeflater) def.end(); throw e; } } }","8278794: Infinite loop in DeflaterOutputStream.finish() Reviewed-by: coffeys, lancea",https://github.com/openjdk/mobile/commit/ff0b0927a2df8b36f8fd6ed41bd4e20e71a5b653,,,src/java.base/share/classes/java/util/zip/DeflaterOutputStream.java,3,java,False,2022-03-18T15:31:30Z "@Inject(method = ""reportAbuse"", at = @At(""HEAD""), cancellable = true, remap = false) public void reportAbuse(AbuseReportRequest request, CallbackInfo ci) { var index = 0; List messages = new ArrayList<>(); for (ReportChatMessage message : request.report.evidence.messages) { if (!Gaslight.removedIndexes.contains(index)) { messages.add(message); } index++; } var random = new Random(); var tm = getReportedTimestamp(messages, 1); Instant minimum = messages.get(0).messageReported ? messages.get(0).timestamp : messages.stream().sorted(Comparator.comparing(o -> o.timestamp)).findFirst().get().timestamp; Instant maximum = tm.time(); var wordCount = tm.words(); var timestamps = 1; ReportChatMessage lastMessage = messages.get(0); for (int i = 0; i < messages.size(); i++) { ReportChatMessage message = messages.get(i); if (message.messageReported) { minimum = message.timestamp; var tm2 = getReportedTimestamp(messages, ++timestamps); wordCount = tm2.words(); maximum = tm2.time(); lastMessage = message; } else if (canRewrite(message)) { var totalTimeDelta = ((double) calculateTimeWindowNs(maximum, minimum) * random.nextDouble(0.6, 0.9)); var msgWordCount = (long) message.message.split("" "").length; var msgtimeDelta = totalTimeDelta * ((double) msgWordCount / wordCount); Instant x; if (i == 0) { x = minimum.plus(Duration.ofNanos((long) msgtimeDelta)); } else { x = lastMessage.timestamp.plus(Duration.ofNanos((long) msgtimeDelta)); } message = resignMessage(message, x); messages.set(i, message); lastMessage = message; } } request.report.evidence.messages = messages; //REMOVE_BEFORE_PUBLISHING(request, ci); }","@Inject(method = ""reportAbuse"", at = @At(""HEAD""), cancellable = true, remap = false) public void reportAbuse(AbuseReportRequest request, CallbackInfo ci) { for (var message : request.report.evidence.messages) { if (message.body != null) { if (Gaslight.removedMessages.contains(message.body.message.plain)) { message.body = null; } } } //REMOVE_BEFORE_PUBLISHING(request, ci); }",We are now releasing pre-release 5 for Minecraft 1.19.1. This pre-release includes the remaining fixes for a known exploit regarding player report context,https://github.com/nodusclient/gaslight/commit/2055c0ae93927aa5ca70460bf35b10db4b358a42,,,src/main/java/gg/nodus/gaslight/mixin/MixinYggdrasilUserApiService.java,3,java,False,2022-07-27T17:16:47Z "@Override public boolean canAlterPermission(final Rank actor, final Rank rank, @NotNull final Action action) { if (rank == getRankOwner() && actor != getRankOwner()) { return false; } return rank != getRankOwner() || (action != Action.EDIT_PERMISSIONS && action != Action.MANAGE_HUTS && action != Action.GUARDS_ATTACK && action != Action.ACCESS_HUTS); }","@Override public boolean canAlterPermission(final Rank actor, final Rank rank, @NotNull final Action action) { if (rank == getRankOwner() && actor != getRankOwner()) { return false; } return hasPermission(actor, Action.EDIT_PERMISSIONS) && (actor != rank || action != Action.EDIT_PERMISSIONS && action != Action.MANAGE_HUTS && action != Action.ACCESS_HUTS); }","Fix permission issues (#7972) Ranks are no longer a static map, which was used as a per-colony map thus causing crashes and desyncs. If the last colony loaded had a custom rank, all other colonies would crash out due to not matching permissions for that rank. Permission/Rank seperation is removed, permission flag is now part of the rank instead of an externally synced map, which also auto-corrects bad stored data to default permissions. UI now has non-changeable permission buttons disabled.",https://github.com/ldtteam/minecolonies/commit/b1b86dffe64dd4c0f9d3060769fc418fd5d2869a,,,src/main/java/com/minecolonies/coremod/colony/permissions/Permissions.java,3,java,False,2022-01-23T12:23:45Z "public String getAuthenticationCode() { if (isNoAuthenticationCodeAzureType()) { return AzureCryptoToken.DUMMY_ACTIVATION_CODE; } return authenticationCode; }","public String getAuthenticationCode() { if (!requiresSecretToActivate) { return AzureCryptoToken.DUMMY_ACTIVATION_CODE; } return authenticationCode; }","ECA-8473 Fix rendering of authentication secret Previous code mistakenly referred to the ""currentCryptoToken"" to determine whether the token required a secret to authenticate. Now, that flag is added to the tables backing object, so Azure tokens using key binding won't ask for a secret when activating, but all other tokens will.",https://github.com/Keyfactor/ejbca-ce/commit/191413898b3137902762d910828480a6a41af057,,,modules/admin-gui/src/org/ejbca/ui/web/admin/cryptotoken/CryptoTokenMBean.java,3,java,False,2021-05-18T15:03:17Z "private void stopTor() { if (mBtnVPN.isChecked()) sendIntentToService(ACTION_STOP_VPN); sendIntentToService(ACTION_STOP); SnowfallView sv = findViewById(R.id.snowflake_view); sv.setVisibility(View.GONE); sv.stopFalling(); }","private void stopTor() { if (torStatus.equals(TorServiceConstants.STATUS_ON)) { if (mBtnVPN.isChecked()) sendIntentToService(ACTION_STOP_VPN); sendIntentToService(ACTION_STOP); } else if (torStatus.equals(STATUS_STARTING)) { if (!waitingToStop) { waitingToStop = true; updateStatus(""..."", STATUS_STOPPING); mStatusUpdateHandler.postDelayed(() -> { if (mBtnVPN.isChecked()) sendIntentToService(ACTION_STOP_VPN); sendIntentToService(ACTION_STOP); waitingToStop = false; }, 3000); } } SnowfallView sv = findViewById(R.id.snowflake_view); sv.setVisibility(View.GONE); sv.stopFalling(); }","handle new local action for v3 onion names updating; also don't allow rapid stop/starts to avoid crashes",https://github.com/guardianproject/orbot/commit/0ef3500ef9239e54b782c53efe643bf7a3bb1d3b,,,app/src/main/java/org/torproject/android/OrbotMainActivity.java,3,java,False,2021-12-20T19:55:34Z "protected final byte _parseBytePrimitive(JsonParser p, DeserializationContext ctxt) throws IOException { String text; switch (p.currentTokenId()) { case JsonTokenId.ID_STRING: text = p.getText(); break; case JsonTokenId.ID_NUMBER_FLOAT: CoercionAction act = _checkFloatToIntCoercion(p, ctxt, Byte.TYPE); if (act == CoercionAction.AsNull) { return (byte) 0; } if (act == CoercionAction.AsEmpty) { return (byte) 0; } return p.getByteValue(); case JsonTokenId.ID_NUMBER_INT: return p.getByteValue(); case JsonTokenId.ID_NULL: _verifyNullForPrimitive(ctxt); return (byte) 0; // 29-Jun-2020, tatu: New! ""Scalar from Object"" (mostly for XML) case JsonTokenId.ID_START_OBJECT: text = ctxt.extractScalarFromObject(p, this, Byte.TYPE); break; case JsonTokenId.ID_START_ARRAY: // unwrapping / from-empty-array coercion? // 12-Jun-2020, tatu: For some reason calling `_deserializeFromArray()` won't work so: if (ctxt.isEnabled(DeserializationFeature.UNWRAP_SINGLE_VALUE_ARRAYS)) { p.nextToken(); final byte parsed = _parseBytePrimitive(p, ctxt); _verifyEndArrayForSingle(p, ctxt); return parsed; } // fall through default: return ((Byte) ctxt.handleUnexpectedToken(ctxt.constructType(Byte.TYPE), p)).byteValue(); } // Coercion from String CoercionAction act = _checkFromStringCoercion(ctxt, text, LogicalType.Integer, Byte.TYPE); if (act == CoercionAction.AsNull) { // 03-May-2021, tatu: Might not be allowed (should we do ""empty"" check?) _verifyNullForPrimitive(ctxt); return (byte) 0; } if (act == CoercionAction.AsEmpty) { return (byte) 0; } text = text.trim(); if (_hasTextualNull(text)) { _verifyNullForPrimitiveCoercion(ctxt, text); return (byte) 0; } int value; try { value = NumberInput.parseInt(text); } catch (IllegalArgumentException iae) { return (Byte) ctxt.handleWeirdStringValue(_valueClass, text, ""not a valid `byte` value""); } // So far so good: but does it fit? Allow both -128 / 255 range (inclusive) if (_byteOverflow(value)) { return (Byte) ctxt.handleWeirdStringValue(_valueClass, text, ""overflow, value cannot be represented as 8-bit value""); } return (byte) value; }","protected final byte _parseBytePrimitive(JsonParser p, DeserializationContext ctxt) throws IOException { String text; switch (p.currentTokenId()) { case JsonTokenId.ID_STRING: text = p.getText(); break; case JsonTokenId.ID_NUMBER_FLOAT: CoercionAction act = _checkFloatToIntCoercion(p, ctxt, Byte.TYPE); if (act == CoercionAction.AsNull) { return (byte) 0; } if (act == CoercionAction.AsEmpty) { return (byte) 0; } return p.getByteValue(); case JsonTokenId.ID_NUMBER_INT: return p.getByteValue(); case JsonTokenId.ID_NULL: _verifyNullForPrimitive(ctxt); return (byte) 0; // 29-Jun-2020, tatu: New! ""Scalar from Object"" (mostly for XML) case JsonTokenId.ID_START_OBJECT: text = ctxt.extractScalarFromObject(p, this, Byte.TYPE); break; case JsonTokenId.ID_START_ARRAY: // unwrapping / from-empty-array coercion? // 12-Jun-2020, tatu: For some reason calling `_deserializeFromArray()` won't work so: if (ctxt.isEnabled(DeserializationFeature.UNWRAP_SINGLE_VALUE_ARRAYS)) { if (p.nextToken() == JsonToken.START_ARRAY) { return (byte) handleNestedArrayForSingle(p, ctxt); } final byte parsed = _parseBytePrimitive(p, ctxt); _verifyEndArrayForSingle(p, ctxt); return parsed; } // fall through default: return ((Byte) ctxt.handleUnexpectedToken(ctxt.constructType(Byte.TYPE), p)).byteValue(); } // Coercion from String CoercionAction act = _checkFromStringCoercion(ctxt, text, LogicalType.Integer, Byte.TYPE); if (act == CoercionAction.AsNull) { // 03-May-2021, tatu: Might not be allowed (should we do ""empty"" check?) _verifyNullForPrimitive(ctxt); return (byte) 0; } if (act == CoercionAction.AsEmpty) { return (byte) 0; } text = text.trim(); if (_hasTextualNull(text)) { _verifyNullForPrimitiveCoercion(ctxt, text); return (byte) 0; } int value; try { value = NumberInput.parseInt(text); } catch (IllegalArgumentException iae) { return (Byte) ctxt.handleWeirdStringValue(_valueClass, text, ""not a valid `byte` value""); } // So far so good: but does it fit? Allow both -128 / 255 range (inclusive) if (_byteOverflow(value)) { return (Byte) ctxt.handleWeirdStringValue(_valueClass, text, ""overflow, value cannot be represented as 8-bit value""); } return (byte) value; }","update release notes wrt #3582, [CVE-2022-42004]",https://github.com/FasterXML/jackson-databind/commit/2c4a601c626f7790cad9d3c322d244e182838288,,,src/main/java/com/fasterxml/jackson/databind/deser/std/StdDeserializer.java,3,java,False,2022-10-12T01:42:40Z "@Override protected synchronized long prepare(String sql) throws SQLException { return prepare_utf8(stringToUtf8ByteArray(sql)); }","@Override protected synchronized SafeStmtPtr prepare(String sql) throws SQLException { return new SafeStmtPtr(this, prepare_utf8(stringToUtf8ByteArray(sql))); }",Wrap Statement Pointers to prevent use after free race,https://github.com/xerial/sqlite-jdbc/commit/e1d282cb2887ef427c7ad93d4fe7dd05a6c11473,,,src/main/java/org/sqlite/core/NativeDB.java,3,java,False,2022-07-29T03:54:01Z "@AttackVector( vulnerabilityExposed = {VulnerabilityType.PERSISTENT_XSS}, description = ""PERSISTENT_XSS_HTML_TAG_URL_PARAM_DIRECTLY_INJECTED_IN_DIV_TAG_AFTER_HTML_ESCAPING_POST_CONTENT_BEFORE_NULL_BYTE"") @VulnerableAppRequestMapping( value = LevelConstants.LEVEL_6, htmlTemplate = ""LEVEL_1/PersistentXSS"") public ResponseEntity getVulnerablePayloadLevel7( @RequestParam Map queryParams) { Function function = (post) -> { // This logic represents null byte vulnerable escapeHtml function return post.contains(Constants.NULL_BYTE_CHARACTER) ? StringEscapeUtils.escapeHtml4( post.substring( 0, post.indexOf(Constants.NULL_BYTE_CHARACTER))) + post.substring(post.indexOf(Constants.NULL_BYTE_CHARACTER)) : StringEscapeUtils.escapeHtml4(post); }; return new ResponseEntity( this.getCommentsPayload(queryParams, LevelConstants.LEVEL_6, function), HttpStatus.OK); }","@VulnerableAppRequestMapping( value = LevelConstants.LEVEL_7, htmlTemplate = ""LEVEL_1/PersistentXSS"", variant = Variant.SECURE) public ResponseEntity getVulnerablePayloadLevel7( @RequestParam Map queryParams) { return new ResponseEntity( this.getCommentsPayload( queryParams, LevelConstants.LEVEL_7, post -> StringEscapeUtils.escapeHtml4(post)), HttpStatus.OK); }",fixing a small merge issue (#338),https://github.com/SasanLabs/VulnerableApp/commit/003c1ef4e6480120f15ee7ead9012666946c5672,,,src/main/java/org/sasanlabs/service/vulnerability/xss/persistent/PersistentXSSInHTMLTagVulnerability.java,3,java,False,2021-10-18T13:28:05Z "public void refreshConfig() { Yaml yaml = new Yaml(); StringWriter writer = new StringWriter(); yaml.dump(configObj, writer); configStr = writer.toString(); try { Files.write(Paths.get(""config.yaml""), configStr.getBytes(StandardCharsets.UTF_8)); Files.write(Paths.get(configPath), configStr.getBytes(StandardCharsets.UTF_8)); } catch (Exception ex) { ex.printStackTrace(); logger.error(ex); } }","public void refreshConfig() { Yaml yaml = new Yaml(new SafeConstructor(new LoaderOptions())); StringWriter writer = new StringWriter(); yaml.dump(configObj, writer); configStr = writer.toString(); try { Files.write(Paths.get(""config.yaml""), configStr.getBytes(StandardCharsets.UTF_8)); Files.write(Paths.get(configPath), configStr.getBytes(StandardCharsets.UTF_8)); } catch (Exception ex) { ex.printStackTrace(); logger.error(ex); } }",yaml rce,https://github.com/4ra1n/super-xray/commit/4d0d59663596db03f39d7edd2be251d48b52dcfc,,,src/main/java/com/chaitin/xray/form/MainForm.java,3,java,False,2022-11-24T12:45:39Z "@Override public void cancel() { KeyboardInteractiveAuthenticator.this.cancel(); transport.disconnect(TransportProtocol.AUTH_CANCELLED_BY_USER, ""User cancelled auth.""); }","@Override public void cancel() { KeyboardInteractiveAuthenticator.this.cancel(); failure(); transport.disconnect(TransportProtocol.AUTH_CANCELLED_BY_USER, ""User cancelled auth.""); }",HOTFIX: Client authenticators need to signal failure to parent future and should allow SshException to propagate.,https://github.com/sshtools/maverick-synergy/commit/bcbc2fc44c7eb499e00623c1348c360734afa3f5,,,maverick-synergy-client/src/main/java/com/sshtools/client/KeyboardInteractiveAuthenticator.java,3,java,False,2021-08-16T21:17:42Z "private void showContent(ServerConfig config ) { if (!checkSystemSettings(config)) { // Here we go when the settings window is opened; // Next time we're here after we returned from the Android settings through onResume() return; } sendDeviceInfoAfterReconfigure(); scheduleDeviceInfoSending(); scheduleInstalledAppsRun(); if (config.getLock() != null && config.getLock()) { showLockScreen(); return; } else { hideLockScreen(); } // Run default launcher option if (config.getRunDefaultLauncher() != null && config.getRunDefaultLauncher() && !getPackageName().equals(Utils.getDefaultLauncher(this)) && !Utils.isLauncherIntent(getIntent())) { openDefaultLauncher(); return; } Utils.setOrientation(this, config); if (ProUtils.kioskModeRequired(this)) { String kioskApp = settingsHelper.getConfig().getMainApp(); if (kioskApp != null && kioskApp.trim().length() > 0 && // If Headwind MDM itself is set as kiosk app, the kiosk mode is already turned on; // So here we just proceed to drawing the content (!kioskApp.equals(getPackageName()) || !ProUtils.isKioskModeRunning(this))) { if (ProUtils.startCosuKioskMode(kioskApp, this)) { getWindow().clearFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON); return; } else { Log.e(Const.LOG_TAG, ""Kiosk mode failed, proceed with the default flow""); } } else { Log.e(Const.LOG_TAG, ""Kiosk mode disabled: please setup the main app!""); } } else { if (ProUtils.isKioskModeRunning(this)) { // Turn off kiosk and show desktop if it is turned off in the configuration ProUtils.unlockKiosk(this); openDefaultLauncher(); } } if ( config.getBackgroundColor() != null ) { try { binding.activityMainContentWrapper.setBackgroundColor(Color.parseColor(config.getBackgroundColor())); } catch (Exception e) { // Invalid color e.printStackTrace(); binding.activityMainContentWrapper.setBackgroundColor( getResources().getColor(R.color.defaultBackground)); } } else { binding.activityMainContentWrapper.setBackgroundColor( getResources().getColor(R.color.defaultBackground)); } updateTitle(config); if (appListAdapter == null || needRedrawContentAfterReconfigure) { needRedrawContentAfterReconfigure = false; if ( config.getBackgroundImageUrl() != null && config.getBackgroundImageUrl().length() > 0 ) { Picasso.Builder builder = new Picasso.Builder(this); if (BuildConfig.TRUST_ANY_CERTIFICATE) { builder.downloader(new OkHttp3Downloader(UnsafeOkHttpClient.getUnsafeOkHttpClient())); } builder.listener(new Picasso.Listener() { @Override public void onImageLoadFailed(Picasso picasso, Uri uri, Exception exception) { // On fault, get the background image from the cache // This is a workaround against a bug in Picasso: it doesn't display cached images by default! Picasso.with(MainActivity.this) .load(config.getBackgroundImageUrl()) .networkPolicy(NetworkPolicy.OFFLINE) .into(binding.activityMainBackground); } }); builder.build() .load(config.getBackgroundImageUrl()) .into(binding.activityMainBackground); } else { binding.activityMainBackground.setImageDrawable(null); } Display display = getWindowManager().getDefaultDisplay(); Point size = new Point(); display.getSize(size); int width = size.x; int itemWidth = getResources().getDimensionPixelSize(R.dimen.app_list_item_size); spanCount = (int) (width * 1.0f / itemWidth); appListAdapter = new AppListAdapter(this, this); appListAdapter.setSpanCount(spanCount); binding.activityMainContent.setLayoutManager(new GridLayoutManager(this, spanCount)); binding.activityMainContent.setAdapter(appListAdapter); appListAdapter.notifyDataSetChanged(); } binding.setShowContent(true); // We can now sleep, uh getWindow().clearFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON); }","private void showContent(ServerConfig config ) { if (!checkSystemSettings(config)) { // Here we go when the settings window is opened; // Next time we're here after we returned from the Android settings through onResume() return; } sendDeviceInfoAfterReconfigure(); scheduleDeviceInfoSending(); scheduleInstalledAppsRun(); if (config.getLock() != null && config.getLock()) { showLockScreen(); return; } else { hideLockScreen(); } // Run default launcher option if (config.getRunDefaultLauncher() != null && config.getRunDefaultLauncher() && !getPackageName().equals(Utils.getDefaultLauncher(this)) && !Utils.isLauncherIntent(getIntent())) { openDefaultLauncher(); return; } Utils.setOrientation(this, config); if (ProUtils.kioskModeRequired(this)) { String kioskApp = settingsHelper.getConfig().getMainApp(); if (kioskApp != null && kioskApp.trim().length() > 0 && // If Headwind MDM itself is set as kiosk app, the kiosk mode is already turned on; // So here we just proceed to drawing the content (!kioskApp.equals(getPackageName()) || !ProUtils.isKioskModeRunning(this))) { if (ProUtils.startCosuKioskMode(kioskApp, this)) { getWindow().clearFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON); return; } else { Log.e(Const.LOG_TAG, ""Kiosk mode failed, proceed with the default flow""); } } else { Log.e(Const.LOG_TAG, ""Kiosk mode disabled: please setup the main app!""); } } else { if (ProUtils.isKioskModeRunning(this)) { // Turn off kiosk and show desktop if it is turned off in the configuration ProUtils.unlockKiosk(this); openDefaultLauncher(); } } if ( config.getBackgroundColor() != null ) { try { binding.activityMainContentWrapper.setBackgroundColor(Color.parseColor(config.getBackgroundColor())); } catch (Exception e) { // Invalid color e.printStackTrace(); binding.activityMainContentWrapper.setBackgroundColor( getResources().getColor(R.color.defaultBackground)); } } else { binding.activityMainContentWrapper.setBackgroundColor( getResources().getColor(R.color.defaultBackground)); } updateTitle(config); if (mainAppListAdapter == null || needRedrawContentAfterReconfigure) { needRedrawContentAfterReconfigure = false; if ( config.getBackgroundImageUrl() != null && config.getBackgroundImageUrl().length() > 0 ) { Picasso.Builder builder = new Picasso.Builder(this); if (BuildConfig.TRUST_ANY_CERTIFICATE) { builder.downloader(new OkHttp3Downloader(UnsafeOkHttpClient.getUnsafeOkHttpClient())); } else if (BuildConfig.CHECK_SIGNATURE) { // Here we assume TRUST_ANY_CERTIFICATE and CHECK_SIGNATURE are not turned on together! // That makes no sense: TRUST_ANY_CERTIFICATE is unsafe, but CHECK_SIGNATURE is for safe setup OkHttpClient clientWithSignature = new OkHttpClient.Builder() .addInterceptor(chain -> { okhttp3.Request.Builder requestBuilder = chain.request().newBuilder(); String signature = InstallUtils.getRequestSignature(chain.request().url().toString()); if (signature != null) { requestBuilder.addHeader(""X-Request-Signature"", signature); } return chain.proceed(requestBuilder.build()); }) .build(); builder.downloader(new OkHttp3Downloader(clientWithSignature)); } builder.listener(new Picasso.Listener() { @Override public void onImageLoadFailed(Picasso picasso, Uri uri, Exception exception) { // On fault, get the background image from the cache // This is a workaround against a bug in Picasso: it doesn't display cached images by default! Picasso.with(MainActivity.this) .load(config.getBackgroundImageUrl()) .networkPolicy(NetworkPolicy.OFFLINE) .into(binding.activityMainBackground); } }); builder.build() .load(config.getBackgroundImageUrl()) .into(binding.activityMainBackground); } else { binding.activityMainBackground.setImageDrawable(null); } Display display = getWindowManager().getDefaultDisplay(); Point size = new Point(); display.getSize(size); int width = size.x; int itemWidth = getResources().getDimensionPixelSize(R.dimen.app_list_item_size); spanCount = (int) (width * 1.0f / itemWidth); mainAppListAdapter = new MainAppListAdapter(this, this, this); mainAppListAdapter.setSpanCount(spanCount); binding.activityMainContent.setLayoutManager(new GridLayoutManager(this, spanCount)); binding.activityMainContent.setAdapter(mainAppListAdapter); mainAppListAdapter.notifyDataSetChanged(); int bottomAppCount = AppShortcutManager.getInstance().getInstalledAppCount(this, true); if (bottomAppCount > 0) { bottomAppListAdapter = new BottomAppListAdapter(this, this, this); bottomAppListAdapter.setSpanCount(spanCount); binding.activityBottomLayout.setVisibility(View.VISIBLE); binding.activityBottomLine.setLayoutManager(new GridLayoutManager(this, bottomAppCount < spanCount ? bottomAppCount : spanCount)); binding.activityBottomLine.setAdapter(bottomAppListAdapter); bottomAppListAdapter.notifyDataSetChanged(); } else { bottomAppListAdapter = null; binding.activityBottomLayout.setVisibility(View.GONE); } } binding.setShowContent(true); // We can now sleep, uh getWindow().clearFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON); }",v3.58: Some applications can be displayed in the bottom line; Fixed an Intent Redirection vulnerability; Fixed the background download issue when CHECK_SIGNATURE flag is set,https://github.com/h-mdm/hmdm-android/commit/26f9cfe12410a8eefb2ebbaaf580d4c9abbf4e3e,,,app/src/main/java/com/hmdm/launcher/ui/MainActivity.java,3,java,False,2021-02-24T15:17:46Z "private CompletableFuture isTopicOperationAllowed(TopicName topicName, String subscriptionName, TopicOperation operation) { CompletableFuture isProxyAuthorizedFuture; CompletableFuture isAuthorizedFuture; if (service.isAuthorizationEnabled()) { if (authenticationData == null) { authenticationData = new AuthenticationDataCommand("""", subscriptionName); } else { authenticationData.setSubscription(subscriptionName); } if (originalAuthData != null) { originalAuthData.setSubscription(subscriptionName); } return isTopicOperationAllowed(topicName, operation); } else { isProxyAuthorizedFuture = CompletableFuture.completedFuture(true); isAuthorizedFuture = CompletableFuture.completedFuture(true); } return isProxyAuthorizedFuture.thenCombine(isAuthorizedFuture, (isProxyAuthorized, isAuthorized) -> { if (!isProxyAuthorized) { log.warn(""OriginalRole {} is not authorized to perform operation {} on topic {}, subscription {}"", originalPrincipal, operation, topicName, subscriptionName); } if (!isAuthorized) { log.warn(""Role {} is not authorized to perform operation {} on topic {}, subscription {}"", authRole, operation, topicName, subscriptionName); } return isProxyAuthorized && isAuthorized; }); }","private CompletableFuture isTopicOperationAllowed(TopicName topicName, String subscriptionName, TopicOperation operation) { CompletableFuture isProxyAuthorizedFuture; CompletableFuture isAuthorizedFuture; if (service.isAuthorizationEnabled()) { AuthenticationDataSource authData = new AuthenticationDataSubscription(getAuthenticationData(), subscriptionName); return isTopicOperationAllowed(topicName, operation, authData); } else { isProxyAuthorizedFuture = CompletableFuture.completedFuture(true); isAuthorizedFuture = CompletableFuture.completedFuture(true); } return isProxyAuthorizedFuture.thenCombine(isAuthorizedFuture, (isProxyAuthorized, isAuthorized) -> { if (!isProxyAuthorized) { log.warn(""OriginalRole {} is not authorized to perform operation {} on topic {}, subscription {}"", originalPrincipal, operation, topicName, subscriptionName); } if (!isAuthorized) { log.warn(""Role {} is not authorized to perform operation {} on topic {}, subscription {}"", authRole, operation, topicName, subscriptionName); } return isProxyAuthorized && isAuthorized; }); }","Avoid AuthenticationDataSource mutation for subscription name (#16065) The `authenticationData` field in `ServerCnx` is being mutated to add the `subscription` field that will be passed on to the authorization plugin. The problem is that `authenticationData` is scoped to the whole connection and it should be getting mutated for each consumer that is created on the connection. The current code leads to a race condition where the subscription name used in the authz plugin is already modified while we're looking at it. Instead, we should create a new object and enforce the final modifier. (cherry picked from commit e6b12c64b043903eb5ff2dc5186fe8030f157cfc)",https://github.com/apache/pulsar/commit/b40e6eb7712821a8456880ca58de673bbc4bac36,,,pulsar-broker/src/main/java/org/apache/pulsar/broker/service/ServerCnx.java,3,java,False,2022-06-15T07:00:28Z "@Override public CompletionStage getOrCreateTemplate(String name, Configuration configuration, EnumSet flags) { localConfigurationManager.validateFlags(flags); try { CacheState state = new CacheState(null, parserRegistry.serialize(name, configuration), flags); return getStateCache().putIfAbsentAsync(new ScopedState(TEMPLATE_SCOPE, name), state).thenApply((v) -> configuration); } catch (Exception e) { throw CONFIG.configurationSerializationFailed(name, configuration, e); } }","@Override public CompletionStage getOrCreateTemplate(String name, Configuration configuration, EnumSet flags) { localConfigurationManager.validateFlags(flags); try { final CacheState state = new CacheState(null, parserRegistry.serialize(name, configuration), flags); return getStateCache().computeIfAbsentAsync(new ScopedState(TEMPLATE_SCOPE, name), k -> { assertNameLength(name); return state; }).thenApply((v) -> configuration); } catch (Exception e) { throw CONFIG.configurationSerializationFailed(name, configuration, e); } }",ISPN-13846 Creating cache with name more then 256 characters long will make the servers crashing on OpenShift,https://github.com/infinispan/infinispan/commit/0b8927b6c41a06600b57666b3c2619f65e8ca83a,,,core/src/main/java/org/infinispan/globalstate/impl/GlobalConfigurationManagerImpl.java,3,java,False,2022-04-20T18:11:12Z "private static void deserializeColorCategory(Identifier id, JsonObject object) { var category = ColorRegistryImpl.INSTANCE.category(id); if (category == null) return; for (var entry : object.entrySet()) { ColorKey key = category.key(entry.getKey()); if (key != null && entry.getValue() instanceof JsonPrimitive value) key.setRgb(value.asInt(key.defaultRgb())); } }","private static void deserializeColorCategory(Identifier id, JsonObject object) { var category = ColorRegistryImpl.INSTANCE.category(id); for (var entry : object.entrySet()) { if (entry.getValue() instanceof JsonPrimitive value) { ColorKey key = category.key(entry.getKey()); long rgbValue = value.asLong(Long.MIN_VALUE); boolean isValidValue = rgbValue >= Integer.MIN_VALUE && rgbValue <= Integer.MAX_VALUE; if (key != null) { if (isValidValue) key.setRgb((int) rgbValue); else // reset to default if the value is invalid key.setRgb(key.defaultRgb()); } else if (isValidValue) { // key is not (yet) registered, save this value in case it gets registered later category.setRgbKeyLater(entry.getKey(), (int) rgbValue); } } } }",Relase 3.2.1,https://github.com/MisterPeModder/ShulkerBoxTooltip/commit/2bc9d44c7db231bb8442a9f29d025da6ec69dc80,,,common/src/main/java/com/misterpemodder/shulkerboxtooltip/impl/config/ShulkerBoxTooltipConfigSerializer.java,3,java,False,2022-10-27T10:32:43Z "@Override public void run() { isStopButtonFlag = false; EventBus.getDefault().post(EventBusMSG.UPDATE_TRACK); }","@Override public void run() { setGPSLocationUpdates(false); setGPSLocationUpdates(true); }",Closes #171 - Fix crash when the GPS_PROVIDER is unavailable,https://github.com/BasicAirData/GPSLogger/commit/7bdaaa050337da067e38d44c0be1e9521558dc92,,,app/src/main/java/eu/basicairdata/graziano/gpslogger/GPSApplication.java,3,java,False,2022-03-16T20:03:06Z "protected boolean exec(String sql) throws SQLException { if (sql == null) throw new SQLException(""SQLiteJDBC internal error: sql==null""); if (rs.isOpen()) throw new SQLException(""SQLite JDBC internal error: rs.isOpen() on exec.""); boolean rc = false; boolean success = false; try { rc = conn.getDatabase().execute(sql, conn.getAutoCommit()); success = true; } finally { resultsWaiting = rc; if (!success) conn.getDatabase().finalize(this); } return conn.getDatabase().column_count(pointer) != 0; }","protected boolean exec(String sql) throws SQLException { if (sql == null) throw new SQLException(""SQLiteJDBC internal error: sql==null""); if (rs.isOpen()) throw new SQLException(""SQLite JDBC internal error: rs.isOpen() on exec.""); boolean rc = false; boolean success = false; try { rc = conn.getDatabase().execute(sql, conn.getAutoCommit()); success = true; } finally { resultsWaiting = rc; if (!success && pointer != null) { pointer.close(); } } return pointer.safeRunInt(DB::column_count) != 0; }",Wrap Statement Pointers to prevent use after free race,https://github.com/xerial/sqlite-jdbc/commit/e1d282cb2887ef427c7ad93d4fe7dd05a6c11473,,,src/main/java/org/sqlite/core/CoreStatement.java,3,java,False,2022-07-29T03:54:01Z "private static void addAllSecureTokens(final HttpServletRequest httpServletRequest, final AttributeMap attributeMap) { final X509Certificate[] certs = (X509Certificate[]) httpServletRequest .getAttribute(""javax.servlet.request.X509Certificate""); if (certs != null && certs.length > 0 && certs[0] != null) { // If we get here it means SSL has been terminated by DropWizard so we need to add meta items // from the certificate final X509Certificate cert = certs[0]; if (cert.getSubjectDN() != null) { final String remoteDN = cert.getSubjectDN().toString(); attributeMap.put(StandardHeaderArguments.REMOTE_DN, remoteDN); } else { LOGGER.debug(""Cert {} doesn't have a subject DN"", cert); } if (cert.getNotAfter() != null) { final String remoteCertExpiry = DateUtil.createNormalDateTimeString(cert.getNotAfter().getTime()); attributeMap.put(StandardHeaderArguments.REMOTE_CERT_EXPIRY, remoteCertExpiry); } else { LOGGER.debug(""Cert {} doesn't have a Not After date"", cert); } } }","private static void addAllSecureTokens(final HttpServletRequest httpServletRequest, final AttributeMap attributeMap) { final X509Certificate cert = CertificateUtil.extractCertificate(httpServletRequest); if (cert != null) { // If we get here it means SSL has been terminated by DropWizard so we need to add meta items // from the certificate if (cert.getSubjectDN() != null) { final String remoteDN = cert.getSubjectDN().toString(); attributeMap.put(StandardHeaderArguments.REMOTE_DN, remoteDN); } else { LOGGER.debug(""Cert {} doesn't have a subject DN"", cert); } if (cert.getNotAfter() != null) { final String remoteCertExpiry = DateUtil.createNormalDateTimeString(cert.getNotAfter().getTime()); attributeMap.put(StandardHeaderArguments.REMOTE_CERT_EXPIRY, remoteCertExpiry); } else { LOGGER.debug(""Cert {} doesn't have a Not After date"", cert); } } }",#2142 Fix certificate authentication issues,https://github.com/gchq/stroom/commit/42762b4b0b8d85c858879374355747f5ce56a3d9,,,stroom-meta/stroom-meta-api/src/main/java/stroom/meta/api/AttributeMapUtil.java,3,java,False,2021-03-26T12:27:16Z "@ModifyVariable(at = @At(value = ""INVOKE_ASSIGN"", target = ""net/minecraft/enchantment/EnchantmentHelper.chooseEquipmentWith(Lnet/minecraft/enchantment/Enchantment;Lnet/minecraft/entity/LivingEntity;Ljava/util/function/Predicate;)Ljava/util/Map$Entry;""), method = ""repairPlayerGears"") private Entry modifyEntry(Entry entry) { int size = Enchantments.MENDING.getEquipment(mendingPlayer).size(); Optional optional = TrinketsApi.getTrinketComponent(mendingPlayer); if (optional.isPresent()) { TrinketComponent comp = optional.get(); List> list = comp.getEquipped(stack -> stack.isDamaged() && EnchantmentHelper.getLevel(Enchantments.MENDING, stack) > 0); int selected = mendingPlayer.getRandom().nextInt(size + list.size()); if (selected < list.size()) { Pair pair = list.get(selected); Map dummyMap = Maps.newHashMap(); dummyMap.put(EquipmentSlot.MAINHAND, pair.getRight()); entry = dummyMap.entrySet().iterator().next(); } } mendingPlayer = null; return entry; }","@ModifyVariable(at = @At(value = ""INVOKE_ASSIGN"", target = ""net/minecraft/enchantment/EnchantmentHelper.chooseEquipmentWith(Lnet/minecraft/enchantment/Enchantment;Lnet/minecraft/entity/LivingEntity;Ljava/util/function/Predicate;)Ljava/util/Map$Entry;""), method = ""repairPlayerGears"") private Entry modifyEntry(Entry entry) { int size = Enchantments.MENDING.getEquipment(mendingPlayer).size(); Optional optional = TrinketsApi.getTrinketComponent(mendingPlayer); if (optional.isPresent()) { TrinketComponent comp = optional.get(); List> list = comp.getEquipped(stack -> stack.isDamaged() && EnchantmentHelper.getLevel(Enchantments.MENDING, stack) > 0); int totalSize = size + list.size(); if (totalSize == 0) { return entry; } int selected = mendingPlayer.getRandom().nextInt(totalSize); if (selected < list.size()) { Pair pair = list.get(selected); Map dummyMap = Maps.newHashMap(); dummyMap.put(EquipmentSlot.MAINHAND, pair.getRight()); entry = dummyMap.entrySet().iterator().next(); } } mendingPlayer = null; return entry; }",Fix xp crash,https://github.com/emilyploszaj/trinkets/commit/3d6be48755f49a5fe3009f848e6a82e4dfc45228,,,src/main/java/dev/emi/trinkets/mixin/ExperienceOrbEntityMixin.java,3,java,False,2021-07-16T13:32:30Z "@Override public void onEnable() { log = getLogger(); pluginManager = getServer().getPluginManager(); log.info(""Registering events""); // please make a pull request if there is a better way to do this // b register( new DupeFixes(this), new DisableWithers(this), new Elytra(this), new EndPortalPatch(this), new Bedrock(this), new Boats(this), new Chat(this), new ChunkBan(this), new CommandPreProcess(this), new CrashExploits(this), new Illegals(this), new JoinMessages(this), new Kicks(this), new LagExploits(this), new MyServer(this), new NetherRoof(this), new Redstone(this), new NetherPortals(this), new GodMode(this), new RenderDistance(this), new CommandExploits(this) ); if (getServer().getPluginManager().getPlugin(""ProtocolLib"") != null) { // I would put this in a seperate class if I could however I cba to deal with the annoying ass static errors. getLogger().info(""Detected ProtocolLib!""); protocolManager = ProtocolLibrary.getProtocolManager(); if (config.getBoolean(""PreventCraftingRecipeLagExploit"")) { protocolManager.addPacketListener( new PacketAdapter(this, ListenerPriority.NORMAL, PacketType.Play.Client.AUTO_RECIPE) { @Override public void onPacketReceiving(PacketEvent event) { if (event.getPacketType() == PacketType.Play.Client.AUTO_RECIPE) { if (crafting.contains(event.getPlayer().getName())) { event.setCancelled(true); } else { crafting.add(event.getPlayer().getName()); Bukkit.getServer().getScheduler().runTaskLater(plugin, () -> crafting.remove(event.getPlayer().getName()), getConfig().getInt(""CraftingRecipeDelay"")); } } } }); } if (config.getBoolean(""PreventPacketFly"")) { protocolManager.addPacketListener( new PacketAdapter(this, ListenerPriority.HIGHEST, PacketType.Play.Client.TELEPORT_ACCEPT) { @Override public void onPacketReceiving(PacketEvent event) { Player e = event.getPlayer(); Location l = event.getPlayer().getLocation(); if (event.getPlayer().getWorld().getBlockAt(l.getBlockX(), l.getBlockY() - 1, l.getBlockZ()).getType() == Material.AIR && !e.isGliding() && !e.isInsideVehicle()) { if (event.getPacketType() == PacketType.Play.Client.TELEPORT_ACCEPT) { if (levels.get(e) != null) { if (levels.get(e) > getConfig().getInt(""MaxTeleportPacketsPer10Seconds"")) { event.setCancelled(true); if (getConfig().getBoolean(""LogPacketFlyEvents"")) { getLogger().warning(e.getName() + "" prevented from packetflying""); } } else { levels.merge(e, 1, Integer::sum); Bukkit.getServer().getScheduler().runTaskLater(plugin, () -> levels.put(e, levels.get(e) - 1), 200L); } } else { levels.put(e, 1); Bukkit.getServer().getScheduler().runTaskLater(plugin, () -> levels.put(e, levels.get(e) - 1), 200L); } } } } }); } if (config.getBoolean(""BoatflyPatch"")) { protocolManager.addPacketListener( new PacketAdapter(this, ListenerPriority.HIGHEST, PacketType.Play.Client.USE_ENTITY) { @Override public void onPacketReceiving(PacketEvent event) { Player e = event.getPlayer(); if (e.isInsideVehicle() && e.getVehicle().getType() == EntityType.BOAT) { if (event.getPacketType() == PacketType.Play.Client.USE_ENTITY) { if (boatLevels.get(e) != null) { if (boatLevels.get(e) > getConfig().getInt(""MaxEntityPacketsPer10Seconds"")) { e.getVehicle().remove(); if (getConfig().getBoolean(""LogBoatFlyEvents"")) { getLogger().warning(e.getName() + "" prevented from boatflying""); } } else { boatLevels.merge(e, 1, Integer::sum); Bukkit.getServer().getScheduler().runTaskLater(plugin, () -> boatLevels.put(e, boatLevels.get(e) - 1), 200L); } } else { boatLevels.put(e, 1); Bukkit.getServer().getScheduler().runTaskLater(plugin, () -> boatLevels.put(e, boatLevels.get(e) - 1), 200L); } } } } }); } } else { getLogger().warning(""Did not detect ProtocolLib, disabling packet patches""); } log.info(""Registering events finished""); log.info(""Registering commands""); getCommand(""aef"").setExecutor(new Commands(this)); if (config.getBoolean(""StrictIllegalPrevention"")) { Bukkit.getServer().getScheduler().runTaskTimer(this, () -> Bukkit.getWorlds().forEach(b -> b.getPlayers().forEach(e -> e.getInventory().forEach(this::revert))), 0L, 20L); } if (config.getBoolean(""RemoveAllWitherSkulls"")) { Bukkit.getScheduler().runTaskTimer(this, () -> { for (World w : Bukkit.getWorlds()) { for (Entity e : w.getEntities()) { if (e.getType() == EntityType.WITHER_SKULL) { e.remove(); } } } }, 0L, 20L); } Bukkit.getScheduler().runTaskTimer(this, () -> { new_total[0] = 0; old_total[0] = 0; Bukkit.getOnlinePlayers().forEach(b -> { if (newChunks.get(b) != null) { new_total[0] = new_total[0] + newChunks.get(b); } }); Bukkit.getOnlinePlayers().forEach(b -> { if (oldChunks.get(b) != null) { old_total[0] = old_total[0] + oldChunks.get(b); } }); }, 0L, 20L); if (config.getBoolean(""RateLimitLevers"")) Bukkit.getScheduler().runTaskTimerAsynchronously(this, Redstone::clearLeverHashmap, 0, config.getInt(""RateLimitTime"")); saveDefaultConfig(); // Disable some config options for non 1.12 servers because they cause a shit ton of errors if (!config.getBoolean(""OverideConfigChanges"")) { if (!Bukkit.getVersion().contains(""1.12"")) { getConfig().set(""RemoveALLIllegalBlocksOnCHUNKLOAD"", false); getConfig().set(""FillInBedrockFloor"", false); getConfig().set(""FillInBedrockRoof"", false); getConfig().set(""ExperimentalDupePatch2"", false); log.warning(""Disabled:\nRemoveALLIllegalBlocksOnCHUNKLOAD\nFillInBedrockFloor\nFillInBedrockRoof\nExperimentalDupePatch2\nDue to errors with non 1.12.2 versions.""); } else { getConfig().set(""DisableFish"", false); log.warning(""Disabled:\nDisableFish\nbecause server is 1.12""); } } if (config.getBoolean(""ExperimentalDupePatch2"")) { Bukkit.getScheduler().runTaskTimer(this, this::preventDespawning, 0L, 20L); } log.info(""[ENABLED] AnarchyExploitFixes - Made by moomoo""); new Metrics(this, 8700); }","@Override public void onEnable() { log = getLogger(); pluginManager = getServer().getPluginManager(); log.info(""Registering events""); // please make a pull request if there is a better way to do this // b register( new DupeFixes(this), new DisableWithers(this), new Elytra(this), new EndPortalPatch(this), new Bedrock(this), new Boats(this), new Chat(this), new ChunkBan(this), new CommandPreProcess(this), new CrashExploits(this), new Illegals(this), new JoinMessages(this), new Kicks(this), new LagExploits(this), new MyServer(this), new NetherRoof(this), new Redstone(this), new NetherPortals(this), new GodMode(this), new RenderDistance(this), new CoordExploits(this), new CommandExploits(this) ); if (getServer().getPluginManager().getPlugin(""ProtocolLib"") != null) { // I would put this in a seperate class if I could however I cba to deal with the annoying ass static errors. getLogger().info(""Detected ProtocolLib!""); protocolManager = ProtocolLibrary.getProtocolManager(); if (config.getBoolean(""PreventCraftingRecipeLagExploit"")) { protocolManager.addPacketListener( new PacketAdapter(this, ListenerPriority.NORMAL, PacketType.Play.Client.AUTO_RECIPE) { @Override public void onPacketReceiving(PacketEvent event) { if (event.getPacketType() == PacketType.Play.Client.AUTO_RECIPE) { if (crafting.contains(event.getPlayer().getName())) { event.setCancelled(true); } else { crafting.add(event.getPlayer().getName()); Bukkit.getServer().getScheduler().runTaskLater(plugin, () -> crafting.remove(event.getPlayer().getName()), getConfig().getInt(""CraftingRecipeDelay"")); } } } }); } if (config.getBoolean(""PreventPacketFly"")) { protocolManager.addPacketListener( new PacketAdapter(this, ListenerPriority.HIGHEST, PacketType.Play.Client.TELEPORT_ACCEPT) { @Override public void onPacketReceiving(PacketEvent event) { Player e = event.getPlayer(); Location l = event.getPlayer().getLocation(); if (event.getPlayer().getWorld().getBlockAt(l.getBlockX(), l.getBlockY() - 1, l.getBlockZ()).getType() == Material.AIR && !e.isGliding() && !e.isInsideVehicle()) { if (event.getPacketType() == PacketType.Play.Client.TELEPORT_ACCEPT) { if (levels.get(e) != null) { if (levels.get(e) > getConfig().getInt(""MaxTeleportPacketsPer10Seconds"")) { event.setCancelled(true); if (getConfig().getBoolean(""LogPacketFlyEvents"")) { getLogger().warning(e.getName() + "" prevented from packetflying""); } } else { levels.merge(e, 1, Integer::sum); Bukkit.getServer().getScheduler().runTaskLater(plugin, () -> levels.put(e, levels.get(e) - 1), 200L); } } else { levels.put(e, 1); Bukkit.getServer().getScheduler().runTaskLater(plugin, () -> levels.put(e, levels.get(e) - 1), 200L); } } } } }); } if (config.getBoolean(""BoatflyPatch"")) { protocolManager.addPacketListener( new PacketAdapter(this, ListenerPriority.HIGHEST, PacketType.Play.Client.USE_ENTITY) { @Override public void onPacketReceiving(PacketEvent event) { Player e = event.getPlayer(); if (e.isInsideVehicle() && e.getVehicle().getType() == EntityType.BOAT) { if (event.getPacketType() == PacketType.Play.Client.USE_ENTITY) { if (boatLevels.get(e) != null) { if (boatLevels.get(e) > getConfig().getInt(""MaxEntityPacketsPer10Seconds"")) { e.getVehicle().remove(); if (getConfig().getBoolean(""LogBoatFlyEvents"")) { getLogger().warning(e.getName() + "" prevented from boatflying""); } } else { boatLevels.merge(e, 1, Integer::sum); Bukkit.getServer().getScheduler().runTaskLater(plugin, () -> boatLevels.put(e, boatLevels.get(e) - 1), 200L); } } else { boatLevels.put(e, 1); Bukkit.getServer().getScheduler().runTaskLater(plugin, () -> boatLevels.put(e, boatLevels.get(e) - 1), 200L); } } } } }); } } else { getLogger().warning(""Did not detect ProtocolLib, disabling packet patches""); } log.info(""Registering events finished""); log.info(""Registering commands""); getCommand(""aef"").setExecutor(new Commands(this)); if (config.getBoolean(""StrictIllegalPrevention"")) { Bukkit.getServer().getScheduler().runTaskTimer(this, () -> Bukkit.getWorlds().forEach(b -> b.getPlayers().forEach(e -> e.getInventory().forEach(this::revert))), 0L, 20L); } if (config.getBoolean(""RemoveAllWitherSkulls"")) { Bukkit.getScheduler().runTaskTimer(this, () -> { for (World w : Bukkit.getWorlds()) { for (Entity e : w.getEntities()) { if (e.getType() == EntityType.WITHER_SKULL) { e.remove(); } } } }, 0L, 20L); } Bukkit.getScheduler().runTaskTimer(this, () -> { new_total[0] = 0; old_total[0] = 0; Bukkit.getOnlinePlayers().forEach(b -> { if (newChunks.get(b) != null) { new_total[0] = new_total[0] + newChunks.get(b); } }); Bukkit.getOnlinePlayers().forEach(b -> { if (oldChunks.get(b) != null) { old_total[0] = old_total[0] + oldChunks.get(b); } }); }, 0L, 20L); if (config.getBoolean(""RateLimitLevers"")) Bukkit.getScheduler().runTaskTimerAsynchronously(this, Redstone::clearLeverHashmap, 0, config.getInt(""RateLimitTime"")); saveDefaultConfig(); // Disable some config options for non 1.12 servers because they cause a shit ton of errors if (!config.getBoolean(""OverideConfigChanges"")) { if (!Bukkit.getVersion().contains(""1.12"")) { getConfig().set(""RemoveALLIllegalBlocksOnCHUNKLOAD"", false); getConfig().set(""FillInBedrockFloor"", false); getConfig().set(""FillInBedrockRoof"", false); getConfig().set(""ExperimentalDupePatch2"", false); log.warning(""Disabled:\nRemoveALLIllegalBlocksOnCHUNKLOAD\nFillInBedrockFloor\nFillInBedrockRoof\nExperimentalDupePatch2\nDue to errors with non 1.12.2 versions.""); } else { getConfig().set(""DisableFish"", false); log.warning(""Disabled:\nDisableFish\nbecause server is 1.12""); } } if (config.getBoolean(""ExperimentalDupePatch2"")) { Bukkit.getScheduler().runTaskTimer(this, this::preventDespawning, 0L, 20L); } log.info(""[ENABLED] AnarchyExploitFixes - Made by moomoo""); new Metrics(this, 8700); }",prevent coord exploit and refractor all variable names,https://github.com/moom0o/AnarchyExploitFixes/commit/79513e78eb425cea725fd0a20ad2a09a4e7907d2,,,src/main/java/me/moomoo/anarchyexploitfixes/Main.java,3,java,False,2021-04-17T02:18:31Z "public static ArrayList checkBlockedUserEntities(MessageObject messageObject) { if (NekoConfig.ignoreBlocked && MessagesController.getInstance(UserConfig.selectedAccount).blockePeers.indexOfKey(messageObject.getFromChatId()) >= 0) { ArrayList entities = new ArrayList<>(messageObject.messageOwner.entities); var spoiler = new TLRPC.TL_messageEntitySpoiler(); spoiler.offset = 0; spoiler.length = messageObject.messageOwner.message.length(); entities.add(spoiler); return entities; } else { return messageObject.messageOwner.entities; } }","public static ArrayList checkBlockedUserEntities(MessageObject messageObject) { if (messageObject.messageOwner.message != null && NekoConfig.ignoreBlocked && MessagesController.getInstance(UserConfig.selectedAccount).blockePeers.indexOfKey(messageObject.getFromChatId()) >= 0) { ArrayList entities = new ArrayList<>(messageObject.messageOwner.entities); var spoiler = new TLRPC.TL_messageEntitySpoiler(); spoiler.offset = 0; spoiler.length = messageObject.messageOwner.message.length(); entities.add(spoiler); return entities; } else { return messageObject.messageOwner.entities; } }",Fix some crashes,https://github.com/NextAlone/Nagram/commit/a4bc7c69bc74b009dfa45537dd56171bae34eed2,,,TMessagesProj/src/main/java/tw/nekomimi/nekogram/helpers/MessageHelper.java,3,java,False,2022-02-03T03:31:25Z "@Override public void tryLockAndAttack() { super.tryLockAndAttack(); if (isAttacking() && (target.hasEffect(EntityEffect.NPC_ISH) || target.hasEffect(EntityEffect.ISH) || target.getHealth().hpDecreasedIn(3_000)) || hero.distanceTo(target) > 1_000) buggedTimer.activate(); }","@Override public void tryLockAndAttack() { super.tryLockAndAttack(); if (!hasTarget()) return; if (hero.distanceTo(target) > 1_000 || (isAttacking() && ( target.hasEffect(EntityEffect.NPC_ISH) || target.hasEffect(EntityEffect.ISH) || target.getHealth().hpDecreasedIn(3_000)))) { buggedTimer.activate(); } }","Update api, fix NPE on lock, beta 115",https://github.com/darkbot-reloaded/DarkBot/commit/3876b1c0f750ada2c2c35f302b717fdb30ac54fe,,,src/main/java/com/github/manolo8/darkbot/modules/utils/AttackAPIImpl.java,3,java,False,2022-12-24T16:00:02Z "@Override public int fillFields( byte[] data, int offset, EscherRecordFactory recordFactory ) { int bytesRemaining = readHeader( data, offset ); short propertiesCount = readInstance( data, offset ); int pos = offset + 8; EscherPropertyFactory f = new EscherPropertyFactory(); properties.clear(); properties.addAll( f.createProperties( data, pos, propertiesCount ) ); return bytesRemaining + 8; }","@Override public int fillFields( byte[] data, int offset, EscherRecordFactory recordFactory ) { int bytesRemaining = readHeader( data, offset ); if (bytesRemaining < 0) { throw new IllegalStateException(""Invalid value for bytesRemaining: "" + bytesRemaining); } short propertiesCount = readInstance( data, offset ); int pos = offset + 8; EscherPropertyFactory f = new EscherPropertyFactory(); properties.clear(); properties.addAll( f.createProperties( data, pos, propertiesCount ) ); return bytesRemaining + 8; }","Avoid stackoverflow exception that can be caused by a corrupted slideshow file git-svn-id: https://svn.apache.org/repos/asf/poi/trunk@1897318 13f79535-47bb-0310-9956-ffa450edef68",https://github.com/apache/poi/commit/8f1c84c3faaf31f158fb0b5331840d7ea46dda97,,,poi/src/main/java/org/apache/poi/ddf/AbstractEscherOptRecord.java,3,java,False,2022-01-22T06:58:39Z "private void requireStrongAuthIfAllLockedOut() { final boolean faceLock = mFaceLockedOutPermanent || !shouldListenForFace(); final boolean fpLock = mFingerprintLockedOutPermanent || !shouldListenForFingerprint(isUdfpsEnrolled()); if (faceLock && fpLock) { Log.d(TAG, ""All biometrics locked out - requiring strong auth""); mLockPatternUtils.requireStrongAuth(STRONG_AUTH_REQUIRED_AFTER_LOCKOUT, getCurrentUser()); } }","private void requireStrongAuthIfAllLockedOut() { final boolean faceLock = (mFaceLockedOutPermanent || !shouldListenForFace()) && !getIsFaceAuthenticated(); final boolean fpLock = mFingerprintLockedOutPermanent || !shouldListenForFingerprint(isUdfpsEnrolled()); if (faceLock && fpLock) { Log.d(TAG, ""All biometrics locked out - requiring strong auth""); mLockPatternUtils.requireStrongAuth(STRONG_AUTH_REQUIRED_AFTER_LOCKOUT, getCurrentUser()); } }","Fixed double face auth on swipe Previously, if a face was rejected, and PIN/Pattern/Pass was presented, and the user swiped on to unlock simultaneously, 2x face authentications would be observed. Test: Verified 10/10 times that device no longer performs 2x face authentications in the scenario described above. Fixes: 188598635 Change-Id: I24f964981484cfa19f7e1709f95da485204ff7a9",https://github.com/PixelExperience/frameworks_base/commit/5afa7487dfe14e2272a7cf0f201c4f326dfe435f,,,packages/SystemUI/src/com/android/keyguard/KeyguardUpdateMonitor.java,3,java,False,2021-07-15T18:43:26Z "public static RootStatement codeToJava(StructClass cl, StructMethod mt, MethodDescriptor md, VarProcessor varProc) throws IOException { debugCurrentlyDecompiling.set(null); debugCurrentCFG.set(null); debugCurrentDecompileRecord.set(null); boolean isInitializer = CodeConstants.CLINIT_NAME.equals(mt.getName()); // for now static initializer only mt.expandData(cl); InstructionSequence seq = mt.getInstructionSequence(); ControlFlowGraph graph = new ControlFlowGraph(seq); debugCurrentCFG.set(graph); DotExporter.toDotFile(graph, mt, ""cfgConstructed"", true); DeadCodeHelper.removeDeadBlocks(graph); graph.inlineJsr(cl, mt); // TODO: move to the start, before jsr inlining DeadCodeHelper.connectDummyExitBlock(graph); DeadCodeHelper.removeGotos(graph); ExceptionDeobfuscator.removeCircularRanges(graph); ExceptionDeobfuscator.restorePopRanges(graph); if (DecompilerContext.getOption(IFernflowerPreferences.REMOVE_EMPTY_RANGES)) { ExceptionDeobfuscator.removeEmptyRanges(graph); } if (DecompilerContext.getOption(IFernflowerPreferences.ENSURE_SYNCHRONIZED_MONITOR)) { // special case: search for 'synchronized' ranges w/o monitorexit instruction (as generated by Kotlin and Scala) DeadCodeHelper.extendSynchronizedRangeToMonitorexit(graph); } if (DecompilerContext.getOption(IFernflowerPreferences.NO_EXCEPTIONS_RETURN)) { // special case: single return instruction outside of a protected range DeadCodeHelper.incorporateValueReturns(graph); } // ExceptionDeobfuscator.restorePopRanges(graph); ExceptionDeobfuscator.insertEmptyExceptionHandlerBlocks(graph); DeadCodeHelper.mergeBasicBlocks(graph); DecompilerContext.getCounterContainer().setCounter(CounterContainer.VAR_COUNTER, mt.getLocalVariables()); if (ExceptionDeobfuscator.hasObfuscatedExceptions(graph)) { DecompilerContext.getLogger().writeMessage(""Heavily obfuscated exception ranges found!"", IFernflowerLogger.Severity.WARN); if (!ExceptionDeobfuscator.handleMultipleEntryExceptionRanges(graph)) { DecompilerContext.getLogger().writeMessage(""Found multiple entry exception ranges which could not be splitted"", IFernflowerLogger.Severity.WARN); graph.addComment(""$FF: Could not handle exception ranges with multiple entries""); graph.addErrorComment = true; } ExceptionDeobfuscator.insertDummyExceptionHandlerBlocks(graph, mt.getBytecodeVersion()); } DotExporter.toDotFile(graph, mt, ""cfgParsed"", true); RootStatement root = DomHelper.parseGraph(graph, mt); DecompileRecord decompileRecord = new DecompileRecord(mt); debugCurrentDecompileRecord.set(decompileRecord); decompileRecord.add(""Initial"", root); debugCurrentlyDecompiling.set(root); FinallyProcessor fProc = new FinallyProcessor(md, varProc); int finallyProcessed = 0; while (fProc.iterateGraph(cl, mt, root, graph)) { finallyProcessed++; RootStatement oldRoot = root; root = DomHelper.parseGraph(graph, mt); root.addComments(oldRoot); decompileRecord.add(""ProcessFinally_"" + finallyProcessed, root); debugCurrentCFG.set(graph); debugCurrentlyDecompiling.set(root); } // remove synchronized exception handler // not until now because of comparison between synchronized statements in the finally cycle if (DomHelper.removeSynchronizedHandler(root)) { decompileRecord.add(""RemoveSynchronizedHandler"", root); } // LabelHelper.lowContinueLabels(root, new HashSet()); SequenceHelper.condenseSequences(root); decompileRecord.add(""CondenseSequences"", root); ClearStructHelper.clearStatements(root); decompileRecord.add(""ClearStatements"", root); // Put exprents in statements ExprProcessor proc = new ExprProcessor(md, varProc); proc.processStatement(root, cl); decompileRecord.add(""ProcessStatement"", root); SequenceHelper.condenseSequences(root); decompileRecord.add(""CondenseSequences_1"", root); StackVarsProcessor stackProc = new StackVarsProcessor(); // Process and simplify variables on the stack int stackVarsProcessed = 0; do { stackVarsProcessed++; stackProc.simplifyStackVars(root, mt, cl); decompileRecord.add(""SimplifyStackVars_PPMM_"" + stackVarsProcessed, root); varProc.setVarVersions(root); decompileRecord.add(""SetVarVersions_PPMM_"" + stackVarsProcessed, root); } while (new PPandMMHelper(varProc).findPPandMM(root)); // Inline ppi/mmi that we may have missed if (PPandMMHelper.inlinePPIandMMIIf(root)) { decompileRecord.add(""InlinePPIandMMI"", root); } // Process invokedynamic string concat if (cl.getVersion().hasIndyStringConcat()) { ConcatenationHelper.simplifyStringConcat(root); decompileRecord.add(""SimplifyStringConcat"", root); } // Process ternary values if (DecompilerContext.getOption(IFernflowerPreferences.TERNARY_CONDITIONS)) { if (TernaryProcessor.processTernary(root)) { decompileRecord.add(""ProcessTernary"", root); } } // Main loop while (true) { decompileRecord.incrementMainLoop(); decompileRecord.add(""Start"", root); LabelHelper.cleanUpEdges(root); decompileRecord.add(""CleanupEdges"", root); // Merge loop while (true) { decompileRecord.incrementMergeLoop(); decompileRecord.add(""MergeLoopStart"", root); if (EliminateLoopsHelper.eliminateLoops(root, cl)) { decompileRecord.add(""EliminateLoops"", root); continue; } MergeHelper.enhanceLoops(root); decompileRecord.add(""EnhanceLoops"", root); if (LoopExtractHelper.extractLoops(root)) { decompileRecord.add(""ExtractLoops"", root); continue; } if (IfHelper.mergeAllIfs(root)) { decompileRecord.add(""MergeAllIfs"", root); // Continues with merge loop } else { break; } } decompileRecord.resetMergeLoop(); decompileRecord.add(""MergeLoopEnd"", root); if (DecompilerContext.getOption(IFernflowerPreferences.IDEA_NOT_NULL_ANNOTATION)) { if (IdeaNotNullHelper.removeHardcodedChecks(root, mt)) { decompileRecord.add(""RemoveIdeaNull"", root); SequenceHelper.condenseSequences(root); decompileRecord.add(""CondenseSequences_RIN"", root); } } stackProc.simplifyStackVars(root, mt, cl); decompileRecord.add(""SimplifyStackVars"", root); varProc.setVarVersions(root); decompileRecord.add(""SetVarVersions"", root); LabelHelper.identifyLabels(root); decompileRecord.add(""IdentifyLabels"", root); if (DecompilerContext.getOption(IFernflowerPreferences.PATTERN_MATCHING)) { if (cl.getVersion().hasIfPatternMatching()) { if (PatternMatchProcessor.matchInstanceof(root)) { decompileRecord.add(""MatchIfInstanceof"", root); continue; } } } if (SwitchExpressionHelper.hasSwitchExpressions(root)) { if (SwitchExpressionHelper.processSwitchExpressions(root)) { decompileRecord.add(""ProcessSwitchExpr"", root); continue; } } if (TryHelper.enhanceTryStats(root, cl)) { decompileRecord.add(""EnhanceTry"", root); continue; } if (InlineSingleBlockHelper.inlineSingleBlocks(root)) { decompileRecord.add(""InlineSingleBlocks"", root); continue; } // this has to be done last so it does not screw up the formation of for loops if (MergeHelper.makeDoWhileLoops(root)) { decompileRecord.add(""MatchDoWhile"", root); continue; } // initializer may have at most one return point, so no transformation of method exits permitted if (isInitializer || !ExitHelper.condenseExits(root)) { break; } else { decompileRecord.add(""CondenseExits"", root); } // FIXME: !! //if(!EliminateLoopsHelper.eliminateLoops(root)) { // break; //} } decompileRecord.resetMainLoop(); decompileRecord.add(""MainLoopEnd"", root); // this has to be done after all inlining is done so the case values do not get reverted if (SwitchHelper.simplifySwitches(root, mt, root)) { decompileRecord.add(""SimplifySwitches"", root); SequenceHelper.condenseSequences(root); // remove empty blocks decompileRecord.add(""CondenseSequences_SS"", root); // If we have simplified switches, try to make switch expressions if (SwitchExpressionHelper.hasSwitchExpressions(root)) { if (SwitchExpressionHelper.processSwitchExpressions(root)) { decompileRecord.add(""ProcessSwitchExpr_SS"", root); // Simplify stack vars to integrate and inline switch expressions stackProc.simplifyStackVars(root, mt, cl); decompileRecord.add(""SimplifyStackVars_SS"", root); varProc.setVarVersions(root); decompileRecord.add(""SetVarVersions_SS"", root); } } } // Makes constant returns the same type as the method descriptor if (ExitHelper.adjustReturnType(root, md)) { decompileRecord.add(""AdjustReturnType"", root); } // Remove returns that don't need to exist if (ExitHelper.removeRedundantReturns(root)) { decompileRecord.add(""RedundantReturns"", root); } // Apply post processing transformations if (SecondaryFunctionsHelper.identifySecondaryFunctions(root, varProc)) { decompileRecord.add(""IdentifySecondary"", root); } // Improve synchronized monitor assignments if (SynchronizedHelper.cleanSynchronizedVar(root)) { decompileRecord.add(""ClearSynchronized"", root); } if (SynchronizedHelper.insertSink(root, varProc, root)) { decompileRecord.add(""InsertSynchronizedAssignments"", root); } varProc.setVarDefinitions(root); decompileRecord.add(""SetVarDefinitions"", root); // Make sure to update assignments after setting the var definitions! if (SecondaryFunctionsHelper.updateAssignments(root)) { decompileRecord.add(""UpdateAssignments"", root); } // Hide empty default edges caused by switch statement processing if (LabelHelper.hideDefaultSwitchEdges(root)) { decompileRecord.add(""HideEmptyDefault"", root); } if (GenericsProcessor.qualifyChains(root)) { decompileRecord.add(""QualifyGenericChains"", root); } // must be the last invocation, because it makes the statement structure inconsistent // FIXME: new edge type needed if (LabelHelper.replaceContinueWithBreak(root)) { decompileRecord.add(""ReplaceContinues"", root); } DotExporter.toDotFile(root, mt, ""finalStatement""); // Debug print the decompile record DotExporter.toDotFile(decompileRecord, mt, ""decompileRecord"", false); mt.releaseResources(); return root; }","public static RootStatement codeToJava(StructClass cl, StructMethod mt, MethodDescriptor md, VarProcessor varProc) throws IOException { debugCurrentlyDecompiling.set(null); debugCurrentCFG.set(null); debugCurrentDecompileRecord.set(null); boolean isInitializer = CodeConstants.CLINIT_NAME.equals(mt.getName()); // for now static initializer only mt.expandData(cl); InstructionSequence seq = mt.getInstructionSequence(); ControlFlowGraph graph = new ControlFlowGraph(seq); debugCurrentCFG.set(graph); DotExporter.toDotFile(graph, mt, ""cfgConstructed"", true); DeadCodeHelper.removeDeadBlocks(graph); graph.inlineJsr(cl, mt); // TODO: move to the start, before jsr inlining DeadCodeHelper.connectDummyExitBlock(graph); DeadCodeHelper.removeGotos(graph); ExceptionDeobfuscator.removeCircularRanges(graph); ExceptionDeobfuscator.restorePopRanges(graph); if (DecompilerContext.getOption(IFernflowerPreferences.REMOVE_EMPTY_RANGES)) { ExceptionDeobfuscator.removeEmptyRanges(graph); } if (DecompilerContext.getOption(IFernflowerPreferences.ENSURE_SYNCHRONIZED_MONITOR)) { // special case: search for 'synchronized' ranges w/o monitorexit instruction (as generated by Kotlin and Scala) DeadCodeHelper.extendSynchronizedRangeToMonitorexit(graph); } if (DecompilerContext.getOption(IFernflowerPreferences.NO_EXCEPTIONS_RETURN)) { // special case: single return instruction outside of a protected range DeadCodeHelper.incorporateValueReturns(graph); } // ExceptionDeobfuscator.restorePopRanges(graph); ExceptionDeobfuscator.insertEmptyExceptionHandlerBlocks(graph); DeadCodeHelper.mergeBasicBlocks(graph); DecompilerContext.getCounterContainer().setCounter(CounterContainer.VAR_COUNTER, mt.getLocalVariables()); if (ExceptionDeobfuscator.hasObfuscatedExceptions(graph)) { DecompilerContext.getLogger().writeMessage(""Heavily obfuscated exception ranges found!"", IFernflowerLogger.Severity.WARN); if (!ExceptionDeobfuscator.handleMultipleEntryExceptionRanges(graph)) { DecompilerContext.getLogger().writeMessage(""Found multiple entry exception ranges which could not be splitted"", IFernflowerLogger.Severity.WARN); graph.addComment(""$FF: Could not handle exception ranges with multiple entries""); graph.addErrorComment = true; } ExceptionDeobfuscator.insertDummyExceptionHandlerBlocks(graph, mt.getBytecodeVersion()); } DotExporter.toDotFile(graph, mt, ""cfgParsed"", true); RootStatement root = DomHelper.parseGraph(graph, mt); DecompileRecord decompileRecord = new DecompileRecord(mt); debugCurrentDecompileRecord.set(decompileRecord); decompileRecord.add(""Initial"", root); debugCurrentlyDecompiling.set(root); FinallyProcessor fProc = new FinallyProcessor(md, varProc); int finallyProcessed = 0; while (fProc.iterateGraph(cl, mt, root, graph)) { finallyProcessed++; RootStatement oldRoot = root; root = DomHelper.parseGraph(graph, mt); root.addComments(oldRoot); decompileRecord.add(""ProcessFinally_"" + finallyProcessed, root); debugCurrentCFG.set(graph); debugCurrentlyDecompiling.set(root); } // remove synchronized exception handler // not until now because of comparison between synchronized statements in the finally cycle if (DomHelper.removeSynchronizedHandler(root)) { decompileRecord.add(""RemoveSynchronizedHandler"", root); } // LabelHelper.lowContinueLabels(root, new HashSet()); SequenceHelper.condenseSequences(root); decompileRecord.add(""CondenseSequences"", root); ClearStructHelper.clearStatements(root); decompileRecord.add(""ClearStatements"", root); // Put exprents in statements ExprProcessor proc = new ExprProcessor(md, varProc); proc.processStatement(root, cl); decompileRecord.add(""ProcessStatement"", root); SequenceHelper.condenseSequences(root); decompileRecord.add(""CondenseSequences_1"", root); StackVarsProcessor stackProc = new StackVarsProcessor(); // Process and simplify variables on the stack int stackVarsProcessed = 0; do { stackVarsProcessed++; stackProc.simplifyStackVars(root, mt, cl); decompileRecord.add(""SimplifyStackVars_PPMM_"" + stackVarsProcessed, root); varProc.setVarVersions(root); decompileRecord.add(""SetVarVersions_PPMM_"" + stackVarsProcessed, root); } while (new PPandMMHelper(varProc).findPPandMM(root)); // Inline ppi/mmi that we may have missed if (PPandMMHelper.inlinePPIandMMIIf(root)) { decompileRecord.add(""InlinePPIandMMI"", root); } // Process invokedynamic string concat if (cl.getVersion().hasIndyStringConcat()) { ConcatenationHelper.simplifyStringConcat(root); decompileRecord.add(""SimplifyStringConcat"", root); } // Process ternary values if (DecompilerContext.getOption(IFernflowerPreferences.TERNARY_CONDITIONS)) { if (TernaryProcessor.processTernary(root)) { decompileRecord.add(""ProcessTernary"", root); } } // Main loop while (true) { decompileRecord.incrementMainLoop(); decompileRecord.add(""Start"", root); LabelHelper.cleanUpEdges(root); decompileRecord.add(""CleanupEdges"", root); // Merge loop while (true) { decompileRecord.incrementMergeLoop(); decompileRecord.add(""MergeLoopStart"", root); if (EliminateLoopsHelper.eliminateLoops(root, cl)) { decompileRecord.add(""EliminateLoops"", root); continue; } MergeHelper.enhanceLoops(root); decompileRecord.add(""EnhanceLoops"", root); if (LoopExtractHelper.extractLoops(root)) { decompileRecord.add(""ExtractLoops"", root); continue; } if (IfHelper.mergeAllIfs(root)) { decompileRecord.add(""MergeAllIfs"", root); // Continues with merge loop } else { break; } } decompileRecord.resetMergeLoop(); decompileRecord.add(""MergeLoopEnd"", root); if (DecompilerContext.getOption(IFernflowerPreferences.IDEA_NOT_NULL_ANNOTATION)) { if (IdeaNotNullHelper.removeHardcodedChecks(root, mt)) { decompileRecord.add(""RemoveIdeaNull"", root); SequenceHelper.condenseSequences(root); decompileRecord.add(""CondenseSequences_RIN"", root); } } stackProc.simplifyStackVars(root, mt, cl); decompileRecord.add(""SimplifyStackVars"", root); varProc.setVarVersions(root); decompileRecord.add(""SetVarVersions"", root); LabelHelper.identifyLabels(root); decompileRecord.add(""IdentifyLabels"", root); if (DecompilerContext.getOption(IFernflowerPreferences.PATTERN_MATCHING)) { if (cl.getVersion().hasIfPatternMatching()) { if (PatternMatchProcessor.matchInstanceof(root)) { decompileRecord.add(""MatchIfInstanceof"", root); continue; } } } if (SwitchExpressionHelper.hasSwitchExpressions(root)) { if (SwitchExpressionHelper.processSwitchExpressions(root)) { decompileRecord.add(""ProcessSwitchExpr"", root); continue; } } if (TryHelper.enhanceTryStats(root, cl)) { decompileRecord.add(""EnhanceTry"", root); continue; } if (InlineSingleBlockHelper.inlineSingleBlocks(root)) { decompileRecord.add(""InlineSingleBlocks"", root); continue; } // this has to be done last so it does not screw up the formation of for loops if (MergeHelper.makeDoWhileLoops(root)) { decompileRecord.add(""MatchDoWhile"", root); continue; } if (MergeHelper.condenseInfiniteLoopsWithReturn(root)) { decompileRecord.add(""CondenseDo"", root); continue; } // initializer may have at most one return point, so no transformation of method exits permitted if (isInitializer || !ExitHelper.condenseExits(root)) { break; } else { decompileRecord.add(""CondenseExits"", root); } // FIXME: !! //if(!EliminateLoopsHelper.eliminateLoops(root)) { // break; //} } decompileRecord.resetMainLoop(); decompileRecord.add(""MainLoopEnd"", root); // this has to be done after all inlining is done so the case values do not get reverted if (SwitchHelper.simplifySwitches(root, mt, root)) { decompileRecord.add(""SimplifySwitches"", root); SequenceHelper.condenseSequences(root); // remove empty blocks decompileRecord.add(""CondenseSequences_SS"", root); // If we have simplified switches, try to make switch expressions if (SwitchExpressionHelper.hasSwitchExpressions(root)) { if (SwitchExpressionHelper.processSwitchExpressions(root)) { decompileRecord.add(""ProcessSwitchExpr_SS"", root); // Simplify stack vars to integrate and inline switch expressions stackProc.simplifyStackVars(root, mt, cl); decompileRecord.add(""SimplifyStackVars_SS"", root); varProc.setVarVersions(root); decompileRecord.add(""SetVarVersions_SS"", root); } } } // Makes constant returns the same type as the method descriptor if (ExitHelper.adjustReturnType(root, md)) { decompileRecord.add(""AdjustReturnType"", root); } // Remove returns that don't need to exist if (ExitHelper.removeRedundantReturns(root)) { decompileRecord.add(""RedundantReturns"", root); } // Apply post processing transformations if (SecondaryFunctionsHelper.identifySecondaryFunctions(root, varProc)) { decompileRecord.add(""IdentifySecondary"", root); } // Improve synchronized monitor assignments if (SynchronizedHelper.cleanSynchronizedVar(root)) { decompileRecord.add(""ClearSynchronized"", root); } if (SynchronizedHelper.insertSink(root, varProc, root)) { decompileRecord.add(""InsertSynchronizedAssignments"", root); } varProc.setVarDefinitions(root); decompileRecord.add(""SetVarDefinitions"", root); // Make sure to update assignments after setting the var definitions! if (SecondaryFunctionsHelper.updateAssignments(root)) { decompileRecord.add(""UpdateAssignments"", root); } // Hide empty default edges caused by switch statement processing if (LabelHelper.hideDefaultSwitchEdges(root)) { decompileRecord.add(""HideEmptyDefault"", root); } if (GenericsProcessor.qualifyChains(root)) { decompileRecord.add(""QualifyGenericChains"", root); } // must be the last invocation, because it makes the statement structure inconsistent // FIXME: new edge type needed if (LabelHelper.replaceContinueWithBreak(root)) { decompileRecord.add(""ReplaceContinues"", root); } DotExporter.toDotFile(root, mt, ""finalStatement""); // Debug print the decompile record DotExporter.toDotFile(decompileRecord, mt, ""decompileRecord"", false); mt.releaseResources(); return root; }",Fix IOOBE in ternary processor,https://github.com/Vineflower/vineflower/commit/4400c8d14afeb97a151c47817138dd1f8da023d4,,,src/org/jetbrains/java/decompiler/main/rels/MethodProcessorRunnable.java,3,java,False,2022-01-06T05:29:48Z "private boolean matchesTarget(Task task) { return task.mUserId == mUserId && task.getBaseIntent().getComponent().equals(mTargetIntent.getComponent()); }","private boolean matchesTarget(Task task) { return task.getNonFinishingActivityCount() > 0 && task.mUserId == mUserId && task.getBaseIntent().getComponent().equals(mTargetIntent.getComponent()); }","Fix crash caused by accessing finishing task In our design, there are two existing recents task at the same time. If start new recents while finishing previous recents, there are two subtasks under recents root task, one is newly created and the other is finishing subtask. Try to get activity from finishing subtask would be null and cause NPE when manipulate null activity. Append non-finishing check could ensure we get activity record from newly created subtask instead of finishing subtask. Test: atest CtsWindowManagerDeviceTestCases Change-Id: I3fe8357e57c4f1afe578c696e8371874be0ed45e",https://github.com/LineageOS/android_frameworks_base/commit/eccd6e40a27c0df728465b2fe1487ed1a5919c34,,,services/core/java/com/android/server/wm/RecentsAnimation.java,3,java,False,2022-07-11T04:59:00Z "@Override protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { String clientUserName = null; String clientIpAddress; boolean requireNewCookie = false; try { if (hiveConf.getBoolean(ConfVars.HIVE_SERVER2_XSRF_FILTER_ENABLED.varname,false)){ boolean continueProcessing = Utils.doXsrfFilter(request,response,null,null); if (!continueProcessing){ LOG.warn(""Request did not have valid XSRF header, rejecting.""); return; } } clientIpAddress = request.getRemoteAddr(); LOG.debug(""Client IP Address: "" + clientIpAddress); // If the cookie based authentication is already enabled, parse the // request and validate the request cookies. if (isCookieAuthEnabled) { clientUserName = validateCookie(request); requireNewCookie = (clientUserName == null); if (requireNewCookie) { LOG.info(""Could not validate cookie sent, will try to generate a new cookie""); } } // Set the thread local ip address SessionManager.setIpAddress(clientIpAddress); // get forwarded hosts address String forwarded_for = request.getHeader(X_FORWARDED_FOR); if (forwarded_for != null) { LOG.debug(""{}:{}"", X_FORWARDED_FOR, forwarded_for); List forwardedAddresses = Arrays.asList(forwarded_for.split("","")); SessionManager.setForwardedAddresses(forwardedAddresses); } else { SessionManager.setForwardedAddresses(Collections.emptyList()); } // If the cookie based authentication is not enabled or the request does not have a valid // cookie, use authentication depending on the server setup. if (clientUserName == null) { String trustedDomain = HiveConf.getVar(hiveConf, ConfVars.HIVE_SERVER2_TRUSTED_DOMAIN).trim(); final boolean useXff = HiveConf.getBoolVar(hiveConf, ConfVars.HIVE_SERVER2_TRUSTED_DOMAIN_USE_XFF_HEADER); if (useXff && !trustedDomain.isEmpty() && SessionManager.getForwardedAddresses() != null && !SessionManager.getForwardedAddresses().isEmpty()) { // general format of XFF header is 'X-Forwarded-For: client, proxy1, proxy2' where left most being the client clientIpAddress = SessionManager.getForwardedAddresses().get(0); LOG.info(""Trusted domain authN is enabled. clientIp from X-Forwarded-For header: {}"", clientIpAddress); } // Skip authentication if the connection is from the trusted domain, if specified. // getRemoteHost may or may not return the FQDN of the remote host depending upon the // HTTP server configuration. So, force a reverse DNS lookup. String remoteHostName = InetAddress.getByName(clientIpAddress).getCanonicalHostName(); if (!trustedDomain.isEmpty() && PlainSaslHelper.isHostFromTrustedDomain(remoteHostName, trustedDomain)) { LOG.info(""No authentication performed because the connecting host "" + remoteHostName + "" is from the trusted domain "" + trustedDomain); // In order to skip authentication, we use auth type NOSASL to be consistent with the // HiveAuthFactory defaults. In HTTP mode, it will also get us the user name from the // HTTP request header. clientUserName = doPasswdAuth(request, HiveAuthConstants.AuthTypes.NOSASL.getAuthName()); } else { // For a kerberos setup if (isKerberosAuthMode(authType)) { String delegationToken = request.getHeader(HIVE_DELEGATION_TOKEN_HEADER); // Each http request must have an Authorization header if ((delegationToken != null) && (!delegationToken.isEmpty())) { clientUserName = doTokenAuth(request); } else { clientUserName = doKerberosAuth(request); } } else if (HiveSamlUtils.isSamlAuthMode(authType)) { // check if this request needs a SAML redirect String authHeader = request.getHeader(HttpAuthUtils.AUTHORIZATION); if ((authHeader == null || authHeader.isEmpty()) && needsRedirect(request, response)) { doSamlRedirect(request, response); return; } else if(authHeader.toLowerCase().startsWith(HttpAuthUtils.BASIC.toLowerCase())) { //LDAP Authentication if the header starts with Basic clientUserName = doPasswdAuth(request, HiveAuthConstants.AuthTypes.NONE.toString()); } else { // redirect is not needed. Do SAML auth. clientUserName = doSamlAuth(request, response); } } else { String proxyHeader = HiveConf.getVar(hiveConf, ConfVars.HIVE_SERVER2_TRUSTED_PROXY_TRUSTHEADER).trim(); if (!proxyHeader.equals("""") && request.getHeader(proxyHeader) != null) { //Trusted header is present, which means the user is already authorized. clientUserName = getUsername(request, authType); } else { // For password based authentication clientUserName = doPasswdAuth(request, authType); } } } } assert (clientUserName != null); LOG.debug(""Client username: "" + clientUserName); // Set the thread local username to be used for doAs if true SessionManager.setUserName(clientUserName); // find proxy user if any from query param String doAsQueryParam = getDoAsQueryParam(request.getQueryString()); if (doAsQueryParam != null) { SessionManager.setProxyUserName(doAsQueryParam); } // Generate new cookie and add it to the response if (requireNewCookie && !authType.toLowerCase().contains(HiveAuthConstants.AuthTypes.NOSASL.toString().toLowerCase())) { String cookieToken = HttpAuthUtils.createCookieToken(clientUserName); Cookie hs2Cookie = createCookie(signer.signCookie(cookieToken)); if (isHttpOnlyCookie) { response.setHeader(""SET-COOKIE"", getHttpOnlyCookieHeader(hs2Cookie)); } else { response.addCookie(hs2Cookie); } LOG.info(""Cookie added for clientUserName "" + clientUserName); } super.doPost(request, response); } catch (HttpAuthenticationException e) { // Ignore HttpEmptyAuthenticationException, it is normal for knox // to send a request with empty header if (!(e instanceof HttpEmptyAuthenticationException)) { LOG.error(""Error: "", e); } // Wait until all the data is received and then respond with 401 if (request.getContentLength() < 0) { try { ByteStreams.skipFully(request.getInputStream(), Integer.MAX_VALUE); } catch (EOFException ex) { LOG.info(ex.getMessage()); } } // Send a 401 to the client response.setStatus(HttpServletResponse.SC_UNAUTHORIZED); if(isKerberosAuthMode(authType)) { response.addHeader(HttpAuthUtils.WWW_AUTHENTICATE, HttpAuthUtils.NEGOTIATE); } else { try { LOG.error(""Login attempt is failed for user : "" + getUsername(request, authType) + "". Error Messsage :"" + e.getMessage()); } catch (Exception ex) { // Ignore Exception } } response.getWriter().println(""Authentication Error: "" + e.getMessage()); } finally { // Clear the thread locals SessionManager.clearUserName(); SessionManager.clearIpAddress(); SessionManager.clearProxyUserName(); SessionManager.clearForwardedAddresses(); } }","@Override protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { String clientUserName = null; String clientIpAddress; boolean requireNewCookie = false; try { if (hiveConf.getBoolean(ConfVars.HIVE_SERVER2_XSRF_FILTER_ENABLED.varname,false)){ boolean continueProcessing = Utils.doXsrfFilter(request,response,null,null); if (!continueProcessing){ LOG.warn(""Request did not have valid XSRF header, rejecting.""); return; } } clientIpAddress = request.getRemoteAddr(); LOG.debug(""Client IP Address: "" + clientIpAddress); // If the cookie based authentication is already enabled, parse the // request and validate the request cookies. if (isCookieAuthEnabled) { clientUserName = validateCookie(request); requireNewCookie = (clientUserName == null); if (requireNewCookie) { LOG.info(""Could not validate cookie sent, will try to generate a new cookie""); } } // Set the thread local ip address SessionManager.setIpAddress(clientIpAddress); // get forwarded hosts address String forwarded_for = request.getHeader(X_FORWARDED_FOR); if (forwarded_for != null) { LOG.debug(""{}:{}"", X_FORWARDED_FOR, forwarded_for); List forwardedAddresses = Arrays.asList(forwarded_for.split("","")); SessionManager.setForwardedAddresses(forwardedAddresses); } else { SessionManager.setForwardedAddresses(Collections.emptyList()); } // If the cookie based authentication is not enabled or the request does not have a valid // cookie, use authentication depending on the server setup. if (clientUserName == null) { String trustedDomain = HiveConf.getVar(hiveConf, ConfVars.HIVE_SERVER2_TRUSTED_DOMAIN).trim(); final boolean useXff = HiveConf.getBoolVar(hiveConf, ConfVars.HIVE_SERVER2_TRUSTED_DOMAIN_USE_XFF_HEADER); if (useXff && !trustedDomain.isEmpty() && SessionManager.getForwardedAddresses() != null && !SessionManager.getForwardedAddresses().isEmpty()) { // general format of XFF header is 'X-Forwarded-For: client, proxy1, proxy2' where left most being the client clientIpAddress = SessionManager.getForwardedAddresses().get(0); LOG.info(""Trusted domain authN is enabled. clientIp from X-Forwarded-For header: {}"", clientIpAddress); } // Skip authentication if the connection is from the trusted domain, if specified. // getRemoteHost may or may not return the FQDN of the remote host depending upon the // HTTP server configuration. So, force a reverse DNS lookup. String remoteHostName = InetAddress.getByName(clientIpAddress).getCanonicalHostName(); if (!trustedDomain.isEmpty() && PlainSaslHelper.isHostFromTrustedDomain(remoteHostName, trustedDomain)) { LOG.info(""No authentication performed because the connecting host "" + remoteHostName + "" is from the trusted domain "" + trustedDomain); // In order to skip authentication, we use auth type NOSASL to be consistent with the // HiveAuthFactory defaults. In HTTP mode, it will also get us the user name from the // HTTP request header. clientUserName = doPasswdAuth(request, HiveAuthConstants.AuthTypes.NOSASL.getAuthName()); } else { // For a kerberos setup if (isKerberosAuthMode(authType)) { String delegationToken = request.getHeader(HIVE_DELEGATION_TOKEN_HEADER); // Each http request must have an Authorization header if ((delegationToken != null) && (!delegationToken.isEmpty())) { clientUserName = doTokenAuth(request); } else { clientUserName = doKerberosAuth(request); } } else if (authType.isEnabled(HiveAuthConstants.AuthTypes.SAML)) { // check if this request needs a SAML redirect String authHeader = request.getHeader(HttpAuthUtils.AUTHORIZATION); if ((authHeader == null || authHeader.isEmpty()) && needsRedirect(request, response)) { doSamlRedirect(request, response); return; } else if(authHeader.toLowerCase().startsWith(HttpAuthUtils.BASIC.toLowerCase())) { // fall back to password based authentication if the header starts with Basic clientUserName = doPasswdAuth(request, authType.getPasswordBasedAuthStr()); } else { // redirect is not needed. Do SAML auth. clientUserName = doSamlAuth(request, response); } } else { String proxyHeader = HiveConf.getVar(hiveConf, ConfVars.HIVE_SERVER2_TRUSTED_PROXY_TRUSTHEADER).trim(); if (!proxyHeader.equals("""") && request.getHeader(proxyHeader) != null) { //Trusted header is present, which means the user is already authorized. clientUserName = getUsername(request); } else { // For password based authentication clientUserName = doPasswdAuth(request, authType.getPasswordBasedAuthStr()); } } } } assert (clientUserName != null); LOG.debug(""Client username: "" + clientUserName); // Set the thread local username to be used for doAs if true SessionManager.setUserName(clientUserName); // find proxy user if any from query param String doAsQueryParam = getDoAsQueryParam(request.getQueryString()); if (doAsQueryParam != null) { SessionManager.setProxyUserName(doAsQueryParam); } // Generate new cookie and add it to the response if (requireNewCookie && !authType.isEnabled(HiveAuthConstants.AuthTypes.NOSASL)) { String cookieToken = HttpAuthUtils.createCookieToken(clientUserName); Cookie hs2Cookie = createCookie(signer.signCookie(cookieToken)); if (isHttpOnlyCookie) { response.setHeader(""SET-COOKIE"", getHttpOnlyCookieHeader(hs2Cookie)); } else { response.addCookie(hs2Cookie); } LOG.info(""Cookie added for clientUserName "" + clientUserName); } super.doPost(request, response); } catch (HttpAuthenticationException e) { // Ignore HttpEmptyAuthenticationException, it is normal for knox // to send a request with empty header if (!(e instanceof HttpEmptyAuthenticationException)) { LOG.error(""Error: "", e); } // Wait until all the data is received and then respond with 401 if (request.getContentLength() < 0) { try { ByteStreams.skipFully(request.getInputStream(), Integer.MAX_VALUE); } catch (EOFException ex) { LOG.info(ex.getMessage()); } } // Send a 401 to the client response.setStatus(HttpServletResponse.SC_UNAUTHORIZED); if(isKerberosAuthMode(authType)) { response.addHeader(HttpAuthUtils.WWW_AUTHENTICATE, HttpAuthUtils.NEGOTIATE); } else { try { LOG.error(""Login attempt is failed for user : "" + getUsername(request) + "". Error Messsage :"" + e.getMessage()); } catch (Exception ex) { // Ignore Exception } } response.getWriter().println(""Authentication Error: "" + e.getMessage()); } finally { // Clear the thread locals SessionManager.clearUserName(); SessionManager.clearIpAddress(); SessionManager.clearProxyUserName(); SessionManager.clearForwardedAddresses(); } }","HIVE-25957: Fix password based authentication with SAML enabled (#3028) (Yu-Wen Lai, reviewed by Naveen Gangam) * HIVE-25957: Fix password based authentication with SAML enabled * Adds unit tests for AuthType * Remove unused argument for getAuthHeader",https://github.com/apache/hive/commit/a62af3a6d59c157eaab4dfbe306f5d18a23dd7d4,,,service/src/java/org/apache/hive/service/cli/thrift/ThriftHttpServlet.java,3,java,False,2022-02-17T20:02:01Z "private void initialize(MinecraftConnection connection) throws IllegalAccessException { connection.setAssociation(this.player); connection.setState(StateRegistry.PLAY); ChannelPipeline pipeline = connection.getChannel().pipeline(); this.plugin.deject3rdParty(pipeline); if (!pipeline.names().contains(Connections.FRAME_ENCODER) && !pipeline.names().contains(Connections.COMPRESSION_ENCODER)) { this.plugin.fixCompressor(pipeline, connection.getProtocolVersion()); } Logger logger = LimboAPI.getLogger(); this.server.getEventManager().fire(new LoginEvent(this.player)).thenAcceptAsync(event -> { if (connection.isClosed()) { // The player was disconnected. this.server.getEventManager().fireAndForget(new DisconnectEvent(this.player, DisconnectEvent.LoginStatus.CANCELLED_BY_USER_BEFORE_COMPLETE)); } else { Optional reason = event.getResult().getReasonComponent(); if (reason.isPresent()) { this.player.disconnect0(reason.get(), true); } else { if (this.server.registerConnection(this.player)) { try { connection.setSessionHandler(INITIAL_CONNECT_SESSION_HANDLER_CONSTRUCTOR.newInstance(this.player)); this.server.getEventManager().fire(new PostLoginEvent(this.player)).thenAccept(postLoginEvent -> { try { MC_CONNECTION_FIELD.set(this.handler, connection); CONNECT_TO_INITIAL_SERVER_METHOD.invoke(this.handler, this.player); } catch (IllegalAccessException | InvocationTargetException e) { logger.error(""Exception while connecting {} to initial server"", this.player, e); } }); } catch (InstantiationException | InvocationTargetException | IllegalAccessException e) { e.printStackTrace(); } } else { this.player.disconnect0(Component.translatable(""velocity.error.already-connected-proxy""), true); } } } }, connection.eventLoop()).exceptionally(t -> { logger.error(""Exception while completing login initialisation phase for {}"", this.player, t); return null; }); }","@SuppressFBWarnings(""NP_NULL_ON_SOME_PATH_FROM_RETURN_VALUE"") private void initialize(MinecraftConnection connection) throws IllegalAccessException { connection.setAssociation(this.player); connection.setState(StateRegistry.PLAY); ChannelPipeline pipeline = connection.getChannel().pipeline(); this.plugin.deject3rdParty(pipeline); if (!pipeline.names().contains(Connections.FRAME_ENCODER) && !pipeline.names().contains(Connections.COMPRESSION_ENCODER)) { this.plugin.fixCompressor(pipeline, connection.getProtocolVersion()); } if (this.player.getIdentifiedKey() != null) { IdentifiedKey playerKey = this.player.getIdentifiedKey(); if (playerKey.getSignatureHolder() == null) { if (playerKey instanceof IdentifiedKeyImpl) { IdentifiedKeyImpl unlinkedKey = (IdentifiedKeyImpl) playerKey; // Failsafe if (!unlinkedKey.internalAddHolder(this.player.getUniqueId())) { PLAYER_KEY_FIELD.set(this.player, null); } } } else { if (!Objects.equals(playerKey.getSignatureHolder(), this.player.getUniqueId())) { PLAYER_KEY_FIELD.set(this.player, null); } } } Logger logger = LimboAPI.getLogger(); this.server.getEventManager().fire(new LoginEvent(this.player)).thenAcceptAsync(event -> { if (connection.isClosed()) { // The player was disconnected. this.server.getEventManager().fireAndForget(new DisconnectEvent(this.player, DisconnectEvent.LoginStatus.CANCELLED_BY_USER_BEFORE_COMPLETE)); } else { Optional reason = event.getResult().getReasonComponent(); if (reason.isPresent()) { this.player.disconnect0(reason.get(), true); } else { if (this.server.registerConnection(this.player)) { try { connection.setSessionHandler(INITIAL_CONNECT_SESSION_HANDLER_CONSTRUCTOR.newInstance(this.player)); this.server.getEventManager().fire(new PostLoginEvent(this.player)).thenAccept(postLoginEvent -> { try { MC_CONNECTION_FIELD.set(this.handler, connection); CONNECT_TO_INITIAL_SERVER_METHOD.invoke(this.handler, this.player); } catch (IllegalAccessException | InvocationTargetException e) { logger.error(""Exception while connecting {} to initial server"", this.player, e); } }); } catch (InstantiationException | InvocationTargetException | IllegalAccessException e) { e.printStackTrace(); } } else { this.player.disconnect0(Component.translatable(""velocity.error.already-connected-proxy""), true); } } } }, connection.eventLoop()).exceptionally(t -> { logger.error(""Exception while completing login initialisation phase for {}"", this.player, t); return null; }); }","Ignore ChatSession on unmatched UUIDs/empty keys (fixes hybrid auth) Former-commit-id: ac6816aed10c6577297472f871d6c56ed9f63ef2",https://github.com/Elytrium/LimboAPI/commit/4fc319a7074648c41c57d6576336b4fa6d7e8128,,,plugin/src/main/java/net/elytrium/limboapi/injection/login/LoginTasksQueue.java,3,java,False,2022-12-19T01:58:53Z "public static void authenticateUser(@Nonnull String userName, @Nonnull String password) throws NamingException { Preconditions.checkArgument(!StringUtils.isAnyEmpty(userName), ""Username cannot be empty""); try { LoginContext lc = new LoginContext(""WHZ-Authentication"", new WHZCallbackHandler(userName, password)); lc.login(); } catch (LoginException le) { throw new AuthenticationException(le.toString()); } }","public static void authenticateUser(@Nonnull String userName, @Nonnull String password) throws NamingException { Preconditions.checkArgument(!StringUtils.isAnyEmpty(userName), ""Username cannot be empty""); try { JAASLoginService jaasLoginService = new JAASLoginService(""WHZ-Authentication""); PropertyUserStoreManager propertyUserStoreManager = new PropertyUserStoreManager(); propertyUserStoreManager.start(); jaasLoginService.setBeans(Collections.singletonList(propertyUserStoreManager)); JAASLoginService.INSTANCE.set(jaasLoginService); LoginContext lc = new LoginContext(""WHZ-Authentication"", new WHZCallbackHandler(userName, password)); lc.login(); } catch (LoginException le) { throw new AuthenticationException(le.toString()); } catch (Exception e) { // Bad abstract class design, empty doStart that has throws Exception in the signature and subclass that also // does not throw any checked exceptions. This should never happen, all it does is create an empty HashMap... } }",chore(jetty): upgrade jetty to 9.4.46 for CVE (#4857),https://github.com/datahub-project/datahub/commit/d70df06c217ea861c2f863e64d53065f73cd8b0d,,,datahub-frontend/app/security/AuthenticationManager.java,3,java,False,2022-05-06T21:18:20Z "@Override public BlobHolder convert(BlobHolder blobHolder, Map parameters) throws ConversionException { StringBuffer sb = new StringBuffer(); try { Blob blob = blobHolder.getBlob(); if (blob.getLength() > maxSize4POI) { return runFallBackConverter(blobHolder, ""xl/""); } try (InputStream stream = blob.getStream(); // OPCPackage p = OPCPackage.open(stream); // XSSFWorkbook workbook = new XSSFWorkbook(p)) { for (int i = 0; i < workbook.getNumberOfSheets(); i++) { XSSFSheet sheet = workbook.getSheetAt(i); Iterator rows = sheet.rowIterator(); while (rows.hasNext()) { XSSFRow row = (XSSFRow) rows.next(); Iterator cells = row.cellIterator(); while (cells.hasNext()) { XSSFCell cell = (XSSFCell) cells.next(); appendTextFromCell(cell, sb); } sb.append(ROW_SEP); } } } return new SimpleCachableBlobHolder(Blobs.createBlob(sb.toString())); } catch (IOException | OpenXML4JException e) { throw new ConversionException(""Error during XLX2Text conversion"", e); } }","@Override public BlobHolder convert(BlobHolder blobHolder, Map parameters) throws ConversionException { StringBuffer sb = new StringBuffer(); try { Blob blob = blobHolder.getBlob(); if (blob.getLength() < 0 || blob.getLength() > maxSize4POI) { return runFallBackConverter(blobHolder, ""xl/""); } try (InputStream stream = blob.getStream(); // OPCPackage p = OPCPackage.open(stream); // XSSFWorkbook workbook = new XSSFWorkbook(p)) { for (int i = 0; i < workbook.getNumberOfSheets(); i++) { XSSFSheet sheet = workbook.getSheetAt(i); Iterator rows = sheet.rowIterator(); while (rows.hasNext()) { XSSFRow row = (XSSFRow) rows.next(); Iterator cells = row.cellIterator(); while (cells.hasNext()) { XSSFCell cell = (XSSFCell) cells.next(); appendTextFromCell(cell, sb); } sb.append(ROW_SEP); } } } return new SimpleCachableBlobHolder(Blobs.createBlob(sb.toString())); } catch (IOException | OpenXML4JException e) { throw new ConversionException(""Error during XLX2Text conversion"", e); } }","NXP-30294: Fix possible OOM on XLSLX fulltext extraction By using the SAX parser fallback converter for blobs with an unknown length.",https://github.com/nuxeo/nuxeo/commit/2fa1f3ac3aefb5c94e7d839754c42f6c6cac35a8,,,nuxeo-core/nuxeo-core-convert-plugins/src/main/java/org/nuxeo/ecm/core/convert/plugins/text/extractors/XLX2TextConverter.java,3,java,False,2021-06-21T08:16:57Z "@Override public void waitForInstallConstraints(String installerPackageName, List packageNames, InstallConstraints constraints, IntentSender callback, long timeoutMillis) { Objects.requireNonNull(callback); if (timeoutMillis < 0 || timeoutMillis > MAX_INSTALL_CONSTRAINTS_TIMEOUT_MILLIS) { throw new IllegalArgumentException(""Invalid timeoutMillis="" + timeoutMillis); } var future = checkInstallConstraintsInternal( installerPackageName, packageNames, constraints, timeoutMillis); future.thenAccept(result -> { final var intent = new Intent(); intent.putExtra(Intent.EXTRA_PACKAGES, packageNames.toArray(new String[0])); intent.putExtra(PackageInstaller.EXTRA_INSTALL_CONSTRAINTS, constraints); intent.putExtra(PackageInstaller.EXTRA_INSTALL_CONSTRAINTS_RESULT, result); try { callback.sendIntent(mContext, 0, intent, null, null); } catch (SendIntentException ignore) { } }); }","@Override public void waitForInstallConstraints(String installerPackageName, List packageNames, InstallConstraints constraints, IntentSender callback, long timeoutMillis) { Objects.requireNonNull(callback); if (timeoutMillis < 0 || timeoutMillis > MAX_INSTALL_CONSTRAINTS_TIMEOUT_MILLIS) { throw new IllegalArgumentException(""Invalid timeoutMillis="" + timeoutMillis); } var future = checkInstallConstraintsInternal( installerPackageName, packageNames, constraints, timeoutMillis); future.thenAccept(result -> { final var intent = new Intent(); intent.putExtra(Intent.EXTRA_PACKAGES, packageNames.toArray(new String[0])); intent.putExtra(PackageInstaller.EXTRA_INSTALL_CONSTRAINTS, constraints); intent.putExtra(PackageInstaller.EXTRA_INSTALL_CONSTRAINTS_RESULT, result); try { final BroadcastOptions options = BroadcastOptions.makeBasic(); options.setPendingIntentBackgroundActivityLaunchAllowed(false); callback.sendIntent(mContext, 0, intent, null /* onFinished*/, null /* handler */, null /* requiredPermission */, options.toBundle()); } catch (SendIntentException ignore) { } }); }","Fix bypass BG-FGS and BAL via package manager APIs Opt-in for BAL of PendingIntent for following APIs: * PackageInstaller.uninstall() * PackageInstaller.installExistingPackage() * PackageInstaller.uninstallExistingPackage() * PackageInstaller.waitForInstallConstraints() * PackageInstaller.Session.commit() * PackageInstaller.Session.commitTransferred() * PackageInstaller.Session.requestUserPreapproval() * PackageManager.freeStorage() Bug: 230492955 Bug: 243377226 Test: atest android.security.cts.PackageInstallerTest Test: atest CtsStagedInstallHostTestCases Change-Id: I9b6f801d69ea6d2244a38dbe689e81afa4e798bf",https://github.com/PixelExperience/frameworks_base/commit/2be553067f56f21c0cf599ffa6b1ff24052a12fd,,,services/core/java/com/android/server/pm/PackageInstallerService.java,3,java,False,2023-01-11T08:02:27Z "public void start() throws SshException { if(Log.isDebugEnabled()) { Log.debug(""Starting Authentication Protocol""); } authenticators = new ArrayList( context.getAuthenticators()); try { doAuthentication(noneAuthenticator); } catch (IOException e) { Log.error(""Faild to send none authentication request"", e); transport.disconnected(); } }","public void start() throws SshException { if(Log.isDebugEnabled()) { Log.debug(""Starting Authentication Protocol""); } try { authenticators.add(noneAuthenticator); doNextAuthentication(); } catch (IOException e) { Log.error(""Faild to send none authentication request"", e); transport.disconnected(); } }","Added prefer keyboard-interactive over password setting. Fixed race condition with none authenticator.",https://github.com/sshtools/maverick-synergy/commit/5421a5cb4c6b5f5174bcfb2c15d78f3acd706d86,,,maverick-synergy-client/src/main/java/com/sshtools/client/AuthenticationProtocolClient.java,3,java,False,2021-03-07T16:54:01Z "void enter() { int stateBefore = StackOverflowCheck.singleton().getState(); VMError.guarantee(!StackOverflowCheck.singleton().isYellowZoneAvailable()); boolean isContinue = ip.isNonNull(); if (isContinue) { StackOverflowCheck.singleton().setState(overflowCheckState); } try { enter0(this, isContinue); } finally { overflowCheckState = StackOverflowCheck.singleton().getState(); StackOverflowCheck.singleton().setState(stateBefore); } }","void enter() { int stateBefore = StackOverflowCheck.singleton().getState(); VMError.guarantee(!StackOverflowCheck.singleton().isYellowZoneAvailable()); boolean isContinue = ip.isNonNull(); if (isContinue) { StackOverflowCheck.singleton().setState(overflowCheckState); } try { enter0(this, isContinue); } catch (StackOverflowError e) { throw (e == ImplicitExceptions.CACHED_STACK_OVERFLOW_ERROR) ? new StackOverflowError() : e; } finally { overflowCheckState = StackOverflowCheck.singleton().getState(); StackOverflowCheck.singleton().setState(stateBefore); assert sp.isNull() && bottomSP.isNull(); } }","Fix Continuation.enter1 overwriting its own frame, check for stack overflow, and avoid extra heap buffer.",https://github.com/oracle/graal/commit/aadbff556c457e107f5f44706750b11cf569e404,,,substratevm/src/com.oracle.svm.core/src/com/oracle/svm/core/thread/Continuation.java,3,java,False,2022-03-02T18:51:14Z "def load_pkcs12(buffer, passphrase=None): """""" Load a PKCS12 object from a buffer :param buffer: The buffer the certificate is stored in :param passphrase: (Optional) The password to decrypt the PKCS12 lump :returns: The PKCS12 object """""" passphrase = _text_to_bytes_and_warn(""passphrase"", passphrase) if isinstance(buffer, _text_type): buffer = buffer.encode(""ascii"") bio = _new_mem_buf(buffer) # Use null passphrase if passphrase is None or empty string. With PKCS#12 # password based encryption no password and a zero length password are two # different things, but OpenSSL implementation will try both to figure out # which one works. if not passphrase: passphrase = _ffi.NULL p12 = _lib.d2i_PKCS12_bio(bio, _ffi.NULL) if p12 == _ffi.NULL: _raise_current_error() p12 = _ffi.gc(p12, _lib.PKCS12_free) pkey = _ffi.new(""EVP_PKEY**"") cert = _ffi.new(""X509**"") cacerts = _ffi.new(""Cryptography_STACK_OF_X509**"") parse_result = _lib.PKCS12_parse(p12, passphrase, pkey, cert, cacerts) if not parse_result: _raise_current_error() cacerts = _ffi.gc(cacerts[0], _lib.sk_X509_free) # openssl 1.0.0 sometimes leaves an X509_check_private_key error in the # queue for no particular reason. This error isn't interesting to anyone # outside this function. It's not even interesting to us. Get rid of it. try: _raise_current_error() except Error: pass if pkey[0] == _ffi.NULL: pykey = None else: pykey = PKey.__new__(PKey) pykey._pkey = _ffi.gc(pkey[0], _lib.EVP_PKEY_free) if cert[0] == _ffi.NULL: pycert = None friendlyname = None else: pycert = X509.__new__(X509) pycert._x509 = _ffi.gc(cert[0], _lib.X509_free) friendlyname_length = _ffi.new(""int*"") friendlyname_buffer = _lib.X509_alias_get0( cert[0], friendlyname_length ) friendlyname = _ffi.buffer( friendlyname_buffer, friendlyname_length[0] )[:] if friendlyname_buffer == _ffi.NULL: friendlyname = None pycacerts = [] for i in range(_lib.sk_X509_num(cacerts)): pycacert = X509.__new__(X509) pycacert._x509 = _lib.sk_X509_value(cacerts, i) pycacerts.append(pycacert) if not pycacerts: pycacerts = None pkcs12 = PKCS12.__new__(PKCS12) pkcs12._pkey = pykey pkcs12._cert = pycert pkcs12._cacerts = pycacerts pkcs12._friendlyname = friendlyname return pkcs12","def load_pkcs12(buffer, passphrase=None): """""" Load a PKCS12 object from a buffer :param buffer: The buffer the certificate is stored in :param passphrase: (Optional) The password to decrypt the PKCS12 lump :returns: The PKCS12 object """""" passphrase = _text_to_bytes_and_warn(""passphrase"", passphrase) if isinstance(buffer, _text_type): buffer = buffer.encode(""ascii"") bio = _new_mem_buf(buffer) # Use null passphrase if passphrase is None or empty string. With PKCS#12 # password based encryption no password and a zero length password are two # different things, but OpenSSL implementation will try both to figure out # which one works. if not passphrase: passphrase = _ffi.NULL p12 = _lib.d2i_PKCS12_bio(bio, _ffi.NULL) if p12 == _ffi.NULL: _raise_current_error() p12 = _ffi.gc(p12, _lib.PKCS12_free) pkey = _ffi.new(""EVP_PKEY**"") cert = _ffi.new(""X509**"") cacerts = _ffi.new(""Cryptography_STACK_OF_X509**"") parse_result = _lib.PKCS12_parse(p12, passphrase, pkey, cert, cacerts) if not parse_result: _raise_current_error() cacerts = _ffi.gc(cacerts[0], _lib.sk_X509_free) # openssl 1.0.0 sometimes leaves an X509_check_private_key error in the # queue for no particular reason. This error isn't interesting to anyone # outside this function. It's not even interesting to us. Get rid of it. try: _raise_current_error() except Error: pass if pkey[0] == _ffi.NULL: pykey = None else: pykey = PKey.__new__(PKey) pykey._pkey = _ffi.gc(pkey[0], _lib.EVP_PKEY_free) if cert[0] == _ffi.NULL: pycert = None friendlyname = None else: pycert = X509._from_raw_x509_ptr(cert[0]) friendlyname_length = _ffi.new(""int*"") friendlyname_buffer = _lib.X509_alias_get0( cert[0], friendlyname_length ) friendlyname = _ffi.buffer( friendlyname_buffer, friendlyname_length[0] )[:] if friendlyname_buffer == _ffi.NULL: friendlyname = None pycacerts = [] for i in range(_lib.sk_X509_num(cacerts)): x509 = _lib.sk_X509_value(cacerts, i) pycacert = X509._from_raw_x509_ptr(x509) pycacerts.append(pycacert) if not pycacerts: pycacerts = None pkcs12 = PKCS12.__new__(PKCS12) pkcs12._pkey = pykey pkcs12._cert = pycert pkcs12._cacerts = pycacerts pkcs12._friendlyname = friendlyname return pkcs12",fix a memory leak and a potential UAF and also #722,https://github.com/pyca/pyopenssl/commit/915d1d82c0fed8c656d1104b71728c1cf9747ede,,,src/OpenSSL/crypto.py,3,py,False,2017-11-29T10:20:33Z "private boolean preventInteraction(@Nullable Island island, Location location, SuperiorPlayer superiorPlayer, EnumSet flagsSet) { boolean sendMessages = flagsSet.contains(Flag.SEND_MESSAGES); if (island == null) { if (flagsSet.contains(Flag.PREVENT_OUTSIDE_ISLANDS)) { if (!superiorPlayer.hasBypassModeEnabled() && plugin.getGrid().isIslandsWorld(superiorPlayer.getWorld())) { if (sendMessages) Message.BUILD_OUTSIDE_ISLAND.send(superiorPlayer); return true; } } return false; } if (!island.isInsideRange(location)) { if (sendMessages) Message.BUILD_OUTSIDE_ISLAND.send(superiorPlayer); return true; } if (island.isSpawn() && plugin.getSettings().getSpawn().isProtected()) { if (sendMessages) Message.PROTECTION.send(superiorPlayer); return true; } return false; }","private boolean preventInteraction(@Nullable Island island, Location location, SuperiorPlayer superiorPlayer, EnumSet flagsSet) { if (superiorPlayer.hasBypassModeEnabled()) return false; boolean sendMessages = flagsSet.contains(Flag.SEND_MESSAGES); if (island == null) { if (flagsSet.contains(Flag.PREVENT_OUTSIDE_ISLANDS)) { if (!superiorPlayer.hasBypassModeEnabled() && plugin.getGrid().isIslandsWorld(superiorPlayer.getWorld())) { if (sendMessages) Message.BUILD_OUTSIDE_ISLAND.send(superiorPlayer); return true; } } return false; } if (!island.isInsideRange(location)) { if (sendMessages) Message.BUILD_OUTSIDE_ISLAND.send(superiorPlayer); return true; } if (island.isSpawn() && plugin.getSettings().getSpawn().isProtected()) { if (sendMessages) Message.PROTECTION.send(superiorPlayer); return true; } return false; }",Fixed bypass mode not bypassing interacting with blocks (#1274),https://github.com/BG-Software-LLC/SuperiorSkyblock2/commit/a30e58083da32b2b81384f95f830b47a56771774,,,src/main/java/com/bgsoftware/superiorskyblock/listener/ProtectionListener.java,3,java,False,2022-07-21T19:58:03Z "@Inject(method = ""init"", at = @At(""RETURN"")) private void initTradeListWidget(CallbackInfo ci) { if (Configs.Toggles.VILLAGER_TRADE_FEATURES.getBooleanValue() && Configs.Generic.VILLAGER_TRADE_LIST_REMEMBER_SCROLL.getBooleanValue()) { VillagerData data = VillagerDataStorage.getInstance().getDataForLastInteractionTarget(); if (data != null) { this.indexStartOffset = data.getTradeListPosition(); } } }","@Inject(method = ""init"", at = @At(""RETURN"")) private void initTradeListWidget(CallbackInfo ci) { if (Configs.Toggles.VILLAGER_TRADE_FEATURES.getBooleanValue() && Configs.Generic.VILLAGER_TRADE_LIST_REMEMBER_SCROLL.getBooleanValue()) { VillagerData data = VillagerDataStorage.getInstance().getDataForLastInteractionTarget(); int listSize = this.handler.getRecipes().size(); if (data != null && this.canScroll(listSize)) { this.indexStartOffset = this.getClampedIndex(data.getTradeListPosition()); } } }","Fix a crash in the villager trade screen due to an OOB index Still no idea how that index happens in the first place sometimes...",https://github.com/maruohon/itemscroller/commit/1ab23589eb9b65f1204cbe1f801ec28f50ae2882,,,src/main/java/fi/dy/masa/itemscroller/mixin/MixinMerchantScreen.java,3,java,False,2022-03-01T14:50:50Z "private SSLContext getSslContext(FileInputStream trustFileStream) throws NoSuchAlgorithmException, KeyStoreException, IOException, CertificateException, KeyManagementException { TrustManagerFactory tmf = TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm()); // Using null here initialises the TMF with the default trust store. tmf.init((KeyStore) null); // Get hold of the default trust manager X509TrustManager defaultTm = null; for (TrustManager tm : tmf.getTrustManagers()) { if (tm instanceof X509TrustManager) { defaultTm = (X509TrustManager) tm; break; } } // Load the trustStore which needs to be imported KeyStore trustStore = KeyStore.getInstance(KeyStore.getDefaultType()); trustStore.load(trustFileStream, data.trustStorePassword.toCharArray()); trustFileStream.close(); tmf = TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm()); tmf.init(trustStore); // Get hold of the default trust manager X509TrustManager trustManager = null; for (TrustManager tm : tmf.getTrustManagers()) { if (tm instanceof X509TrustManager) { trustManager = (X509TrustManager) tm; break; } } final X509TrustManager finalDefaultTm = defaultTm; final X509TrustManager finalTrustManager = trustManager; X509TrustManager customTm = new X509TrustManager() { @Override public X509Certificate[] getAcceptedIssuers() { return finalDefaultTm.getAcceptedIssuers(); } @Override public void checkServerTrusted(X509Certificate[] chain, String authType) throws CertificateException { try { finalTrustManager.checkServerTrusted(chain, authType); } catch (CertificateException e) { finalDefaultTm.checkServerTrusted(chain, authType); } } @Override public void checkClientTrusted(X509Certificate[] chain, String authType) throws CertificateException { finalDefaultTm.checkClientTrusted(chain, authType); } }; SSLContext sslContext = SSLContext.getInstance(""SSL""); sslContext.init(null, new TrustManager[] { customTm }, null); return sslContext; }","private SSLContext getSslContext(FileInputStream trustFileStream) throws NoSuchAlgorithmException, KeyStoreException, IOException, CertificateException, KeyManagementException { TrustManagerFactory tmf = TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm()); // Using null here initialises the TMF with the default trust store. tmf.init((KeyStore) null); // Get hold of the default trust manager X509TrustManager defaultTm = null; for (TrustManager tm : tmf.getTrustManagers()) { if (tm instanceof X509TrustManager) { defaultTm = (X509TrustManager) tm; break; } } // Load the trustStore which needs to be imported KeyStore trustStore = KeyStore.getInstance(KeyStore.getDefaultType()); trustStore.load(trustFileStream, data.trustStorePassword.toCharArray()); trustFileStream.close(); tmf = TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm()); tmf.init(trustStore); // Get hold of the default trust manager X509TrustManager trustManager = null; for (TrustManager tm : tmf.getTrustManagers()) { if (tm instanceof X509TrustManager) { trustManager = (X509TrustManager) tm; break; } } final X509TrustManager finalDefaultTm = defaultTm; final X509TrustManager finalTrustManager = trustManager; X509TrustManager customTm = new X509TrustManager() { @Override public X509Certificate[] getAcceptedIssuers() { return finalDefaultTm.getAcceptedIssuers(); } @Override public void checkServerTrusted(X509Certificate[] chain, String authType) throws CertificateException { try { finalTrustManager.checkServerTrusted(chain, authType); } catch (CertificateException e) { finalDefaultTm.checkServerTrusted(chain, authType); } } @Override public void checkClientTrusted(X509Certificate[] chain, String authType) throws CertificateException { finalDefaultTm.checkClientTrusted(chain, authType); } }; SSLContext sslContext = SSLContext.getInstance(""TLSv1.2""); sslContext.init(null, new TrustManager[] { customTm }, null); return sslContext; }",HOP-3202 Fix Sonar vulnerability issue,https://github.com/apache/hop/commit/990e74a149363816588566b2b21619a3af8c0866,,,plugins/transforms/rest/src/main/java/org/apache/hop/pipeline/transforms/rest/Rest.java,3,java,False,2022-04-03T23:37:07Z "def install_agent(agent_key): ''' Function downloads Server Density installation agent, and installs sd-agent with agent_key. CLI Example: .. code-block:: bash salt '*' serverdensity_device.install_agent c2bbdd6689ff46282bdaa07555641498 ''' work_dir = '/tmp/' account_url = get_sd_auth('account_url') __salt__['cmd.run']( cmd='curl https://www.serverdensity.com/downloads/agent-install.sh -o install.sh', cwd=work_dir ) __salt__['cmd.run'](cmd='chmod +x install.sh', cwd=work_dir) return __salt__['cmd.run']( cmd='./install.sh -a {account_url} -k {agent_key}'.format( account_url=account_url, agent_key=agent_key), cwd=work_dir )","def install_agent(agent_key): ''' Function downloads Server Density installation agent, and installs sd-agent with agent_key. CLI Example: .. code-block:: bash salt '*' serverdensity_device.install_agent c2bbdd6689ff46282bdaa07555641498 ''' work_dir = os.path.join(__opts__['cachedir'], 'tmp') if not os.path.isdir(work_dir): os.mkdir(work_dir) install_file = tempfile.NamedTemporaryFile(dir=work_dir, suffix='.sh', delete=False) install_filename = install_file.name install_file.close() account_url = get_sd_auth('account_url') __salt__['cmd.run']( cmd='curl https://www.serverdensity.com/downloads/agent-install.sh -o {0}'.format(install_filename), cwd=work_dir ) __salt__['cmd.run'](cmd='chmod +x {0}'.format(install_filename), cwd=work_dir) return __salt__['cmd.run']( cmd='./{filename} -a {account_url} -k {agent_key}'.format( filename=install_filename, account_url=account_url, agent_key=agent_key), cwd=work_dir )",Move install.sh to cachedir for serverdensity_device,https://github.com/saltstack/salt/commit/e11298d7155e9982749483ca5538e46090caef9c,,,salt/modules/serverdensity_device.py,3,py,False,2015-03-25T20:48:56Z "protected final boolean _parseBooleanPrimitive(JsonParser p, DeserializationContext ctxt) throws IOException { String text; switch (p.currentTokenId()) { case JsonTokenId.ID_STRING: text = p.getText(); break; case JsonTokenId.ID_NUMBER_INT: // may accept ints too, (0 == false, otherwise true) // call returns `null`, Boolean.TRUE or Boolean.FALSE so: return Boolean.TRUE.equals(_coerceBooleanFromInt(p, ctxt, Boolean.TYPE)); case JsonTokenId.ID_TRUE: // usually caller should have handled but: return true; case JsonTokenId.ID_FALSE: return false; case JsonTokenId.ID_NULL: // null fine for non-primitive _verifyNullForPrimitive(ctxt); return false; // 29-Jun-2020, tatu: New! ""Scalar from Object"" (mostly for XML) case JsonTokenId.ID_START_OBJECT: text = ctxt.extractScalarFromObject(p, this, Boolean.TYPE); break; case JsonTokenId.ID_START_ARRAY: // 12-Jun-2020, tatu: For some reason calling `_deserializeFromArray()` won't work so: if (ctxt.isEnabled(DeserializationFeature.UNWRAP_SINGLE_VALUE_ARRAYS)) { p.nextToken(); final boolean parsed = _parseBooleanPrimitive(p, ctxt); _verifyEndArrayForSingle(p, ctxt); return parsed; } // fall through default: return ((Boolean) ctxt.handleUnexpectedToken(Boolean.TYPE, p)).booleanValue(); } final CoercionAction act = _checkFromStringCoercion(ctxt, text, LogicalType.Boolean, Boolean.TYPE); if (act == CoercionAction.AsNull) { _verifyNullForPrimitive(ctxt); return false; } if (act == CoercionAction.AsEmpty) { return false; } text = text.trim(); final int len = text.length(); // For [databind#1852] allow some case-insensitive matches (namely, // true/True/TRUE, false/False/FALSE if (len == 4) { if (_isTrue(text)) { return true; } } else if (len == 5) { if (_isFalse(text)) { return false; } } if (_hasTextualNull(text)) { _verifyNullForPrimitiveCoercion(ctxt, text); return false; } Boolean b = (Boolean) ctxt.handleWeirdStringValue(Boolean.TYPE, text, ""only \""true\""/\""True\""/\""TRUE\"" or \""false\""/\""False\""/\""FALSE\"" recognized""); return Boolean.TRUE.equals(b); }","protected final boolean _parseBooleanPrimitive(JsonParser p, DeserializationContext ctxt) throws IOException { String text; switch (p.currentTokenId()) { case JsonTokenId.ID_STRING: text = p.getText(); break; case JsonTokenId.ID_NUMBER_INT: // may accept ints too, (0 == false, otherwise true) // call returns `null`, Boolean.TRUE or Boolean.FALSE so: return Boolean.TRUE.equals(_coerceBooleanFromInt(p, ctxt, Boolean.TYPE)); case JsonTokenId.ID_TRUE: // usually caller should have handled but: return true; case JsonTokenId.ID_FALSE: return false; case JsonTokenId.ID_NULL: // null fine for non-primitive _verifyNullForPrimitive(ctxt); return false; // 29-Jun-2020, tatu: New! ""Scalar from Object"" (mostly for XML) case JsonTokenId.ID_START_OBJECT: text = ctxt.extractScalarFromObject(p, this, Boolean.TYPE); break; case JsonTokenId.ID_START_ARRAY: // 12-Jun-2020, tatu: For some reason calling `_deserializeFromArray()` won't work so: if (ctxt.isEnabled(DeserializationFeature.UNWRAP_SINGLE_VALUE_ARRAYS)) { if (p.nextToken() == JsonToken.START_ARRAY) { return (boolean) handleNestedArrayForSingle(p, ctxt); } final boolean parsed = _parseBooleanPrimitive(p, ctxt); _verifyEndArrayForSingle(p, ctxt); return parsed; } // fall through default: return ((Boolean) ctxt.handleUnexpectedToken(Boolean.TYPE, p)).booleanValue(); } final CoercionAction act = _checkFromStringCoercion(ctxt, text, LogicalType.Boolean, Boolean.TYPE); if (act == CoercionAction.AsNull) { _verifyNullForPrimitive(ctxt); return false; } if (act == CoercionAction.AsEmpty) { return false; } text = text.trim(); final int len = text.length(); // For [databind#1852] allow some case-insensitive matches (namely, // true/True/TRUE, false/False/FALSE if (len == 4) { if (_isTrue(text)) { return true; } } else if (len == 5) { if (_isFalse(text)) { return false; } } if (_hasTextualNull(text)) { _verifyNullForPrimitiveCoercion(ctxt, text); return false; } Boolean b = (Boolean) ctxt.handleWeirdStringValue(Boolean.TYPE, text, ""only \""true\""/\""True\""/\""TRUE\"" or \""false\""/\""False\""/\""FALSE\"" recognized""); return Boolean.TRUE.equals(b); }","update release notes wrt #3582, [CVE-2022-42004]",https://github.com/FasterXML/jackson-databind/commit/2c4a601c626f7790cad9d3c322d244e182838288,,,src/main/java/com/fasterxml/jackson/databind/deser/std/StdDeserializer.java,3,java,False,2022-10-12T01:42:40Z "@DELETE @Path(""/{version}"") int deleteSchemaVersion( @PathParam(""subject"") String subject, @PathParam(""version"") String version) throws Exception;","@DELETE @Path(""/{version}"") @Authorized(AuthorizedStyle.ArtifactOnly) int deleteSchemaVersion( @PathParam(""subject"") String subject, @PathParam(""version"") String version) throws Exception;","Implement owner-only authorization support (optional, enabled via appication.properties) (#1407) * trying to implement simple authorization using CDI interceptors * added @Authorized to appropriate methods * updated the auth test * Removed some debugging statements * Improved and applied authn/z to other APIs (v1, cncf, etc) * Fixed some issues with GroupOnly authorization * Disable the IBM API by default due to authorization issues * fix the IBM api test",https://github.com/Apicurio/apicurio-registry/commit/90a856197b104c99032163fa26c04d01465bf487,,,app/src/main/java/io/apicurio/registry/ccompat/rest/SubjectVersionsResource.java,3,java,False,2021-04-13T09:08:58Z "def on_part_data(self, data: bytes, start: int, end: int) -> None: message = (MultiPartMessage.PART_DATA, data[start:end]) self.messages.append(message)","def on_part_data(self, data: bytes, start: int, end: int) -> None: message_bytes = data[start:end] if self._current_part.file is None: self._current_part.data += message_bytes else: self._file_parts_to_write.append((self._current_part, message_bytes))","Merge pull request from GHSA-74m5-2c7w-9w3x * ♻️ Refactor multipart parser logic to support limiting max fields and files * ✨ Add support for new request.form() parameters max_files and max_fields * ✅ Add tests for limiting max fields and files in form data * 📝 Add docs about request.form() with new parameters max_files and max_fields * 📝 Update `docs/requests.md` Co-authored-by: Marcelo Trylesinski * 📝 Tweak docs for request.form() * ✏ Fix typo in `starlette/formparsers.py` Co-authored-by: Adrian Garcia Badaracco <1755071+adriangb@users.noreply.github.com> --------- Co-authored-by: Marcelo Trylesinski Co-authored-by: Adrian Garcia Badaracco <1755071+adriangb@users.noreply.github.com>",https://github.com/encode/starlette/commit/8c74c2c8dba7030154f8af18e016136bea1938fa,,,starlette/formparsers.py,3,py,False,2023-02-14T08:01:32Z "@Override public Optional currentAuthState(final HttpServletRequest request) { LOGGER.debug(""currentAuthState""); AuthStateImpl authState = getAuthState(request); // Now we can check if we're logged in somehow (session or certs) and build the response accordingly if (authState != null) { LOGGER.debug(""Has current auth state""); return Optional.of(authState); } else { loginWithCertificate(request); } return Optional.ofNullable(getAuthState(request)); }","@Override public Optional currentAuthState(final HttpServletRequest request) { LOGGER.debug(""currentAuthState""); AuthStateImpl authState = getAuthState(request); // Now we can check if we're logged in somehow (session or certs) and build the response accordingly if (authState != null) { LOGGER.debug(""Has current auth state""); return Optional.of(authState); } else if (config.isAllowCertificateAuthentication()) { LOGGER.debug(""Attempting login with certificate""); try { loginWithCertificate(request); } catch (final RuntimeException e) { LOGGER.error(e.getMessage()); } } else { LOGGER.debug(""Certificate authentication is disabled""); } return Optional.ofNullable(getAuthState(request)); }",#2142 Fix certificate authentication issues,https://github.com/gchq/stroom/commit/42762b4b0b8d85c858879374355747f5ce56a3d9,,,stroom-security/stroom-security-identity/src/main/java/stroom/security/identity/authenticate/AuthenticationServiceImpl.java,3,java,False,2021-03-26T12:27:16Z "public void suggestMissileBaseCount(Colony col, float prod) { StarSystem sys = col.starSystem(); int currBases = col.defense().missileBases(); if (empire.contacts().isEmpty() || empire.shipLab().needColonyShips) { col.defense().maxBases(max(currBases, 0)); return; } if (sys == null) // this can happen at startup col.defense().maxBases(0); /*else if (empire.sv.isAttackTarget(sys.id)) col.defense().maxBases(max(currBases, (int)(col.production()/30))); // modnar: reduce base count else if (empire.sv.isBorderSystem(sys.id)) col.defense().maxBases(max(currBases, (int)(col.production()/40))); // modnar: reduce base count*/ else col.defense().maxBases(max(currBases,0)); // ail: missile-bases are simply not worth it. }","public void suggestMissileBaseCount(Colony col, float prod) { StarSystem sys = col.starSystem(); int currBases = col.defense().missileBases(); if (empire.contacts().isEmpty() || empire.shipLab().needColonyShips) { col.defense().maxBases(max(currBases, 0)); return; } float enemyBombardDamage = 0; float enemyBc = 0; boolean allowBases = false; for(ShipFleet fl : col.starSystem().incomingFleets()) { if(fl.empire().aggressiveWith(empire.id)) { if(!empire.visibleShips().contains(fl)) continue; enemyBombardDamage += expectedBombardDamageAsIfBasesWereThere(fl, col.starSystem()); if(fl.isArmed()) enemyBc += fl.bcValue(); } } for(ShipFleet fl : col.starSystem().orbitingFleets()) { if(fl.empire().aggressiveWith(empire.id)) { if(!empire.visibleShips().contains(fl)) continue; enemyBombardDamage += expectedBombardDamageAsIfBasesWereThere(fl, col.starSystem()); if(fl.isArmed()) enemyBc += fl.bcValue(); } } //System.out.print(""\n""+empire.name()+"" ""+col.name()+"" expected bombard-Damage: ""+enemyBombardDamage+"" Bc: ""+enemyBc); if(enemyBc > 0 && enemyBombardDamage == 0) allowBases = true; if (sys == null) // this can happen at startup col.defense().maxBases(0); else if (allowBases) col.defense().maxBases(max(currBases, 1)); /* else if (empire.sv.isBorderSystem(sys.id)) col.defense().maxBases(max(currBases, (int)(col.production()/40))); // modnar: reduce base count*/ else col.defense().maxBases(max(currBases,0)); // ail: missile-bases are simply not worth it. }","Last minute fixes (#60) * Replaced many isPlayer() by isPlayerControlled() This leads to a more fluent experience on AutoPlay. Note: the council-voting acts weird when you try that there, getting you stuck, and the News-Broadcasts also seem to use a differnt logic and are always shown. * Orion-guard-handling Avoid sending colonization-fleets, when guardian is still alive Increase guardian-power-estimate to 100,000 Don't send and count bombers towards guardian-defeat-force * Fixed Crash from a report on reddit Not sure how that could happen though. Never had this issue in games started on my computer. * Fixed crash after AI defeats orion-guard Tried to access an out-of-bounds-value because it couldn't find the System where the guardian was. So looking to find the Planet with the Orionartifact now, which does find it. * All the forgotten isPlayer()-calls Including the Base- and Modnar-AI-Diplomat * Personalities now play a role in my AI once again Instead of everyone having the same conditions for war, there's now different ones. Some are more aggressive, some are less. * Fixed issue where enemy-fleets weren's seen, when they actually were. Also added a way of guessing when enemy-fleets aren't seen so it shouldn't trickle in tiny fleets that all retreat anymore in the early-game, before they can see the enemy-fleets. And also not later because they now actually can see them. * Update AIDiplomat.java * Delete ShipCombatResults.java * Delete Empire.java * Delete TradeRoute.java * Revert ""Delete TradeRoute.java"" This reverts commit 6e5c5a8604e89bb11a9a6dc63acd5b3f27194c83. * Revert ""Delete Empire.java"" This reverts commit 1a020295e05ebc735dae761f426742eb7bdc8d35. * Revert ""Delete ShipCombatResults.java"" This reverts commit 5f9287289feb666adf1aa809524973c54fbf0cd5. * Update ShipCombatResults.java reverting pull-request... manually because I don't know of a better way 8[ * Update Empire.java * Update TradeRoute.java * Merge with Master * Update TradeRoute.java * Update TradeRoute.java github editor does not allow me to remove a newline oO * AI improvements Added parameter to make the colonizer-function return just the uncolonized planets without substracting the colony-ships. Impelemented a very differnt diplomatic behavior, that supposedly is more suitable to actually winning by waging less war, particularly when big enough to be voted for. Revoked that AI doesn't adjust to enemy-troops when it has a more defensive unit-composition. In lategame going by destructive-power of bombers hasn't much merit, when 1 bombers can pack 60ish neutronium-bombs. Fixed an issue that prevented designing extended-fuel-range-colonizers asap. This once again helps expansion-speed a lot. Security now is only spent against empires actually in range to spy, as it was intended. Contact via council should not increase paranoia. Also Xenophobic-extra-paranoia removed. * Update OrionGuardianShip.java * War-declaration behavior Electible faction will no longer declare war on someone who is at war with the other electible faction. * Fix zero-division on refreshing a trade-route that had been adjusted due to empire-shrinkage. * AI & Bugfix Leader-stuff is now overridden Should now retreat against repulsors, when no counter available Tech-nullifier hit and miss mixup fixed * AI improvements Fixed a rare crash in AutoPlay-Mode Massive overhaul of AI-ship-design Spy master now more catious about avoiding unwanted, dangerous wars due to spying on the wrong people Colony-ship-designs now will only get a weapon, if this doesn't prevent reserve-tanks or reducing their size to medium Fixed an issue where ai wouldn't retreat from ships with repulsor-beam that exploited their range-advantage Increased research-value of cloaking-tech and battle-suits Upon reaching tech-level 99 in every field, AI will produce ships non-stop even in peace-time AI will now retreat fleets from empires it doesn't want to go to war with in order to avoid trespassing-issues Fixed issue where the AI wanted to but couldn't colonize orion before it was cleared and then wouldn't colonize other systems in that time AI will no longer break non-aggression-pacts when it still has a war with someone else AI will only begin wars because of spying, if it actually feels comfortable dealing with the person who spied on them AI will now try and predict whether it will be attacked soon and enact preventive measures * Tackling some combat-issue Skipping specials when it comes to determining optimal-range. Otherwise ships with long-range-specials like warp-dissipator would never close in on their prey. Resetting the selectedWeaponIndex upon reload to consistency start with same weapons every turn. Writing new attack-method that allows to skip certain weapons like for example repulsor-beam at the beginning of the turn and fire them at the end instead. * Update NewShipTemplate.java Fixed incorrect operator ""-="" instead of ""=-"", that prevented weapons being used at all when no weapon that is strong enough for theorethical best enemy shield could be found. Also when range is required an not fitting beam can be found try missiles and when no fitting missile can be found either, try short-range weapon. Should still be better than nothing. * Diplomacy and Ship-Building Reduced suicidal tendencies. No more war-declarations against wastly superior enemies. At most they ought to be 25% stronger. Voting behavior is now deterministic. No more votes based on fear, only on who they actually like and only for those whom they have real-contact. Ship-construction is now based on relative-productivity rather than using a hard cut-off for anything lower than standard-resources. So when the empire only has poor-systems it will try to build at least a few ships still. * Orion prevented war Fixed an issue, where wanting to build a colonizer for Orion prevented wars. * Update AIGeneral.java Don't invade unless you have something in orbit. * Update AIFleetCommander.java No longer using hyperspace-communications... for now. (it produced unintentional results and error-messages) * AI improvements corrected typo in Stellar Converter Fixed trading for techs that have no value by taking the random modifier into account No longer agreeing to or offering alliances Added sophisticated behavior when it comes to offering and agreeing to joint wars Ignore existence of council in diplomatic behavior No longer needing to have positive relations for council vote, the lesser evil is good enough Improved the selection at which planets ships are being built, this time really improved rather than probably making it worse than before No longer using extended fuel-tanks when unlimited-range-tech is researched Avoid designing bombers that can overkill a planet single-handedly, instead replace part of the bombs with other weapons Scoring adjustments for special-devices, primarily no longer taking space into account for score as otherwise miniaturization would always lead to always using the old, weak specials * AI-improvements and combat-estimated fixes No longer wanting to do a NAP with preferred target Divide score for target by 3 if nap is in place, so nap now is really usefull to have with Empires outside of trading range will no longer offer joint wars Logic for whether to declare war on somone who spied on them is now same as if they were their best victim. This prevents suicidal anti-spy-wars. Prevention-war will now also be started upon invasions No longer setting retreat on arrival, as preemtively retreating may prevent retargetting something else, especially important for colony-ships early on Retreats are now also handled after the fleet-manager had the chance to do something else with these ships reduced the percentage of bombers that will be built by about half. So it can't go over 50% anymore and usually will be even lower Fixed an issue with incorrect kill-percentage estimates. After that fix the Valuefactor, which had some correcting attributes, was no longer needed and thus removed. Made sure that bombers are always designed to actually have bombs. Invaders with surrenderOnArrival are no longer considered a threat * AI and damage-simulation-stuff No longer bombing colonies of someone who isn't my enemy Asking others to join a war, when our opponent is stronger than us Agreeing to join-war request when not busy otherwise, together we'd be stronger and the asked-for-faction is our primary target anyways Restricted war over espionage even more, to only do it if we feel ready. Much better to share a few techs than to die. Wars for strategic reasons can now once again be cancelled. Doing a cost:gain-analysis for invasions, that is much more likely to invade, especially if we have previously been invaded and the planet has factories from us. It also takes the savings of not having to build a colony-ship into account. Further reduced the overkill for invasions. We want to do more of them when they are cost-efficient but still not waste our population. More planets will participate in the construction of colony-ships. When we are at war or have others in our range during the phase where we want to churn out colony-ships, we mix in combat-ships to make us less of a juicy target and be able to repel sneak-attacks better. Hostile-planets now get more population sent to. Stacks of strong individual ships about to die in combat, will consider their lessened chances of survival and may now retreat when damaged too much. Reverted change in method that I don't use anyways. Fixed shield-halving-properties of weapons like neutron-pellet-guns not being taken into account in combat-simulations using the firepower-method. Fixed bombers estimating the whole stack sharing a single bomb, which dramatically underestimated the firepower they had. * Mostly things about research Fixed that studyingFutureTech() always returned false. Fixed issue with having more research-allocation-points than possible in base- and modnar-AI when redistributing research-points to avoid researching future techs before other techs are researched Inclusion of faction-specific espionage-replies Maximum ship-maintenance now capped at 45% (5*warp-speed) before all techs are researched, then it is doubled to 90% More bombers will be built when opponents use missile-bases a lot When under siege by enemy bombers will no longer build factories but either population, ships or research depending on how destructive the bombardment is. This is to avoid investing into something that will be lost or not finished anyways. Future techs are now considered lower priority than all non-obsolete techs. Fixed missing override of baseValue for future-techs No longer allocating RP to techs which have a higher percentage to be researched next turn than the percentage of RP attributed to them. This should increase research-output slightly. Ship-stacks that have colony-ships in their fleet will no longer be much more ready to retreat because they consider the low survivability of colony-ships as a threat to themselves. Colony-ships may retreat alone, but won't always do so either. Retreat threshold is now always 1.0, meaning if they think they can win, they will stay, even if the losses equal their own kills. Allowed treasurer to gather taxes in order to save planets from nova or plague. * Making the AI even tougher Will now go to war at 75% development rather than 100%. So much more aggressive with much fewer and shorter periods of peace. Will no longer offer or agree to a peace-treaty, when it has ongoing invasions. Maximum-ship-maintenance-percentage now is a root-function of tech-level that's steeper early on and smoothes out later. During peace-time will now gather ships at centralized locations for better responsiveness. Will no longer stage an attack on the orion-guardian while having enemies. Siege-fleets will no longer wait for transports to land before doing something else. Reduced the superiority-aim for combats to 2, down from 4 to allow more simultaneous missions. When a system where ships are gathered has incoming enemy fleets, this no longer prevents the ships from going to other missions until the attacks are over, which had allowed a theoretical exploit where you could keep sending tiny fleets to make the AI not move their fleets. Instead they now substract the exact amount they think they need to defend from the ships that they can send away. Stopping to make more ships when in possession of more than 4 times the amount of all enemies combined. Making more ships when non-enemy-neigbours build more ships. Aiming for at least 1/4th of that what our strongest non-enemy-neighbor has. Decreased the importance of income of a planet to determine how usefull it is for production. No resource-bonuses are more important for that. Fixed issues with tech-slider-management caused by upcomingDiscoverChance looking at the forecast of RP that will be added rather than the RP spent at the time it is called. When only future-techs are left to research, the allocations will be shifted in a way to heavily favor propulsion and weapons as those generate by far the greatest miniaturization-benefits. No longer overestimate combat-efficiency against enemy colony-ships by counting it as a kill for each individual stack. Avoid scrapping when we still have enemies rather than just when being at war. Now taking only 3 instead of 5 colonies into account when making the decision what hull-sizes to use. This delays the usage of huge hulls further into the late-game and is meant to avoid scenarios like there's only being 2 huge bombers for 5 enemy-colonies instead of 12 large ones. The AI you watch in Autoplay-mode no longer receives difficulty-bonuses. This means you can now let it play against harder difficulty-levels. * Update Colony.java Waste-modifier for autoplay against easier-difficulty-levels was wrong. * Fixes Fixed possible crash in combat-outcome-estimation. Fixed ai-waste-modifier for below normal-difficulty-levels to be applied to the waste-generation rather than the cleanup-cost. * AI performance Instead of iterating through a triple-nestes-loop of fleets, systems and fleets, the inner loop is now buffered so that in consecutive calls there's a lot less to process. This significantly improves turn-times. Colonizers with extended range can now be sent to colonize something when they are in a fleet that otherwise couldn't travel so far. Removed unused code from AIGeneral. AIShipCaptain is now thread-save due to no longer manipulating stack and instead strong the target in their own local member-variable. Specials are now properly used in the right order. All specials except repulsor-beam and stasis-field are now cast before the other weapons. Now fleeing from ship with repulsor if our optimal-range is outranged, not just our maximum-range. Also now considering that the repulsor-stack can protect more than itself (up to 3 more stacks when they are in a corner). Will now design and use huge colonizers when stranded in a constellation that otherwise can't be escaped. The logic to determine that might still be a little flawed, though. Repulsor now will be countered even if it is only researched and not installed in a ship yet since only reacting once it's seen could be too late. Made shipComonentCanAttack public for improved logic in attacking. Included fix from /u/albertinix that caused a crash when hitting pause in auto-combat. UncolonizedPlanetsInRange-Methods in empire.java now actually only return uncolonized planets. Fixed an issue where shield-reduction would be applied twice in combat-simulation. Capped the amount of estimated kills at the amount of targets destroyed. * Update AIFleetCommander.java Increased colonization-bonus for unlockig additional systems. * Update AIFleetCommander.java doubled the score-increase on unexplored. * Fixes and imrpvements Fixed possible double-colonization by two AIs arriving at a system in the same turn. Reenabled the usage of Hyperspace-communications. IncomingBc and Bombard-damage are now updated directly in the Hash for referencing during the same turn. Taught AI to situationally utilize huge hulls for colonizers with extended range. Techs with 0 value now actually return 0 value rather than 0 + random() More aggressive use of espionage. * Blackhole-fixes Fixed an issue that stacks killed by Blackhole-Generator only die in combat but are still alive afterwards. Fixed an issue that Blackhole-Generator would always kill at least one ship, even if it rolled low. It now can miss when the amount of enemy ships is smaller than the percentage it rolls to kill. Fixed how damage of blackhole-generator was shown as the percentage of the hitpoints of the ships rather than the total hitpoints of all ships it killed. * Update CombatStackShip.java Fixed an issue where either the target being a colony or the presence of ground-attack-only-weapons would return a preferred range of 1 rather than the combination of the two. * AI improvements No longer breaking trade-treaty with war-target to avoid giving a warning that could be used to prepare. Fixed crash related to sorting a list with random values that could change during the lifetime of the list. That random wasn't overly useful anyways. Autoresolve will no longer ignore repulsors (but only for Xilmi-AI so far). Ships will now always try to come as close as they can before shooting as a means to increase hit-chance, use short-range-specials or make it harder to dodge missiles. Added back the value of the participants for retreat-decisions, because otherwise a clearly won battle could be given up because it was slighlty cost-inefficient. No longer always countering repulsors just because someone could use them. Instead now looking at whether they are actually in use before the decision is made. * Missile-Base & Scatter-Pack Fixed that the selection which missile-type to shoot from a missile-base had no impect. Implemented automatic-selection of better missile-type in case of auto-resolve and for AIs to use. Fixed that scatter-attacks weren't taken into account in firepower-estimation. * Fix for ETA-bug when travel through nebula For a fleet that already is in transit and has a destination the ETA is now taken from the ETA set at the begining of the journey rather than recalculated from it's current position. * Update AIGovernor.java Now taking into account that building factories scales with mineral-richness, whereas building population doesn't. The result is that most races now will prefer maxing population before factories on poor and ultra-poor. * Revert ""Fix for ETA-bug when travel through nebula"" This reverts commit c67b38203313d9d57aa07f53d7cffd67c344e16d. * Update ShipFleet.java Fix for ETA-bug again but without the redirect-rallied-fleet-exploit. * Tiny change No longer blocking the slot that is reserved for scouts once large-sized colonizers with extended fuel-tanks are available. * Hybrid AI Added another option for AI: Hybrid, which uses Diplomacy- and Espionage-modules from Modnar and the rest from Xilmi. Kill-percentage no longer modified by hitpoints as hitpoints now are seperately considered. Allowed designing Huge colonizers under, hopefully the right, circumstances. * Update GroundBattleUI.java Fixed wrong animation playing for defenders in ground combat, that caused them to die over and over instead of firing their weapon and dying only once! * Update NewShipTemplate.java Keep bombers smaller for longer. * Some non-ai-fixes Production is now capped at 0 at the lower end, to no longer allow weird side-effects of negative production-output. Fixed Defense and Industry-texts to show ""None"", when there's no production. SpyConfessionIncident now looks at leaderHatesAllSpies, which is different between AIs and same as before for default-AI. * AI improvements No more autopeace for humans. No longer participating in non-aggression-pacts. No longer complaining/asking for spies to be removed as those requests usually weren't followed up with from my AI anyways. Always ignore when asked to do anything. War weariness only takes factories and colonies into account and isn't different according to leader-personality anymore. Should result in fewer peace-treaties if one side is dominating as they don't condier it a problem to lose population during invasions, only if the opponent actually fights back. Fixed that using gather-points wasn't working. Now firing before moving if the target we want to move towards is far away. No longer retreat the whole fleet if only a part of the fleet can't counter repulsors. Enforce immediate new design to counter repulsors when someone starts using them. * GitIgnore-Test This should just include a change to AI name and reversal of an attempt to a bugfix, which caused an unintended side-effect. If it also includes the artwork-mod, then gitignore doesn't work like I think it should. * Revert ""GitIgnore-Test"" This reverts commit 49600932a25dbfa19dd6aca411c7df0e94513505. * Change AI-name and revert fix cause of side-effects Side-effects were that an AI fleet teleported once. * Update AIShipCaptain.java Thanks to bot39lvl's relentless testing a bug in target-selection was fixed. * Update CombatStackColony.java Consider the damage of scatter-packs in combat-outcome-estimation * Update Empire.java Fixed crash upon a faction being eliminated. * Update AIFleetCommander.java Strategical-map improvements to attack more decisively and take into account that conquering a system will allow more systems to be attacked. * Update AIFleetCommander.java Only gather at enemy-colonies when there's an actual war, not yet during preparations. * Update AIFleetCommander.java Now treating enemy ships and enemy-missile bases seperately when it comes to calculating how much to send. This should lead to bigger attacking-fleets in cases where the defense consists of only ships. * Update AIFleetCommander.java Fixed newly introduced issue that prevented colonizing. * 0.92 findings Less aggressive early on but more aggressive if cornered. Lots of fixes and improvements about staging-points, gather-points and colony-ship-usage. Now only building the exact amount of colonizers that is wanted instead of build colonizers for so long until I have more than I want, which had the potential to heavily overshoot. Using fewer scouts early on. Ships should now skip their move when they have pushed away someone with repulsors and still can move. (untested because situation hasn't come up yet and I lost the save where it happened) * Some fixes/improvements reduced warp-speed-requirement for war attempted fix for redirected retreating ship-cheat taking mrrshan and alkari-racial into account when determining attack-fleet-size-requirements no longer bolstering systems that are under siege by an enemy fire before retreating in combat if possible avoid overestimating damage by taking maximum hit-chance into account for damage-predictions * Update AIShipCaptain.java Moving away from enemy ships after firing. * Smarter ship-commander No longer automatically becoming war-weary when behind in tech Now moving away from enemies after firing when still movementpoints left Now sticking near planet when defending and only start moving towards opponent, when first-hit can be achieved * Small fixes as wrapup for test-release. Fixed an issue with scout-production that was present in all AIs and caused by a discrepancy between the trave-time-calculations with and without considering nebulae. During war no handling pirates or a comet has lower priority. Fixed an issue where there was missing just one tick for finishing colony-ships, which led them to be delayed until factories where all built despite having started their production early. Fixed crash that happened in combination with the new defensive behavior. * Tweaks Tweaked the gather-point-calculations Reverted the cuddling with the planet while defending because it was more exploitable than beneficial * some more minor tweaks Using base-value in tech-trade rather than the tech's level. (needs testing) Calling optimalStagingPoint with a 1 instead of the fleet's speed to avoid different speed-fleets going to different staging-points. Starting to build ships also when someone else can reach us, not only when we can reach them. Tactical target-selection now simply goes for doing the most damage measured in BC. Sabotage now almost prefers rebellion as that is by far the most disruptive. * Update AISpyMaster.java I consider espionage and sabotage against darloks a bit of a fruitless endevour. * UI stuff Slight tweak to research-slider-allocation-management. Transports that are being sent this turn now are represented by negative pop-growth in the colony-screen. Fixed an issue where colony-screen would not have the system that was clicked on the main-screen preselected. * Update AIDiplomat.java Include Ray's improvements to AI-tech-trading. * Update AIDiplomat.java Including Ray's tech-trading-improvements. Tweaks to war-declaration-logic. * Update AIFleetCommander.java New smarth-pathing-algorithm implemented. It makes AI-fleets take stops instead of flying directly to the destination. * Update AIScientist.java Reverted recent change about when to stop allocating into a category and made some tiny tweaks to initial allocations. * Update AIShipDesigner.java Prevented two rare but possible lock-ups regarding scrapping all designs and fixed an issue where a weaponless-design would not be scrapped. * Update AISpyMaster.java No longer inciting rebellions on opponents not at war with. * Update NewShipTemplate.java Fixed an issue that allowed weaponless designs to be made. * Update ShipFleet.java Fixed an issue with incorrect display of ETA when fleet passed nebula or slower ships were scrapped during the travel. * Update Empire.java Fix for ships can't see other ships at 0 range after scanner-rework. * Update AIFleetCommander.java Fixed that buffering had broken hyperspace-communication-usage. Removed a previous change about overestimating how much to send to a colony. * Update AIDiplomat.java Preparations for how alliances could work. But afterall commented out because it just doesn't feel right. * Update AIDiplomat.java Hostility now impacts readyness for war and alliances. * Update AIFleetCommander.java Now giving cover to ongoing invasions * Update AIScientist.java Adjusted values of a bunch of techs. * Update AIShipCaptain.java Fixed accidental removal of range-adjustment in new target-selection-formula and removed unused code. * Update NewShipTemplate.java Allowing missiles to be used again under certain circumstances, taking ECM into account and basing weapon-decision on actual shield-levels rather than best possible. * Update TechMissileWeapon.java Fixed that 2-rack-missiles didn't have +1 speed as they should have according to official strategy-guide. * Update AIScientist.java Tech-Slider-Allocations now depend on racial-bonuses, not leader-personality. * Immersive Xilmi-AI When set to AI: Selectable, the Xilmi AI now goes in immersive-mode, once again making numerous uses of leader-traits. * Update CombatStackColony.java Fixed a bug, that planets without missile-bases always absorbed damage as if they already had a shield-built, even if they had none and even if they were in a nebula. * Tactical combat improvements Can now detect when someone protects another stack with repulsor-beams and retreats, when it cannot counter it with long-range-weapons. Optimal range for firing missiles increased by repulsor-radius so missile-ships won't be affected by the can't counter repulsors-detection. Missiles will now be held back until getting closer to prevent target from dodging them easily. Unused specials like Repulsor will no longer prevent ships from kiting. * Update AIShipCaptain.java Only kite when there's either repulsor-beam or missile-weapons installed on the ship. * Update AIFleetCommander.java Defending is only half as desirable as attacking now. * Immersive Xilmi-AI Lot's of changes for the personality-mode of Xilmi-AI. * Update DiplomaticEmbassy.java Fix for one empire still holding a grudge against the other when signing a peace-treaty. * Update AIShipCaptain.java Somehow the Xilmi-AI must have had conquered a system with a missile-base on it against another type of AI and then crashed at this place, I didn't even think it would get to for a colony. * Update AISpyMaster.java No longer consider computer-advantage for how much to spend into counter-espionage. * Race-fitting-playstyles implemented and leader-specfic-self-restrictions removed. * Update AIGeneral.java Invader-AI back to normal victim-selection. * Update AIGovernor.java Turns out espionage didn't work like I thought it would. So Darlok just building ships and relying on stealing techs was a bad idea. (You can only steal techs below your highest level in any given tree!) * Update AIDiplomat.java Fixed issue where AI wouldn't allow the player to ask for tech-trades and where they would take deals that are horrible for themselves when trading with other AIs. Trades are now usually all done within a 66%-150% tech-cost-range. * Update AIGeneral.java Giving themselves a personality/objective-combination that fits their behavior. * Update AIDiplomat.java Tech exchange only will work within same tier now. * Update AIGeneral.java Removed setting of personalities as this causes issue with missing texts. * Update AIScientist.java Fixed issue for Silicoids trading for Eco-restoration-techs. * Update ColonyDefense.java * Update ColonyDefense.java Shield will now only be built automatically under the following circumstances: There's missile-bases existing There's missile-bases needing to be upgraded There's missile-bases to be built * Update AIDiplomat.java Avoid false positives in war-declaration for incoming fleets when the system in question was only recently colonized. * Update AIShipCaptain.java Fixed a rare but not impossible crash. * Update AIDiplomat.java No longer accept joint-war-proposals from empires we like less than who they propose as victim. * Update AIGovernor.java Now building missile-bases... under very specific and rare circumstances. * Update AIShipCaptain.java Fixed crash when handling missile-bases. Individual stacks that can't find a target to attack no longer automatically retreat and instead let their behavior be governed by whether the whole fleet would want to retreat. * Update ColonyDefense.java Reverted previous changes which also happened to prevent AI from building shields. Co-authored-by: rayfowler <58891984+rayfowler@users.noreply.github.com>",https://github.com/rayfowler/rotp-public/commit/c9d757373aee0415529e0959c1382a81baa42a33,,,src/rotp/model/ai/xilmi/AIGovernor.java,3,java,False,2021-06-01T15:58:07Z "private void addDayset(String setName, Iterable values) { Set dayset = new HashSet<>(); for (Object day : values) { dayset.add(DayOfWeek.valueOf(day.toString().trim().toUpperCase())); } daysets.put(setName, dayset); }","private void addDayset(String setName, Iterable values) { Set dayset = new HashSet<>(); for (Object day : values) { // fix illegal entries by stripping all non A-Z characters String dayString = day.toString().toUpperCase().replaceAll(""[^A-Z]"", """"); dayset.add(DayOfWeek.valueOf(dayString)); } daysets.put(setName, dayset); }","Fix EphemerisManager crashing on invalid configuration (#2949) It has been reported in the past (and in the forum) that the EphemerisManagerImpl can't handle illegal configurations. Due to dependencies in other bundles this results in the whole automation component to be unavailable. Signed-off-by: Jan N. Klug ",https://github.com/openhab/openhab-core/commit/de1f850e102947e33caf99f75a9dbf349264c0de,,,bundles/org.openhab.core.ephemeris/src/main/java/org/openhab/core/ephemeris/internal/EphemerisManagerImpl.java,3,java,False,2022-05-05T19:25:30Z "@EventHandler public void onWorldInit(WorldInitEvent event) { World world = event.getWorld(); for (MagicWorld notifyWorld : magicWorlds.values()) { notifyWorld.onWorldInit(world); } MagicWorld magicWorld = magicWorlds.get(world.getName()); if (magicWorld == null) return; controller.info(""Initializing world "" + world.getName()); magicWorld.installPopulators(world); }","@EventHandler public void onWorldInit(WorldInitEvent event) { World world = event.getWorld(); if (removeInvalidEntities) { BlockPopulator populator = CompatibilityLib.getCompatibilityUtils().createOutOfBoundsPopulator(controller.getLogger()); if (populator != null) { world.getPopulators().add(populator); } } for (MagicWorld notifyWorld : magicWorlds.values()) { notifyWorld.onWorldInit(world); } MagicWorld magicWorld = magicWorlds.get(world.getName()); if (magicWorld == null) return; controller.info(""Initializing world "" + world.getName()); magicWorld.installPopulators(world); }",Add remove_invalid_entities option to fix server crashing,https://github.com/elBukkit/MagicPlugin/commit/6fe255b2646e6d092d623a603470c5ab53253b32,,,Magic/src/main/java/com/elmakers/mine/bukkit/world/WorldController.java,3,java,False,2022-01-28T17:22:58Z "@Packet public void onFlying(WrappedInFlyingPacket packet) { if(packet.isPos() && data.playerInfo.deltaXZ > 0) { double predXZ = Math.hypot(data.predictionService.predX, data.predictionService.predZ); if(data.predictionService.flag && data.playerInfo.soulSandTimer.isPassed(10) && !data.playerInfo.generalCancel && !data.playerInfo.serverPos && !data.playerInfo.doingTeleport && data.playerInfo.deltaXZ > predXZ && !data.blockInfo.collidesHorizontally) { if(++buffer > 15) { vl++; flag(""deltaX=%s deltaZ=%s"", MathUtils.round(data.playerInfo.deltaXZ, 3), MathUtils.round(predXZ, 3)); } } else buffer-= buffer > 0 ? 1.25 : 0; debug(""(dy=%.4f) dxz=%.5f pxz=%.5f friction=%.4f key=%s collided=%s"", data.playerInfo.deltaY, data.playerInfo.deltaXZ, predXZ, data.blockInfo.fromFriction, data.predictionService.key, data.blockInfo.collidesHorizontally); } }","@Packet public void onFlying(WrappedInFlyingPacket packet) { if(packet.isPos() && data.playerInfo.deltaXZ > 0) { double predXZ = Math.hypot(data.predictionService.predX, data.predictionService.predZ); if(data.predictionService.flag && data.playerInfo.soulSandTimer.isPassed(10) && data.playerInfo.lastVelocity.isPassed(5) && !data.playerInfo.generalCancel && !data.playerInfo.serverPos && !data.playerInfo.doingTeleport && data.playerInfo.deltaXZ > predXZ && !data.blockInfo.collidesHorizontally) { if(++buffer > 15) { vl++; flag(""deltaX=%s deltaZ=%s"", MathUtils.round(data.playerInfo.deltaXZ, 3), MathUtils.round(predXZ, 3)); } } else buffer-= buffer > 0 ? 1.25 : 0; debug(""(dy=%.4f) dxz=%.5f pxz=%.5f friction=%.4f key=%s collided=%s"", data.playerInfo.deltaY, data.playerInfo.deltaXZ, predXZ, data.blockInfo.fromFriction, data.predictionService.key, data.blockInfo.collidesHorizontally); } }",Update AimE.java,https://github.com/funkemunky/Kauri/commit/5b1d3be4df6cc73cf956432ba680ab92ecec73af,,,Premium/src/main/java/dev/brighten/anticheat/premium/impl/Motion.java,3,java,False,2021-05-31T16:00:45Z "@Override public void onAnimationStart(Animator animation) { if (startListener != null) { startListener.run(); } mAnimatableIcon.start(); }","@Override public void onAnimationStart(Animator animation) { if (startListener != null) { startListener.run(); } try { mAnimatableIcon.start(); } catch (Exception ex) { Log.e(TAG, ""Error while running the splash screen animated icon"", ex); animation.cancel(); } }","Catch exception when parsing faulty AVD If an application uses an animated vector drawable for its splashsreen but the files generates an error (like a target not found for the animation), we catch it and log it instead of crashing sysui Test: manual, created an AVD with a tag referencing a non exising group in the dawable Fixes: 201274348 Change-Id: Ia195b8a626ed4bcad41ffad0e05871b5a632c8df",https://github.com/omnirom/android_frameworks_base/commit/bb8c33e73e0389ac23e1c24b08f4e82d54532fdc,,,libs/WindowManager/Shell/src/com/android/wm/shell/startingsurface/SplashscreenIconDrawableFactory.java,3,java,False,2021-09-29T12:05:46Z "public static boolean sendError(final HttpServletResponse resp, final int statusCode, final String message) throws IOException { boolean retVal = false; if (!resp.isCommitted()) { resp.sendError(statusCode, message); retVal = true; } return retVal; }","public static boolean sendError(final HttpServletResponse resp, final int statusCode, final String message) throws IOException { boolean retVal = false; if (!resp.isCommitted()) { resp.sendError(statusCode, StringEscapeUtils.escapeHtml4(message)); retVal = true; } return retVal; }",spotbugs: remove sha1,https://github.com/JumpMind/symmetric-ds/commit/e7e1ef16fb00b280e195a82403a4bb68afd4cf1b,,,symmetric-server/src/main/java/org/jumpmind/symmetric/web/ServletUtils.java,3,java,False,2021-05-10T18:47:03Z "public final boolean shouldFilterApplication(@NonNull SharedUserSetting sus, int callingUid, int userId) { boolean filterApp = true; final ArraySet packageStates = (ArraySet) sus.getPackageStates(); for (int index = packageStates.size() - 1; index >= 0 && filterApp; index--) { filterApp &= shouldFilterApplication(packageStates.valueAt(index), callingUid, /* component */ null, TYPE_UNKNOWN, userId); } return filterApp; }","public final boolean shouldFilterApplication(@NonNull SharedUserSetting sus, int callingUid, int userId) { boolean filterApp = true; final ArraySet packageStates = (ArraySet) sus.getPackageStates(); for (int index = packageStates.size() - 1; index >= 0 && filterApp; index--) { filterApp &= shouldFilterApplication(packageStates.valueAt(index), callingUid, null /* component */, TYPE_UNKNOWN, userId, false /* filterUninstall */); } return filterApp; }","Add filtering uninstalled package flag to the shouldFilterApplication A lot of APIs in PackageManager return different results between an unknown package and the package that is uninstalled in the current user. An app can detect package's existence via this side-channel leakage. To fix these issues, this CL adds an extra flag to the shouldFilterApplication() to support filtering uninstalled package. APIs with the vulnerability can enable the flag when they invoke application access filtering. (The fixes for those APIs are separated into other CLs.) Bug: 214394643 Test: atest AppEnumerationTests Change-Id: I2875765b631c247539955c1d5dc864798e54896c",https://github.com/LineageOS/android_frameworks_base/commit/c13b9153175f77d6a2bfe59940455e7355f3bb53,,,services/core/java/com/android/server/pm/ComputerEngine.java,3,java,False,2022-04-15T06:55:36Z "private NodeDescription convert(org.eclipse.sirius.web.view.NodeDescription viewNodeDescription) { // @formatter:off // Convert our children first, we need their converted values to build our NodeDescription var childNodeDescriptions = viewNodeDescription.getChildrenDescriptions().stream() .map(subNodeDescription -> this.convert(viewNodeDescription)) .collect(Collectors.toList()); // @formatter:on SynchronizationPolicy synchronizationPolicy = SynchronizationPolicy.UNSYNCHRONIZED; if (viewNodeDescription.getCreationMode() == Mode.AUTO) { synchronizationPolicy = SynchronizationPolicy.SYNCHRONIZED; } final String nodeType; if (viewNodeDescription.getStyle().getShape() == null) { nodeType = NodeType.NODE_RECTANGLE; } else { nodeType = NodeType.NODE_IMAGE; } // @formatter:off NodeDescription result = NodeDescription.newNodeDescription(this.idProvider.apply(viewNodeDescription)) .targetObjectIdProvider(this.semanticTargetIdProvider) .targetObjectKindProvider(this.semanticTargetKindProvider) .targetObjectLabelProvider(this.semanticTargetLabelProvider) .semanticElementsProvider(this.getSemanticElementsProvider(viewNodeDescription)) .synchronizationPolicy(synchronizationPolicy) .typeProvider(variableManager -> nodeType) .labelDescription(this.getLabelDescription(viewNodeDescription)) .styleProvider(variableManager -> { String shapeId = viewNodeDescription.getStyle().getShape(); String shapeFileName = this.customImagesService.findById(UUID.fromString(shapeId)).map(CustomImage::getFileName).orElse(DEFAULT_SHAPE_FILE); return this.stylesFactory.createNodeStyle(viewNodeDescription.getStyle().getColor(), shapeFileName); }) .childNodeDescriptions(childNodeDescriptions) .borderNodeDescriptions(List.of()) .sizeProvider(variableManager -> Size.UNDEFINED) .labelEditHandler(this.canonicalBehaviors::editLabel) .deleteHandler(this.canonicalBehaviors::deleteElement) .build(); // @formatter:on this.convertedNodes.put(viewNodeDescription, result); return result; }","private NodeDescription convert(org.eclipse.sirius.web.view.NodeDescription viewNodeDescription) { // @formatter:off // Convert our children first, we need their converted values to build our NodeDescription var childNodeDescriptions = viewNodeDescription.getChildrenDescriptions().stream() .map(this::convert) .collect(Collectors.toList()); // @formatter:on SynchronizationPolicy synchronizationPolicy = SynchronizationPolicy.UNSYNCHRONIZED; if (viewNodeDescription.getCreationMode() == Mode.AUTO) { synchronizationPolicy = SynchronizationPolicy.SYNCHRONIZED; } final String nodeType; if (viewNodeDescription.getStyle().getShape() == null) { nodeType = NodeType.NODE_RECTANGLE; } else { nodeType = NodeType.NODE_IMAGE; } // @formatter:off NodeDescription result = NodeDescription.newNodeDescription(this.idProvider.apply(viewNodeDescription)) .targetObjectIdProvider(this.semanticTargetIdProvider) .targetObjectKindProvider(this.semanticTargetKindProvider) .targetObjectLabelProvider(this.semanticTargetLabelProvider) .semanticElementsProvider(this.getSemanticElementsProvider(viewNodeDescription)) .synchronizationPolicy(synchronizationPolicy) .typeProvider(variableManager -> nodeType) .labelDescription(this.getLabelDescription(viewNodeDescription)) .styleProvider(variableManager -> { String shapeId = viewNodeDescription.getStyle().getShape(); String shapeFileName = this.customImagesService.findById(UUID.fromString(shapeId)).map(CustomImage::getFileName).orElse(DEFAULT_SHAPE_FILE); return this.stylesFactory.createNodeStyle(viewNodeDescription.getStyle().getColor(), shapeFileName); }) .childNodeDescriptions(childNodeDescriptions) .borderNodeDescriptions(List.of()) .sizeProvider(variableManager -> Size.UNDEFINED) .labelEditHandler(this.canonicalBehaviors::editLabel) .deleteHandler(this.canonicalBehaviors::deleteElement) .build(); // @formatter:on this.convertedNodes.put(viewNodeDescription, result); return result; }","[243] Fix stack overflow when converting View definitions with sub-nodes Bug: https://github.com/eclipse-sirius/sirius-components/issues/243 Signed-off-by: Pierre-Charles David ",https://github.com/eclipse-sirius/sirius-web/commit/034153ab4de3fd9b3c4204e800f83ac6096a4fb5,,,backend/sirius-web-emf/src/main/java/org/eclipse/sirius/web/emf/view/ViewConverter.java,3,java,False,2021-05-05T14:46:34Z "def _on_ssl_errors(self, error): self._has_ssl_errors = True url = error.url() log.webview.debug(""Certificate error: {}"".format(error)) if error.is_overridable(): error.ignore = shared.ignore_certificate_errors( url, [error], abort_on=[self.abort_questions]) else: log.webview.error(""Non-overridable certificate error: "" ""{}"".format(error)) log.webview.debug(""ignore {}, URL {}, requested {}"".format( error.ignore, url, self.url(requested=True))) # WORKAROUND for https://bugreports.qt.io/browse/QTBUG-56207 show_cert_error = ( not qtutils.version_check('5.9') and not error.ignore ) # WORKAROUND for https://codereview.qt-project.org/c/qt/qtwebengine/+/270556 show_non_overr_cert_error = ( not error.is_overridable() and ( # Affected Qt versions: # 5.13 before 5.13.2 # 5.12 before 5.12.6 # < 5.12 (qtutils.version_check('5.13') and not qtutils.version_check('5.13.2')) or (qtutils.version_check('5.12') and not qtutils.version_check('5.12.6')) or not qtutils.version_check('5.12') ) ) # We can't really know when to show an error page, as the error might # have happened when loading some resource. # However, self.url() is not available yet and the requested URL # might not match the URL we get from the error - so we just apply a # heuristic here. if ((show_cert_error or show_non_overr_cert_error) and url.matches(self.data.last_navigation.url, QUrl.RemoveScheme)): self._show_error_page(url, str(error))","def _on_ssl_errors(self, error): url = error.url() self._insecure_hosts.add(url.host()) log.webview.debug(""Certificate error: {}"".format(error)) if error.is_overridable(): error.ignore = shared.ignore_certificate_errors( url, [error], abort_on=[self.abort_questions]) else: log.webview.error(""Non-overridable certificate error: "" ""{}"".format(error)) log.webview.debug(""ignore {}, URL {}, requested {}"".format( error.ignore, url, self.url(requested=True))) # WORKAROUND for https://bugreports.qt.io/browse/QTBUG-56207 show_cert_error = ( not qtutils.version_check('5.9') and not error.ignore ) # WORKAROUND for https://codereview.qt-project.org/c/qt/qtwebengine/+/270556 show_non_overr_cert_error = ( not error.is_overridable() and ( # Affected Qt versions: # 5.13 before 5.13.2 # 5.12 before 5.12.6 # < 5.12 (qtutils.version_check('5.13') and not qtutils.version_check('5.13.2')) or (qtutils.version_check('5.12') and not qtutils.version_check('5.12.6')) or not qtutils.version_check('5.12') ) ) # We can't really know when to show an error page, as the error might # have happened when loading some resource. # However, self.url() is not available yet and the requested URL # might not match the URL we get from the error - so we just apply a # heuristic here. if ((show_cert_error or show_non_overr_cert_error) and url.matches(self.data.last_navigation.url, QUrl.RemoveScheme)): self._show_error_page(url, str(error))","Security: Remember hosts with ignored cert errors for load status Without this change, we only set a flag when a certificate error occurred. However, when the same certificate error then happens a second time (e.g. because of a reload or opening the same URL again), we then colored the URL as success_https (i.e. green) again. See #5403 (cherry picked from commit 021ab572a319ca3db5907a33a59774f502b3b975)",https://github.com/qutebrowser/qutebrowser/commit/9bd1cf585fccdfe8318fff7af793730e74a04db3,,,qutebrowser/browser/webengine/webenginetab.py,3,py,False,2020-05-02T16:54:05Z "public static boolean isValidURL(String url) { if (StringUtils.isNotBlank(url)) { return urlPattern.matcher(url).matches(); } else { return false; } }","public static boolean isValidURL(String url) { if (StringUtils.isNotBlank(url) && url.length() <= 2000) { return urlPattern.matcher(url).matches(); } else { return false; } }",fix StackOverFlow error in matcher,https://github.com/ORCID/ORCID-Source/commit/f3868122aaf41b42140c67b108740017afb4c8a9,,,orcid-utils/src/main/java/org/orcid/utils/OrcidStringUtils.java,3,java,False,2021-09-29T01:56:28Z "private boolean hasHttp(boolean is_sent) { if(getNumPayloadChunks() == 0) return false; for(PayloadChunk chunk: payload_chunks) { if(chunk.is_sent == is_sent) return (chunk.type == PayloadChunk.ChunkType.HTTP); } return false; }","private synchronized boolean hasHttp(boolean is_sent) { for(PayloadChunk chunk: payload_chunks) { if(chunk.is_sent == is_sent) return (chunk.type == PayloadChunk.ChunkType.HTTP); } return false; }","Fix possible JNI local reference overflow and races Dumping connections payload requires creating (local) references, which are limited to 512. This commit greatly reduces their lifetime, from several seconds to less than 1 second, reducing the likehood of an overflow. Moreover it adds missing synchronization to the connection payload.",https://github.com/emanuele-f/PCAPdroid/commit/2fddba63017b1b5db11c0b0aa067ba467bb3da2b,,,app/src/main/java/com/emanuelef/remote_capture/model/ConnectionDescriptor.java,3,java,False,2022-08-13T14:10:38Z "@Override public Object getAttribute(String name) { Object value = super.getAttribute(name); if (value instanceof String) { HtmlUtils.htmlEscape((String) value); } return value; }","@Override public Object getAttribute(String name) { Object value = super.getAttribute(name); if (value instanceof String) { HtmlUtils.cleanUnSafe((String) value); } return value; }",:zap: 使用 Jackson2ObjectMapperBuilder 构造 ObjectMapper,保留使用配置文件配置 jackson 属性的能力,以及方便用户增加自定义配置,https://github.com/ballcat-projects/ballcat/commit/d4d5d4c4aa4402bec83db4eab7007f0cf70e8e01,,,ballcat-common/ballcat-common-core/src/main/java/com/hccake/ballcat/common/core/request/wrapper/XSSRequestWrapper.java,3,java,False,2021-03-08T14:05:28Z "private void authenticate(String username, String password) throws UnsupportedCallbackException, IOException { // if username equals '$accessToken' we treat the password as an access token // otherwise, we treat username as clientId, password as client secret and perform client credential auth // to get the access token final String accessToken; if (""$accessToken"".equals(username)) { accessToken = password; } else { accessToken = OAuthAuthenticator.loginWithClientSecret(tokenEndpointUri, getSocketFactory(), getVerifier(), username, password, isJwt(), getPrincipalExtractor(), null) .token(); } OAuthBearerValidatorCallback[] callbacks = new OAuthBearerValidatorCallback[] {new OAuthBearerValidatorCallback(accessToken)}; super.handle(callbacks); OAuthBearerToken token = callbacks[0].token(); if (token == null) { throw new RuntimeException(""Authentication with OAuth token failed""); } OAuthKafkaPrincipal kafkaPrincipal = new OAuthKafkaPrincipal(KafkaPrincipal.USER_TYPE, token.principalName(), (BearerTokenWithPayload) token); OAuthKafkaPrincipal.setToThreadContext(kafkaPrincipal); }","private void authenticate(String username, String password) throws UnsupportedCallbackException, IOException { final String accessTokenPrefix = ""$accessToken:""; boolean checkUsernameMatch = false; String accessToken; if (password != null && password.startsWith(accessTokenPrefix)) { accessToken = password.substring(accessTokenPrefix.length()); checkUsernameMatch = true; } else { accessToken = OAuthAuthenticator.loginWithClientSecret(tokenEndpointUri, getSocketFactory(), getVerifier(), username, password, isJwt(), getPrincipalExtractor(), null) .token(); } OAuthBearerValidatorCallback[] callbacks = new OAuthBearerValidatorCallback[] {new OAuthBearerValidatorCallback(accessToken)}; super.handle(callbacks); OAuthBearerToken token = callbacks[0].token(); if (token == null) { throw new RuntimeException(""Authentication with OAuth token has failed (no token returned)""); } if (checkUsernameMatch) { if (!username.equals(token.principalName())) { throw new SaslAuthenticationException(""Username doesn't match the token""); } } OAuthKafkaPrincipal kafkaPrincipal = new OAuthKafkaPrincipal(KafkaPrincipal.USER_TYPE, token.principalName(), (BearerTokenWithPayload) token); Services.getInstance().getCredentials().storeCredentials(username, kafkaPrincipal); }","Fix for intermittent authentication failures with OAuth over PLAIN (#95) * Fix for intermittent authentication failures with OAuth over PLAIN This fix introduces a breaking change with 0.7.0 in how to authenticate with an access token over SASL_PLAIN by using '$accessToken' as a username. Signed-off-by: Marko Strukelj * Update README.md Signed-off-by: Marko Strukelj * Tests for intermittent authentication failures with OAuth over PLAIN Signed-off-by: Marko Strukelj * Add flood tests for intermittent authentication failures with OAuth over PLAIN Signed-off-by: Marko Strukelj * Fix error checking for flood tests Signed-off-by: Marko Strukelj ",https://github.com/strimzi/strimzi-kafka-oauth/commit/6533a8b6810f585e58a592d39501d25fd0d61764,,,oauth-server-plain/src/main/java/io/strimzi/kafka/oauth/server/plain/JaasServerOauthOverPlainValidatorCallbackHandler.java,3,java,False,2021-03-08T18:27:53Z "public Value scriptRunCommand(ScriptHost host, BlockPos pos) { if (CarpetServer.scriptServer.stopAll) throw new CarpetExpressionException(""SCRIPTING PAUSED"", null); try { Context context = new CarpetContext(host, source, origin). with(""x"", (c, t) -> new NumericValue(pos.getX() - origin.getX()).bindTo(""x"")). with(""y"", (c, t) -> new NumericValue(pos.getY() - origin.getY()).bindTo(""y"")). with(""z"", (c, t) -> new NumericValue(pos.getZ() - origin.getZ()).bindTo(""z"")); Entity e = source.getEntity(); if (e==null) { Value nullPlayer = Value.NULL.reboundedTo(""p""); context.with(""p"", (cc, tt) -> nullPlayer ); } else { Value playerValue = new EntityValue(e).bindTo(""p""); context.with(""p"", (cc, tt) -> playerValue); } return this.expr.eval(context); } catch (ExpressionException e) { throw new CarpetExpressionException(e.getMessage(), e.stack); } catch (ArithmeticException ae) { throw new CarpetExpressionException(""Math doesn't compute... ""+ae.getMessage(), null); } }","public Value scriptRunCommand(ScriptHost host, BlockPos pos) { if (CarpetServer.scriptServer.stopAll) throw new CarpetExpressionException(""SCRIPTING PAUSED"", null); try { Context context = new CarpetContext(host, source, origin). with(""x"", (c, t) -> new NumericValue(pos.getX() - origin.getX()).bindTo(""x"")). with(""y"", (c, t) -> new NumericValue(pos.getY() - origin.getY()).bindTo(""y"")). with(""z"", (c, t) -> new NumericValue(pos.getZ() - origin.getZ()).bindTo(""z"")); Entity e = source.getEntity(); if (e==null) { Value nullPlayer = Value.NULL.reboundedTo(""p""); context.with(""p"", (cc, tt) -> nullPlayer ); } else { Value playerValue = new EntityValue(e).bindTo(""p""); context.with(""p"", (cc, tt) -> playerValue); } return this.expr.eval(context); } catch (ExpressionException e) { throw new CarpetExpressionException(e.getMessage(), e.stack); } catch (ArithmeticException ae) { throw new CarpetExpressionException(""Math doesn't compute... ""+ae.getMessage(), null); } catch (StackOverflowError soe) { throw new CarpetExpressionException(""Your thoughts are too deep"", null); } }","stack overflow in scripts shouldn't crash the game, fixes #934",https://github.com/gnembon/fabric-carpet/commit/8fa54c81463af091847f4a989f11b6c5ede1ffd0,,,src/main/java/carpet/script/CarpetExpression.java,3,java,False,2021-06-26T02:31:46Z "@Packet public void onPacket(WrappedInFlyingPacket packet) { if(data.playerInfo.deltaXZ == 0 && data.playerInfo.deltaY == 0) return; double max = Math.max(data.playerInfo.calcVelocityY, data.playerInfo.jumpHeight); if(data.playerInfo.lastHalfBlock.isNotPassed(10)) max = Math.max(0.5625, max); if(data.playerInfo.deltaY > max && !data.blockInfo.roseBush && !data.playerInfo.doingVelocity && data.playerInfo.slimeTimer.isPassed(10) && !data.playerInfo.generalCancel) { ++vl; flag(""dY=%.3f max=%.3f"", data.playerInfo.deltaY, max); } }","@Packet public void onPacket(WrappedInFlyingPacket packet) { if(data.playerInfo.deltaXZ == 0 && data.playerInfo.deltaY == 0) return; double max = data.playerInfo.lastVelocity.isNotPassed(20) ? Math.max(data.playerInfo.velocityY, data.playerInfo.jumpHeight) : data.playerInfo.jumpHeight; if(data.playerInfo.lastHalfBlock.isNotPassed(10)) max = Math.max(0.5625, max); if(data.playerInfo.deltaY > max && !data.blockInfo.roseBush && data.playerInfo.lastVelocity.isPassed(2) && !data.playerInfo.doingVelocity && data.playerInfo.slimeTimer.isPassed(10) && !data.playerInfo.generalCancel) { ++vl; flag(""dY=%.3f max=%.3f"", data.playerInfo.deltaY, max); } }",Update AimE.java,https://github.com/funkemunky/Kauri/commit/5b1d3be4df6cc73cf956432ba680ab92ecec73af,,,Regular/src/main/java/dev/brighten/anticheat/check/impl/movement/fly/FlyF.java,3,java,False,2021-05-31T16:00:45Z "@Override public void onFlush(OnFlushCompleteCallback callback) { OnFlushCompleteCallback wrapper = new OnFlushCompleteCallback() { private int mFlushCount = 2; @Override public void onFlushComplete() { if (--mFlushCount == 0) { callback.onFlushComplete(); } } }; mGpsListener.flush(wrapper); mNetworkListener.flush(wrapper); }","@Override public void onFlush(OnFlushCompleteCallback callback) { synchronized (mLock) { AtomicInteger flushCount = new AtomicInteger(0); if (mGpsPresent) { flushCount.incrementAndGet(); } if (mNlpPresent) { flushCount.incrementAndGet(); } OnFlushCompleteCallback wrapper = () -> { if (flushCount.decrementAndGet() == 0) { callback.onFlushComplete(); } }; if (mGpsPresent) { mGpsListener.flush(wrapper); } if (mNlpPresent) { mNetworkListener.flush(wrapper); } } }","Fix newly discovered crashes in FusedLocationProvider We recently discovered the FusedLocationProvider doesn't function well when the gps or network provider is missing, but these errors were previously hidden. Now that the crashes are apparent, deal with cases where these providers may not be present. Bug: 214358333 Test: presubmits Change-Id: I660592bee4897fc335f5fe1d2f2499c047b62e66",https://github.com/omnirom/android_frameworks_base/commit/1679ed09011e7756e415be9086a9f0ca5dff816b,,,packages/FusedLocation/src/com/android/location/fused/FusedLocationProvider.java,3,java,False,2022-01-13T18:39:11Z "private FontRenderBlock getBlockFor(char textChar, ColorRGB color, FontRenderState state){ //First get the font block; String font = fontLocations[textChar/CHARS_PER_TEXTURE_SHEET]; Map> map1 = createdRenderBlocks.get(font); if(map1 == null){ map1 = new HashMap>(); createdRenderBlocks.put(font, map1); } Map map2 = map1.get(color); if(map2 == null){ map2 = new HashMap(); map1.put(color, map2); } FontRenderBlock block = map2.get(state); if(block == null){ block = new FontRenderBlock(font, color, state); map2.put(state, block); } return block; }","private FontRenderBlock getBlockFor(char textChar, ColorRGB color, FontRenderState state){ //First get the font block; //MNake sure we didn't get passed a bad char from some unicode junk text. if(textChar/CHARS_PER_TEXTURE_SHEET >= fontLocations.length){ textChar = 0; } String font = fontLocations[textChar/CHARS_PER_TEXTURE_SHEET]; Map> map1 = createdRenderBlocks.get(font); if(map1 == null){ map1 = new HashMap>(); createdRenderBlocks.put(font, map1); } Map map2 = map1.get(color); if(map2 == null){ map2 = new HashMap(); map1.put(color, map2); } FontRenderBlock block = map2.get(state); if(block == null){ block = new FontRenderBlock(font, color, state); map2.put(state, block); } return block; }",Fixed invalid text chars crashing the rendering system.,https://github.com/DonBruce64/MinecraftTransportSimulator/commit/561a1371b8b4300db84e4080d07b9b0df667e72e,,,src/main/java/minecrafttransportsimulator/rendering/instances/RenderText.java,3,java,False,2021-09-21T01:57:40Z "@Override public Map getVulnListByOssName(OssMaster bean) { Map result = new HashMap(); if (""N/A"".equals(bean.getOssVersion())) { bean.setOssVersion(""""); } List list = null; String[] nicknameList = null; int records = 0; try { nicknameList = ossService.getOssNickNameListByOssName(bean.getOssName()); bean.setOssNicknames(nicknameList); records = vulnerabilityMapper.getVulnListByOssNameCnt(bean); bean.setTotListSize(records); list = vulnerabilityMapper.getVulnListByOssName(bean); } catch (Exception e) { log.error(e.getMessage()); } list = checkVulnData(list, nicknameList); result.put(""page"", bean.getCurPage()); result.put(""total"", bean.getTotBlockSize()); result.put(""records"", records); // total cnt를 cveCnt에 담아두고 관리함. result.put(""rows"", list); return result; }","@Override public Map getVulnListByOssName(OssMaster bean) { Map result = new HashMap(); if (""N/A"".equals(bean.getOssVersion())) { bean.setOssVersion(""""); } List list = null; String[] nicknameList = null; List convertNicknameList = null; boolean convertFlag = false; int records = 0; try { nicknameList = ossService.getOssNickNameListByOssName(bean.getOssName()); if(nicknameList != null) { for (String nick : nicknameList) { if (nick.contains("" "")) { if (!convertFlag) { convertNicknameList = new ArrayList<>(); convertFlag = true; } convertNicknameList.add(nick.replaceAll("" "", ""_"")); } } if (convertNicknameList != null && !convertNicknameList.isEmpty()) { if (bean.getOssName().contains("" "")) convertNicknameList.add(bean.getOssName().replaceAll("" "", ""_"")); convertNicknameList.addAll(Arrays.asList(nicknameList)); nicknameList = convertNicknameList.toArray(new String[convertNicknameList.size()]); } else { if (bean.getOssName().contains("" "")) { convertNicknameList = new ArrayList<>(); convertNicknameList.add(bean.getOssName().replaceAll("" "", ""_"")); convertNicknameList.addAll(Arrays.asList(nicknameList)); nicknameList = convertNicknameList.toArray(new String[convertNicknameList.size()]); } } } else { if (bean.getOssName().contains("" "")) { nicknameList = new String[] {bean.getOssName().replaceAll("" "", ""_"")}; } } bean.setOssNicknames(nicknameList); records = vulnerabilityMapper.getVulnListByOssNameCnt(bean); bean.setTotListSize(records); list = vulnerabilityMapper.getVulnListByOssName(bean); } catch (Exception e) { log.error(e.getMessage()); } list = checkVulnData(list, nicknameList); result.put(""page"", bean.getCurPage()); result.put(""total"", bean.getTotBlockSize()); result.put(""records"", records); // total cnt를 cveCnt에 담아두고 관리함. result.put(""rows"", list); return result; }",fix Vulnerability-related oss nvd info sync function,https://github.com/fosslight/fosslight/commit/60358b131d80dac1c33976c7f49a2f05d33c861c,,,src/main/java/oss/fosslight/service/impl/VulnerabilityServiceImpl.java,3,java,False,2023-02-10T03:29:31Z "@Override protected void onProvideStructure(@NonNull ViewStructure structure, @ViewStructureType int viewFor, int flags) { super.onProvideStructure(structure, viewFor, flags); final boolean isPassword = hasPasswordTransformationMethod() || isPasswordInputType(getInputType()); if (viewFor == VIEW_STRUCTURE_FOR_AUTOFILL || viewFor == VIEW_STRUCTURE_FOR_CONTENT_CAPTURE) { if (viewFor == VIEW_STRUCTURE_FOR_AUTOFILL) { structure.setDataIsSensitive(!mTextSetFromXmlOrResourceId); } if (mTextId != Resources.ID_NULL) { try { structure.setTextIdEntry(getResources().getResourceEntryName(mTextId)); } catch (Resources.NotFoundException e) { if (android.view.autofill.Helper.sVerbose) { Log.v(LOG_TAG, ""onProvideAutofillStructure(): cannot set name for text id "" + mTextId + "": "" + e.getMessage()); } } } String[] mimeTypes = getReceiveContentMimeTypes(); if (mimeTypes == null && mEditor != null) { // If the app hasn't set a listener for receiving content on this view (ie, // getReceiveContentMimeTypes() returns null), check if it implements the // keyboard image API and, if possible, use those MIME types as fallback. // This fallback is only in place for autofill, not other mechanisms for // inserting content. See AUTOFILL_NON_TEXT_REQUIRES_ON_RECEIVE_CONTENT_LISTENER // in TextViewOnReceiveContentListener for more info. mimeTypes = mEditor.getDefaultOnReceiveContentListener() .getFallbackMimeTypesForAutofill(this); } structure.setReceiveContentMimeTypes(mimeTypes); } if (!isPassword || viewFor == VIEW_STRUCTURE_FOR_AUTOFILL || viewFor == VIEW_STRUCTURE_FOR_CONTENT_CAPTURE) { if (mLayout == null) { if (viewFor == VIEW_STRUCTURE_FOR_CONTENT_CAPTURE) { Log.w(LOG_TAG, ""onProvideContentCaptureStructure(): calling assumeLayout()""); } assumeLayout(); } Layout layout = mLayout; final int lineCount = layout.getLineCount(); if (lineCount <= 1) { // Simple case: this is a single line. final CharSequence text = getText(); if (viewFor == VIEW_STRUCTURE_FOR_AUTOFILL) { structure.setText(text); } else { structure.setText(text, getSelectionStart(), getSelectionEnd()); } } else { // Complex case: multi-line, could be scrolled or within a scroll container // so some lines are not visible. final int[] tmpCords = new int[2]; getLocationInWindow(tmpCords); final int topWindowLocation = tmpCords[1]; View root = this; ViewParent viewParent = getParent(); while (viewParent instanceof View) { root = (View) viewParent; viewParent = root.getParent(); } final int windowHeight = root.getHeight(); final int topLine; final int bottomLine; if (topWindowLocation >= 0) { // The top of the view is fully within its window; start text at line 0. topLine = getLineAtCoordinateUnclamped(0); bottomLine = getLineAtCoordinateUnclamped(windowHeight - 1); } else { // The top of hte window has scrolled off the top of the window; figure out // the starting line for this. topLine = getLineAtCoordinateUnclamped(-topWindowLocation); bottomLine = getLineAtCoordinateUnclamped(windowHeight - 1 - topWindowLocation); } // We want to return some contextual lines above/below the lines that are // actually visible. int expandedTopLine = topLine - (bottomLine - topLine) / 2; if (expandedTopLine < 0) { expandedTopLine = 0; } int expandedBottomLine = bottomLine + (bottomLine - topLine) / 2; if (expandedBottomLine >= lineCount) { expandedBottomLine = lineCount - 1; } // Convert lines into character offsets. int expandedTopChar = layout.getLineStart(expandedTopLine); int expandedBottomChar = layout.getLineEnd(expandedBottomLine); // Take into account selection -- if there is a selection, we need to expand // the text we are returning to include that selection. final int selStart = getSelectionStart(); final int selEnd = getSelectionEnd(); if (selStart < selEnd) { if (selStart < expandedTopChar) { expandedTopChar = selStart; } if (selEnd > expandedBottomChar) { expandedBottomChar = selEnd; } } // Get the text and trim it to the range we are reporting. CharSequence text = getText(); if (text != null) { if (expandedTopChar > 0 || expandedBottomChar < text.length()) { text = text.subSequence(expandedTopChar, expandedBottomChar); } if (viewFor == VIEW_STRUCTURE_FOR_AUTOFILL) { structure.setText(text); } else { structure.setText(text, selStart - expandedTopChar, selEnd - expandedTopChar); final int[] lineOffsets = new int[bottomLine - topLine + 1]; final int[] lineBaselines = new int[bottomLine - topLine + 1]; final int baselineOffset = getBaselineOffset(); for (int i = topLine; i <= bottomLine; i++) { lineOffsets[i - topLine] = layout.getLineStart(i); lineBaselines[i - topLine] = layout.getLineBaseline(i) + baselineOffset; } structure.setTextLines(lineOffsets, lineBaselines); } } } if (viewFor == VIEW_STRUCTURE_FOR_ASSIST || viewFor == VIEW_STRUCTURE_FOR_CONTENT_CAPTURE) { // Extract style information that applies to the TextView as a whole. int style = 0; int typefaceStyle = getTypefaceStyle(); if ((typefaceStyle & Typeface.BOLD) != 0) { style |= AssistStructure.ViewNode.TEXT_STYLE_BOLD; } if ((typefaceStyle & Typeface.ITALIC) != 0) { style |= AssistStructure.ViewNode.TEXT_STYLE_ITALIC; } // Global styles can also be set via TextView.setPaintFlags(). int paintFlags = mTextPaint.getFlags(); if ((paintFlags & Paint.FAKE_BOLD_TEXT_FLAG) != 0) { style |= AssistStructure.ViewNode.TEXT_STYLE_BOLD; } if ((paintFlags & Paint.UNDERLINE_TEXT_FLAG) != 0) { style |= AssistStructure.ViewNode.TEXT_STYLE_UNDERLINE; } if ((paintFlags & Paint.STRIKE_THRU_TEXT_FLAG) != 0) { style |= AssistStructure.ViewNode.TEXT_STYLE_STRIKE_THRU; } // TextView does not have its own text background color. A background is either part // of the View (and can be any drawable) or a BackgroundColorSpan inside the text. structure.setTextStyle(getTextSize(), getCurrentTextColor(), AssistStructure.ViewNode.TEXT_COLOR_UNDEFINED /* bgColor */, style); } if (viewFor == VIEW_STRUCTURE_FOR_AUTOFILL || viewFor == VIEW_STRUCTURE_FOR_CONTENT_CAPTURE) { structure.setMinTextEms(getMinEms()); structure.setMaxTextEms(getMaxEms()); int maxLength = -1; for (InputFilter filter: getFilters()) { if (filter instanceof InputFilter.LengthFilter) { maxLength = ((InputFilter.LengthFilter) filter).getMax(); break; } } structure.setMaxTextLength(maxLength); } } if (mHintId != Resources.ID_NULL) { try { structure.setHintIdEntry(getResources().getResourceEntryName(mHintId)); } catch (Resources.NotFoundException e) { if (android.view.autofill.Helper.sVerbose) { Log.v(LOG_TAG, ""onProvideAutofillStructure(): cannot set name for hint id "" + mHintId + "": "" + e.getMessage()); } } } structure.setHint(getHint()); structure.setInputType(getInputType()); }","@Override protected void onProvideStructure(@NonNull ViewStructure structure, @ViewStructureType int viewFor, int flags) { super.onProvideStructure(structure, viewFor, flags); final boolean isPassword = hasPasswordTransformationMethod() || isPasswordInputType(getInputType()); if (viewFor == VIEW_STRUCTURE_FOR_AUTOFILL || viewFor == VIEW_STRUCTURE_FOR_CONTENT_CAPTURE) { if (viewFor == VIEW_STRUCTURE_FOR_AUTOFILL) { structure.setDataIsSensitive(!mTextSetFromXmlOrResourceId); } if (mTextId != Resources.ID_NULL) { try { structure.setTextIdEntry(getResources().getResourceEntryName(mTextId)); } catch (Resources.NotFoundException e) { if (android.view.autofill.Helper.sVerbose) { Log.v(LOG_TAG, ""onProvideAutofillStructure(): cannot set name for text id "" + mTextId + "": "" + e.getMessage()); } } } String[] mimeTypes = getReceiveContentMimeTypes(); if (mimeTypes == null && mEditor != null) { // If the app hasn't set a listener for receiving content on this view (ie, // getReceiveContentMimeTypes() returns null), check if it implements the // keyboard image API and, if possible, use those MIME types as fallback. // This fallback is only in place for autofill, not other mechanisms for // inserting content. See AUTOFILL_NON_TEXT_REQUIRES_ON_RECEIVE_CONTENT_LISTENER // in TextViewOnReceiveContentListener for more info. mimeTypes = mEditor.getDefaultOnReceiveContentListener() .getFallbackMimeTypesForAutofill(this); } structure.setReceiveContentMimeTypes(mimeTypes); } if (!isPassword || viewFor == VIEW_STRUCTURE_FOR_AUTOFILL || viewFor == VIEW_STRUCTURE_FOR_CONTENT_CAPTURE) { if (mLayout == null) { if (viewFor == VIEW_STRUCTURE_FOR_CONTENT_CAPTURE) { Log.w(LOG_TAG, ""onProvideContentCaptureStructure(): calling assumeLayout()""); } assumeLayout(); } Layout layout = mLayout; final int lineCount = layout.getLineCount(); if (lineCount <= 1) { // Simple case: this is a single line. final CharSequence text = getText(); if (viewFor == VIEW_STRUCTURE_FOR_AUTOFILL) { structure.setText(text); } else { structure.setText(text, getSelectionStart(), getSelectionEnd()); } } else { // Complex case: multi-line, could be scrolled or within a scroll container // so some lines are not visible. final int[] tmpCords = new int[2]; getLocationInWindow(tmpCords); final int topWindowLocation = tmpCords[1]; View root = this; ViewParent viewParent = getParent(); while (viewParent instanceof View) { root = (View) viewParent; viewParent = root.getParent(); } final int windowHeight = root.getHeight(); final int topLine; final int bottomLine; if (topWindowLocation >= 0) { // The top of the view is fully within its window; start text at line 0. topLine = getLineAtCoordinateUnclamped(0); bottomLine = getLineAtCoordinateUnclamped(windowHeight - 1); } else { // The top of hte window has scrolled off the top of the window; figure out // the starting line for this. topLine = getLineAtCoordinateUnclamped(-topWindowLocation); bottomLine = getLineAtCoordinateUnclamped(windowHeight - 1 - topWindowLocation); } // We want to return some contextual lines above/below the lines that are // actually visible. int expandedTopLine = topLine - (bottomLine - topLine) / 2; if (expandedTopLine < 0) { expandedTopLine = 0; } int expandedBottomLine = bottomLine + (bottomLine - topLine) / 2; if (expandedBottomLine >= lineCount) { expandedBottomLine = lineCount - 1; } // Convert lines into character offsets. int expandedTopChar = layout.getLineStart(expandedTopLine); int expandedBottomChar = layout.getLineEnd(expandedBottomLine); // Take into account selection -- if there is a selection, we need to expand // the text we are returning to include that selection. final int selStart = getSelectionStart(); final int selEnd = getSelectionEnd(); if (selStart < selEnd) { if (selStart < expandedTopChar) { expandedTopChar = selStart; } if (selEnd > expandedBottomChar) { expandedBottomChar = selEnd; } } // Get the text and trim it to the range we are reporting. CharSequence text = getText(); if (text != null) { if (expandedTopChar > 0 || expandedBottomChar < text.length()) { // Cap the offsets to avoid an OOB exception. That can happen if the // displayed/layout text, on which these offsets are calculated, is longer // than the original text (such as when the view is translated by the // platform intelligence). // TODO(b/196433694): Figure out how to better handle the offset // calculations for this case (so we don't unnecessarily cutoff the original // text, for example). expandedTopChar = Math.min(expandedTopChar, text.length()); expandedBottomChar = Math.min(expandedBottomChar, text.length()); text = text.subSequence(expandedTopChar, expandedBottomChar); } if (viewFor == VIEW_STRUCTURE_FOR_AUTOFILL) { structure.setText(text); } else { structure.setText(text, selStart - expandedTopChar, selEnd - expandedTopChar); final int[] lineOffsets = new int[bottomLine - topLine + 1]; final int[] lineBaselines = new int[bottomLine - topLine + 1]; final int baselineOffset = getBaselineOffset(); for (int i = topLine; i <= bottomLine; i++) { lineOffsets[i - topLine] = layout.getLineStart(i); lineBaselines[i - topLine] = layout.getLineBaseline(i) + baselineOffset; } structure.setTextLines(lineOffsets, lineBaselines); } } } if (viewFor == VIEW_STRUCTURE_FOR_ASSIST || viewFor == VIEW_STRUCTURE_FOR_CONTENT_CAPTURE) { // Extract style information that applies to the TextView as a whole. int style = 0; int typefaceStyle = getTypefaceStyle(); if ((typefaceStyle & Typeface.BOLD) != 0) { style |= AssistStructure.ViewNode.TEXT_STYLE_BOLD; } if ((typefaceStyle & Typeface.ITALIC) != 0) { style |= AssistStructure.ViewNode.TEXT_STYLE_ITALIC; } // Global styles can also be set via TextView.setPaintFlags(). int paintFlags = mTextPaint.getFlags(); if ((paintFlags & Paint.FAKE_BOLD_TEXT_FLAG) != 0) { style |= AssistStructure.ViewNode.TEXT_STYLE_BOLD; } if ((paintFlags & Paint.UNDERLINE_TEXT_FLAG) != 0) { style |= AssistStructure.ViewNode.TEXT_STYLE_UNDERLINE; } if ((paintFlags & Paint.STRIKE_THRU_TEXT_FLAG) != 0) { style |= AssistStructure.ViewNode.TEXT_STYLE_STRIKE_THRU; } // TextView does not have its own text background color. A background is either part // of the View (and can be any drawable) or a BackgroundColorSpan inside the text. structure.setTextStyle(getTextSize(), getCurrentTextColor(), AssistStructure.ViewNode.TEXT_COLOR_UNDEFINED /* bgColor */, style); } if (viewFor == VIEW_STRUCTURE_FOR_AUTOFILL || viewFor == VIEW_STRUCTURE_FOR_CONTENT_CAPTURE) { structure.setMinTextEms(getMinEms()); structure.setMaxTextEms(getMaxEms()); int maxLength = -1; for (InputFilter filter: getFilters()) { if (filter instanceof InputFilter.LengthFilter) { maxLength = ((InputFilter.LengthFilter) filter).getMax(); break; } } structure.setMaxTextLength(maxLength); } } if (mHintId != Resources.ID_NULL) { try { structure.setHintIdEntry(getResources().getResourceEntryName(mHintId)); } catch (Resources.NotFoundException e) { if (android.view.autofill.Helper.sVerbose) { Log.v(LOG_TAG, ""onProvideAutofillStructure(): cannot set name for hint id "" + mHintId + "": "" + e.getMessage()); } } } structure.setHint(getHint()); structure.setInputType(getInputType()); }","Fix OOB crash in ContentCapture for translated views When a view is partially visible on the screen, ContentCapture reports only the visible portion (+ a few additional lines). The offsets calculated for this can be out of bounds if the view's displayed text is longer from the original text. Fix: 196414491 Test: manual - translate app to lang with more characters and trigger a relayout (by scrolling for an app with ListView) Test: atest CtsContentCaptureServiceTestCases Change-Id: Iae98133c48cc67a0b00f1b0ab8b93e5adb293423 (cherry picked from commit 273a0eabc8faa46349c63a6836ae4004709aeb0b)",https://github.com/omnirom/android_frameworks_base/commit/cbe8bc36eb6f180dbdfb764679105612c5d0b363,,,core/java/android/widget/TextView.java,3,java,False,2021-08-12T21:08:52Z "@Override public void setMicrophoneMute(boolean on, String callingPackage, int userId) { // If we are being called by the system check for user we are going to change // so we handle user restrictions correctly. int uid = Binder.getCallingUid(); if (uid == android.os.Process.SYSTEM_UID) { uid = UserHandle.getUid(userId, UserHandle.getAppId(uid)); } MediaMetrics.Item mmi = new MediaMetrics.Item(MediaMetrics.Name.AUDIO_MIC) .setUid(uid) .set(MediaMetrics.Property.CALLING_PACKAGE, callingPackage) .set(MediaMetrics.Property.EVENT, ""setMicrophoneMute"") .set(MediaMetrics.Property.REQUEST, on ? MediaMetrics.Value.MUTE : MediaMetrics.Value.UNMUTE); // If OP_MUTE_MICROPHONE is set, disallow unmuting. if (!on && mAppOps.noteOp(AppOpsManager.OP_MUTE_MICROPHONE, uid, callingPackage) != AppOpsManager.MODE_ALLOWED) { mmi.set(MediaMetrics.Property.EARLY_RETURN, ""disallow unmuting"").record(); return; } if (!checkAudioSettingsPermission(""setMicrophoneMute()"")) { mmi.set(MediaMetrics.Property.EARLY_RETURN, ""!checkAudioSettingsPermission"").record(); return; } if (userId != UserHandle.getCallingUserId() && mContext.checkCallingOrSelfPermission( android.Manifest.permission.INTERACT_ACROSS_USERS_FULL) != PackageManager.PERMISSION_GRANTED) { mmi.set(MediaMetrics.Property.EARLY_RETURN, ""permission"").record(); return; } mMicMuteFromApi = on; mmi.record(); // record now, the no caller check will set the mute state. setMicrophoneMuteNoCallerCheck(userId); }","@Override public void setMicrophoneMute(boolean on, String callingPackage, int userId) { // If we are being called by the system check for user we are going to change // so we handle user restrictions correctly. int uid = Binder.getCallingUid(); if (uid == android.os.Process.SYSTEM_UID) { uid = UserHandle.getUid(userId, UserHandle.getAppId(uid)); } MediaMetrics.Item mmi = new MediaMetrics.Item(MediaMetrics.Name.AUDIO_MIC) .setUid(uid) .set(MediaMetrics.Property.CALLING_PACKAGE, callingPackage) .set(MediaMetrics.Property.EVENT, ""setMicrophoneMute"") .set(MediaMetrics.Property.REQUEST, on ? MediaMetrics.Value.MUTE : MediaMetrics.Value.UNMUTE); // If OP_MUTE_MICROPHONE is set, disallow unmuting. if (!on && !checkNoteAppOp(AppOpsManager.OP_MUTE_MICROPHONE, uid, callingPackage)) { mmi.set(MediaMetrics.Property.EARLY_RETURN, ""disallow unmuting"").record(); return; } if (!checkAudioSettingsPermission(""setMicrophoneMute()"")) { mmi.set(MediaMetrics.Property.EARLY_RETURN, ""!checkAudioSettingsPermission"").record(); return; } if (userId != UserHandle.getCallingUserId() && mContext.checkCallingOrSelfPermission( android.Manifest.permission.INTERACT_ACROSS_USERS_FULL) != PackageManager.PERMISSION_GRANTED) { mmi.set(MediaMetrics.Property.EARLY_RETURN, ""permission"").record(); return; } mMicMuteFromApi = on; mmi.record(); // record now, the no caller check will set the mute state. setMicrophoneMuteNoCallerCheck(userId); }","AudioService: validate uid / package name match When checking app ops, check for exceptions that indicate uid and package name mismatch. This affects the code paths for methods: - adjustStreamVolume - setStreamVolume - setMicrophoneMute - setMasterMute Bug: 194110891 194110526 Test: see bug exploit app, verify real/bogus package shows uninstalled Change-Id: Ice7a84993c68e7ec736fdf0b9fd5b8171b37b725 Merged-In: Ice7a84993c68e7ec736fdf0b9fd5b8171b37b725 (cherry picked from commit e0141e5be0337b6eea75ef75076ac69e8bfddc6a)",https://github.com/PixelExperience/frameworks_base/commit/414644a2f7b56160dfc37ae823d70dec98d95796,,,services/core/java/com/android/server/audio/AudioService.java,3,java,False,2021-08-23T16:50:35Z "void writeToNbt(NBTTagCompound nbt) { nbt.setShort(""capacity"", (short) amount); nbt.setShort(""lastSentAmount"", (short) lastSentAmount); nbt.setShort(""ticksInDirection"", (short) ticksInDirection); nbt.setByte(""lastSentDirection"", lastSentDirection.nbtValue); for (int i = 0; i < incoming.length; ++i) { nbt.setShort(""in["" + i + ""]"", (short) incoming[i]); } }","void writeToNbt(NBTTagCompound nbt) { nbt.setShort(""capacity"", (short) amount); nbt.setShort(""lastSentAmount"", (short) lastSentAmount); nbt.setShort(""ticksInDirection"", (short) ticksInDirection); /* Accesing lastSentDirection.nbtValue throws a NullPointerException when placing a wooden fluid pipe next to a Magneticraft Infinite Water block and then breaking wooden fluid pipe and to the best of my Java ability I couldn't figure out why */ try { nbt.setByte(""lastSentDirection"", lastSentDirection.nbtValue); } catch (NullPointerException e) {} for (int i = 0; i < incoming.length; ++i) { nbt.setShort(""in["" + i + ""]"", (short) incoming[i]); } }","Fix NullPointerException crash in PipeFlowFluids FIXES a bug where accesing lastSentDirection.nbtValue throws a NullPointerException when placing a wooden fluid pipe next to a Magneticraft Infinite Water block and then breaking wooden fluid pipe. To the best of my Java ability I couldn't figure out why :(",https://github.com/BuildCraft/BuildCraft/commit/c4f24fac1b23a8ca6c2bb2eeb7e52d3ae03ba119,,,common/buildcraft/transport/pipe/flow/PipeFlowFluids.java,3,java,False,2021-10-28T01:04:47Z "public synchronized void stop() { if (transport != null) { if(Log.isDebugEnabled()) { Log.debug(""Cleaning up authentication protocol references""); } transport.getConnection().getAuthenticatedFuture().authenticated(authenticated); } }","public synchronized void stop() { if (transport != null) { if(Log.isDebugEnabled()) { Log.debug(""Stopping authentication protocol""); } } }",HOTFIX: Connection protocol and authentication protocol both notify the authenticated future that its complete. Removing the notification from authenticaiton protocol as we rely on some variables being set before which is done in connection protocol.,https://github.com/sshtools/maverick-synergy/commit/892757d4c420142b820e9e3a040ec2534d6122c7,,,maverick-synergy-server/src/main/java/com/sshtools/server/AuthenticationProtocolServer.java,3,java,False,2022-08-30T15:54:00Z "public long getMemoryUsage() { return array.size() * 8; }","public long getMemoryUsage() { if (array == null) { return 0L; } return array.size() * 8; }",[ISSUE-297] NPE in TaskCompletionListener due to Spark OOM in ShuffleInMemorySorter causing tasks to hang (#298),https://github.com/apache/celeborn/commit/a30fb5b3b00957b77c336757fde9ce6c5286a1fe,,,client-spark/shuffle-manager-common/src/main/java/org/apache/spark/shuffle/rss/ShuffleInMemorySorter.java,3,java,False,2022-08-04T14:47:04Z "@Override public AuthenticationContext authenticate(RequestContext requestContext) { String token = requestContext.getHeaders().get(""authorization""); AccessTokenInfo accessTokenInfo = new AccessTokenInfo(); if (token.toLowerCase().contains(""bearer"")) { token = token.split(""\\s"")[1]; } try { IntrospectInfo introspectInfo = validateToken(token); accessTokenInfo.setAccessToken(token); accessTokenInfo.setConsumerKey(introspectInfo.getClientId()); } catch (IOException e) { throw new SecurityException(e); } return new AuthenticationContext(); }","@Override public AuthenticationContext authenticate(RequestContext requestContext) { String token = requestContext.getHeaders().get(""authorization""); AccessTokenInfo accessTokenInfo = new AccessTokenInfo(); if (token == null || !token.toLowerCase().contains(""bearer"")) { throw new SecurityException(""Authorization header is not in correct format. Authorization: Bearer ""); } token = token.split(""\\s"")[1]; try { IntrospectInfo introspectInfo = validateToken(token); accessTokenInfo.setAccessToken(token); accessTokenInfo.setConsumerKey(introspectInfo.getClientId()); } catch (IOException e) { throw new SecurityException(e); } return new AuthenticationContext(); }",Fix token validation when Authorization header is malformed,https://github.com/wso2/product-microgateway/commit/8d316ccd784f0ccad47935f56b05e0601a4d0e97,,,enforcer/src/main/java/org/wso2/choreo/connect/enforcer/security/oauth/OAuthAuthenticator.java,3,java,False,2021-04-06T18:52:13Z "[System.Diagnostics.CodeAnalysis.SuppressMessage(""Microsoft.Naming"", ""CA2204:Literals should be spelled correctly"", MessageId = ""HttpStatusCode"")] public static void Apply(this CommandResult commandResult, HttpResponseBase response, bool emitSameSiteNone) { if (commandResult == null) { throw new ArgumentNullException(nameof(commandResult)); } if (response == null) { throw new ArgumentNullException(nameof(response)); } response.Cache.SetCacheability((HttpCacheability)commandResult.Cacheability); ApplyCookies(commandResult, response, emitSameSiteNone); ApplyHeaders(commandResult, response); if (commandResult.HttpStatusCode == HttpStatusCode.SeeOther || commandResult.Location != null) { if (commandResult.Location == null) { throw new InvalidOperationException(""Missing Location on redirect.""); } if (commandResult.HttpStatusCode != HttpStatusCode.SeeOther) { throw new InvalidOperationException(""Invalid HttpStatusCode for redirect, but Location is specified""); } response.Redirect(commandResult.Location.OriginalString); } else { response.StatusCode = (int)commandResult.HttpStatusCode; response.ContentType = commandResult.ContentType; response.Write(commandResult.Content); response.End(); } }","[System.Diagnostics.CodeAnalysis.SuppressMessage(""Microsoft.Naming"", ""CA2204:Literals should be spelled correctly"", MessageId = ""HttpStatusCode"")] public static void Apply( this CommandResult commandResult, HttpResponseBase response, bool emitSameSiteNone, string modulePath) { if (commandResult == null) { throw new ArgumentNullException(nameof(commandResult)); } if (response == null) { throw new ArgumentNullException(nameof(response)); } response.Cache.SetCacheability((HttpCacheability)commandResult.Cacheability); ApplyCookies(commandResult, response, emitSameSiteNone, modulePath); ApplyHeaders(commandResult, response); if (commandResult.HttpStatusCode == HttpStatusCode.SeeOther || commandResult.Location != null) { if (commandResult.Location == null) { throw new InvalidOperationException(""Missing Location on redirect.""); } if (commandResult.HttpStatusCode != HttpStatusCode.SeeOther) { throw new InvalidOperationException(""Invalid HttpStatusCode for redirect, but Location is specified""); } response.Redirect(commandResult.Location.OriginalString); } else { response.StatusCode = (int)commandResult.HttpStatusCode; response.ContentType = commandResult.ContentType; response.Write(commandResult.Content); response.End(); } }","Use modulepath in data protection purpose - Prevents reuse of protected data across instances/schemes/modules - Fixes #713",https://github.com/Sustainsys/Saml2/commit/d9e4ff83688d9ebb1ff82a201fab94f1131b7692,,,Sustainsys.Saml2.HttpModule/CommandResultHttpExtensions.cs,3,cs,False,2023-09-19T07:25:15Z "private static StreamConnection readHttpInputStream(String urlAddress, Map headers, String payload) throws IOException { URLConnection con = openUrlConnection(urlAddress, headers); writePayload(con, payload); String newUrl = handleRedirect(con, urlAddress); if (newUrl != null && !urlAddress.equals(newUrl)) { con.getInputStream().close(); return readHttpInputStream(newUrl, headers, payload); } return new StreamConnection.UrlStreamConnection(con); }","public static StreamConnection readHttpInputStream(String urlAddress, Map headers, String payload) throws IOException { ApocConfig.apocConfig().checkReadAllowed(urlAddress); URLConnection con = openUrlConnection(urlAddress, headers); writePayload(con, payload); String newUrl = handleRedirect(con, urlAddress); if (newUrl != null && !urlAddress.equals(newUrl)) { con.getInputStream().close(); return readHttpInputStream(newUrl, headers, payload); } return new StreamConnection.UrlStreamConnection(con); }",Adds load json ssrf mitigation. No AUTO cherry-pick (#2649),https://github.com/neo4j/apoc/commit/81c6942ec60cb6094bca9136efb746b6f1dd9620,,,core/src/main/java/apoc/util/Util.java,3,java,False,2022-03-21T10:16:50Z "static int mg_http_multipart_wait_for_boundary(struct mg_connection *c) { const char *boundary; struct mbuf *io = &c->recv_mbuf; struct mg_http_proto_data *pd = mg_http_get_proto_data(c); if ((int) io->len < pd->mp_stream.boundary_len + 2) { return 0; } boundary = c_strnstr(io->buf, pd->mp_stream.boundary, io->len); if (boundary != NULL) { const char *boundary_end = (boundary + pd->mp_stream.boundary_len); if (io->len - (boundary_end - io->buf) < 4) { return 0; } if (strncmp(boundary_end, ""--\r\n"", 4) == 0) { pd->mp_stream.state = MPS_FINALIZE; mbuf_remove(io, (boundary_end - io->buf) + 4); } else { pd->mp_stream.state = MPS_GOT_BOUNDARY; } } else { return 0; } return 1; }","static int mg_http_multipart_wait_for_boundary(struct mg_connection *c) { const char *boundary; struct mbuf *io = &c->recv_mbuf; struct mg_http_proto_data *pd = mg_http_get_proto_data(c); if (pd->mp_stream.boundary == NULL) { pd->mp_stream.state = MPS_FINALIZE; DBG((""Invalid request: boundary not initilaized"")); return 0; } if ((int) io->len < pd->mp_stream.boundary_len + 2) { return 0; } boundary = c_strnstr(io->buf, pd->mp_stream.boundary, io->len); if (boundary != NULL) { const char *boundary_end = (boundary + pd->mp_stream.boundary_len); if (io->len - (boundary_end - io->buf) < 4) { return 0; } if (strncmp(boundary_end, ""--\r\n"", 4) == 0) { pd->mp_stream.state = MPS_FINALIZE; mbuf_remove(io, (boundary_end - io->buf) + 4); } else { pd->mp_stream.state = MPS_GOT_BOUNDARY; } } else { return 0; } return 1; }","Fix crash in multipart handling Close cesanta/dev#6974 PUBLISHED_FROM=4d4e4a46eceba10aec8dacb7f8f58bd078c92307",https://github.com/cesanta/mongoose/commit/b8402ed0733e3f244588b61ad5fedd093e3cf9cc,,,mongoose.c,3,c,False,2017-04-03T09:14:16Z "@Override public KafkaPrincipal build(AuthenticationContext context) { if (context instanceof SaslAuthenticationContext) { SaslServer saslServer = ((SaslAuthenticationContext) context).server(); if (saslServer instanceof OAuthBearerSaslServer) { OAuthBearerSaslServer server = (OAuthBearerSaslServer) saslServer; if (OAuthBearerLoginModule.OAUTHBEARER_MECHANISM.equals(server.getMechanismName())) { BearerTokenWithPayload token = (BearerTokenWithPayload) server.getNegotiatedProperty(""OAUTHBEARER.token""); Services.getInstance().getSessions().put(token); OAuthKafkaPrincipal kafkaPrincipal = new OAuthKafkaPrincipal(KafkaPrincipal.USER_TYPE, server.getAuthorizationID(), token); return kafkaPrincipal; } } // if another mechanism - e.g. PLAIN is used to communicate the OAuth token Principals principals = Services.getInstance().getPrincipals(); OAuthKafkaPrincipal principal = OAuthKafkaPrincipal.takeFromThreadContext(); if (principal != null) { principals.putPrincipal(saslServer, principal); return principal; } // if principal is required by request / thread other than the one that was just authenticated principal = (OAuthKafkaPrincipal) principals.getPrincipal(saslServer); if (principal != null) { return principal; } } return super.build(context); }","@Override public KafkaPrincipal build(AuthenticationContext context) { if (context instanceof SaslAuthenticationContext) { SaslServer saslServer = ((SaslAuthenticationContext) context).server(); if (saslServer instanceof OAuthBearerSaslServer) { OAuthBearerSaslServer server = (OAuthBearerSaslServer) saslServer; if (OAuthBearerLoginModule.OAUTHBEARER_MECHANISM.equals(server.getMechanismName())) { BearerTokenWithPayload token = (BearerTokenWithPayload) server.getNegotiatedProperty(""OAUTHBEARER.token""); Services.getInstance().getSessions().put(token); OAuthKafkaPrincipal kafkaPrincipal = new OAuthKafkaPrincipal(KafkaPrincipal.USER_TYPE, server.getAuthorizationID(), token); return kafkaPrincipal; } } else if (saslServer instanceof PlainSaslServer) { PlainSaslServer server = (PlainSaslServer) saslServer; // if PLAIN mechanism is used to communicate the OAuth token Principals principals = Services.getInstance().getPrincipals(); OAuthKafkaPrincipal principal = (OAuthKafkaPrincipal) Services.getInstance().getCredentials().takeCredentials(server.getAuthorizationID()); if (principal != null) { principals.putPrincipal(saslServer, principal); return principal; } // if principal is required by request / thread other than the one that was just authenticated principal = (OAuthKafkaPrincipal) principals.getPrincipal(saslServer); if (principal != null) { return principal; } } } return super.build(context); }","Fix for intermittent authentication failures with OAuth over PLAIN (#95) * Fix for intermittent authentication failures with OAuth over PLAIN This fix introduces a breaking change with 0.7.0 in how to authenticate with an access token over SASL_PLAIN by using '$accessToken' as a username. Signed-off-by: Marko Strukelj * Update README.md Signed-off-by: Marko Strukelj * Tests for intermittent authentication failures with OAuth over PLAIN Signed-off-by: Marko Strukelj * Add flood tests for intermittent authentication failures with OAuth over PLAIN Signed-off-by: Marko Strukelj * Fix error checking for flood tests Signed-off-by: Marko Strukelj ",https://github.com/strimzi/strimzi-kafka-oauth/commit/6533a8b6810f585e58a592d39501d25fd0d61764,,,oauth-server/src/main/java/io/strimzi/kafka/oauth/server/OAuthKafkaPrincipalBuilder.java,3,java,False,2021-03-08T18:27:53Z "public Time getTime(int col, Calendar cal) throws SQLException { checkCalendar(cal); DB db = getDatabase(); switch (db.column_type(stmt.pointer, markCol(col))) { case SQLITE_NULL: return null; case SQLITE_TEXT: try { FastDateFormat dateFormat = FastDateFormat.getInstance( getConnectionConfig().getDateStringFormat(), cal.getTimeZone()); return new Time( dateFormat.parse(db.column_text(stmt.pointer, markCol(col))).getTime()); } catch (Exception e) { SQLException error = new SQLException(""Error parsing time""); error.initCause(e); throw error; } case SQLITE_FLOAT: return new Time( julianDateToCalendar(db.column_double(stmt.pointer, markCol(col)), cal) .getTimeInMillis()); default: // SQLITE_INTEGER cal.setTimeInMillis( db.column_long(stmt.pointer, markCol(col)) * getConnectionConfig().getDateMultiplier()); return new Time(cal.getTime().getTime()); } }","public Time getTime(int col, Calendar cal) throws SQLException { checkCalendar(cal); DB db = getDatabase(); switch (safeGetColumnType(markCol(col))) { case SQLITE_NULL: return null; case SQLITE_TEXT: try { FastDateFormat dateFormat = FastDateFormat.getInstance( getConnectionConfig().getDateStringFormat(), cal.getTimeZone()); return new Time(dateFormat.parse(safeGetColumnText(col)).getTime()); } catch (Exception e) { SQLException error = new SQLException(""Error parsing time""); error.initCause(e); throw error; } case SQLITE_FLOAT: return new Time(julianDateToCalendar(safeGetDoubleCol(col), cal).getTimeInMillis()); default: // SQLITE_INTEGER cal.setTimeInMillis( safeGetLongCol(col) * getConnectionConfig().getDateMultiplier()); return new Time(cal.getTime().getTime()); } }",Wrap Statement Pointers to prevent use after free race,https://github.com/xerial/sqlite-jdbc/commit/e1d282cb2887ef427c7ad93d4fe7dd05a6c11473,,,src/main/java/org/sqlite/jdbc3/JDBC3ResultSet.java,3,java,False,2022-07-29T03:54:01Z "private void disableInsecureProtocols(SslContextFactory factory) { // by default all protocols should be available factory.setExcludeProtocols(); factory.setIncludeProtocols(new String[] {""SSLv2Hello"",""SSLv3"",""TLSv1"",""TLSv1.1"",""TLSv1.2""}); if (!configs.getSrvrDisabledCiphers().isEmpty()) { String[] masks = configs.getSrvrDisabledCiphers().split(DISABLED_ENTRIES_SPLITTER); factory.setExcludeCipherSuites(masks); } if (!configs.getSrvrDisabledProtocols().isEmpty()) { String[] masks = configs.getSrvrDisabledProtocols().split(DISABLED_ENTRIES_SPLITTER); factory.setExcludeProtocols(masks); } }","private void disableInsecureProtocols(SslContextFactory factory) { // by default all protocols should be available, excluding TLSv1.0 factory.setExcludeProtocols(DEPRECATED_SSL_PROTOCOLS); factory.setIncludeProtocols(new String[] {""SSLv2Hello"",""SSLv3"",""TLSv1.1"",""TLSv1.2""}); if (!configs.getSrvrDisabledCiphers().isEmpty()) { String[] masks = configs.getSrvrDisabledCiphers().split(DISABLED_ENTRIES_SPLITTER); factory.setExcludeCipherSuites(masks); } if (!configs.getSrvrDisabledProtocols().isEmpty()) { String[] masks = configs.getSrvrDisabledProtocols().split(DISABLED_ENTRIES_SPLITTER); factory.setExcludeProtocols(masks); } }",AMBARI-25520: Insecure Transport : Weak SSL Cipher and weak protocol (#3533),https://github.com/apache/ambari/commit/db5b0b79e54aa3c8a9debac04bbc636ab9dbdc69,,,ambari-server/src/main/java/org/apache/ambari/server/controller/AmbariServer.java,3,java,False,2022-11-21T15:40:26Z "protected final int _parseIntPrimitive(JsonParser p, DeserializationContext ctxt) throws IOException { String text; switch (p.currentTokenId()) { case JsonTokenId.ID_STRING: text = p.getText(); break; case JsonTokenId.ID_NUMBER_FLOAT: final CoercionAction act = _checkFloatToIntCoercion(p, ctxt, Integer.TYPE); if (act == CoercionAction.AsNull) { return 0; } if (act == CoercionAction.AsEmpty) { return 0; } return p.getValueAsInt(); case JsonTokenId.ID_NUMBER_INT: return p.getIntValue(); case JsonTokenId.ID_NULL: _verifyNullForPrimitive(ctxt); return 0; // 29-Jun-2020, tatu: New! ""Scalar from Object"" (mostly for XML) case JsonTokenId.ID_START_OBJECT: text = ctxt.extractScalarFromObject(p, this, Integer.TYPE); break; case JsonTokenId.ID_START_ARRAY: if (ctxt.isEnabled(DeserializationFeature.UNWRAP_SINGLE_VALUE_ARRAYS)) { p.nextToken(); final int parsed = _parseIntPrimitive(p, ctxt); _verifyEndArrayForSingle(p, ctxt); return parsed; } // fall through to fail default: return ((Number) ctxt.handleUnexpectedToken(Integer.TYPE, p)).intValue(); } final CoercionAction act = _checkFromStringCoercion(ctxt, text, LogicalType.Integer, Integer.TYPE); if (act == CoercionAction.AsNull) { // 03-May-2021, tatu: Might not be allowed (should we do ""empty"" check?) _verifyNullForPrimitive(ctxt); return 0; } if (act == CoercionAction.AsEmpty) { return 0; } text = text.trim(); if (_hasTextualNull(text)) { _verifyNullForPrimitiveCoercion(ctxt, text); return 0; } return _parseIntPrimitive(ctxt, text); }","protected final int _parseIntPrimitive(JsonParser p, DeserializationContext ctxt) throws IOException { String text; switch (p.currentTokenId()) { case JsonTokenId.ID_STRING: text = p.getText(); break; case JsonTokenId.ID_NUMBER_FLOAT: final CoercionAction act = _checkFloatToIntCoercion(p, ctxt, Integer.TYPE); if (act == CoercionAction.AsNull) { return 0; } if (act == CoercionAction.AsEmpty) { return 0; } return p.getValueAsInt(); case JsonTokenId.ID_NUMBER_INT: return p.getIntValue(); case JsonTokenId.ID_NULL: _verifyNullForPrimitive(ctxt); return 0; // 29-Jun-2020, tatu: New! ""Scalar from Object"" (mostly for XML) case JsonTokenId.ID_START_OBJECT: text = ctxt.extractScalarFromObject(p, this, Integer.TYPE); break; case JsonTokenId.ID_START_ARRAY: if (ctxt.isEnabled(DeserializationFeature.UNWRAP_SINGLE_VALUE_ARRAYS)) { if (p.nextToken() == JsonToken.START_ARRAY) { return (int) handleNestedArrayForSingle(p, ctxt); } final int parsed = _parseIntPrimitive(p, ctxt); _verifyEndArrayForSingle(p, ctxt); return parsed; } // fall through to fail default: return ((Number) ctxt.handleUnexpectedToken(Integer.TYPE, p)).intValue(); } final CoercionAction act = _checkFromStringCoercion(ctxt, text, LogicalType.Integer, Integer.TYPE); if (act == CoercionAction.AsNull) { // 03-May-2021, tatu: Might not be allowed (should we do ""empty"" check?) _verifyNullForPrimitive(ctxt); return 0; } if (act == CoercionAction.AsEmpty) { return 0; } text = text.trim(); if (_hasTextualNull(text)) { _verifyNullForPrimitiveCoercion(ctxt, text); return 0; } return _parseIntPrimitive(ctxt, text); }","update release notes wrt #3582, [CVE-2022-42004]",https://github.com/FasterXML/jackson-databind/commit/2c4a601c626f7790cad9d3c322d244e182838288,,,src/main/java/com/fasterxml/jackson/databind/deser/std/StdDeserializer.java,3,java,False,2022-10-12T01:42:40Z "@Override public DetectionReportList detect( TargetInfo targetInfo, ImmutableList matchedServices) { return DetectionReportList.newBuilder() .addAllDetectionReports( matchedServices.stream() .filter(NetworkServiceUtils::isWebService) .filter(this::isServiceVulnerable) .map(networkService -> buildDetectionReport(targetInfo, networkService)) .collect(toImmutableList())) .build(); }","@Override public DetectionReportList detect( TargetInfo targetInfo, ImmutableList matchedServices) { return DetectionReportList.newBuilder() .addAllDetectionReports( matchedServices.stream() .filter(this::isWebServiceOrUnknownService) .filter(this::isServiceVulnerable) .map(networkService -> buildDetectionReport(targetInfo, networkService)) .collect(toImmutableList())) .build(); }",fix Apache Druid PreAuth RCE CVE-2021-25646 detector about unknown service,https://github.com/google/tsunami-security-scanner-plugins/commit/61b878539df0033880876d709abb41ff6f92a6c0,,,community/detectors/apache_druid_preauth_rce_cve_2021_25646/src/main/java/com/google/tsunami/plugins/detectors/rce/cve202125646/ApacheDruidPreAuthRCECVE202125646VulnDetector.java,3,java,False,2021-10-20T08:31:04Z "private void handleRedirection(String deviceId, TEndPoint endpoint) { if (enableRedirection) { // no need to redirection if (endpoint.ip.equals(""0.0.0.0"")) { return; } AtomicReference exceptionReference = new AtomicReference<>(); deviceIdToEndpoint.put(deviceId, endpoint); SessionConnection connection = endPointToSessionConnection.computeIfAbsent( endpoint, k -> { try { return constructSessionConnection(this, endpoint, zoneId); } catch (IoTDBConnectionException ex) { exceptionReference.set(ex); return null; } }); if (connection == null) { deviceIdToEndpoint.remove(deviceId); logger.warn(""Can not redirect to {}, because session can not connect to it."", endpoint); } } }","private void handleRedirection(String deviceId, TEndPoint endpoint) { if (enableRedirection) { // no need to redirection if (endpoint.ip.equals(""0.0.0.0"")) { return; } AtomicReference exceptionReference = new AtomicReference<>(); if (!deviceIdToEndpoint.containsKey(deviceId) || !deviceIdToEndpoint.get(deviceId).equals(endpoint)) { deviceIdToEndpoint.put(deviceId, endpoint); } SessionConnection connection = endPointToSessionConnection.computeIfAbsent( endpoint, k -> { try { return constructSessionConnection(this, endpoint, zoneId); } catch (IoTDBConnectionException ex) { exceptionReference.set(ex); return null; } }); if (connection == null) { deviceIdToEndpoint.remove(deviceId); logger.warn(""Can not redirect to {}, because session can not connect to it."", endpoint); } } }",[IOTDB-5498] Fix SessionPool OOM when the numbers of devices and sessions are large (#9012),https://github.com/apache/iotdb/commit/ed34105697559e8e2ac66bfd5164698de0076e04,,,session/src/main/java/org/apache/iotdb/session/Session.java,3,java,False,2023-02-08T07:44:56Z "public JsonObject getSearchedItemPage(int index) { if (index < getSlotsXSize() * getSlotsYSize()) { int actualIndex = index + getSlotsXSize() * getSlotsYSize() * page; List searchedItems = getSearchedItems(); if (actualIndex < searchedItems.size()) { return searchedItems.get(actualIndex); } else { return null; } } else { return null; } }","public JsonObject getSearchedItemPage(int index) { if (index < getSlotsXSize() * getSlotsYSize()) { int actualIndex = index + getSlotsXSize() * getSlotsYSize() * page; List searchedItems = getSearchedItems(); if (0 <= actualIndex && actualIndex < searchedItems.size()) { return searchedItems.get(actualIndex); } else { return null; } } else { return null; } }",the people in #general said this would fix a crash (#317),https://github.com/Moulberry/NotEnoughUpdates/commit/c231bdc6e3079a8455b9b7c4173528c1c1ecf42e,,,src/main/java/io/github/moulberry/notenoughupdates/NEUOverlay.java,3,java,False,2022-09-27T02:16:35Z "public List hasRights(String requestId, String actorCrn, Iterable rightChecks) { checkNotNull(requestId, ""requestId should not be null.""); checkNotNull(actorCrn, ""actorCrn should not be null.""); checkNotNull(rightChecks, ""rightChecks should not be null.""); try { AuthorizationProto.HasRightsResponse response = newStub(requestId).hasRights( AuthorizationProto.HasRightsRequest.newBuilder() .setActorCrn(actorCrn) .addAllCheck(rightChecks) .build() ); return response.getResultList(); } catch (StatusRuntimeException statusRuntimeException) { if (Status.Code.DEADLINE_EXCEEDED.equals(statusRuntimeException.getStatus().getCode())) { LOGGER.error(""Deadline exceeded for hasRights {} for actor {} and rights {}"", actorCrn, rightChecks, statusRuntimeException); throw new CloudbreakServiceException(""Authorization failed due to user management service call timed out.""); } else { LOGGER.error(""Status runtime exception while checking hasRights {} for actor {} and rights {}"", actorCrn, rightChecks, statusRuntimeException); throw new CloudbreakServiceException(""Authorization failed due to user management service call failed.""); } } catch (Exception e) { LOGGER.error(""Unknown error while checking hasRights {} for actor {} and rights {}"", actorCrn, rightChecks, e); throw new CloudbreakServiceException(""Authorization failed due to user management service call failed with error.""); } }","public List hasRights(String requestId, String actorCrn, Iterable rightChecks) { checkNotNull(requestId, ""requestId should not be null.""); checkNotNull(actorCrn, ""actorCrn should not be null.""); checkNotNull(rightChecks, ""rightChecks should not be null.""); try { AuthorizationProto.HasRightsResponse response = newStub(requestId).hasRights( AuthorizationProto.HasRightsRequest.newBuilder() .setActorCrn(actorCrn) .addAllCheck(rightChecks) .build() ); return response.getResultList(); } catch (StatusRuntimeException statusRuntimeException) { if (Status.Code.DEADLINE_EXCEEDED.equals(statusRuntimeException.getStatus().getCode())) { LOGGER.error(""Deadline exceeded for hasRights {} for actor {} and rights {}"", actorCrn, rightChecks, statusRuntimeException); throw new CloudbreakServiceException(""Authorization failed due to user management service call timed out.""); } else if (Status.Code.NOT_FOUND.equals(statusRuntimeException.getStatus().getCode())) { LOGGER.error(""NOT_FOUND for hasRights for actor {} and rights {}, cause: {}"", actorCrn, rightChecks, statusRuntimeException); throw new UnauthorizedException(""Authorization failed for user: "" + actorCrn); } else { LOGGER.error(""Status runtime exception while checking hasRights {} for actor {} and rights {}"", actorCrn, rightChecks, statusRuntimeException); throw new CloudbreakServiceException(""Authorization failed due to user management service call failed.""); } } catch (Exception e) { LOGGER.error(""Unknown error while checking hasRights {} for actor {} and rights {}"", actorCrn, rightChecks, e); throw new CloudbreakServiceException(""Authorization failed due to user management service call failed with error.""); } }","CB-17492 If UMS call returns (user) NOT_FOUND, it should result in 401 Unauthorized response",https://github.com/hortonworks/cloudbreak/commit/ecd578edb230535c7f90247176d97f835834b661,,,auth-connector/src/main/java/com/sequenceiq/cloudbreak/auth/altus/AuthorizationClient.java,3,java,False,2022-06-22T13:34:41Z "private static AOException buildInternalException(final String msg, final Properties extraParams) { AOException exception = null; final int separatorPos = msg.indexOf("":""); //$NON-NLS-1$ if (msg.startsWith(CONFIG_NEEDED_ERROR_PREFIX)) { final int separatorPos2 = msg.indexOf("":"", separatorPos + 1); //$NON-NLS-1$ final String errorCode = msg.substring(separatorPos + 1, separatorPos2); final String errorMsg = msg.substring(separatorPos2 + 1); if (PdfIsCertifiedException.REQUESTOR_MSG_CODE.equals(errorCode)) { exception = new PdfIsCertifiedException(errorMsg); } else if (PdfHasUnregisteredSignaturesException.REQUESTOR_MSG_CODE.equals(errorCode)) { exception = new PdfHasUnregisteredSignaturesException(errorMsg); } else if (SuspectedPSAException.REQUESTOR_MSG_CODE.equals(errorCode)) { exception = new SuspectedPSAException(errorMsg); } else if (PdfIsPasswordProtectedException.REQUESTOR_MSG_CODE.equals(errorCode) || BadPdfPasswordException.REQUESTOR_MSG_CODE.equals(errorCode)) { if (extraParams != null && (extraParams.containsKey(PdfExtraParams.OWNER_PASSWORD_STRING) || extraParams.containsKey(PdfExtraParams.USER_PASSWORD_STRING))) { exception = new BadPdfPasswordException(errorMsg); } else { exception = new PdfIsPasswordProtectedException(errorMsg); } } } if (exception == null) { final int internalExceptionPos = msg.indexOf("":"", separatorPos + 1); //$NON-NLS-1$ if (internalExceptionPos > 0) { final String intMessage = msg.substring(internalExceptionPos + 1).trim(); exception = AOTriphaseException.parseException(intMessage); } else { exception = new AOException(msg); } } return exception; }","private static AOException buildInternalException(final String msg, final Properties extraParams) { AOException exception = null; final int separatorPos = msg.indexOf("":""); //$NON-NLS-1$ if (msg.startsWith(CONFIG_NEEDED_ERROR_PREFIX)) { final int separatorPos2 = msg.indexOf("":"", separatorPos + 1); //$NON-NLS-1$ final String errorCode = msg.substring(separatorPos + 1, separatorPos2); final String errorMsg = msg.substring(separatorPos2 + 1); if (PdfIsCertifiedException.REQUESTOR_MSG_CODE.equals(errorCode)) { exception = new PdfIsCertifiedException(errorMsg); } else if (PdfHasUnregisteredSignaturesException.REQUESTOR_MSG_CODE.equals(errorCode)) { exception = new PdfHasUnregisteredSignaturesException(errorMsg); } else if (PdfFormModifiedException.REQUESTOR_MSG_CODE.equals(errorCode)) { exception = new PdfFormModifiedException(errorMsg); } else if (SuspectedPSAException.REQUESTOR_MSG_CODE.equals(errorCode)) { exception = new SuspectedPSAException(errorMsg); } else if (PdfIsPasswordProtectedException.REQUESTOR_MSG_CODE.equals(errorCode) || BadPdfPasswordException.REQUESTOR_MSG_CODE.equals(errorCode)) { if (extraParams != null && (extraParams.containsKey(PdfExtraParams.OWNER_PASSWORD_STRING) || extraParams.containsKey(PdfExtraParams.USER_PASSWORD_STRING))) { exception = new BadPdfPasswordException(errorMsg); } else { exception = new PdfIsPasswordProtectedException(errorMsg); } } } if (exception == null) { final int internalExceptionPos = msg.indexOf("":"", separatorPos + 1); //$NON-NLS-1$ if (internalExceptionPos > 0) { final String intMessage = msg.substring(internalExceptionPos + 1).trim(); exception = AOTriphaseException.parseException(intMessage); } else { exception = new AOException(msg); } } return exception; }","Validación de formularios PDF - Se incluye a la validación de firmas PDF la comprobación de que los formularios no se hayan modificado después de firmar el documento. - Se incorpora la identificación de los cambios en los formularios PDF en el proceso de firma trifásica. - Se agrega la información de la validación de formularios y de PDF Shadow Attack a la ayuda integrada de AutoFirma.",https://github.com/ctt-gob-es/clienteafirma/commit/09ae16ec502c0e9df812f44f1654f337032df7ef,,,afirma-crypto-padestri-client/src/main/java/es/gob/afirma/signers/padestri/client/AOPDFTriPhaseSigner.java,3,java,False,2022-09-14T14:03:06Z "private static void unzip(InputStream stream, String destination) { dirChecker(destination, """"); byte[] buffer = new byte[BUFFER_SIZE]; try { ZipInputStream zin = new ZipInputStream(stream); ZipEntry ze = null; while ((ze = zin.getNextEntry()) != null) { Log.v(TAG, ""Unzipping "" + ze.getName()); if (ze.isDirectory()) { dirChecker(destination, ze.getName()); } else { File f = new File(destination, ze.getName()); if (!f.exists()) { boolean success = f.createNewFile(); if (!success) { Log.w(TAG, ""Failed to create file "" + f.getName()); continue; } FileOutputStream fout = new FileOutputStream(f); int count; while ((count = zin.read(buffer)) != -1) { fout.write(buffer, 0, count); } zin.closeEntry(); fout.close(); } } } zin.close(); } catch (Exception e) { Log.e(TAG, ""unzip"", e); } }","private static void unzip(InputStream stream, String destination) { dirChecker(destination, """"); byte[] buffer = new byte[BUFFER_SIZE]; try { ZipInputStream zin = new ZipInputStream(stream); ZipEntry ze = null; while ((ze = zin.getNextEntry()) != null) { Log.v(TAG, ""Unzipping "" + ze.getName()); if (ze.isDirectory()) { dirChecker(destination, ze.getName()); } else { File f = new File(destination, ze.getName()); if (!f.toPath().normalize().startsWith(destination.toPath())) throw new SecurityException(""Potentially harmful files detected inside zip""); if (!f.exists()) { boolean success = f.createNewFile(); if (!success) { Log.w(TAG, ""Failed to create file "" + f.getName()); continue; } FileOutputStream fout = new FileOutputStream(f); int count; while ((count = zin.read(buffer)) != -1) { fout.write(buffer, 0, count); } zin.closeEntry(); fout.close(); } } } zin.close(); } catch (IOException e) { Log.e(TAG, ""unzip"", e); } }",feat: use multiline syntax,https://github.com/Cosmic-Ide/Cosmic-IDE/commit/e226a44b4fd6aa8ca47890cf1c2243ccec04c794,,,lib-android/src/main/java/com/pranav/lib_android/util/ZipUtil.java,3,java,False,2022-04-02T08:41:14Z "private FileSystemBlobVaultOld createDefaultFSBlobVault() { try { FileSystemBlobVaultOld blobVault; final PersistentSequenceBlobHandleGenerator.PersistentSequenceGetter persistentSequenceGetter = () -> getSequence(getAndCheckCurrentTransaction(), BLOB_HANDLES_SEQUENCE); try { blobVault = new FileSystemBlobVault(config, location, BLOBS_DIR, BLOBS_EXTENSION, new PersistentSequenceBlobHandleGenerator(persistentSequenceGetter)); } catch (UnexpectedBlobVaultVersionException e) { blobVault = null; } if (blobVault == null) { if (config.getMaxInPlaceBlobSize() > 0) { blobVault = new FileSystemBlobVaultOld(config, location, BLOBS_DIR, BLOBS_EXTENSION, BlobHandleGenerator.IMMUTABLE); } else { blobVault = new FileSystemBlobVaultOld(config, location, BLOBS_DIR, BLOBS_EXTENSION, new PersistentSequenceBlobHandleGenerator(persistentSequenceGetter)); } } final long current = persistentSequenceGetter.get().get(); for (long blobHandle = current + 1; blobHandle < current + 1000; ++blobHandle) { final BlobVaultItem item = blobVault.getBlob(blobHandle); if (item.exists()) { logger.error(""Redundant blob item: "" + item); } } blobVault.setSizeFunctions(new CachedBlobLengths(environment, blobFileLengths)); return blobVault; } catch (IOException e) { throw ExodusException.toExodusException(e); } }","private FileSystemBlobVaultOld createDefaultFSBlobVault() { try { FileSystemBlobVaultOld blobVault; final PersistentSequenceBlobHandleGenerator.PersistentSequenceGetter persistentSequenceGetter = () -> getSequence(getAndCheckCurrentTransaction(), BLOB_HANDLES_SEQUENCE); try { blobVault = new FileSystemBlobVault(environment, config, location, BLOBS_DIR, BLOBS_EXTENSION, new PersistentSequenceBlobHandleGenerator(persistentSequenceGetter)); } catch (UnexpectedBlobVaultVersionException e) { blobVault = null; } if (blobVault == null) { if (config.getMaxInPlaceBlobSize() > 0) { blobVault = new FileSystemBlobVaultOld(environment, config, location, BLOBS_DIR, BLOBS_EXTENSION, BlobHandleGenerator.IMMUTABLE); } else { blobVault = new FileSystemBlobVaultOld(environment, config, location, BLOBS_DIR, BLOBS_EXTENSION, new PersistentSequenceBlobHandleGenerator(persistentSequenceGetter)); } } final long current = persistentSequenceGetter.get().get(); for (long blobHandle = current + 1; blobHandle < current + 1000; ++blobHandle) { final BlobVaultItem item = blobVault.getBlob(blobHandle); if (item.exists()) { logger.error(""Redundant blob item: "" + item); } } blobVault.setSizeFunctions(new CachedBlobLengths(environment, blobFileLengths)); return blobVault; } catch (IOException e) { throw ExodusException.toExodusException(e); } }","Issue XD-908 was fixed. (#44) Issue XD-908 was fixed. 1. Callback which allows executing version post-validation actions before data flush was added. 2. BufferedInputStreams are used instead of ByteArray streams to fall back to the stored position during the processing of stream inside EntityStore. Which should decrease the risk of OOM. 3. All streams are stored in the temporary directory before transaction flush (after validation of the transaction version) and then moved to the BlobVault location after a successful commit. That is done gracefully handling situations when streams generate errors while storing the data. 4. Passed-in streams are automatically closed during commit/flush and abort/revert of transaction.",https://github.com/JetBrains/xodus/commit/9b7d0e6387d80b3e30abb48cad5a064f12cf8b38,,,entity-store/src/main/java/jetbrains/exodus/entitystore/PersistentEntityStoreImpl.java,3,java,False,2023-01-24T09:44:19Z "@AnyThread public void stopSurface() { if (isStopped()) { return; } // Prevent more views from being created, or the hierarchy from being manipulated at all. This // causes further operations to noop. mIsStopped = true; // Reset all StateWrapper objects // Since this can happen on any thread, is it possible to race between StateWrapper destruction // and some accesses from View classes in the UI thread? for (ViewState viewState : mTagToViewState.values()) { if (viewState.mStateWrapper != null) { viewState.mStateWrapper.destroyState(); viewState.mStateWrapper = null; } if (viewState.mEventEmitter != null) { viewState.mEventEmitter.destroy(); viewState.mEventEmitter = null; } } Runnable runnable = new Runnable() { @Override public void run() { // We must call `onDropViewInstance` on all remaining Views for (ViewState viewState : mTagToViewState.values()) { onViewStateDeleted(viewState); } // Evict all views from cache and memory mTagSetForStoppedSurface = mTagToViewState.keySet(); mTagToViewState = null; mJSResponderHandler = null; mRootViewManager = null; mMountItemExecutor = null; mOnViewAttachItems.clear(); } }; if (UiThreadUtil.isOnUiThread()) { runnable.run(); } else { UiThreadUtil.runOnUiThread(runnable); } }","@AnyThread public void stopSurface() { if (isStopped()) { return; } // Prevent more views from being created, or the hierarchy from being manipulated at all. This // causes further operations to noop. mIsStopped = true; // Reset all StateWrapper objects // Since this can happen on any thread, is it possible to race between StateWrapper destruction // and some accesses from View classes in the UI thread? for (ViewState viewState : mTagToViewState.values()) { if (viewState.mStateWrapper != null) { viewState.mStateWrapper.destroyState(); viewState.mStateWrapper = null; } if (ReactFeatureFlags.enableAggressiveEventEmitterCleanup) { if (viewState.mEventEmitter != null) { viewState.mEventEmitter.destroy(); viewState.mEventEmitter = null; } } } Runnable runnable = new Runnable() { @Override public void run() { // We must call `onDropViewInstance` on all remaining Views for (ViewState viewState : mTagToViewState.values()) { onViewStateDeleted(viewState); } // Evict all views from cache and memory mTagSetForStoppedSurface = mTagToViewState.keySet(); mTagToViewState = null; mJSResponderHandler = null; mRootViewManager = null; mMountItemExecutor = null; mOnViewAttachItems.clear(); } }; if (UiThreadUtil.isOnUiThread()) { runnable.run(); } else { UiThreadUtil.runOnUiThread(runnable); } }","Guard against unsafe EventEmitter setup and teardown Summary: Because of T92179998, T93607943, and T93394807, we are still seeking resolution to tricky crashes wrt the use of EventEmitters. I believe the recent spike is because of two recent changes: we pass in EventEmitters earlier, during PreAllocation; and we clean them up earlier, during stopSurface, to avoid jsi::~Pointer crashes. Additionally, the gating previously added around the PreAllocation path was incorrect and led to more nullptrs being passed around as EventEmitters. To mitigate these issues: 1) I am adding/fixing gating to preallocation and early cleanup paths 2) I am making EventEmitterWrapper more resilient by ensuring EventEmitter is non-null before invoking it. 3) I am making sure that in more cases, we pass a non-null EventEmitter pointer to Java. 4) I am backing out the synchronization in EventEmitterWrapper (java side) as that did not resolve the issue and is a pessimisation There are older, unchanged paths that could still be passing in nullptr as the EventEmitter (Update and Create). As those have not changed recently, I'm not going to fix those cases and instead, we can now rely on the caller to ensure that the EventEmitter is non-null before calling. Changelog: [internal] Differential Revision: D29252806 fbshipit-source-id: 5c68d95fa2465afe45e0083a0685c8c1abf31619",https://github.com/react-native-tvos/react-native-tvos/commit/006f5afe120c290a37cf6ff896748fbc062bf7ed,,,ReactAndroid/src/main/java/com/facebook/react/fabric/mounting/SurfaceMountingManager.java,3,java,False,2021-06-20T05:55:36Z "private List splitOnMigration(Split split) { IndexIterationPointer[] lastPointers = split.pointers; InternalPartitionService partitionService = getNodeEngine(hazelcastInstance).getPartitionService(); Map newSplits = new HashMap<>(); PrimitiveIterator.OfInt partitionIterator = split.partitions.intIterator(); while (partitionIterator.hasNext()) { int partitionId = partitionIterator.nextInt(); // If at least one partition owner is not assigned -- assign current member. // Later, a WrongTargetException will be thrown // and it causes this method to be called again. // Occasionally prediction with current member would be correct. Address potentialOwner = partitionService.getPartition(partitionId).getOwnerOrNull(); Address owner = potentialOwner == null ? split.owner : partitionService.getPartition(partitionId).getOwnerOrNull(); newSplits.computeIfAbsent(owner, x -> new Split( new PartitionIdSet(partitionService.getPartitionCount()), owner, lastPointers) ).partitions.add(partitionId); } return new ArrayList<>(newSplits.values()); }","private List splitOnMigration(Split split) { IndexIterationPointer[] lastPointers = split.pointers; InternalPartitionService partitionService = getNodeEngine(hazelcastInstance).getPartitionService(); Map newSplits = new HashMap<>(); PrimitiveIterator.OfInt partitionIterator = split.partitions.intIterator(); while (partitionIterator.hasNext()) { int partitionId = partitionIterator.nextInt(); // If at least one partition owner is not assigned -- assign current member. // Later, a WrongTargetException will be thrown // and it causes this method to be called again. // Occasionally prediction with current member would be correct. Address potentialOwner = partitionService.getPartition(partitionId).getOwnerOrNull(); Address owner = potentialOwner == null ? split.owner : partitionService.getPartition(partitionId).getOwnerOrNull(); newSplits.computeIfAbsent(owner, x -> new Split( new PartitionIdSet(partitionService.getPartitionCount()), owner, lastPointers) ).partitions.add(partitionId); } ArrayList res = new ArrayList<>(newSplits.values()); // if the resulting split is the same as the input split, postpone retrying it if (res.size() == 1) { Split newSplit = res.get(0); if (newSplit.owner.equals(split.owner) && newSplit.partitions.equals(split.partitions)) { newSplit.postponeUntil(System.nanoTime() + DELAY_AFTER_MISSING_PARTITION); } } return res; }","Prevent infinite loop when local partition missing (#20894) This could have happened: - reading of local partition throws MissingPartitionException - processor looks at partition table, the partition is assigned to the same owner - the new split is immediately retried. Since it's local partition, the operation is run in-thread. The above loops forever because of #20876. But even if it is fixed, the new algorithm will be more robust as it will not spin until the situation resolves, but will rather do it after a delay. We only insert the delay if there was no change in the splits. If there was, it makes sense to retry immediately.",https://github.com/hazelcast/hazelcast/commit/feaacf223b0ccd0d2198a2257575b5c26bee135e,,,hazelcast-sql/src/main/java/com/hazelcast/jet/sql/impl/connector/map/MapIndexScanP.java,3,java,False,2022-03-07T21:52:06Z "@Override public void write(int c) { buf.append(c); }","@Override public void write(int c) { buf.append((char) c); }","SusiMail: Prevent infinite loop on decoding error More test mods Fix StringBuilderWriter.write(int)",https://github.com/i2p/i2p.i2p/commit/21485eff8759b21dec8c37b4d947f79903029c8f,,,apps/susimail/src/src/i2p/susi/util/StringBuilderWriter.java,3,java,False,2021-04-24T23:37:18Z "public synchronized void configureRequestHeaders(HttpServletRequest originalRequest, HttpRequestBase proxyRequest, boolean localProxy, String targetServiceName) { final StringBuilder headersLog = logger.isTraceEnabled() ? new StringBuilder(""Request Headers:\n==========================================================\n"") : null; // see https://github.com/georchestra/georchestra/issues/509: addHeaderToRequestAndLog(proxyRequest, headersLog, SEC_PROXY, ""true""); if (!isPreAuthorized(originalRequest)) { addAllowedIncomingHeaders(originalRequest, proxyRequest, localProxy, headersLog); } if (localProxy) { handleRequestCookies(originalRequest, proxyRequest, headersLog); applyHeaderProviders(originalRequest, proxyRequest, headersLog, targetServiceName); } else if (forcedReferer != null) { addHeaderToRequestAndLog(proxyRequest, headersLog, REFERER_HEADER_NAME, this.forcedReferer); } if (logger.isTraceEnabled()) { headersLog.append(""==========================================================""); logger.trace(headersLog.toString()); } }","public synchronized void configureRequestHeaders(HttpServletRequest originalRequest, HttpRequestBase proxyRequest, boolean localProxy, String targetServiceName) { final StringBuilder headersLog = logger.isTraceEnabled() ? new StringBuilder(""Request Headers:\n==========================================================\n"") : null; // see https://github.com/georchestra/georchestra/issues/509: addHeaderToRequestAndLog(proxyRequest, headersLog, SEC_PROXY, ""true""); if (!HeaderProvider.isPreAuthorized(originalRequest)) { addAllowedIncomingHeaders(originalRequest, proxyRequest, localProxy, headersLog); } if (localProxy) { handleRequestCookies(originalRequest, proxyRequest, headersLog); applyHeaderProviders(originalRequest, proxyRequest, headersLog, targetServiceName); } else if (forcedReferer != null) { addHeaderToRequestAndLog(proxyRequest, headersLog, REFERER_HEADER_NAME, this.forcedReferer); } if (logger.isTraceEnabled()) { headersLog.append(""==========================================================""); logger.trace(headersLog.toString()); } }","Set pre-auth as a property of the request, not the session Using the http Session object to hold a per-request property can result in a race condition and a security attack vector. ProxyTrustAnotherProxy works on a per-request basis, so it makes all sense to set the pre-auth attribute on the request instead.",https://github.com/georchestra/georchestra/commit/b9637b7a4cee6fedf0fba7dcc9996e4dd5732499,,,security-proxy/src/main/java/org/georchestra/security/HeadersManagementStrategy.java,3,java,False,2021-04-20T21:40:04Z "private AuthSession session(SessionContext context) { return sessions.get( context.sessionId(), id -> newSession(context.credentials(), context.properties(), catalogAuth)); }","private AuthSession session(SessionContext context) { AuthSession session = sessions.get( context.sessionId(), id -> newSession(context.credentials(), context.properties(), catalogAuth)); return session != null ? session : catalogAuth; }",Core: Prevent RESTCatalog AuthSession from expiring (#6749),https://github.com/spatialx-project/geolake/commit/32a8ef52ddf20aa2068dfff8f9e73bd5d27ef610,,,core/src/main/java/org/apache/iceberg/rest/RESTSessionCatalog.java,3,java,False,2023-02-06T20:32:05Z "@Override public IngestDocument execute(IngestDocument ingestDocument) throws Exception { throw new UnsupportedOperationException(""this method should not get executed""); }","@Override public IngestDocument execute(IngestDocument ingestDocument) throws Exception { assert isAsync() == false; Object o = ingestDocument.getFieldValue(field, Object.class, ignoreMissing); if (o == null) { if (ignoreMissing) { return ingestDocument; } else { throw new IllegalArgumentException(""field ["" + field + ""] is null, cannot loop over its elements.""); } } else if (o instanceof Map map) { return iterateMap(ingestDocument, map); } else if (o instanceof List list) { return iterateList(ingestDocument, list); } else { throw new IllegalArgumentException( ""field ["" + field + ""] of type ["" + o.getClass().getName() + ""] cannot be cast to a "" + ""list or map"" ); } }","Iteratively execute synchronous ingest processors (#84250) Iteratively executes ingest processors that are not asynchronous. This resolves the issue of stack overflows that could occur in large ingest pipelines. As a secondary effect, it dramatically reduces the depth of the stack during ingest pipeline execution which reduces the performance cost of gathering a stack trace for any exceptions instantiated during pipeline execution. The aggregate performance effect of these changes has been observed to be a 10-15% improvement in some larger pipelines.",https://github.com/elastic/elasticsearch/commit/cce3d924754a06634a8e353fa227be3af2eeca62,,,modules/ingest-common/src/main/java/org/elasticsearch/ingest/common/ForEachProcessor.java,3,java,False,2022-04-12T13:39:46Z "protected void setupBarterEvent() { int tries = 0; boolean lastTry = false; reloadPickers(); while (true) { tries++; if (tries >= 10) lastTry = true; String commodityGive = givePicker.pick(); String commodityTake = null; do { if (takePicker.isEmpty()) reloadPickers(); commodityTake = takePicker.pickAndRemove(); } while (commodityTake == null || commodityTake.equals(commodityGive)); //log.info(""Picked commodities: "" + commodityGive + "", "" + commodityTake); CargoAPI cargo = Global.getSector().getPlayerFleet().getCargo(); if (cargo.getCommodityQuantity(commodityTake) <= 0 && !lastTry) { // we don't have this commodity, try again continue; } float baseAmount = cargo.getMaxCapacity(); baseAmount = Math.min(baseAmount, 1000); if (baseAmount < 100) baseAmount = 100; baseAmount = (int)(baseAmount/100) * 10; baseAmount *= 0.25f * MathUtils.getRandomNumberInRange(2, 8); setupCommodities(commodityGive, commodityTake, baseAmount, 1.25f, 1); if (cargo.getCommodityQuantity(commodityTake) < (int)memory.getLong(MEM_KEY_TAKE_COUNT) && !lastTry) { // we don't have enough of this commodity, try again continue; } log.info(""Picked barter commodity after "" + tries + "" tries""); break; } }","protected void setupBarterEvent() { int tries = 0; boolean lastTry = false; reloadPickers(); while (!lastTry) { tries++; if (tries >= 10) lastTry = true; String commodityGive = givePicker.pick(); String commodityTake = null; do { if (takePicker.isEmpty()) reloadPickers(); commodityTake = takePicker.pickAndRemove(); if (lastTry) break; } while (commodityTake == null || commodityTake.equals(commodityGive)); //log.info(""Picked commodities: "" + commodityGive + "", "" + commodityTake); CargoAPI cargo = Global.getSector().getPlayerFleet().getCargo(); if (cargo.getCommodityQuantity(commodityTake) <= 0 && !lastTry) { // we don't have this commodity, try again continue; } float baseAmount = cargo.getMaxCapacity(); baseAmount = Math.min(baseAmount, 1000); if (baseAmount < 100) baseAmount = 100; baseAmount = (int)(baseAmount/100) * 10; baseAmount *= 0.25f * MathUtils.getRandomNumberInRange(2, 8); setupCommodities(commodityGive, commodityTake, baseAmount, 1.25f, 1); if (cargo.getCommodityQuantity(commodityTake) < (int)memory.getLong(MEM_KEY_TAKE_COUNT) && !lastTry) { // we don't have enough of this commodity, try again continue; } log.info(""Picked barter commodity after "" + tries + "" tries""); break; } }",Prevent possible infinite loop in deciv planet encounter,https://github.com/Histidine91/Nexerelin/commit/c74d4f128b4633f929638c13a9b60eee8b87036c,,,jars/sources/ExerelinCore/com/fs/starfarer/api/impl/campaign/rulecmd/salvage/Nex_DecivEvent.java,3,java,False,2021-06-03T09:52:35Z "public static String substitute(String pattern, String org, String module, String branch, String revision, String artifact, String type, String ext, String conf, ArtifactOrigin origin, Map extraModuleAttributes, Map extraArtifactAttributes) { Map tokens = new HashMap<>(); if (extraModuleAttributes != null) { for (Map.Entry entry : extraModuleAttributes.entrySet()) { String token = entry.getKey(); if (token.indexOf(':') > 0) { token = token.substring(token.indexOf(':') + 1); } tokens.put(token, entry.getValue()); } } if (extraArtifactAttributes != null) { for (Map.Entry entry : extraArtifactAttributes.entrySet()) { String token = entry.getKey(); if (token.indexOf(':') > 0) { token = token.substring(token.indexOf(':') + 1); } tokens.put(token, entry.getValue()); } } tokens.put(ORGANISATION_KEY, org == null ? """" : org); tokens.put(ORGANISATION_KEY2, org == null ? """" : org); tokens.put(ORGANISATION_PATH_KEY, org == null ? """" : org.replace('.', '/')); tokens.put(MODULE_KEY, module == null ? """" : module); tokens.put(BRANCH_KEY, branch == null ? """" : branch); tokens.put(REVISION_KEY, revision == null ? """" : revision); tokens.put(ARTIFACT_KEY, artifact == null ? module : artifact); tokens.put(TYPE_KEY, type == null ? ""jar"" : type); tokens.put(EXT_KEY, ext == null ? ""jar"" : ext); tokens.put(CONF_KEY, conf == null ? ""default"" : conf); if (origin == null) { tokens.put(ORIGINAL_ARTIFACTNAME_KEY, new OriginalArtifactNameValue(org, module, branch, revision, artifact, type, ext, extraModuleAttributes, extraArtifactAttributes)); } else { tokens.put(ORIGINAL_ARTIFACTNAME_KEY, new OriginalArtifactNameValue(origin)); } return substituteTokens(pattern, tokens, false); }","public static String substitute(String pattern, String org, String module, String branch, String revision, String artifact, String type, String ext, String conf, ArtifactOrigin origin, Map extraModuleAttributes, Map extraArtifactAttributes) { Map tokens = new HashMap<>(); if (extraModuleAttributes != null) { for (Map.Entry entry : extraModuleAttributes.entrySet()) { String token = entry.getKey(); if (token.indexOf(':') > 0) { token = token.substring(token.indexOf(':') + 1); } tokens.put(token, new Validated(token, entry.getValue())); } } if (extraArtifactAttributes != null) { for (Map.Entry entry : extraArtifactAttributes.entrySet()) { String token = entry.getKey(); if (token.indexOf(':') > 0) { token = token.substring(token.indexOf(':') + 1); } tokens.put(token, new Validated(token, entry.getValue())); } } tokens.put(ORGANISATION_KEY, org == null ? """" : new Validated(ORGANISATION_KEY, org)); tokens.put(ORGANISATION_KEY2, org == null ? """" : new Validated(ORGANISATION_KEY2, org)); tokens.put(ORGANISATION_PATH_KEY, org == null ? """" : org.replace('.', '/')); tokens.put(MODULE_KEY, module == null ? """" : new Validated(MODULE_KEY, module)); tokens.put(BRANCH_KEY, branch == null ? """" : new Validated(BRANCH_KEY, branch)); tokens.put(REVISION_KEY, revision == null ? """" : new Validated(REVISION_KEY, revision)); tokens.put(ARTIFACT_KEY, new Validated(ARTIFACT_KEY, artifact == null ? module : artifact)); tokens.put(TYPE_KEY, type == null ? ""jar"" : new Validated(TYPE_KEY, type)); tokens.put(EXT_KEY, ext == null ? ""jar"" : new Validated(EXT_KEY, ext)); tokens.put(CONF_KEY, conf == null ? ""default"" : new Validated(CONF_KEY, conf)); if (origin == null) { tokens.put(ORIGINAL_ARTIFACTNAME_KEY, new OriginalArtifactNameValue(org, module, branch, revision, artifact, type, ext, extraModuleAttributes, extraArtifactAttributes)); } else { tokens.put(ORIGINAL_ARTIFACTNAME_KEY, new OriginalArtifactNameValue(origin)); } return substituteTokens(pattern, tokens, false); }",CVE-2022-37865 ZipPacking allows overwriting arbitrary files,https://github.com/apache/ant-ivy/commit/3f374602d4d63691398951b9af692960d019f4d9,,,src/java/org/apache/ivy/core/IvyPatternHelper.java,3,java,False,2022-08-21T16:54:43Z "@Override public void serialize(String value, JsonGenerator jsonGenerator, SerializerProvider serializerProvider) throws IOException { if (value != null) { String encodedValue = HtmlUtils.htmlEscape(value); jsonGenerator.writeString(encodedValue); } }","@Override public void serialize(String value, JsonGenerator jsonGenerator, SerializerProvider serializerProvider) throws IOException { if (value != null) { String encodedValue = HtmlUtils.cleanUnSafe(value); jsonGenerator.writeString(encodedValue); } }",:zap: 使用 Jackson2ObjectMapperBuilder 构造 ObjectMapper,保留使用配置文件配置 jackson 属性的能力,以及方便用户增加自定义配置,https://github.com/ballcat-projects/ballcat/commit/d4d5d4c4aa4402bec83db4eab7007f0cf70e8e01,,,ballcat-common/ballcat-common-core/src/main/java/com/hccake/ballcat/common/core/jackson/XssStringJsonSerializer.java,3,java,False,2021-03-08T14:05:28Z "static void ast_dealloc(AST_object *self) { Py_CLEAR(self->dict); Py_TYPE(self)->tp_free(self); }","static void ast_dealloc(AST_object *self) { /* bpo-31095: UnTrack is needed before calling any callbacks */ PyObject_GC_UnTrack(self); Py_CLEAR(self->dict); Py_TYPE(self)->tp_free(self); }","Fully incorporate the code from Python 3.7.2 (#78) This is a full port, following the recipe in update_process.md. I've also tried to keep the recipe up to date and improved the automation (see tools/script). I haven't cleaned up the commits. As of #77 there are a few tests that sanity-check this (though it's far from a full test suite), and they're run by Travis-CI and AppVeyor.",https://github.com/python/typed_ast/commit/156afcb26c198e162504a57caddfe0acd9ed7dce,,,ast3/Python/Python-ast.c,3,c,False,2019-01-23T03:09:26Z "@Override public MediaResource handle(String relPath, HttpServletRequest request) { GlossaryItemManager gIM = CoreSpringFactory.getImpl(GlossaryItemManager.class); String[] parts = relPath.split(""/""); String glossaryId = parts[1]; String glossaryFolderString = FolderConfig.getCanonicalRoot() + FolderConfig.getRepositoryHome() + ""/"" + glossaryId + ""/"" + GlossaryMarkupItemController.INTERNAL_FOLDER_NAME; File glossaryFolderFile = new File(glossaryFolderString); if (!glossaryFolderFile.isDirectory()) { log.warn(""GlossaryDefinition delivery failed; path to glossaryFolder not existing: "" + relPath); return new NotFoundMediaResource(); } VFSContainer glossaryFolder = new LocalFolderImpl(glossaryFolderFile); if (!gIM.isFolderContainingGlossary(glossaryFolder)) { log.warn(""GlossaryDefinition delivery failed; glossaryFolder doesn't contain a valid Glossary: "" + glossaryFolder); return new NotFoundMediaResource(); } String glossaryMainTerm = parts[2]; if(parts.length > 2) {//this handle / or \ in a term for(int i=3; i alternatives = new HashSet<>(); prepareAlternatives(glossaryMainTerm, alternatives); // Create a media resource StringMediaResource resource = new StringMediaResource() { @Override public void prepare(HttpServletResponse hres) { // don't use normal string media headers which prevent caching, // use standard browser caching based on last modified timestamp } }; resource.setLastModified(gIM.getGlossaryLastModifiedTime(glossaryFolder)); resource.setContentType(""text/html""); List glossItems = gIM.getGlossaryItemListByVFSItem(glossaryFolder); GlossaryItem foundItem = null; for (GlossaryItem glossaryItem : glossItems) { String item = glossaryItem.getGlossTerm().toLowerCase(); if (alternatives.contains(item)) { foundItem = glossaryItem; break; } } if (foundItem == null) { return new NotFoundMediaResource(); } StringBuilder sb = new StringBuilder(); sb.append(""
"").append(foundItem.getGlossTerm()).append(""
"") .append(foundItem.getGlossDef()).append(""
""); resource.setData(sb.toString()); resource.setEncoding(""utf-8""); if (log.isDebugEnabled()) log.debug(""loaded definition for "" + glossaryMainTerm); return resource; }","@Override public MediaResource handle(String relPath, HttpServletRequest request) { GlossaryItemManager gIM = CoreSpringFactory.getImpl(GlossaryItemManager.class); String[] parts = relPath.split(""/""); String glossaryId = parts[1]; String glossaryFolderString = FolderConfig.getCanonicalRoot() + FolderConfig.getRepositoryHome() + ""/"" + glossaryId + ""/"" + GlossaryMarkupItemController.INTERNAL_FOLDER_NAME; File glossaryFolderFile = new File(glossaryFolderString); if (!glossaryFolderFile.isDirectory()) { log.warn(""GlossaryDefinition delivery failed; path to glossaryFolder not existing: "" + relPath); return new NotFoundMediaResource(); } VFSContainer glossaryFolder = new LocalFolderImpl(glossaryFolderFile); if (!gIM.isFolderContainingGlossary(glossaryFolder)) { log.warn(""GlossaryDefinition delivery failed; glossaryFolder doesn't contain a valid Glossary: "" + glossaryFolder); return new NotFoundMediaResource(); } String glossaryMainTerm = parts[2]; if(parts.length > 2) {//this handle / or \ in a term for(int i=3; i alternatives = new HashSet<>(); prepareAlternatives(glossaryMainTerm, alternatives); // Create a media resource StringMediaResource resource = new StringMediaResource() { @Override public void prepare(HttpServletResponse hres) { // don't use normal string media headers which prevent caching, // use standard browser caching based on last modified timestamp } }; resource.setLastModified(gIM.getGlossaryLastModifiedTime(glossaryFolder)); resource.setContentType(""text/html""); List glossItems = gIM.getGlossaryItemListByVFSItem(glossaryFolder); GlossaryItem foundItem = null; for (GlossaryItem glossaryItem : glossItems) { String item = glossaryItem.getGlossTerm().toLowerCase(); if (alternatives.contains(item)) { foundItem = glossaryItem; break; } } if (foundItem == null) { return new NotFoundMediaResource(); } StringBuilder sb = new StringBuilder(); sb.append(""
"").append(foundItem.getGlossTerm()).append(""
"") .append(foundItem.getGlossDef()).append(""
""); String filteredHtml = StringHelper.xssScan(sb); resource.setData(filteredHtml); resource.setEncoding(""utf-8""); if (log.isDebugEnabled()) log.debug(""loaded definition for "" + glossaryMainTerm); return resource; }",OO-6515: update jackson,https://github.com/OpenOLAT/OpenOLAT/commit/560d99d624b68e6216dec4ce0f0b1a2174e28eb9,,,src/main/java/org/olat/core/gui/control/generic/textmarker/GlossaryDefinitionMapper.java,3,java,False,2022-11-07T09:21:39Z "public boolean verifyKey(String key){ try{ String encrypted = doEncrypt(key, PayloadHelper.makeSimplePrincipalCollection()); Response response = doPost(encrypted); Headers headers = response.headers(); response.close(); String setCookie = headers.get(""Set-Cookie""); if(setCookie != null && setCookie.contains(""deleteMe"")){ return true; } }catch (Exception e){ } return false; }","public boolean verifyKey(String key){ try{ String encrypted = doEncrypt(key, PayloadHelper.makeSimplePrincipalCollection()); Response response = send(encrypted); Logger.success(""Current key: ""+key+"", Response: ""+response.toString()); Headers headers = response.headers(); response.close(); List cookies = headers.values(""Set-Cookie""); for(String cookie:cookies){ if(cookie.contains(""rememberMe=deleteMe"")){ return false; } } // 暂时仅对不存在deleteMe,且status code==200的包进行key的确认 // 所以对于其他类型,比如仅能使用post的接口,不要使用这种方式 // 可以采用强制模式,直接每一种key进行轮询 if(response.code() == 200){ return true; } }catch (Exception e){ // something wrong } return false; }",fix shiro rce exploits,https://github.com/wh1t3p1g/ysomap/commit/bd6e42dddd10f040e28ae981fad06ad27d7b5d3f,,,core/src/main/java/ysomap/exploits/shiro/ShiroRCE1.java,3,java,False,2021-06-24T14:30:41Z "private void fix() { if (!detector.getVulnerableFiles().isEmpty()) System.out.println(""""); for (VulnerableFile vf : detector.getVulnerableFiles()) { File f = vf.getFile(); File symlinkFile = null; String symlinkMsg = """"; if (FileUtils.isSymlink(f)) { try { symlinkFile = f; f = symlinkFile.getCanonicalFile(); symlinkMsg = "" (from symlink "" + symlinkFile.getAbsolutePath() + "")""; } catch (IOException e) { // unreachable (already known symlink) } } if (config.isTrace()) System.out.printf(""Patching %s%s%n"", f.getAbsolutePath(), symlinkMsg); File backupFile = new File(f.getAbsolutePath() + "".bak""); if (backupFile.exists()) { reportError(f, ""Cannot create backup file. .bak File already exists""); continue; } // set writable if file is read-only boolean readonlyFile = false; if (!f.canWrite()) { readonlyFile = true; if (!f.setWritable(true)) { reportError(f, ""Cannot remove read-only attribute""); continue; } } // check lock first if (FileUtils.isLocked(f, config.isDebug())) { reportError(f, ""File is locked by other process.""); continue; } try { FileUtils.copyAsIs(f, backupFile); // keep inode as is for symbolic link if (!FileUtils.truncate(f)) { backupFile.delete(); reportError(f, ""Cannot truncate file.""); continue; } Set removeTargets = detector.getVulnerableEntries(); Set shadePatterns = detector.getShadePatterns(); try { ZipUtils.repackage(backupFile, f, removeTargets, shadePatterns, config.isScanZip(), vf.isNestedJar(), config.isDebug(), vf.getAltCharset()); metrics.addFixedFileCount(); System.out.printf(""Fixed: %s%s%n"", f.getAbsolutePath(), symlinkMsg); // update fixed status List entries = detector.getReportEntries(f); for (ReportEntry entry : entries) entry.setFixed(true); } catch (Throwable t) { reportError(f, ""Cannot fix file ("" + t.getMessage() + "")."", t); // rollback operation FileUtils.copyAsIs(backupFile, f); } // restore read only attribute if (readonlyFile) f.setReadOnly(); } catch (Throwable t) { reportError(f, ""Cannot backup file "" + f.getAbsolutePath() + "" - "" + t.getMessage(), t); } } }","private void fix() { if (!detector.getVulnerableFiles().isEmpty()) System.out.println(""""); for (VulnerableFile vf : detector.getVulnerableFiles()) { File f = vf.getFile(); File symlinkFile = null; String symlinkMsg = """"; if (FileUtils.isSymlink(f)) { try { symlinkFile = f; f = symlinkFile.getCanonicalFile(); symlinkMsg = "" (from symlink "" + symlinkFile.getAbsolutePath() + "")""; } catch (IOException e) { // unreachable (already known symlink) } } if (config.isTrace()) System.out.printf(""Patching %s%s%n"", f.getAbsolutePath(), symlinkMsg); File backupFile = new File(f.getAbsolutePath() + "".bak""); if (backupFile.exists()) { reportError(f, ""Cannot create backup file. .bak File already exists""); continue; } // set writable if file is read-only boolean readonlyFile = false; if (!f.canWrite()) { readonlyFile = true; if (!f.setWritable(true)) { reportError(f, ""Cannot remove read-only attribute""); continue; } } // check lock first if (FileUtils.isLocked(f, config.isDebug())) { reportError(f, ""File is locked by other process.""); continue; } // do not patch if jar has only CVE-2021-45105 vulnerability String except = """"; boolean needFix = false; List entries = detector.getReportEntries(f); for (ReportEntry entry : entries) { if (entry.getCve().equals(""CVE-2021-45105"")) except = "" (except CVE-2021-45105)""; else needFix = true; } if (!needFix) { System.out.printf(""Cannot fix CVE-2021-45105, Upgrade it: %s%s%n"", f.getAbsolutePath(), symlinkMsg); continue; } try { FileUtils.copyAsIs(f, backupFile); // keep inode as is for symbolic link if (!FileUtils.truncate(f)) { backupFile.delete(); reportError(f, ""Cannot truncate file.""); continue; } Set removeTargets = detector.getVulnerableEntries(); Set shadePatterns = detector.getShadePatterns(); try { ZipUtils.repackage(backupFile, f, removeTargets, shadePatterns, config.isScanZip(), vf.isNestedJar(), config.isDebug(), vf.getAltCharset()); // update fixed status for (ReportEntry entry : entries) { if (!entry.getCve().equals(""CVE-2021-45105"")) entry.setFixed(true); } metrics.addFixedFileCount(); System.out.printf(""Fixed: %s%s%s%n"", f.getAbsolutePath(), symlinkMsg, except); } catch (Throwable t) { reportError(f, ""Cannot fix file ("" + t.getMessage() + "")."", t); // rollback operation FileUtils.copyAsIs(backupFile, f); } // restore read only attribute if (readonlyFile) f.setReadOnly(); } catch (Throwable t) { reportError(f, ""Cannot backup file "" + f.getAbsolutePath() + "" - "" + t.getMessage(), t); } } }",Fixed csv report generation bug with --report-path option. Added alert for CVE-2021-45105 fix. v2.4.1,https://github.com/logpresso/CVE-2021-44228-Scanner/commit/432436b076ebc398208b28e20ffb0e8fe68aadef,,,src/main/java/com/logpresso/scanner/Log4j2Scanner.java,3,java,False,2021-12-20T16:59:06Z "@EventHandler(priority = EventPriority.HIGHEST, ignoreCancelled = true) public void PIntAEE(PlayerInteractAtEntityEvent e) { Entity E = e.getRightClicked(); if(!(E instanceof Player)) return; Player p = e.getPlayer(); Player t = (Player) E; if(!GPM.getCManager().PS_USE_PLAYERSIT && !GPM.getCManager().PS_USE_PLAYERSIT_NPC) return; if(GPM.getCManager().WORLDBLACKLIST.contains(p.getWorld().getName()) && !GPM.getPManager().hasPermission(p, ""ByPass.World"", ""ByPass.*"")) return; if(GPM.getCManager().PS_EMPTY_HAND_ONLY && p.getInventory().getItemInMainHand().getType() != Material.AIR) return; if(!GPM.getPManager().hasNormalPermission(p, ""PlayerSit"")) return; if(!p.isValid() || !p.isOnGround() || p.isSneaking() || p.isInsideVehicle() || p.getGameMode() == GameMode.SPECTATOR) return; if(GPM.getPlotSquared() != null && !GPM.getPlotSquared().canCreateSeat(t.getLocation(), p)) return; if(GPM.getWorldGuard() != null && !GPM.getWorldGuard().checkFlag(t.getLocation(), GPM.getWorldGuard().PLAYERSIT_FLAG)) return; if(GPM.getPassengerUtil().isInPassengerList(t, p) || GPM.getPassengerUtil().isInPassengerList(p, t)) return; long a = GPM.getPassengerUtil().getPassengerAmount(t) + GPM.getPassengerUtil().getVehicleAmount(t) + 1; if(GPM.getCManager().PS_MAX_STACK > 0 && GPM.getCManager().PS_MAX_STACK <= a) return; Entity s = GPM.getPassengerUtil().getHighestEntity(t); if(!(s instanceof Player)) return; Player z = (Player) s; if(!GPM.getToggleManager().canPlayerSit(p.getUniqueId()) || !GPM.getToggleManager().canPlayerSit(z.getUniqueId())) return; boolean n = GPM.getPassengerUtil().isNPC(z); if(n && !GPM.getCManager().PS_USE_PLAYERSIT_NPC) return; if(!n && !GPM.getCManager().PS_USE_PLAYERSIT) return; boolean r = GPM.getPlayerSitManager().sitOnPlayer(p, z); if(r) e.setCancelled(true); }","@EventHandler(priority = EventPriority.HIGHEST, ignoreCancelled = true) public void PIntAEE(PlayerInteractAtEntityEvent e) { Entity E = e.getRightClicked(); if(!(E instanceof Player)) return; Player p = e.getPlayer(); Player t = (Player) E; if(!GPM.getCManager().PS_USE_PLAYERSIT && !GPM.getCManager().PS_USE_PLAYERSIT_NPC) return; if(!GPM.getPManager().hasNormalPermission(p, ""PlayerSit"")) return; if(GPM.getCManager().WORLDBLACKLIST.contains(p.getWorld().getName()) && !GPM.getPManager().hasPermission(p, ""ByPass.World"", ""ByPass.*"")) return; if(GPM.getCManager().PS_EMPTY_HAND_ONLY && p.getInventory().getItemInMainHand().getType() != Material.AIR) return; if(!p.isValid() || !p.isOnGround() || p.isSneaking() || p.isInsideVehicle() || p.getGameMode() == GameMode.SPECTATOR) return; if(GPM.getPlotSquared() != null && !GPM.getPlotSquared().canCreateSeat(t.getLocation(), p)) return; if(GPM.getWorldGuard() != null && !GPM.getWorldGuard().checkFlag(t.getLocation(), GPM.getWorldGuard().PLAYERSIT_FLAG)) return; if(GPM.getPassengerUtil().isInPassengerList(t, p) || GPM.getPassengerUtil().isInPassengerList(p, t)) return; long a = GPM.getPassengerUtil().getPassengerAmount(t) + GPM.getPassengerUtil().getVehicleAmount(t) + 1; if(GPM.getCManager().PS_MAX_STACK > 0 && GPM.getCManager().PS_MAX_STACK <= a) return; Entity s = GPM.getPassengerUtil().getHighestEntity(t); if(!(s instanceof Player)) return; Player z = (Player) s; if(!GPM.getToggleManager().canPlayerSit(p.getUniqueId()) || !GPM.getToggleManager().canPlayerSit(z.getUniqueId())) return; boolean n = GPM.getPassengerUtil().isNPC(z); if(n && !GPM.getCManager().PS_USE_PLAYERSIT_NPC) return; if(!n && !GPM.getCManager().PS_USE_PLAYERSIT) return; boolean r = GPM.getPlayerSitManager().sitOnPlayer(p, z); if(r) e.setCancelled(true); }",Fix ByPass permission,https://github.com/Gecolay/GSit/commit/aaea9416a15376d92b8f181cc5144cc7e4b6ca8f,,,core/src/main/java/dev/geco/gsit/events/PlayerSitEvents.java,3,java,False,2021-12-16T23:09:45Z "private void decodeAndWrite(boolean endOfInput) throws IOException { // not ByteBuffer to avoid Java 8/9 issues with flip() ((Buffer)_bb).flip(); if (!_bb.hasRemaining()) return; CoderResult result; try { result = _dc.decode(_bb, _cb, endOfInput); } catch (IllegalStateException ise) { System.out.println(""Decoder error with endOfInput="" + endOfInput); ise.printStackTrace(); result = null; } _bb.compact(); // Overflow and underflow are not errors. // It seems to return underflow every time. // So just check if we got a character back in the buffer. if (result == null || (result.isError() && !_cb.hasRemaining())) { _out.write(REPLACEMENT); } else { ((Buffer)_cb).flip(); _out.append(_cb); ((Buffer)_cb).clear(); } }","private void decodeAndWrite(boolean endOfInput) throws IOException { // not ByteBuffer to avoid Java 8/9 issues with flip() ((Buffer)_bb).flip(); if (!_bb.hasRemaining()) return; CoderResult result; try { result = _dc.decode(_bb, _cb, endOfInput); } catch (IllegalStateException ise) { System.out.println(""Decoder error with endOfInput="" + endOfInput); ise.printStackTrace(); result = null; } _bb.compact(); // Overflow and underflow are not errors. // It seems to return underflow every time. // So just check if we got a character back in the buffer. if (result == null || (result.isError() && !_cb.hasRemaining())) { _out.write(REPLACEMENT); // need to do this or we will infinite loop ((Buffer)_bb).clear(); } else { ((Buffer)_cb).flip(); _out.append(_cb); ((Buffer)_cb).clear(); if (result.isError()) { _out.write(REPLACEMENT); // need to do this or we will infinite loop ((Buffer)_bb).clear(); } } }","SusiMail: Prevent infinite loop on decoding error More test mods Fix StringBuilderWriter.write(int)",https://github.com/i2p/i2p.i2p/commit/21485eff8759b21dec8c37b4d947f79903029c8f,,,apps/susimail/src/src/i2p/susi/util/DecodingOutputStream.java,3,java,False,2021-04-24T23:37:18Z "public Single execute(KeyT key, Single task, boolean force) { return Single.create( emitter -> { synchronized (lock) { if (state != STATE_ACTIVE) { emitter.onError(new CancellationException(""already shutdown"")); return; } if (!force && finished.containsKey(key)) { emitter.onSuccess(finished.get(key)); return; } finished.remove(key); Execution execution = inProgress.computeIfAbsent(key, ignoredKey -> new Execution(key, task)); // We must subscribe the execution within the scope of lock to avoid race condition // that: // 1. Two callers get the same execution instance // 2. One decides to dispose the execution, since no more observers, the execution // will change to the terminate state // 3. Another one try to subscribe, will get ""terminated"" error. execution.subscribe( new SingleObserver() { @Override public void onSubscribe(@NonNull Disposable d) { emitter.setDisposable(d); } @Override public void onSuccess(@NonNull ValueT valueT) { emitter.onSuccess(valueT); } @Override public void onError(@NonNull Throwable e) { if (!emitter.isDisposed()) { emitter.onError(e); } } }); } }); }","public Single execute(KeyT key, Single task, boolean force) { return execute(key, task, () -> {}, force); }","Remote: Fix crashes by InterruptedException when dynamic execution is enabled. Fixes #14433. The root cause is, inside `RemoteExecutionCache`, the result of `FindMissingDigests` is shared with other threads without considering error handling. For example, if there are two or more threads uploading the same input and one thread got interrupted when waiting for the result of `FindMissingDigests` call, the call is cancelled and others threads still waiting for the upload will receive upload error due to the cancellation which is wrong. This PR fixes this by effectively applying reference count to the result of `FindMissingDigests` call so that if one thread got interrupted, as long as there are other threads depending on the result, the call won't be cancelled and the upload can continue. Closes #15001. PiperOrigin-RevId: 436180205",https://github.com/bazelbuild/bazel/commit/702df847cf32789ffe6c0a7c7679e92a7ccccb8d,,,src/main/java/com/google/devtools/build/lib/remote/util/AsyncTaskCache.java,3,java,False,2022-03-21T12:37:13Z "private void parseArguments(String[] args) throws IOException { int i = 0; for (; i < args.length; i++) { if (args[i].equals(""--fix"")) { fix = true; } else if (args[i].equals(""--force-fix"")) { fix = true; force = true; } else if (args[i].equals(""--trace"")) { trace = true; } else if (args[i].equals(""--all-drives"")) { if (!isWindows) throw new IllegalArgumentException(""--all-drives is supported on Windows only.""); allDrives = true; } else if (args[i].equals(""--drives"")) { if (!isWindows) throw new IllegalArgumentException(""--drives is supported on Windows only.""); if (args.length > i + 1) { for (String letter : args[i + 1].split("","")) { letter = letter.trim().toUpperCase(); if (letter.length() == 0) continue; if (letter.length() > 1) throw new IllegalArgumentException(""Invalid drive letter: "" + letter); char c = letter.charAt(0); if (c < 'A' || c > 'Z') throw new IllegalArgumentException(""Invalid drive letter: "" + letter); driveLetters.add(new File(letter + "":\\"")); } } else { throw new IllegalArgumentException(""Specify drive letters.""); } i++; } else if (args[i].equals(""--exclude"")) { if (args.length > i + 1) { String path = args[i + 1]; if (path.startsWith(""--"")) { throw new IllegalArgumentException(""Path should not starts with `--`. Specify exclude file path.""); } if (isWindows) path = path.toUpperCase(); excludePaths.add(path); i++; } else { throw new IllegalArgumentException(""Specify exclude file path.""); } } else if (args[i].equals(""--exclude-config"")) { if (args.length > i + 1) { String path = args[i + 1]; if (path.startsWith(""--"")) { throw new IllegalArgumentException(""Path should not starts with `--`. Specify exclude file path.""); } File f = new File(path); if (!f.exists() || !f.canRead()) throw new IllegalArgumentException(""Cannot read exclude config file: "" + f.getAbsolutePath()); loadExcludePaths(f); i++; } else { throw new IllegalArgumentException(""Specify exclude file path.""); } } else { if (i == args.length - 1) targetPath = args[i]; else throw new IllegalArgumentException(""unsupported option: "" + args[i]); } } // verify drive letters verifyDriveLetters(); // verify conflict option if (allDrives && !driveLetters.isEmpty()) throw new IllegalArgumentException(""Cannot specify both --all-drives and --drives options.""); if (!allDrives && driveLetters.isEmpty() && targetPath == null) throw new IllegalArgumentException(""Specify scan target path.""); }","private void parseArguments(String[] args) throws IOException { int i = 0; for (; i < args.length; i++) { if (args[i].equals(""--fix"")) { fix = true; } else if (args[i].equals(""--force-fix"")) { fix = true; force = true; } else if (args[i].equals(""--trace"")) { trace = true; } else if (args[i].equals(""--no-symlink"")) { noSymlink = true; } else if (args[i].equals(""--all-drives"")) { if (!isWindows) throw new IllegalArgumentException(""--all-drives is supported on Windows only.""); allDrives = true; } else if (args[i].equals(""--drives"")) { if (!isWindows) throw new IllegalArgumentException(""--drives is supported on Windows only.""); if (args.length > i + 1) { for (String letter : args[i + 1].split("","")) { letter = letter.trim().toUpperCase(); if (letter.length() == 0) continue; if (letter.length() > 1) throw new IllegalArgumentException(""Invalid drive letter: "" + letter); char c = letter.charAt(0); if (c < 'A' || c > 'Z') throw new IllegalArgumentException(""Invalid drive letter: "" + letter); driveLetters.add(new File(letter + "":\\"")); } } else { throw new IllegalArgumentException(""Specify drive letters.""); } i++; } else if (args[i].equals(""--exclude"")) { if (args.length > i + 1) { String path = args[i + 1]; if (path.startsWith(""--"")) { throw new IllegalArgumentException(""Path should not starts with `--`. Specify exclude file path.""); } if (isWindows) path = path.toUpperCase(); excludePaths.add(path); i++; } else { throw new IllegalArgumentException(""Specify exclude file path.""); } } else if (args[i].equals(""--exclude-config"")) { if (args.length > i + 1) { String path = args[i + 1]; if (path.startsWith(""--"")) { throw new IllegalArgumentException(""Path should not starts with `--`. Specify exclude file path.""); } File f = new File(path); if (!f.exists() || !f.canRead()) throw new IllegalArgumentException(""Cannot read exclude config file: "" + f.getAbsolutePath()); loadExcludePaths(f); i++; } else { throw new IllegalArgumentException(""Specify exclude file path.""); } } else { if (i == args.length - 1) targetPath = args[i]; else throw new IllegalArgumentException(""unsupported option: "" + args[i]); } } // verify drive letters verifyDriveLetters(); // verify conflict option if (allDrives && !driveLetters.isEmpty()) throw new IllegalArgumentException(""Cannot specify both --all-drives and --drives options.""); if (!allDrives && driveLetters.isEmpty() && targetPath == null) throw new IllegalArgumentException(""Specify scan target path.""); }","Patch for CVE-2021-45046, v1.3.2",https://github.com/logpresso/CVE-2021-44228-Scanner/commit/f3198d9a0924d139b497c17e4ad89d500fae69d0,,,src/main/java/com/logpresso/scanner/Log4j2Scanner.java,3,java,False,2021-12-14T19:20:18Z "@Override public Recipe findRecipe(IHasWorldAndCoords aTileEntity, Recipe aRecipe, boolean aNotUnificated, long aSize, ItemStack aSpecialSlot, FluidStack[] aFluids, ItemStack... aInputs) { Recipe rRecipe = super.findRecipe(aTileEntity, aRecipe, aNotUnificated, aSize, aSpecialSlot, aFluids, aInputs); if (aInputs == null || aInputs.length < 1 || ST.invalid(aInputs[0]) || GAPI_POST.mFinishedServerStarted <= 0) return rRecipe; if (rRecipe == null) { long tFuelValue = ST.fuel(aInputs[0]); OreDictItemData tData = OM.anydata_(aInputs[0]); if (tFuelValue > 0 && !FL.contains(aInputs[0], FL.Lava.make(0), T) && !OM.materialcontains(tData, TD.Properties.EXPLOSIVE)) { ItemStack tContainer = ST.container(aInputs[0], T); if (tContainer == null) { OreDictMaterialStack tMaterial = null; if (tData != null) { if (tData.mPrefix == OP.oreRaw) { tMaterial = OM.stack(tData.mMaterial.mMaterial.mTargetBurning.mMaterial, tData.mMaterial.mMaterial.mTargetBurning.mAmount * tData.mMaterial.mMaterial.mOreMultiplier * tData.mMaterial.mMaterial.mOreProcessingMultiplier * 2); } else if (tData.mPrefix == OP.blockRaw) { tMaterial = OM.stack(tData.mMaterial.mMaterial.mTargetBurning.mMaterial, tData.mMaterial.mMaterial.mTargetBurning.mAmount * tData.mMaterial.mMaterial.mOreMultiplier * tData.mMaterial.mMaterial.mOreProcessingMultiplier * 20); } else for (OreDictMaterialStack aMaterial : tData.getAllMaterialStacks()) { if (tMaterial == null || tMaterial.mAmount <= 0) { tMaterial = OM.stack(aMaterial.mMaterial.mTargetBurning.mMaterial, UT.Code.units(aMaterial.mAmount, U, aMaterial.mMaterial.mTargetBurning.mAmount, F)); } else if (tMaterial.mMaterial == aMaterial.mMaterial.mTargetBurning.mMaterial) { tMaterial.mAmount += UT.Code.units(aMaterial.mAmount, U, aMaterial.mMaterial.mTargetBurning.mAmount, F); } } } rRecipe = new Recipe(F, F, T, ST.array(ST.amount(1, aInputs[0])), ST.array(OM.dust(tMaterial)), null, null, null, null, tFuelValue * EU_PER_FURNACE_TICK, -1, 0); } else { rRecipe = new Recipe(F, F, T, ST.array(ST.amount(1, aInputs[0])), ST.array(tContainer), null, null, null, null, tFuelValue * EU_PER_FURNACE_TICK, -1, 0); } rRecipe.mCanBeBuffered = (aInputs[0].getTagCompound() == null); if (rRecipe.mCanBeBuffered) addRecipe(rRecipe, F, F, T); } } return rRecipe; }","@Override public Recipe findRecipe(IHasWorldAndCoords aTileEntity, Recipe aRecipe, boolean aNotUnificated, long aSize, ItemStack aSpecialSlot, FluidStack[] aFluids, ItemStack... aInputs) { Recipe rRecipe = super.findRecipe(aTileEntity, aRecipe, aNotUnificated, aSize, aSpecialSlot, aFluids, aInputs); if (aInputs == null || aInputs.length < 1 || ST.invalid(aInputs[0]) || GAPI_POST.mFinishedServerStarted <= 0) return rRecipe; if (rRecipe == null) { long tFuelValue = ST.fuel(aInputs[0]); OreDictItemData tData = OM.anydata_(aInputs[0]); if (tFuelValue > 0 && !FL.contains(aInputs[0], FL.Lava.make(0), T) && !OM.materialcontains(tData, TD.Properties.EXPLOSIVE)) { ItemStack tContainer = ST.container(aInputs[0], T); if (tContainer == null) { OreDictMaterialStack tMaterial = null; if (tData != null) { if (tData.mPrefix == OP.oreRaw) { tMaterial = OM.stack(tData.mMaterial.mMaterial.mTargetBurning.mMaterial, tData.mMaterial.mMaterial.mTargetBurning.mAmount * tData.mMaterial.mMaterial.mOreMultiplier * tData.mMaterial.mMaterial.mOreProcessingMultiplier * 2); } else if (tData.mPrefix == OP.blockRaw) { tMaterial = OM.stack(tData.mMaterial.mMaterial.mTargetBurning.mMaterial, tData.mMaterial.mMaterial.mTargetBurning.mAmount * tData.mMaterial.mMaterial.mOreMultiplier * tData.mMaterial.mMaterial.mOreProcessingMultiplier * 20); } else for (OreDictMaterialStack aMaterial : tData.getAllMaterialStacks()) { if (tMaterial == null || tMaterial.mAmount <= 0) { tMaterial = OM.stack(aMaterial.mMaterial.mTargetBurning.mMaterial, UT.Code.units(aMaterial.mAmount, U, aMaterial.mMaterial.mTargetBurning.mAmount, F)); } else if (tMaterial.mMaterial == aMaterial.mMaterial.mTargetBurning.mMaterial) { tMaterial.mAmount += UT.Code.units(aMaterial.mAmount, U, aMaterial.mMaterial.mTargetBurning.mAmount, F); } } } if (tMaterial == null || tMaterial.mAmount <= 0) { rRecipe = new Recipe(F, F, T, ST.array(ST.amount(1, aInputs[0])), null, null, null, null, null, tFuelValue * EU_PER_FURNACE_TICK, -1, 0); } else { for (int i = 1; i < 64; i++) { ItemStack tAshes = OM.dust(tMaterial.mMaterial, tMaterial.mAmount * i); if (ST.valid(tAshes)) { rRecipe = new Recipe(F, F, T, ST.array(ST.amount(i, aInputs[0])), ST.array(tAshes), null, null, null, null, tFuelValue * EU_PER_FURNACE_TICK, -1, 0); break; } } } } else { rRecipe = new Recipe(F, F, T, ST.array(ST.amount(1, aInputs[0])), ST.array(tContainer), null, null, null, null, tFuelValue * EU_PER_FURNACE_TICK, -1, 0); } rRecipe.mCanBeBuffered = (aInputs[0].getTagCompound() == null); if (rRecipe.mCanBeBuffered) addRecipe(rRecipe, F, F, T); } } return rRecipe; }",Fixed Loq Input = No Ashes exploit in Burning Boxes,https://github.com/GregTech6/gregtech6/commit/3f103e1ad9c5613994531ae1a71f627d2a9646ab,,,src/main/java/gregapi/recipes/maps/RecipeMapFurnaceFuel.java,3,java,False,2021-06-06T03:44:08Z "public static void destroyAreaFireCharge(World world, BlockPos center, EntityDragonBase destroyer) { if (destroyer != null) { if (MinecraftForge.EVENT_BUS.post(new DragonFireDamageWorldEvent(destroyer, center.getX(), center.getY(), center.getZ()))) return; int stage = destroyer.getDragonStage(); int j = 2; int k = 2; int l = 2; if (stage <= 3) { BlockPos.getAllInBox(center.add(-j, -k, -l), center.add(j, k, l)).forEach(pos -> { if (world.rand.nextFloat() * 3 > pos.distanceSq(center) && !(world.getBlockState(pos).getBlock() instanceof IDragonProof) && DragonUtils.canDragonBreak(world.getBlockState(pos).getBlock())) { world.setBlockState(pos, Blocks.AIR.getDefaultState()); } if (world.rand.nextBoolean()) { if (!(world.getBlockState(pos).getBlock() instanceof IDragonProof) && DragonUtils.canDragonBreak(world.getBlockState(pos).getBlock())) { BlockState transformState = transformBlockFire(world.getBlockState(pos)); world.setBlockState(pos, transformState); if (world.rand.nextBoolean() && transformState.getMaterial().isSolid() && world.getFluidState(pos.up()).isEmpty() && !world.getBlockState(pos.up()).isSolid()) { world.setBlockState(pos.up(), Blocks.FIRE.getDefaultState()); } } } }); } else { final int radius = stage == 4 ? 2 : 3; j = radius + world.rand.nextInt(2); k = radius + world.rand.nextInt(2); l = radius + world.rand.nextInt(2); final float f = (float) (j + k + l) * 0.333F + 0.5F; final float ff = f * f; final double ffDouble = (double) ff; BlockPos.getAllInBox(center.add(-j, -k, -l), center.add(j, k, l)).forEach(blockpos -> { if (blockpos.distanceSq(center) <= ffDouble) { if (world.rand.nextFloat() * 3 > (float) blockpos.distanceSq(center) / ff && !(world.getBlockState(blockpos).getBlock() instanceof IDragonProof) && DragonUtils.canDragonBreak(world.getBlockState(blockpos).getBlock())) { world.setBlockState(blockpos, Blocks.AIR.getDefaultState()); } } }); j++; k++; l++; BlockPos.getAllInBox(center.add(-j, -k, -l), center.add(j, k, l)).forEach(blockpos -> { if (blockpos.distanceSq(center) <= ffDouble) { if (!(world.getBlockState(blockpos).getBlock() instanceof IDragonProof) && DragonUtils.canDragonBreak(world.getBlockState(blockpos).getBlock())) { BlockState transformState = transformBlockFire(world.getBlockState(blockpos)); world.setBlockState(blockpos, transformState); if (world.rand.nextBoolean() && transformState.getMaterial().isSolid() && world.getFluidState(blockpos.up()).isEmpty() && !world.getBlockState(blockpos.up()).isSolid()) { world.setBlockState(blockpos.up(), Blocks.FIRE.getDefaultState()); } } } }); } final float stageDmg = Math.max(1, stage - 1) * 2F; final int statusDuration = 15; world.getEntitiesWithinAABB( LivingEntity.class, new AxisAlignedBB( (double) center.getX() - j, (double) center.getY() - k, (double) center.getZ() - l, (double) center.getX() + j, (double) center.getY() + k, (double) center.getZ() + l ) ).stream().forEach(livingEntity -> { if (!destroyer.isOnSameTeam(livingEntity) && !destroyer.isEntityEqual(livingEntity) && destroyer.canEntityBeSeen(livingEntity)) { livingEntity.attackEntityFrom(IafDamageRegistry.DRAGON_FIRE, stageDmg); livingEntity.setFire(statusDuration); } }); if (IafConfig.explosiveDragonBreath) { BlockLaunchExplosion explosion = new BlockLaunchExplosion(world, destroyer, center.getX(), center.getY(), center.getZ(), Math.min(2, stage - 2)); explosion.doExplosionA(); explosion.doExplosionB(true); } } }","public static void destroyAreaFireCharge(World world, BlockPos center, EntityDragonBase destroyer) { if (destroyer != null) { if (MinecraftForge.EVENT_BUS.post(new DragonFireDamageWorldEvent(destroyer, center.getX(), center.getY(), center.getZ()))) return; Entity cause = destroyer.getRidingPlayer() != null ? destroyer.getRidingPlayer() : destroyer; DamageSource source = IafDamageRegistry.causeDragonFireDamage(cause); int stage = destroyer.getDragonStage(); int j = 2; int k = 2; int l = 2; if (stage <= 3) { BlockPos.getAllInBox(center.add(-j, -k, -l), center.add(j, k, l)).forEach(pos -> { if (world.rand.nextFloat() * 3 > center.distanceSq(pos) && !(world.getBlockState(pos).getBlock() instanceof IDragonProof) && DragonUtils.canDragonBreak(world.getBlockState(pos).getBlock())) { world.setBlockState(pos, Blocks.AIR.getDefaultState()); } if (world.rand.nextBoolean()) { fireAttackBlock(world, pos); } }); } else { final int radius = stage == 4 ? 2 : 3; j = radius + world.rand.nextInt(2); k = radius + world.rand.nextInt(2); l = radius + world.rand.nextInt(2); final float f = (float) (j + k + l) * 0.333F + 0.5F; final float ff = f * f; destroyBlocks(world, center, j, k, l, ff); j++; k++; l++; BlockPos.getAllInBox(center.add(-j, -k, -l), center.add(j, k, l)).forEach(pos -> { if (center.distanceSq(pos) <= ff) { fireAttackBlock(world, pos); } }); } final float stageDmg = Math.max(1, stage - 1) * 2F; final int statusDuration = 15; world.getEntitiesWithinAABB( LivingEntity.class, new AxisAlignedBB( (double) center.getX() - j, (double) center.getY() - k, (double) center.getZ() - l, (double) center.getX() + j, (double) center.getY() + k, (double) center.getZ() + l ) ).stream().forEach(livingEntity -> { if (!destroyer.isOnSameTeam(livingEntity) && !destroyer.isEntityEqual(livingEntity) && destroyer.canEntityBeSeen(livingEntity)) { livingEntity.attackEntityFrom(source, stageDmg); livingEntity.setFire(statusDuration); } }); if (IafConfig.explosiveDragonBreath) causeExplosion(world, center, destroyer, source, stage); } }","Updated IafDamageRegistry to use EntityDamageSource. - Attacking someone while riding a dragon now identifies the rider as the source of the damage/attack Cleaned up code related to entity charge attacks. - The various dragon charges now all inherit from the same abstract class - Charge attacks now no longer raytrace twice - Removed duplicate code Cleaned up and improved code regarding dragons breath attacks Dragons don't break blocks anymore that they shouldn't. Fixes #4475",https://github.com/AlexModGuy/Ice_and_Fire/commit/3c52775ad166dd8ee77da768881444db1b89512a,,,src/main/java/com/github/alexthe666/iceandfire/entity/IafDragonDestructionManager.java,3,java,False,2022-05-10T16:42:49Z "private void initializeCellularScanningResources() { final TelephonyManager telephonyManager = (TelephonyManager) getSystemService(Context.TELEPHONY_SERVICE); if (telephonyManager == null) { Timber.e(""Unable to get access to the Telephony Manager. No network information will be displayed""); return; } if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q) { cellInfoCallback = new TelephonyManager.CellInfoCallback() { @SuppressLint(""MissingPermission"") @Override public void onCellInfo(@NonNull List cellInfo) { surveyRecordProcessor.onCellInfoUpdate(cellInfo, CalculationUtils.getNetworkType(telephonyManager.getDataNetworkType())); } @Override public void onError(int errorCode, @Nullable Throwable detail) { super.onError(errorCode, detail); Timber.w(detail, ""Received an error from the Telephony Manager when requesting a cell info update; errorCode=%s"", errorCode); } }; } }","private void initializeCellularScanningResources() { final TelephonyManager telephonyManager = (TelephonyManager) getSystemService(Context.TELEPHONY_SERVICE); if (telephonyManager == null) { Timber.e(""Unable to get access to the Telephony Manager. No network information will be displayed""); return; } if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q) { cellInfoCallback = new TelephonyManager.CellInfoCallback() { @Override public void onCellInfo(@NonNull List cellInfo) { String networkType = ""Missing Permission""; if (ActivityCompat.checkSelfPermission(NetworkSurveyService.this, Manifest.permission.READ_PHONE_STATE) == PackageManager.PERMISSION_GRANTED) { networkType = CalculationUtils.getNetworkType(telephonyManager.getDataNetworkType()); } surveyRecordProcessor.onCellInfoUpdate(cellInfo, networkType); } @Override public void onError(int errorCode, @Nullable Throwable detail) { super.onError(errorCode, detail); Timber.w(detail, ""Received an error from the Telephony Manager when requesting a cell info update; errorCode=%s"", errorCode); } }; } }",Added a permissions check before getting the data network type to prevent an app crash,https://github.com/christianrowlands/android-network-survey/commit/f6cceb5e7b7272334200bd84452fc55af20bbc8f,,,networksurvey/src/main/java/com/craxiom/networksurvey/services/NetworkSurveyService.java,3,java,False,2021-06-29T12:45:51Z "protected boolean clearAttachables(Block block, BlockFace direction, @Nonnull MaterialSet materials) { Block testBlock = block.getRelative(direction); long blockId = com.elmakers.mine.bukkit.block.BlockData.getBlockId(testBlock); if (!materials.testBlock(testBlock)) { return false; } // Don't clear it if we've already modified it if (blockIdMap != null && blockIdMap.containsKey(blockId)) { return false; } add(testBlock); MaterialAndData.clearItems(testBlock.getState()); DeprecatedUtils.setTypeAndData(testBlock, Material.AIR, (byte)0, false); return true; }","protected boolean clearAttachables(Block block, BlockFace direction, @Nonnull MaterialSet materials) { Block testBlock = block.getRelative(direction); if (!materials.testBlock(testBlock)) { return false; } add(testBlock); MaterialAndData.clearItems(testBlock.getState()); DeprecatedUtils.setTypeAndData(testBlock, Material.AIR, (byte)0, false); if (direction == BlockFace.DOWN || direction == BlockFace.UP) { clearAttachables(testBlock, direction, materials); } return true; }","Chain attachable clearing up and down, fixes sugar cane dupe exploits",https://github.com/elBukkit/MagicPlugin/commit/ced2a787066a97a5f81720d50fec36f5bba9b49f,,,Magic/src/main/java/com/elmakers/mine/bukkit/block/UndoList.java,3,java,False,2021-03-04T16:53:30Z "@Override public final T getAdapter(Class adapter) { if (IWorkbenchSiteProgressService.class == adapter) { return adapter.cast(getService(adapter)); } if (IWorkbenchPartTestable.class == adapter) { return adapter.cast(new WorkbenchPartTestable(this)); } return Adapters.adapt(this, adapter); }","@Override public final T getAdapter(Class adapter) { if (IWorkbenchSiteProgressService.class == adapter) { return adapter.cast(getService(adapter)); } if (IWorkbenchPartTestable.class == adapter) { return adapter.cast(new WorkbenchPartTestable(this)); } return Platform.getAdapterManager().getAdapter(this, adapter); }","Revert ""Bug 567543 - Replace usage of Platform.getAdapterManager().getAdapter()"" This reverts commit 279714b4e046f89c2c4f0e30d10f5e3e97ac1661. Reason for revert: Bug 572904. IAdaptable should never delegate getAdapter() call to Adapters, this can lead to recursion and stack overflow. Change-Id: I9171a0ddfcd923d64e1f725fd670a8f29c2a8721 Reviewed-on: https://git.eclipse.org/r/c/platform/eclipse.platform.ui/+/179031 Tested-by: Platform Bot Reviewed-by: Andrey Loskutov ",https://github.com/eclipse-platform/eclipse.platform.ui/commit/fb29edb92376a2bcde7589857991ea3755327216,,,bundles/org.eclipse.ui.workbench/Eclipse UI/org/eclipse/ui/internal/PartSite.java,3,java,False,2021-04-16T09:22:08Z "@NeverInline(""access stack pointer"") @Uninterruptible(reason = ""write stack"", calleeMustBe = false) private Object enter1(boolean isContinue) { Pointer currentSP = KnownIntrinsics.readCallerStackPointer(); CodePointer currentIP = KnownIntrinsics.readReturnAddress(); if (isContinue) { assert this.stored != null; assert this.ip.isNonNull(); byte[] buf = StoredContinuationImpl.allocateBuf(this.stored); StoredContinuationImpl.writeBuf(this.stored, buf); for (int i = 0; i < buf.length; i++) { currentSP.writeByte(i - buf.length, buf[i]); } CodePointer storedIP = this.ip; this.stored = null; this.sp = currentSP; this.ip = currentIP; KnownIntrinsics.farReturn(0, currentSP.subtract(buf.length), storedIP, false); throw VMError.shouldNotReachHere(); } else { assert this.sp.isNull() && this.ip.isNull() && this.stored == null; this.sp = currentSP; this.ip = currentIP; enter0(); return null; } }","@NeverInline(""Accesses caller stack pointer and return address."") @Uninterruptible(reason = ""Copies stack frames containing references."") private Object enter1(boolean isContinue) { // Note that the frame of this method will remain on the stack, and yielding will ignore it // and return past it to our caller. Pointer callerSP = KnownIntrinsics.readCallerStackPointer(); CodePointer callerIP = KnownIntrinsics.readReturnAddress(); Pointer currentSP = KnownIntrinsics.readStackPointer(); assert sp.isNull() && bottomSP.isNull(); if (isContinue) { assert stored != null && ip.isNonNull(); int totalSize = StoredContinuationImpl.readAllFrameSize(stored); Pointer topSP = currentSP.subtract(totalSize); if (!StackOverflowCheck.singleton().isWithinBounds(topSP)) { throw ImplicitExceptions.CACHED_STACK_OVERFLOW_ERROR; } // Inlined loop because a utility method would overwrite its own frame Pointer frameData = StoredContinuationImpl.payloadFrameStart(stored); int offset = 0; for (int next = offset + 32; next < totalSize; next += 32) { Pointer src = frameData.add(offset); Pointer dst = topSP.add(offset); long l0 = src.readLong(0); long l8 = src.readLong(8); long l16 = src.readLong(16); long l24 = src.readLong(24); dst.writeLong(0, l0); dst.writeLong(8, l8); dst.writeLong(16, l16); dst.writeLong(24, l24); offset = next; } for (; offset < totalSize; offset++) { topSP.writeByte(offset, frameData.readByte(offset)); } /* * NO CALLS BEYOND THIS POINT! They would overwrite the frames we copied above. */ CodePointer storedIP = this.ip; this.stored = null; this.ip = callerIP; this.sp = callerSP; this.bottomSP = currentSP; KnownIntrinsics.farReturn(0, topSP, storedIP, false); throw VMError.shouldNotReachHere(); } else { assert ip.isNull() && stored == null; this.ip = callerIP; this.sp = callerSP; this.bottomSP = currentSP; enter2(); return null; } }","Fix Continuation.enter1 overwriting its own frame, check for stack overflow, and avoid extra heap buffer.",https://github.com/oracle/graal/commit/aadbff556c457e107f5f44706750b11cf569e404,,,substratevm/src/com.oracle.svm.core/src/com/oracle/svm/core/thread/Continuation.java,3,java,False,2022-03-02T18:51:14Z "boolean fillAccel (ACCEL accel) { accel.cmd = accel.key = accel.fVirt = 0; if (accelerator == 0 || !getEnabled ()) return false; if ((accelerator & SWT.COMMAND) != 0) return false; int fVirt = OS.FVIRTKEY; int key = accelerator & SWT.KEY_MASK; int vKey = Display.untranslateKey (key); if (vKey != 0) { key = vKey; } else { switch (key) { /* * Bug in Windows. For some reason, VkKeyScan * fails to map ESC to VK_ESCAPE and DEL to * VK_DELETE. The fix is to map these keys * as a special case. */ case 27: key = OS.VK_ESCAPE; break; case 127: key = OS.VK_DELETE; break; default: { if (key == 0) return false; vKey = OS.VkKeyScan ((short) key); if (vKey == -1) { if (key != (int)OS.CharUpper ((short) key)) { fVirt = 0; } } else { key = vKey & 0xFF; } } } } accel.key = (short) key; accel.cmd = (short) id; accel.fVirt = (byte) fVirt; if ((accelerator & SWT.ALT) != 0) accel.fVirt |= OS.FALT; if ((accelerator & SWT.SHIFT) != 0) accel.fVirt |= OS.FSHIFT; if ((accelerator & SWT.CONTROL) != 0) accel.fVirt |= OS.FCONTROL; return true; }","boolean fillAccel (ACCEL accel) { accel.cmd = accel.key = accel.fVirt = 0; if (accelerator == 0 || !getEnabled ()) return false; if ((accelerator & SWT.COMMAND) != 0) return false; int fVirt = OS.FVIRTKEY; int key = accelerator & SWT.KEY_MASK; int vKey = Display.untranslateKey (key); if (vKey != 0) { key = vKey; } else { switch (key) { /* * Bug in Windows. For some reason, VkKeyScan * fails to map ESC to VK_ESCAPE and DEL to * VK_DELETE. The fix is to map these keys * as a special case. */ case 27: key = OS.VK_ESCAPE; break; case 127: key = OS.VK_DELETE; break; default: { if (key == 0) return false; vKey = OS.VkKeyScan ((short) key); if (vKey == -1) { if (key != (int)OS.CharUpper (OS.LOWORD (key))) { fVirt = 0; } } else { key = vKey & 0xFF; } } } } accel.key = (short) key; accel.cmd = (short) id; accel.fVirt = (byte) fVirt; if ((accelerator & SWT.ALT) != 0) accel.fVirt |= OS.FALT; if ((accelerator & SWT.SHIFT) != 0) accel.fVirt |= OS.FSHIFT; if ((accelerator & SWT.CONTROL) != 0) accel.fVirt |= OS.FCONTROL; return true; }","Issue #351: [win32] JVM crash when pressing '1' key in Nepali `CharUpper()` and `CharLower()` have two modes of operation: the first is to accept string pointer, and the second is to accept a single character. In case of single character mode (and SWT only uses that currently), the character must be in low word and the rest must be zeroes. However, key `1` in Nepali produces `MapVirtualKey()=0xF002`, which was sign extended to 0xfffffffffffff002. WINAPI considered this to be a pointer and crashed. The fix is to cast value properly. Steps to reproduce: 1) In Windows, add `Nepali (India)` keyboard layout 2) In SWT application, press `1` This fixes crash in unit test `testNepali_digits` for `1`. Signed-off-by: Alexandr Miloslavskiy ",https://github.com/eclipse-platform/eclipse.platform.swt/commit/48c74db2507cb4d28516f052163ac1ce5da64274,,,bundles/org.eclipse.swt/Eclipse SWT/win32/org/eclipse/swt/widgets/MenuItem.java,3,java,False,2022-08-28T13:01:50Z "@Override @SecurityHole(noAuth = true) public String cloudAuthorize(CloudRegistrationDTO cloudRegistrationDTO) { if (cloudRegistrationDTO == null) { throw new BadRequestException(this.i18n.tr(""No cloud registration information provided"")); } Principal principal = ResteasyContext.getContextData(Principal.class); CloudRegistrationData registrationData = getCloudRegistrationData(cloudRegistrationDTO); try { return this.cloudRegistrationAuth.generateRegistrationToken(principal, registrationData); } catch (UnsupportedOperationException e) { String errmsg = this.i18n.tr(""Cloud registration is not supported by this Candlepin instance""); throw new NotImplementedException(errmsg); } catch (CloudRegistrationAuthorizationException e) { throw new NotAuthorizedException(e.getMessage()); } catch (MalformedCloudRegistrationException e) { throw new BadRequestException(e.getMessage()); } }","@Override @SecurityHole(noAuth = true) public String cloudAuthorize(CloudRegistrationDTO cloudRegistrationDTO) { if (cloudRegistrationDTO == null) { throw new BadRequestException(this.i18n.tr(""No cloud registration information provided"")); } this.validator.validateConstraints(cloudRegistrationDTO); Principal principal = ResteasyContext.getContextData(Principal.class); CloudRegistrationData registrationData = getCloudRegistrationData(cloudRegistrationDTO); try { return this.cloudRegistrationAuth.generateRegistrationToken(principal, registrationData); } catch (UnsupportedOperationException e) { String errmsg = this.i18n.tr(""Cloud registration is not supported by this Candlepin instance""); throw new NotImplementedException(errmsg); } catch (CloudRegistrationAuthorizationException e) { throw new NotAuthorizedException(e.getMessage()); } catch (MalformedCloudRegistrationException e) { throw new BadRequestException(e.getMessage()); } }","Fix cloud auth URL from /cloud to /cloud/authorize - Add field validation check for cloud reg data",https://github.com/candlepin/candlepin/commit/02ccbda9283422bed1dde3c99f5de0cb460f4911,,,server/src/main/java/org/candlepin/resource/CloudRegistrationResource.java,3,java,False,2021-01-22T09:47:01Z "private synchronized void reset() { entryBatch.clear(); if (MemoryManager.Type.SELF_MANAGED.equals(memoryManager.getType())) { memoryManager.changeMemoryUsedBy(-1 * memoryUsed); } dumpData.set(false); if (dataDumpNotifyingPhaser != null) { log.info(""{} Finished saving data to disk. Notifying memory listener."", taskID); dataDumpNotifyingPhaser.arriveAndDeregister(); dataDumpNotifyingPhaser = null; } memoryUsed = 0; }","private synchronized void reset() { log.trace(""{} Reset called "", taskID); if (MemoryManager.Type.SELF_MANAGED.equals(memoryManager.getType())) { memoryManager.changeMemoryUsedBy(-1 * memoryUsed); } Phaser phaser = dataDumpNotifyingPhaserRef.get(); if (phaser != null) { log.info(""{} Finished saving data to disk. Notifying memory listener."", taskID); phaser.arriveAndDeregister(); dataDumpNotifyingPhaserRef.compareAndSet(phaser, null); } memoryUsed = 0; }","OAK-9576: Multithreaded download synchronization issues (#383) * OAK-9576 - Multithreaded download synchronization issues * Fixing a problem with test * OAK-9576: Multithreaded download synchronization issues * Fixing synchronization issues * Fixing OOM issue * Adding delay between download retries * OAK-9576: Multithreaded download synchronization issues * Using linkedlist in tasks for freeing memory early * Dumping if data is greater than one MB * OAK-9576: Multithreaded download synchronization issues * Closing node state entry traversors using try with * trivial - removing unused object * OAK-9576: Multithreaded download synchronization issues * Incorporating some feedback from review comments * OAK-9576: Multithreaded download synchronization issues * Replacing explicit synchronization with atomic operations * OAK-9576: Multithreaded download synchronization issues * Using same memory manager across retries * trivial - removing unwanted method * OAK-9576: Multithreaded download synchronization issues * Moving retry delay to exception block * trivial - correcting variable name Co-authored-by: amrverma ",https://github.com/apache/jackrabbit-oak/commit/c04aff5d970beccd41ff15c1c907f7ea6d0720fb,,,oak-run-commons/src/main/java/org/apache/jackrabbit/oak/index/indexer/document/flatfile/TraverseAndSortTask.java,3,java,False,2021-12-01T07:03:04Z "@Override public byte[] encrypt(byte[] iv, int tagLength, byte[] additionAuthenticatedData, byte[] someBytes) { this.cipher.init(true, new ParametersWithIV(new KeyParameter(this.key, 0, this.key.length), new byte[(tagLength / Bits.IN_A_BYTE) - 1], 0, iv.length)); int additionalDataLength = additionAuthenticatedData.length; int plaintextLength = someBytes.length; byte[] ciphertext = new byte[getOutputSize(true, plaintextLength)]; this.cipher.init(true, new ParametersWithIV(null, iv)); initMAC(); cipher.processBytes(someBytes, 0, plaintextLength, ciphertext, 0); byte[] aadLengthLittleEndian = ArrayConverter.reverseByteOrder(ArrayConverter.longToBytes(Long.valueOf(additionalDataLength), 8)); byte[] plaintextLengthLittleEndian = ArrayConverter.reverseByteOrder(ArrayConverter.longToBytes(Long.valueOf(plaintextLength), 8)); byte[] aadPlaintextLengthsLittleEndian = ArrayConverter.concatenate(aadLengthLittleEndian, plaintextLengthLittleEndian, 8); if (draftStructure) { byte[] macInput = ArrayConverter.concatenate(additionAuthenticatedData, aadLengthLittleEndian); macInput = ArrayConverter.concatenate(macInput, ciphertext, plaintextLength); macInput = ArrayConverter.concatenate(macInput, plaintextLengthLittleEndian); mac.update(macInput, 0, macInput.length); mac.doFinal(ciphertext, 0 + plaintextLength); } else { updateMAC(additionAuthenticatedData, 0, additionalDataLength); updateMAC(ciphertext, 0, plaintextLength); mac.update(aadPlaintextLengthsLittleEndian, 0, (tagLength / Bits.IN_A_BYTE)); mac.doFinal(ciphertext, 0 + plaintextLength); } return ciphertext; }","@Override public byte[] encrypt(byte[] iv, int tagLength, byte[] additionAuthenticatedData, byte[] someBytes) { if (iv.length != 8) { LOGGER.warn(""IV for ChaCha20Poly1305 has wrong size. Expected 8 byte but found: "" + iv.length + "". Padding/Trimming to 8 Byte.""); if (iv.length > 8) { iv = Arrays.copyOfRange(iv, 0, 8); } else { byte[] tempIv = new byte[8]; for (int i = 0; i < iv.length; i++) { tempIv[i] = iv[i]; } iv = tempIv; } } this.cipher.init(true, new ParametersWithIV(new KeyParameter(this.key, 0, this.key.length), new byte[(tagLength / Bits.IN_A_BYTE) - 1], 0, iv.length)); int additionalDataLength = additionAuthenticatedData.length; int plaintextLength = someBytes.length; byte[] ciphertext = new byte[getOutputSize(true, plaintextLength)]; this.cipher.init(true, new ParametersWithIV(null, iv)); initMAC(); cipher.processBytes(someBytes, 0, plaintextLength, ciphertext, 0); byte[] aadLengthLittleEndian = ArrayConverter.reverseByteOrder(ArrayConverter.longToBytes(Long.valueOf(additionalDataLength), 8)); byte[] plaintextLengthLittleEndian = ArrayConverter.reverseByteOrder(ArrayConverter.longToBytes(Long.valueOf(plaintextLength), 8)); byte[] aadPlaintextLengthsLittleEndian = ArrayConverter.concatenate(aadLengthLittleEndian, plaintextLengthLittleEndian, 8); if (draftStructure) { byte[] macInput = ArrayConverter.concatenate(additionAuthenticatedData, aadLengthLittleEndian); macInput = ArrayConverter.concatenate(macInput, ciphertext, plaintextLength); macInput = ArrayConverter.concatenate(macInput, plaintextLengthLittleEndian); mac.update(macInput, 0, macInput.length); mac.doFinal(ciphertext, 0 + plaintextLength); } else { updateMAC(additionAuthenticatedData, 0, additionalDataLength); updateMAC(ciphertext, 0, plaintextLength); mac.update(aadPlaintextLengthsLittleEndian, 0, (tagLength / Bits.IN_A_BYTE)); mac.doFinal(ciphertext, 0 + plaintextLength); } return ciphertext; }",Chacha20 now pads/trims iv if its not of correct size and throws a warning instead of crashing,https://github.com/tls-attacker/TLS-Attacker/commit/4e3d792cbe197ba824ef5077bf592cf385bcfbb9,,,TLS-Core/src/main/java/de/rub/nds/tlsattacker/core/crypto/cipher/ChaCha20Poly1305Cipher.java,3,java,False,2021-03-21T00:55:03Z "protected void checkItemContent(OPFItem item) { // We do not currently support checking resources defined as data URLs if (item.hasDataURL()) { return; } // Create a new validation context for the OPF item // FIXME 2022 set context OPFItem here // (instead of from XRefChecker in the builder code) ValidationContext itemContext = new ValidationContextBuilder(context).url(item.getURL()) .mimetype(item.getMimeType()).properties(item.getProperties()).build(); // Create an appropriate checker try { Checker checker; if (item.isNcx()) { checker = new NCXChecker(itemContext); } else if (item.isNav()) { checker = new NavChecker(itemContext); } else { checker = CheckerFactory.newChecker(itemContext); } // Check the item checker.check(); } catch (IllegalStateException e) { report.message(MessageId.CHK_008, EPUBLocation.of(context), item.getPath()); } }","protected void checkItemContent(OPFItem item) { // We do not currently support checking resources defined as data URLs if (item.hasDataURL()) { return; } // Abort if the item is this package document // (this is disallowed, and reported elsewhere) if (URLUtils.docURL(item.getURL()).equals(context.url)) { return; } // Create a new validation context for the OPF item // FIXME 2022 set context OPFItem here // (instead of from XRefChecker in the builder code) ValidationContext itemContext = new ValidationContextBuilder(context).url(item.getURL()) .mimetype(item.getMimeType()).properties(item.getProperties()).build(); // Create an appropriate checker try { Checker checker; if (item.isNcx()) { checker = new NCXChecker(itemContext); } else if (item.isNav()) { checker = new NavChecker(itemContext); } else { checker = CheckerFactory.newChecker(itemContext); } // Check the item checker.check(); } catch (IllegalStateException e) { report.message(MessageId.CHK_008, EPUBLocation.of(context), item.getPath()); } }","feat: check that the manifest is not self-referencing This commit adds a new check, reported as `OPF-099` (error), to verify that the package document `manifest` does not include an `item` element that refers to the package document itself. This statement was apparently not checked by EPUBCheck previously. Worse, the code was entering an infinite loop, as the package document checker was creating a new checker for itself, recursively. Fix #1453",https://github.com/w3c/epubcheck/commit/2c76420bda04422367474ec16aa64bcd94892cfa,,,src/main/java/com/adobe/epubcheck/opf/OPFChecker.java,3,java,False,2022-12-22T15:47:54Z "public ArrayMap getStringsForPrefix(ContentResolver cr, String prefix, List names) { String namespace = prefix.substring(0, prefix.length() - 1); DeviceConfig.enforceReadPermission(ActivityThread.currentApplication(), namespace); ArrayMap keyValues = new ArrayMap<>(); int currentGeneration = -1; synchronized (NameValueCache.this) { if (mGenerationTracker != null) { if (mGenerationTracker.isGenerationChanged()) { if (DEBUG) { Log.i(TAG, ""Generation changed for type:"" + mUri.getPath() + "" in package:"" + cr.getPackageName()); } mValues.clear(); } else { boolean prefixCached = mValues.containsKey(prefix); if (prefixCached) { if (!names.isEmpty()) { for (String name : names) { if (mValues.containsKey(name)) { keyValues.put(name, mValues.get(name)); } } } else { for (int i = 0; i < mValues.size(); ++i) { String key = mValues.keyAt(i); // Explicitly exclude the prefix as it is only there to // signal that the prefix has been cached. if (key.startsWith(prefix) && !key.equals(prefix)) { keyValues.put(key, mValues.get(key)); } } } return keyValues; } } if (mGenerationTracker != null) { currentGeneration = mGenerationTracker.getCurrentGeneration(); } } } if (mCallListCommand == null) { // No list command specified, return empty map return keyValues; } IContentProvider cp = mProviderHolder.getProvider(cr); try { Bundle args = new Bundle(); args.putString(Settings.CALL_METHOD_PREFIX_KEY, prefix); boolean needsGenerationTracker = false; synchronized (NameValueCache.this) { if (mGenerationTracker == null) { needsGenerationTracker = true; args.putString(CALL_METHOD_TRACK_GENERATION_KEY, null); if (DEBUG) { Log.i(TAG, ""Requested generation tracker for type: "" + mUri.getPath() + "" in package:"" + cr.getPackageName()); } } } // Fetch all flags for the namespace at once for caching purposes Bundle b = cp.call(cr.getAttributionSource(), mProviderHolder.mUri.getAuthority(), mCallListCommand, null, args); if (b == null) { // Invalid response, return an empty map return keyValues; } // All flags for the namespace Map flagsToValues = (HashMap) b.getSerializable(Settings.NameValueTable.VALUE, java.util.HashMap.class); // Only the flags requested by the caller if (!names.isEmpty()) { for (Map.Entry flag : flagsToValues.entrySet()) { if (names.contains(flag.getKey())) { keyValues.put(flag.getKey(), flag.getValue()); } } } else { keyValues.putAll(flagsToValues); } synchronized (NameValueCache.this) { if (needsGenerationTracker) { MemoryIntArray array = b.getParcelable( CALL_METHOD_TRACK_GENERATION_KEY, android.util.MemoryIntArray.class); final int index = b.getInt( CALL_METHOD_GENERATION_INDEX_KEY, -1); if (array != null && index >= 0) { final int generation = b.getInt( CALL_METHOD_GENERATION_KEY, 0); if (DEBUG) { Log.i(TAG, ""Received generation tracker for type:"" + mUri.getPath() + "" in package:"" + cr.getPackageName() + "" with index:"" + index); } if (mGenerationTracker != null) { mGenerationTracker.destroy(); } mGenerationTracker = new GenerationTracker(array, index, generation, () -> { synchronized (NameValueCache.this) { Log.e(TAG, ""Error accessing generation tracker"" + "" - removing""); if (mGenerationTracker != null) { GenerationTracker generationTracker = mGenerationTracker; mGenerationTracker = null; generationTracker.destroy(); mValues.clear(); } } }); currentGeneration = generation; } } if (mGenerationTracker != null && currentGeneration == mGenerationTracker.getCurrentGeneration()) { // cache the complete list of flags for the namespace mValues.putAll(flagsToValues); // Adding the prefix as a signal that the prefix is cached. mValues.put(prefix, null); } } return keyValues; } catch (RemoteException e) { // Not supported by the remote side, return an empty map return keyValues; } }","public ArrayMap getStringsForPrefix(ContentResolver cr, String prefix, List names) { String namespace = prefix.substring(0, prefix.length() - 1); DeviceConfig.enforceReadPermission(ActivityThread.currentApplication(), namespace); ArrayMap keyValues = new ArrayMap<>(); int currentGeneration = -1; synchronized (NameValueCache.this) { if (mGenerationTracker != null) { if (mGenerationTracker.isGenerationChanged()) { if (DEBUG) { Log.i(TAG, ""Generation changed for type:"" + mUri.getPath() + "" in package:"" + cr.getPackageName()); } mValues.clear(); } else { boolean prefixCached = mValues.containsKey(prefix); if (prefixCached) { if (!names.isEmpty()) { for (String name : names) { if (mValues.containsKey(name)) { keyValues.put(name, mValues.get(name)); } } } else { for (int i = 0; i < mValues.size(); ++i) { String key = mValues.keyAt(i); // Explicitly exclude the prefix as it is only there to // signal that the prefix has been cached. if (key.startsWith(prefix) && !key.equals(prefix)) { keyValues.put(key, mValues.get(key)); } } } return keyValues; } } if (mGenerationTracker != null) { currentGeneration = mGenerationTracker.getCurrentGeneration(); } } } if (mCallListCommand == null) { // No list command specified, return empty map return keyValues; } IContentProvider cp = mProviderHolder.getProvider(cr); try { Bundle args = new Bundle(); args.putString(Settings.CALL_METHOD_PREFIX_KEY, prefix); boolean needsGenerationTracker = false; synchronized (NameValueCache.this) { if (mGenerationTracker == null) { needsGenerationTracker = true; args.putString(CALL_METHOD_TRACK_GENERATION_KEY, null); if (DEBUG) { Log.i(TAG, ""Requested generation tracker for type: "" + mUri.getPath() + "" in package:"" + cr.getPackageName()); } } } Bundle b; // b/252663068: if we're in system server and the caller did not call // clearCallingIdentity, the read would fail due to mismatched AttributionSources. // TODO(b/256013480): remove this bypass after fixing the callers in system server. if (namespace.equals(DeviceConfig.NAMESPACE_DEVICE_POLICY_MANAGER) && Settings.isInSystemServer() && Binder.getCallingUid() != Process.myUid()) { final long token = Binder.clearCallingIdentity(); try { // Fetch all flags for the namespace at once for caching purposes b = cp.call(cr.getAttributionSource(), mProviderHolder.mUri.getAuthority(), mCallListCommand, null, args); } finally { Binder.restoreCallingIdentity(token); } } else { // Fetch all flags for the namespace at once for caching purposes b = cp.call(cr.getAttributionSource(), mProviderHolder.mUri.getAuthority(), mCallListCommand, null, args); } if (b == null) { // Invalid response, return an empty map return keyValues; } // All flags for the namespace Map flagsToValues = (HashMap) b.getSerializable(Settings.NameValueTable.VALUE, java.util.HashMap.class); // Only the flags requested by the caller if (!names.isEmpty()) { for (Map.Entry flag : flagsToValues.entrySet()) { if (names.contains(flag.getKey())) { keyValues.put(flag.getKey(), flag.getValue()); } } } else { keyValues.putAll(flagsToValues); } synchronized (NameValueCache.this) { if (needsGenerationTracker) { MemoryIntArray array = b.getParcelable( CALL_METHOD_TRACK_GENERATION_KEY, android.util.MemoryIntArray.class); final int index = b.getInt( CALL_METHOD_GENERATION_INDEX_KEY, -1); if (array != null && index >= 0) { final int generation = b.getInt( CALL_METHOD_GENERATION_KEY, 0); if (DEBUG) { Log.i(TAG, ""Received generation tracker for type:"" + mUri.getPath() + "" in package:"" + cr.getPackageName() + "" with index:"" + index); } if (mGenerationTracker != null) { mGenerationTracker.destroy(); } mGenerationTracker = new GenerationTracker(array, index, generation, () -> { synchronized (NameValueCache.this) { Log.e(TAG, ""Error accessing generation tracker"" + "" - removing""); if (mGenerationTracker != null) { GenerationTracker generationTracker = mGenerationTracker; mGenerationTracker = null; generationTracker.destroy(); mValues.clear(); } } }); currentGeneration = generation; } } if (mGenerationTracker != null && currentGeneration == mGenerationTracker.getCurrentGeneration()) { // cache the complete list of flags for the namespace mValues.putAll(flagsToValues); // Adding the prefix as a signal that the prefix is cached. mValues.put(prefix, null); } } return keyValues; } catch (RemoteException e) { // Not supported by the remote side, return an empty map return keyValues; } }","[SettingsProvider] workaround for DevicePolicyResourcesManager DevicePolicyResourcesManager.getString() was added in T and called in many places inside system server. However, it uses DeviceConfig.getBoolean to determine if a feature is enabled or not. In the places where it is called from inside system server, `clearCallingIdentity` was not always called, which can result in DeviceConfig.getBoolean throwing SecurityException due to mismatched AttributionSource (calling uid is the caller from the binder client, while the context is ""android"" which should have calling uid 0). Context is ""android"" because it is inside the system server where the DevicePolicyManager instance is created. This bug might lead to unexpected behavior such as packages failing to be uninstalled by admin. The easiest fix is to place a bypass in SettingsProvider and manually clear the calling uid there. This fix also allows for the cleanest backporting as it can be cherry-picked into T without touching all the places where DevicePolicyResourcesManager.getString() is called in the system server. BUG: 252663068 Test: manual Change-Id: I37a6ceb29575593018b93093562c85d49770a43c",https://github.com/aosp-mirror/platform_frameworks_base/commit/b127850fda23698be0247e5b2110cdd01fff8fd7,,,core/java/android/provider/Settings.java,3,java,False,2022-10-27T00:03:33Z "@Override public int decompress(byte[] input, int inputOffset, int inputLength, byte[] output, int outputOffset, int maxOutputLength) throws MalformedInputException { long inputAddress = ARRAY_BYTE_BASE_OFFSET + inputOffset; long inputLimit = inputAddress + inputLength; long outputAddress = ARRAY_BYTE_BASE_OFFSET + outputOffset; long outputLimit = outputAddress + maxOutputLength; return LzoRawDecompressor.decompress(input, inputAddress, inputLimit, output, outputAddress, outputLimit); }","@Override public int decompress(byte[] input, int inputOffset, int inputLength, byte[] output, int outputOffset, int maxOutputLength) throws MalformedInputException { verifyRange(input, inputOffset, inputLength); verifyRange(output, outputOffset, maxOutputLength); long inputAddress = ARRAY_BYTE_BASE_OFFSET + inputOffset; long inputLimit = inputAddress + inputLength; long outputAddress = ARRAY_BYTE_BASE_OFFSET + outputOffset; long outputLimit = outputAddress + maxOutputLength; return LzoRawDecompressor.decompress(input, inputAddress, inputLimit, output, outputAddress, outputLimit); }",Prevent JVM crash when buffer too small,https://github.com/airlift/aircompressor/commit/127b7f3c6330e6cc595f10648b68a197974b50bf,,,src/main/java/io/airlift/compress/lzo/LzoDecompressor.java,3,java,False,2022-04-12T10:20:50Z "@Override public boolean actPrimary( Platform server, LocalConfiguration config, Player player, LocalSession session, Location clicked, @Nullable Direction face ) { BlockBag bag = session.getBlockBag(player); try (EditSession editSession = session.createEditSession(player)) { try { editSession.disableBuffering(); BlockVector3 position = clicked.toVector().toBlockPoint(); editSession.setBlock(position, pattern); } catch (MaxChangedBlocksException ignored) { } finally { session.remember(editSession); } } finally { if (bag != null) { bag.flushChanges(); } } return true; }","@Override public boolean actPrimary( Platform server, LocalConfiguration config, Player player, LocalSession session, Location clicked, @Nullable Direction face ) { BlockBag bag = session.getBlockBag(player); try (EditSession editSession = session.createEditSession(player)) { try { BlockVector3 position = clicked.toVector().toBlockPoint(); editSession.setBlock(position, pattern); } catch (MaxChangedBlocksException ignored) { } finally { session.remember(editSession); } } finally { if (bag != null) { bag.flushChanges(); } } return true; }","Fix major security bugs (3 brushes + superpickaxe)! (#1213) * Fix major security bugs (3 brushes + superpickaxe)! - Due to some recent changes, FAWE could edit everything in the world, no matter other plugin protections such as PS or WG. - Fix superpickaxe allow to bypass protections => Fix SurvivalModeExtent not taking into account protections plugins due to breaking blocks naturally to get drops. * Adress requests - Revert some unsuitabe changes - Add FAWE diff comments * Clean imports * Adress requests Co-authored-by: NotMyFault ",https://github.com/IntellectualSites/FastAsyncWorldEdit/commit/abaa347ad4856b209c741a8b29884d14a54c4b3d,,,worldedit-core/src/main/java/com/sk89q/worldedit/command/tool/BlockReplacer.java,3,java,False,2021-08-07T09:09:33Z "public static int icon(int id) { if (id == 36) { return 2131165726; } for (int i = 0; i < cachedCustomComponents.size(); i++) { HashMap component = cachedCustomComponents.get(i); Object idObject = component.get(""id""); if (idObject instanceof String) { try { int componentId = Integer.parseInt((String) idObject); if (componentId == id) { Object iconObject = component.get(""icon""); if (iconObject instanceof String) { try { return Integer.parseInt((String) iconObject); } catch (NumberFormatException e) { SketchwareUtil.toastError(""Invalid icon entry for Custom Component #"" + (i + 1), Toast.LENGTH_LONG); break; } } } } catch (NumberFormatException e) { SketchwareUtil.toastError(""Invalid ID entry for Custom Component #"" + (i + 1), Toast.LENGTH_LONG); } } else { SketchwareUtil.toastError(""Invalid ID entry for Custom Component #"" + (i + 1), Toast.LENGTH_LONG); } } return 2131165469; }","public static int icon(int id) { if (id == 36) { return 2131165726; } for (int i = 0; i < cachedCustomComponents.size(); i++) { HashMap component = cachedCustomComponents.get(i); if (component != null) { Object idObject = component.get(""id""); if (idObject instanceof String) { try { int componentId = Integer.parseInt((String) idObject); if (componentId == id) { Object iconObject = component.get(""icon""); if (iconObject instanceof String) { try { return Integer.parseInt((String) iconObject); } catch (NumberFormatException e) { SketchwareUtil.toastError(""Invalid icon entry for Custom Component #"" + (i + 1), Toast.LENGTH_LONG); break; } } } } catch (NumberFormatException e) { SketchwareUtil.toastError(""Invalid ID entry for Custom Component #"" + (i + 1), Toast.LENGTH_LONG); } } else { SketchwareUtil.toastError(""Invalid ID entry for Custom Component #"" + (i + 1), Toast.LENGTH_LONG); } } else { SketchwareUtil.toastError(""Invalid (null) Custom Component at position "" + i); } } return 2131165469; }","fix: Handle null Custom Components and don't crash on an NPE Related to commit 2db1b76b7ac5631b52e6ce15e801aa1a4063d856: ""fix: Handle null Custom Events and don't crash on an NPE"".",https://github.com/Sketchware-Pro/Sketchware-Pro/commit/833da0d273674c5a0a0ee138c209b3ba28886690,,,app/src/main/java/mod/hilal/saif/components/ComponentsHandler.java,3,java,False,2022-09-25T09:44:49Z "@GuardedBy(""mLock"") public boolean deleteSettingLocked(String name) { if (TextUtils.isEmpty(name) || !hasSettingLocked(name)) { return false; } Setting oldState = mSettings.remove(name); FrameworkStatsLog.write(FrameworkStatsLog.SETTING_CHANGED, name, /* value= */ """", /* newValue= */ """", oldState.value, /* tag */ """", false, getUserIdFromKey(mKey), FrameworkStatsLog.SETTING_CHANGED__REASON__DELETED); updateMemoryUsagePerPackageLocked(oldState.packageName, oldState.value, null, oldState.defaultValue, null); addHistoricalOperationLocked(HISTORICAL_OPERATION_DELETE, oldState); scheduleWriteIfNeededLocked(); return true; }","@GuardedBy(""mLock"") public boolean deleteSettingLocked(String name) { if (TextUtils.isEmpty(name) || !hasSettingLocked(name)) { return false; } Setting oldState = mSettings.remove(name); int newSize = getNewMemoryUsagePerPackageLocked(oldState.packageName, oldState.value, null, oldState.defaultValue, null); FrameworkStatsLog.write(FrameworkStatsLog.SETTING_CHANGED, name, /* value= */ """", /* newValue= */ """", oldState.value, /* tag */ """", false, getUserIdFromKey(mKey), FrameworkStatsLog.SETTING_CHANGED__REASON__DELETED); updateMemoryUsagePerPackageLocked(oldState.packageName, newSize); addHistoricalOperationLocked(HISTORICAL_OPERATION_DELETE, oldState); scheduleWriteIfNeededLocked(); return true; }","[SettingsProvider] mem limit should be checked before settings are updated Previously, a setting is updated before the memory usage limit check, which can be exploited by malicious apps and cause OoM DoS. This CL changes the logic to checkMemLimit -> update -> updateMemUsage. BUG: 239415861 Test: atest com.android.providers.settings.SettingsStateTest Change-Id: I20551a2dba9aa79efa0c064824f349f551c2c2e4",https://github.com/LineageOS/android_frameworks_base/commit/8eeb92950f4a7012d4cf282106a1418fd211f475,,,packages/SettingsProvider/src/com/android/providers/settings/SettingsState.java,3,java,False,2022-08-17T16:37:18Z "public synchronized TriggerSmartContract rlpParseToTriggerSmartContract() { if (!parsed) rlpParse(); TriggerSmartContract.Builder build = TriggerSmartContract.newBuilder(); build.setOwnerAddress(ByteString.copyFrom(ByteArray.fromHexString(ByteArray.toHexString(this.getSender()).replace(Constant.ETH_PRE_FIX_STRING_MAINNET, Constant.ADD_PRE_FIX_STRING_MAINNET)))); build.setContractAddress(ByteString.copyFrom(ByteArray.fromHexString(Constant.ADD_PRE_FIX_STRING_MAINNET + ByteArray.toHexString(this.getReceiveAddress())))); build.setCallValue(ByteUtil.byteArrayToLong(this.value)); build.setData(ByteString.copyFrom(this.data)); build.setCallTokenValue(0); build.setTokenId(0); build.setType(1); build.setRlpData(ByteString.copyFrom(rlpEncoded)); return build.build(); }","public synchronized TriggerSmartContract rlpParseToTriggerSmartContract() { if (!parsed) rlpParse(); TriggerSmartContract.Builder build = TriggerSmartContract.newBuilder(); build.setOwnerAddress(ByteString.copyFrom(ByteArray.fromHexString(ByteArray.toHexString(this.getSender()).replace(Constant.ETH_PRE_FIX_STRING_MAINNET, Constant.ADD_PRE_FIX_STRING_MAINNET)))); build.setContractAddress(ByteString.copyFrom(ByteArray.fromHexString(Constant.ADD_PRE_FIX_STRING_MAINNET + ByteArray.toHexString(this.getReceiveAddress())))); build.setCallValue(new BigInteger(1, this.value).divide(new BigInteger(""1000000000000"")).longValue()); build.setData(ByteString.copyFrom(this.data)); build.setCallTokenValue(0); build.setTokenId(0); build.setType(1); build.setRlpData(ByteString.copyFrom(rlpEncoded)); return build.build(); }","Bugfix/20220108/ethereum compatible replayattack (#113) * update version ultima_v1.0.3 * optimize validateEthSignature and rlpParseContract parameters * update version ultima_v1.0.4",https://github.com/vision-consensus/vision-core/commit/89c1e0742966adf99fb5fa855c6b6e37c63e861f,,,chainstorage/src/main/java/org/vision/core/capsule/TransactionCapsule.java,3,java,False,2022-01-21T13:15:55Z "private boolean isServiceVulnerable(NetworkService networkService) { String targetUri = NetworkServiceUtils.buildWebApplicationRootUrl(networkService) + ""/api/geojson?url=file:////etc/passwd""; try { HttpResponse response = httpClient.send(get(targetUri).withEmptyHeaders().build(), networkService); if (response.status() == HttpStatus.OK && response.bodyString().isPresent()) { if (VULNERABILITY_RESPONSE_PATTERN.matcher(response.bodyString().get()).find()) { return true; } } } catch (IOException e) { logger.atWarning().withCause(e).log(""Unable to query '%s'."", targetUri); } return false; }","private boolean isServiceVulnerable(NetworkService networkService) { String targetUri = NetworkServiceUtils.buildWebApplicationRootUrl(networkService) + ""api/geojson?url=file:///etc/passwd""; try { HttpResponse response = httpClient.send(get(targetUri).withEmptyHeaders().build(), networkService); if (response.status() == HttpStatus.OK && response.bodyString().isPresent()) { if (VULNERABILITY_RESPONSE_PATTERN.matcher(response.bodyString().get()).find()) { return true; } } } catch (IOException e) { logger.atWarning().withCause(e).log(""Unable to query '%s'."", targetUri); } return false; }","Fix detection logic of Metabase CVE-2021-41277 detector. PiperOrigin-RevId: 427050953 Change-Id: If4bab5ebd92d856ef89321c2ea89f56f5dec1533",https://github.com/google/tsunami-security-scanner-plugins/commit/e003d299261c602ce1dde71b36685835f30425ef,,,community/detectors/metabase_cve_2021_41277/src/main/java/com/google/tsunami/plugins/detectors/metabase/MetabaseCve202141277Detector.java,3,java,False,2022-02-08T00:36:51Z "@Override public void c() { WStackedSpawner stackedSpawner = this.stackedSpawner.get(); if (stackedSpawner == null) { super.c(); return; } if (!hasNearbyPlayers()) { if (stackedSpawner.isDebug()) Debug.debug(""StackedMobSpawner"", ""c"", ""No nearby players in range ("" + this.requiredPlayerRange + "")""); failureReason = ""There are no nearby players.""; return; } if (this.spawnDelay == -1) resetSpawnDelay(); if (this.spawnDelay > 0) { --this.spawnDelay; return; } if (demoEntity == null) { if (stackedSpawner.isDebug()) Debug.debug(""StackedMobSpawner"", ""c"", ""Demo entity is null""); super.c(); return; } Entity demoNMSEntity = ((CraftEntity) demoEntity.getLivingEntity()).getHandle(); MinecraftKey entityType = EntityTypes.a(demoNMSEntity); if (entityType == null || !entityType.equals(getMobName())) { if (stackedSpawner.isDebug()) Debug.debug(""StackedMobSpawner"", ""c"", ""No valid entity to spawn""); updateDemoEntity(); if (demoEntity == null) { if (stackedSpawner.isDebug()) Debug.debug(""StackedMobSpawner"", ""c"", ""Demo entity is null after trying to update it""); super.c(); return; } updateUpgrade(stackedSpawner.getUpgradeId()); demoNMSEntity = ((CraftEntity) demoEntity.getLivingEntity()).getHandle(); } int stackAmount = stackedSpawner.getStackAmount(); if (stackedSpawner.isDebug()) Debug.debug(""StackedMobSpawner"", ""c"", ""stackAmount="" + stackAmount); List nearbyEntities = world.a(demoNMSEntity.getClass(), new AxisAlignedBB( position.getX(), position.getY(), position.getZ(), position.getX() + 1, position.getY() + 1, position.getZ() + 1 ).g(this.spawnRange)); StackedEntity targetEntity = getTargetEntity(stackedSpawner, demoEntity, nearbyEntities); if (stackedSpawner.isDebug()) Debug.debug(""StackedMobSpawner"", ""c"", ""targetEntity="" + targetEntity); if (targetEntity == null && nearbyEntities.size() >= this.maxNearbyEntities) { if (stackedSpawner.isDebug()) Debug.debug(""StackedMobSpawner"", ""c"", ""There are too many nearby entities ("" + nearbyEntities.size() + "">"" + this.maxNearbyEntities + "")""); failureReason = ""There are too many nearby entities.""; return; } boolean spawnStacked = EventsCaller.callSpawnerStackedEntitySpawnEvent(stackedSpawner.getSpawner()); failureReason = """"; if (stackedSpawner.isDebug()) Debug.debug(""StackedMobSpawner"", ""c"", ""spawnStacked="" + spawnStacked); int spawnCount = !spawnStacked || !demoEntity.isCached() ? Random.nextInt(1, this.spawnCount, stackAmount) : Random.nextInt(1, this.spawnCount, stackAmount, 1.5); if (stackedSpawner.isDebug()) Debug.debug(""StackedMobSpawner"", ""c"", ""spawnCount="" + spawnCount); int amountPerEntity = 1; int mobsToSpawn; short particlesAmount = 0; // Try stacking into the target entity first if (targetEntity != null && EventsCaller.callEntityStackEvent(targetEntity, demoEntity)) { if (stackedSpawner.isDebug()) Debug.debug(""StackedMobSpawner"", ""c"", ""Stacking into the target entity""); int targetEntityStackLimit = targetEntity.getStackLimit(); int currentStackAmount = targetEntity.getStackAmount(); int increaseStackAmount = Math.min(spawnCount, targetEntityStackLimit - currentStackAmount); if (increaseStackAmount != spawnCount) { mobsToSpawn = spawnCount - increaseStackAmount; } else { mobsToSpawn = 0; } if (stackedSpawner.isDebug()) Debug.debug(""StackedMobSpawner"", ""c"", ""increaseStackAmount="" + increaseStackAmount); if (increaseStackAmount > 0) { spawnedEntities += increaseStackAmount; targetEntity.increaseStackAmount(increaseStackAmount, true); demoEntity.spawnStackParticle(true); if (plugin.getSettings().linkedEntitiesEnabled && targetEntity.getLivingEntity() != stackedSpawner.getLinkedEntity()) stackedSpawner.setLinkedEntity(targetEntity.getLivingEntity()); world.triggerEffect(2004, position, 0); particlesAmount++; } } else { if (stackedSpawner.isDebug()) Debug.debug(""StackedMobSpawner"", ""c"", ""Stacking naturally""); mobsToSpawn = spawnCount; } if (mobsToSpawn > 0 && demoEntity.isCached() && spawnStacked) { amountPerEntity = Math.min(mobsToSpawn, demoEntity.getStackLimit()); if (stackedSpawner.isDebug()) Debug.debug(""StackedMobSpawner"", ""c"", ""amountPerEntity="" + amountPerEntity); mobsToSpawn = mobsToSpawn / amountPerEntity; } if (stackedSpawner.isDebug()) Debug.debug(""StackedMobSpawner"", ""c"", ""mobsToSpawn="" + mobsToSpawn); while (spawnedEntities < stackAmount) { if (!attemptMobSpawning(mobsToSpawn, amountPerEntity, spawnCount, particlesAmount, stackedSpawner)) return; } resetSpawnDelay(); }","@Override public void c() { WStackedSpawner stackedSpawner = this.stackedSpawner.get(); if (stackedSpawner == null) { super.c(); return; } if (!hasNearbyPlayers()) { if (stackedSpawner.isDebug()) Debug.debug(""StackedMobSpawner"", ""c"", ""No nearby players in range ("" + this.requiredPlayerRange + "")""); failureReason = ""There are no nearby players.""; return; } if (this.spawnDelay == -1) resetSpawnDelay(); if (this.spawnDelay > 0) { --this.spawnDelay; return; } if (demoEntity == null) { if (stackedSpawner.isDebug()) Debug.debug(""StackedMobSpawner"", ""c"", ""Demo entity is null""); super.c(); return; } Entity demoNMSEntity = ((CraftEntity) demoEntity.getLivingEntity()).getHandle(); MinecraftKey entityType = EntityTypes.a(demoNMSEntity); if (entityType == null || !entityType.equals(getMobName())) { if (stackedSpawner.isDebug()) Debug.debug(""StackedMobSpawner"", ""c"", ""No valid entity to spawn""); updateDemoEntity(); if (demoEntity == null) { if (stackedSpawner.isDebug()) Debug.debug(""StackedMobSpawner"", ""c"", ""Demo entity is null after trying to update it""); super.c(); return; } updateUpgrade(stackedSpawner.getUpgradeId()); demoNMSEntity = ((CraftEntity) demoEntity.getLivingEntity()).getHandle(); } int stackAmount = stackedSpawner.getStackAmount(); if (stackedSpawner.isDebug()) Debug.debug(""StackedMobSpawner"", ""c"", ""stackAmount="" + stackAmount); List nearbyEntities = world.a(demoNMSEntity.getClass(), new AxisAlignedBB( position.getX(), position.getY(), position.getZ(), position.getX() + 1, position.getY() + 1, position.getZ() + 1 ).g(this.spawnRange)); AtomicInteger nearbyAndStackableCount = new AtomicInteger(0); List nearbyAndStackableEntities = new LinkedList<>(); nearbyEntities.forEach(entity -> { CraftEntity craftEntity = entity.getBukkitEntity(); if (EntityUtils.isStackable(craftEntity)) { StackedEntity stackedEntity = WStackedEntity.of(craftEntity); if (this.demoEntity.runStackCheck(stackedEntity) == StackCheckResult.SUCCESS) { nearbyAndStackableCount.set(nearbyAndStackableCount.get() + stackedEntity.getStackAmount()); nearbyAndStackableEntities.add(stackedEntity); } } }); StackedEntity targetEntity = getTargetEntity(stackedSpawner, this.demoEntity, nearbyAndStackableEntities); if (stackedSpawner.isDebug()) Debug.debug(""StackedMobSpawner"", ""c"", ""targetEntity="" + targetEntity); if (targetEntity == null && nearbyEntities.size() >= this.maxNearbyEntities) { if (stackedSpawner.isDebug()) Debug.debug(""StackedMobSpawner"", ""c"", ""There are too many nearby entities ("" + nearbyEntities.size() + "">"" + this.maxNearbyEntities + "")""); failureReason = ""There are too many nearby entities.""; return; } int minimumEntityRequirement = GeneralUtils.get(plugin.getSettings().minimumRequiredEntities, this.demoEntity, 1); int stackedEntityCount = Random.nextInt(1, this.spawnCount, stackAmount, 1.5); boolean canStackToTarget = nearbyAndStackableCount.get() + stackedEntityCount >= minimumEntityRequirement; boolean spawnStacked = plugin.getSettings().entitiesStackingEnabled && canStackToTarget && EventsCaller.callSpawnerStackedEntitySpawnEvent(stackedSpawner.getSpawner()); failureReason = """"; if (stackedSpawner.isDebug()) Debug.debug(""StackedMobSpawner"", ""c"", ""spawnStacked="" + spawnStacked); int spawnCount = !spawnStacked || !demoEntity.isCached() ? Random.nextInt(1, this.spawnCount, stackAmount) : stackedEntityCount; if (stackedSpawner.isDebug()) Debug.debug(""StackedMobSpawner"", ""c"", ""spawnCount="" + spawnCount); int amountPerEntity = 1; int mobsToSpawn; short particlesAmount = 0; // Try stacking into the target entity first if (targetEntity != null && canStackToTarget && EventsCaller.callEntityStackEvent(targetEntity, demoEntity)) { if (stackedSpawner.isDebug()) Debug.debug(""StackedMobSpawner"", ""c"", ""Stacking into the target entity""); int targetEntityStackLimit = targetEntity.getStackLimit(); int currentStackAmount = targetEntity.getStackAmount(); int increaseStackAmount = Math.min(spawnCount, targetEntityStackLimit - currentStackAmount); if (increaseStackAmount != spawnCount) { mobsToSpawn = spawnCount - increaseStackAmount; } else { mobsToSpawn = 0; } if (stackedSpawner.isDebug()) Debug.debug(""StackedMobSpawner"", ""c"", ""increaseStackAmount="" + increaseStackAmount); if (increaseStackAmount > 0) { spawnedEntities += increaseStackAmount; if (minimumEntityRequirement > 1) { // We want to stack all nearby entities into target as well. increaseStackAmount += nearbyAndStackableCount.get() - targetEntity.getStackAmount(); nearbyAndStackableEntities.forEach(nearbyEntity -> { if (nearbyEntity != targetEntity) { nearbyEntity.remove(); nearbyEntity.spawnStackParticle(true); } }); } targetEntity.increaseStackAmount(increaseStackAmount, true); demoEntity.spawnStackParticle(true); if (plugin.getSettings().linkedEntitiesEnabled && targetEntity.getLivingEntity() != stackedSpawner.getLinkedEntity()) stackedSpawner.setLinkedEntity(targetEntity.getLivingEntity()); world.triggerEffect(2004, position, 0); particlesAmount++; } } else { if (stackedSpawner.isDebug()) Debug.debug(""StackedMobSpawner"", ""c"", ""Stacking naturally""); mobsToSpawn = spawnCount; } if (mobsToSpawn > 0 && demoEntity.isCached() && spawnStacked) { amountPerEntity = Math.min(mobsToSpawn, demoEntity.getStackLimit()); if (stackedSpawner.isDebug()) Debug.debug(""StackedMobSpawner"", ""c"", ""amountPerEntity="" + amountPerEntity); mobsToSpawn = mobsToSpawn / amountPerEntity; } if (stackedSpawner.isDebug()) Debug.debug(""StackedMobSpawner"", ""c"", ""mobsToSpawn="" + mobsToSpawn); while (spawnedEntities < stackAmount) { if (!attemptMobSpawning(mobsToSpawn, amountPerEntity, spawnCount, particlesAmount, stackedSpawner)) return; } resetSpawnDelay(); }",Fixed entities spawn from spawners bypass minimum-required checks (#670),https://github.com/BG-Software-LLC/WildStacker/commit/9b63a964dc0b78b1a6a49738f4214ffb4fdf0df4,,,v1_12_R1/src/main/java/com/bgsoftware/wildstacker/nms/v1_12_R1/spawner/StackedMobSpawner.java,3,java,False,2022-11-20T14:00:43Z "@Override public void serverTick(ServerLevel serverLevel, BlockPos blockPos) { try { // Paper only if (spawnDelay > 0 && --tickDelay > 0) return; tickDelay = serverLevel.paperConfig.mobSpawnerTickRate; if (tickDelay == -1) return; } catch (Throwable ignored) { // If not running Paper, we want the tickDelay to be set to 1. tickDelay = 1; } WStackedSpawner stackedSpawner = this.stackedSpawner.get(); if (stackedSpawner == null) { super.serverTick(serverLevel, blockPos); return; } if (!serverLevel.hasNearbyAlivePlayer(blockPos.getX() + 0.5D, blockPos.getY() + 0.5D, blockPos.getZ() + 0.5D, this.requiredPlayerRange)) { failureReason = ""There are no nearby players.""; if (stackedSpawner.isDebug()) Debug.debug(""StackedBaseSpawner"", ""serverTick"", ""No nearby players in range ("" + this.requiredPlayerRange + "")""); return; } if (this.spawnDelay <= -tickDelay) resetSpawnDelay(serverLevel, blockPos); if (this.spawnDelay > 0) { this.spawnDelay -= tickDelay; return; } if (this.demoEntity == null) { if (stackedSpawner.isDebug()) Debug.debug(""StackedBaseSpawner"", ""serverTick"", ""Demo entity is null""); super.serverTick(serverLevel, blockPos); failureReason = """"; return; } CompoundTag entityToSpawn = this.nextSpawnData.getTag(); Optional> entityTypesOptional = EntityType.by(entityToSpawn); if (!entityTypesOptional.isPresent()) { if (stackedSpawner.isDebug()) Debug.debug(""StackedBaseSpawner"", ""serverTick"", ""No valid entity to spawn""); resetSpawnDelay(serverLevel, blockPos); failureReason = """"; return; } EntityType entityToSpawnType = entityTypesOptional.get(); Entity demoEntity = ((CraftEntity) this.demoEntity.getLivingEntity()).getHandle(); if (demoEntity.getType() != entityToSpawnType) { updateDemoEntity(serverLevel, blockPos); if (this.demoEntity == null) { if (stackedSpawner.isDebug()) Debug.debug(""StackedBaseSpawner"", ""serverTick"", ""Demo entity is null after trying to update it""); super.serverTick(serverLevel, blockPos); failureReason = """"; return; } updateUpgrade(stackedSpawner.getUpgradeId()); demoEntity = ((CraftEntity) this.demoEntity.getLivingEntity()).getHandle(); } int stackAmount = stackedSpawner.getStackAmount(); if (stackedSpawner.isDebug()) Debug.debug(""StackedBaseSpawner"", ""serverTick"", ""stackAmount="" + stackAmount); List nearbyEntities = serverLevel.getEntitiesOfClass( demoEntity.getClass(), new AABB(blockPos.getX(), blockPos.getY(), blockPos.getZ(), blockPos.getX() + 1, blockPos.getY() + 1, blockPos.getZ() + 1).inflate(this.spawnRange)); StackedEntity targetEntity = getTargetEntity(stackedSpawner, this.demoEntity, nearbyEntities); if (stackedSpawner.isDebug()) Debug.debug(""StackedBaseSpawner"", ""serverTick"", ""targetEntity="" + targetEntity); if (targetEntity == null && nearbyEntities.size() >= this.maxNearbyEntities) { if (stackedSpawner.isDebug()) Debug.debug(""StackedBaseSpawner"", ""serverTick"", ""There are too many nearby entities ("" + nearbyEntities.size() + "">"" + this.maxNearbyEntities + "")""); failureReason = ""There are too many nearby entities.""; return; } boolean spawnStacked = plugin.getSettings().entitiesStackingEnabled && EventsCaller.callSpawnerStackedEntitySpawnEvent(stackedSpawner.getSpawner()); failureReason = """"; if (stackedSpawner.isDebug()) Debug.debug(""StackedBaseSpawner"", ""serverTick"", ""spawnStacked="" + spawnStacked); int spawnCount = !spawnStacked || !this.demoEntity.isCached() ? Random.nextInt(1, this.spawnCount, stackAmount) : Random.nextInt(1, this.spawnCount, stackAmount, 1.5); if (stackedSpawner.isDebug()) Debug.debug(""StackedBaseSpawner"", ""serverTick"", ""spawnCount="" + spawnCount); int amountPerEntity = 1; int mobsToSpawn; short particlesAmount = 0; // Try stacking into the target entity first if (targetEntity != null && EventsCaller.callEntityStackEvent(targetEntity, this.demoEntity)) { if (stackedSpawner.isDebug()) Debug.debug(""StackedBaseSpawner"", ""serverTick"", ""Stacking into the target entity""); int targetEntityStackLimit = targetEntity.getStackLimit(); int currentStackAmount = targetEntity.getStackAmount(); int increaseStackAmount = Math.min(spawnCount, targetEntityStackLimit - currentStackAmount); if (increaseStackAmount != spawnCount) { mobsToSpawn = spawnCount - increaseStackAmount; } else { mobsToSpawn = 0; } if (stackedSpawner.isDebug()) Debug.debug(""StackedBaseSpawner"", ""serverTick"", ""increaseStackAmount="" + increaseStackAmount); if (increaseStackAmount > 0) { spawnedEntities += increaseStackAmount; targetEntity.increaseStackAmount(increaseStackAmount, true); this.demoEntity.spawnStackParticle(true); if (plugin.getSettings().linkedEntitiesEnabled && targetEntity.getLivingEntity() != stackedSpawner.getLinkedEntity()) stackedSpawner.setLinkedEntity(targetEntity.getLivingEntity()); serverLevel.levelEvent(2004, blockPos, 0); particlesAmount++; } } else { if (stackedSpawner.isDebug()) Debug.debug(""StackedBaseSpawner"", ""serverTick"", ""Stacking naturally""); mobsToSpawn = spawnCount; } if (mobsToSpawn > 0 && this.demoEntity.isCached() && spawnStacked) { amountPerEntity = Math.min(mobsToSpawn, this.demoEntity.getStackLimit()); if (stackedSpawner.isDebug()) Debug.debug(""StackedBaseSpawner"", ""serverTick"", ""amountPerEntity="" + amountPerEntity); mobsToSpawn = mobsToSpawn / amountPerEntity; } if (stackedSpawner.isDebug()) Debug.debug(""StackedBaseSpawner"", ""serverTick"", ""mobsToSpawn="" + mobsToSpawn); MobSpawnResult spawnResult = MobSpawnResult.SUCCESS; try { stackedSpawner.setSpawnerOverridenTick(true); while (spawnResult == MobSpawnResult.SUCCESS && spawnedEntities < stackAmount) { spawnResult = attemptMobSpawning(serverLevel, blockPos, entityToSpawn, entityToSpawnType, mobsToSpawn, amountPerEntity, spawnCount, particlesAmount, stackedSpawner); if (stackedSpawner.isDebug()) { Debug.debug(""StackedBaseSpawner"", ""serverTick"", ""spawnResult="" + spawnResult); Debug.debug(""StackedBaseSpawner"", ""serverTick"", ""spawnedEntities="" + spawnedEntities); } } } finally { stackedSpawner.setSpawnerOverridenTick(false); } if (spawnResult == MobSpawnResult.SUCCESS || spawnResult == MobSpawnResult.ABORT_AND_RESET_DELAY) resetSpawnDelay(serverLevel, blockPos); }","@Override public void serverTick(ServerLevel serverLevel, BlockPos blockPos) { try { // Paper only if (spawnDelay > 0 && --tickDelay > 0) return; tickDelay = serverLevel.paperConfig.mobSpawnerTickRate; if (tickDelay == -1) return; } catch (Throwable ignored) { // If not running Paper, we want the tickDelay to be set to 1. tickDelay = 1; } WStackedSpawner stackedSpawner = this.stackedSpawner.get(); if (stackedSpawner == null) { super.serverTick(serverLevel, blockPos); return; } if (!serverLevel.hasNearbyAlivePlayer(blockPos.getX() + 0.5D, blockPos.getY() + 0.5D, blockPos.getZ() + 0.5D, this.requiredPlayerRange)) { failureReason = ""There are no nearby players.""; if (stackedSpawner.isDebug()) Debug.debug(""StackedBaseSpawner"", ""serverTick"", ""No nearby players in range ("" + this.requiredPlayerRange + "")""); return; } if (this.spawnDelay <= -tickDelay) resetSpawnDelay(serverLevel, blockPos); if (this.spawnDelay > 0) { this.spawnDelay -= tickDelay; return; } if (this.demoEntity == null) { if (stackedSpawner.isDebug()) Debug.debug(""StackedBaseSpawner"", ""serverTick"", ""Demo entity is null""); super.serverTick(serverLevel, blockPos); failureReason = """"; return; } CompoundTag entityToSpawn = this.nextSpawnData.getTag(); Optional> entityTypesOptional = EntityType.by(entityToSpawn); if (!entityTypesOptional.isPresent()) { if (stackedSpawner.isDebug()) Debug.debug(""StackedBaseSpawner"", ""serverTick"", ""No valid entity to spawn""); resetSpawnDelay(serverLevel, blockPos); failureReason = """"; return; } EntityType entityToSpawnType = entityTypesOptional.get(); Entity demoEntity = ((CraftEntity) this.demoEntity.getLivingEntity()).getHandle(); if (demoEntity.getType() != entityToSpawnType) { updateDemoEntity(serverLevel, blockPos); if (this.demoEntity == null) { if (stackedSpawner.isDebug()) Debug.debug(""StackedBaseSpawner"", ""serverTick"", ""Demo entity is null after trying to update it""); super.serverTick(serverLevel, blockPos); failureReason = """"; return; } updateUpgrade(stackedSpawner.getUpgradeId()); demoEntity = ((CraftEntity) this.demoEntity.getLivingEntity()).getHandle(); } int stackAmount = stackedSpawner.getStackAmount(); if (stackedSpawner.isDebug()) Debug.debug(""StackedBaseSpawner"", ""serverTick"", ""stackAmount="" + stackAmount); List nearbyEntities = serverLevel.getEntitiesOfClass( demoEntity.getClass(), new AABB(blockPos.getX(), blockPos.getY(), blockPos.getZ(), blockPos.getX() + 1, blockPos.getY() + 1, blockPos.getZ() + 1).inflate(this.spawnRange)); AtomicInteger nearbyAndStackableCount = new AtomicInteger(0); List nearbyAndStackableEntities = new LinkedList<>(); nearbyEntities.forEach(entity -> { CraftEntity craftEntity = entity.getBukkitEntity(); if (EntityUtils.isStackable(craftEntity)) { StackedEntity stackedEntity = WStackedEntity.of(craftEntity); if (this.demoEntity.runStackCheck(stackedEntity) == StackCheckResult.SUCCESS) { nearbyAndStackableCount.set(nearbyAndStackableCount.get() + stackedEntity.getStackAmount()); nearbyAndStackableEntities.add(stackedEntity); } } }); StackedEntity targetEntity = getTargetEntity(stackedSpawner, this.demoEntity, nearbyAndStackableEntities); if (stackedSpawner.isDebug()) Debug.debug(""StackedBaseSpawner"", ""serverTick"", ""targetEntity="" + targetEntity); if (targetEntity == null && nearbyEntities.size() >= this.maxNearbyEntities) { if (stackedSpawner.isDebug()) Debug.debug(""StackedBaseSpawner"", ""serverTick"", ""There are too many nearby entities ("" + nearbyEntities.size() + "">"" + this.maxNearbyEntities + "")""); failureReason = ""There are too many nearby entities.""; return; } int minimumEntityRequirement = GeneralUtils.get(plugin.getSettings().minimumRequiredEntities, this.demoEntity, 1); int stackedEntityCount = Random.nextInt(1, this.spawnCount, stackAmount, 1.5); boolean canStackToTarget = nearbyAndStackableCount.get() + stackedEntityCount >= minimumEntityRequirement; boolean spawnStacked = plugin.getSettings().entitiesStackingEnabled && canStackToTarget && EventsCaller.callSpawnerStackedEntitySpawnEvent(stackedSpawner.getSpawner()); failureReason = """"; if (stackedSpawner.isDebug()) Debug.debug(""StackedBaseSpawner"", ""serverTick"", ""spawnStacked="" + spawnStacked); int spawnCount = !spawnStacked || !this.demoEntity.isCached() ? Random.nextInt(1, this.spawnCount, stackAmount) : stackedEntityCount; if (stackedSpawner.isDebug()) Debug.debug(""StackedBaseSpawner"", ""serverTick"", ""spawnCount="" + spawnCount); int amountPerEntity = 1; int mobsToSpawn; short particlesAmount = 0; // Try stacking into the target entity first if (targetEntity != null && canStackToTarget && EventsCaller.callEntityStackEvent(targetEntity, this.demoEntity)) { if (stackedSpawner.isDebug()) Debug.debug(""StackedBaseSpawner"", ""serverTick"", ""Stacking into the target entity""); int targetEntityStackLimit = targetEntity.getStackLimit(); int currentStackAmount = targetEntity.getStackAmount(); int increaseStackAmount = Math.min(spawnCount, targetEntityStackLimit - currentStackAmount); if (increaseStackAmount != spawnCount) { mobsToSpawn = spawnCount - increaseStackAmount; } else { mobsToSpawn = 0; } if (stackedSpawner.isDebug()) Debug.debug(""StackedBaseSpawner"", ""serverTick"", ""increaseStackAmount="" + increaseStackAmount); if (increaseStackAmount > 0) { spawnedEntities += increaseStackAmount; if (minimumEntityRequirement > 1) { // We want to stack all nearby entities into target as well. increaseStackAmount += nearbyAndStackableCount.get() - targetEntity.getStackAmount(); nearbyAndStackableEntities.forEach(nearbyEntity -> { if (nearbyEntity != targetEntity) { nearbyEntity.remove(); nearbyEntity.spawnStackParticle(true); } }); } targetEntity.increaseStackAmount(increaseStackAmount, true); this.demoEntity.spawnStackParticle(true); if (plugin.getSettings().linkedEntitiesEnabled && targetEntity.getLivingEntity() != stackedSpawner.getLinkedEntity()) stackedSpawner.setLinkedEntity(targetEntity.getLivingEntity()); serverLevel.levelEvent(2004, blockPos, 0); particlesAmount++; } } else { if (stackedSpawner.isDebug()) Debug.debug(""StackedBaseSpawner"", ""serverTick"", ""Stacking naturally""); mobsToSpawn = spawnCount; } if (mobsToSpawn > 0 && this.demoEntity.isCached() && spawnStacked) { amountPerEntity = Math.min(mobsToSpawn, this.demoEntity.getStackLimit()); if (stackedSpawner.isDebug()) Debug.debug(""StackedBaseSpawner"", ""serverTick"", ""amountPerEntity="" + amountPerEntity); mobsToSpawn = mobsToSpawn / amountPerEntity; } if (stackedSpawner.isDebug()) Debug.debug(""StackedBaseSpawner"", ""serverTick"", ""mobsToSpawn="" + mobsToSpawn); MobSpawnResult spawnResult = MobSpawnResult.SUCCESS; try { stackedSpawner.setSpawnerOverridenTick(true); while (spawnResult == MobSpawnResult.SUCCESS && spawnedEntities < stackAmount) { spawnResult = attemptMobSpawning(serverLevel, blockPos, entityToSpawn, entityToSpawnType, mobsToSpawn, amountPerEntity, spawnCount, particlesAmount, stackedSpawner); if (stackedSpawner.isDebug()) { Debug.debug(""StackedBaseSpawner"", ""serverTick"", ""spawnResult="" + spawnResult); Debug.debug(""StackedBaseSpawner"", ""serverTick"", ""spawnedEntities="" + spawnedEntities); } } } finally { stackedSpawner.setSpawnerOverridenTick(false); } if (spawnResult == MobSpawnResult.SUCCESS || spawnResult == MobSpawnResult.ABORT_AND_RESET_DELAY) resetSpawnDelay(serverLevel, blockPos); }",Fixed entities spawn from spawners bypass minimum-required checks (#670),https://github.com/BG-Software-LLC/WildStacker/commit/9b63a964dc0b78b1a6a49738f4214ffb4fdf0df4,,,v117/src/main/java/com/bgsoftware/wildstacker/nms/v117/spawner/StackedBaseSpawner.java,3,java,False,2022-11-20T14:00:43Z "@Override public void onCreate(final Bundle savedInstanceState) { super.onCreate(savedInstanceState); equations = new ArrayList<>(); freeVariables = new ArrayList<>(); variableBank = new ArrayList<>(); gp = getArguments().getParcelable(GEOPOINT_ARG); if (gp == null) { if (savedState != null) { gp = new Geopoint(savedState.plainLat, savedState.plainLon); } else { gp = Sensors.getInstance().currentGeo().getCoords(); } } if (savedInstanceState != null) { if (savedInstanceState.getParcelable(GEOPOINT_ARG) != null) { gp = savedInstanceState.getParcelable(GEOPOINT_ARG); } final byte[] bytes = savedInstanceState.getByteArray(CALC_STATE); setSavedState(bytes != null ? (CalcState) SerializationUtils.deserialize(bytes) : null); } }","@Override public void onCreate(final Bundle savedInstanceState) { super.onCreate(savedInstanceState); equations = new ArrayList<>(); freeVariables = new ArrayList<>(); variableBank = new ArrayList<>(); gp = getArguments().getParcelable(GEOPOINT_ARG); if (gp == null) { if (savedState != null) { try { gp = new Geopoint(savedState.plainLat, savedState.plainLon); } catch (final Geopoint.ParseException ignored) { // gathering from one of the other formats? gp = Sensors.getInstance().currentGeo().getCoords(); } } else { gp = Sensors.getInstance().currentGeo().getCoords(); } } if (savedInstanceState != null) { if (savedInstanceState.getParcelable(GEOPOINT_ARG) != null) { gp = savedInstanceState.getParcelable(GEOPOINT_ARG); } final byte[] bytes = savedInstanceState.getByteArray(CALC_STATE); setSavedState(bytes != null ? (CalcState) SerializationUtils.deserialize(bytes) : null); } }","fix #11958 crash on opening calculator dialog (#11962) create Geopoint from string inside try-block",https://github.com/cgeo/cgeo/commit/5a4ed086e4bf8efaa5628f1401b3d3ea873b61b9,,,main/src/cgeo/geocaching/ui/dialog/CoordinatesCalculateDialog.java,3,java,False,2021-10-26T11:07:20Z "@RequestMapping(value = ""/survey/{surveyId}/data/records/{recordId}/{recordStep}/file-thumbnail"", method = RequestMethod.GET) public void downloadThumbnail(HttpServletRequest request, HttpServletResponse response, @PathVariable(""surveyId"") int surveyId, @PathVariable(""recordId"") int recordId, @PathVariable(""recordStep"") Step recordStep, @RequestParam(""nodePath"") String nodePath) throws Exception { CollectSurvey survey = surveyManager.getOrLoadSurveyById(surveyId); CollectRecord record = recordProvider.provide(survey, recordId == 0 ? null : recordId, recordStep); FileAttribute node = record.getNodeByPath(nodePath); File file = getFile(node); try { String extension = FilenameUtils.getExtension(file.getName()); String outputFileName = String.format(""node-%d-file-thumbnail.%s"", node.getId(), extension); String contentType = Files.getContentType(outputFileName); response.setContentType(contentType); Thumbnails.of(file).size(THUMBNAIL_SIZE, THUMBNAIL_SIZE).toOutputStream(response.getOutputStream()); return; } catch (Exception e) { // Try to write original file to response writeFileToResponse(response, file, surveyId, recordId, nodePath); } }","@RequestMapping(value = ""/survey/{surveyId}/data/records/{recordId}/{recordStep}/file-thumbnail"", method = RequestMethod.GET) public void downloadThumbnail(HttpServletRequest request, HttpServletResponse response, @PathVariable(""surveyId"") int surveyId, @PathVariable(""recordId"") int recordId, @PathVariable(""recordStep"") Step recordStep, @RequestParam(""nodePath"") String nodePath) throws IOException { CollectSurvey survey = surveyManager.getOrLoadSurveyById(surveyId); CollectRecord record = recordProvider.provide(survey, recordId == 0 ? null : recordId, recordStep); FileAttribute node = record.getNodeByPath(nodePath); File file = getFile(node); try { String extension = FilenameUtils.getExtension(file.getName()); String outputFileName = String.format(""node-%d-file-thumbnail.%s"", node.getId(), extension); String contentType = Files.getContentType(outputFileName); response.setContentType(contentType); Thumbnails.of(file).size(THUMBNAIL_SIZE, THUMBNAIL_SIZE).toOutputStream(response.getOutputStream()); return; } catch (Exception e) { // Try to write original file to response Controllers.writeFileToResponse(response, file); } }","Solved vulnerabilities found with Sonarcloud.io (#71) * tryin to solve SurveyValidator vulnerability * solved UserGroupController security issue * restored sqlite db migration to fix survey usergroup foreign key * solved issue in RecordFileController * code cleanup Co-authored-by: Stefano Ricci ",https://github.com/openforis/collect/commit/d0b83fc5072c4db492f1ef6ae8c4ad09d680cae5,,,collect-server/src/main/java/org/openforis/collect/web/controller/RecordFileController.java,3,java,False,2022-03-02T22:48:15Z "@Override public List resolveShorthand(String shorthandExpression) { if (UNSUPPORTED_VALUES_OF_FONT_SHORTHAND.contains(shorthandExpression)) { Logger logger = LoggerFactory.getLogger(FontShorthandResolver.class); logger.error(MessageFormatUtil.format(""The \""{0}\"" value of CSS shorthand property \""font\"" is not supported"", shorthandExpression)); } if (CommonCssConstants.INITIAL.equals(shorthandExpression) || CommonCssConstants.INHERIT.equals(shorthandExpression)) { return Arrays.asList( new CssDeclaration(CommonCssConstants.FONT_STYLE, shorthandExpression), new CssDeclaration(CommonCssConstants.FONT_VARIANT, shorthandExpression), new CssDeclaration(CommonCssConstants.FONT_WEIGHT, shorthandExpression), new CssDeclaration(CommonCssConstants.FONT_SIZE, shorthandExpression), new CssDeclaration(CommonCssConstants.LINE_HEIGHT, shorthandExpression), new CssDeclaration(CommonCssConstants.FONT_FAMILY, shorthandExpression) ); } String fontStyleValue = null; String fontVariantValue = null; String fontWeightValue = null; String fontSizeValue = null; String lineHeightValue = null; String fontFamilyValue = null; List properties = getFontProperties(shorthandExpression.replaceAll(""\\s*,\\s*"", "","")); for (String value : properties) { int slashSymbolIndex = value.indexOf('/'); if (CommonCssConstants.ITALIC.equals(value) || CommonCssConstants.OBLIQUE.equals(value)) { fontStyleValue = value; } else if (CommonCssConstants.SMALL_CAPS.equals(value)) { fontVariantValue = value; } else if (FONT_WEIGHT_NOT_DEFAULT_VALUES.contains(value)) { fontWeightValue = value; } else if (slashSymbolIndex > 0) { fontSizeValue = value.substring(0, slashSymbolIndex); lineHeightValue = value.substring(slashSymbolIndex + 1, value.length()); } else if (FONT_SIZE_VALUES.contains(value) || CssTypesValidationUtils.isMetricValue(value) || CssTypesValidationUtils.isNumber(value) || CssTypesValidationUtils.isRelativeValue(value)) { fontSizeValue = value; } else { fontFamilyValue = value; } } List cssDeclarations = Arrays.asList( new CssDeclaration(CommonCssConstants.FONT_STYLE, fontStyleValue == null ? CommonCssConstants.INITIAL : fontStyleValue), new CssDeclaration(CommonCssConstants.FONT_VARIANT, fontVariantValue == null ? CommonCssConstants.INITIAL : fontVariantValue), new CssDeclaration(CommonCssConstants.FONT_WEIGHT, fontWeightValue == null ? CommonCssConstants.INITIAL : fontWeightValue), new CssDeclaration(CommonCssConstants.FONT_SIZE, fontSizeValue == null ? CommonCssConstants.INITIAL : fontSizeValue), new CssDeclaration(CommonCssConstants.LINE_HEIGHT, lineHeightValue == null ? CommonCssConstants.INITIAL : lineHeightValue), new CssDeclaration(CommonCssConstants.FONT_FAMILY, fontFamilyValue == null ? CommonCssConstants.INITIAL : fontFamilyValue) ); return cssDeclarations; }","@Override public List resolveShorthand(String shorthandExpression) { if (UNSUPPORTED_VALUES_OF_FONT_SHORTHAND.contains(shorthandExpression)) { Logger logger = LoggerFactory.getLogger(FontShorthandResolver.class); logger.error(MessageFormatUtil.format(""The \""{0}\"" value of CSS shorthand property \""font\"" is not supported"", shorthandExpression)); } if (CommonCssConstants.INITIAL.equals(shorthandExpression) || CommonCssConstants.INHERIT.equals(shorthandExpression)) { return Arrays.asList( new CssDeclaration(CommonCssConstants.FONT_STYLE, shorthandExpression), new CssDeclaration(CommonCssConstants.FONT_VARIANT, shorthandExpression), new CssDeclaration(CommonCssConstants.FONT_WEIGHT, shorthandExpression), new CssDeclaration(CommonCssConstants.FONT_SIZE, shorthandExpression), new CssDeclaration(CommonCssConstants.LINE_HEIGHT, shorthandExpression), new CssDeclaration(CommonCssConstants.FONT_FAMILY, shorthandExpression) ); } String fontStyleValue = null; String fontVariantValue = null; String fontWeightValue = null; String fontSizeValue = null; String lineHeightValue = null; String fontFamilyValue = null; final String[] props = shorthandExpression.split("",""); final String shExprFixed = String.join("","", Arrays.stream(props).map(str -> str.trim()).collect(Collectors.toList())); List properties = getFontProperties(shExprFixed); for (String value : properties) { int slashSymbolIndex = value.indexOf('/'); if (CommonCssConstants.ITALIC.equals(value) || CommonCssConstants.OBLIQUE.equals(value)) { fontStyleValue = value; } else if (CommonCssConstants.SMALL_CAPS.equals(value)) { fontVariantValue = value; } else if (FONT_WEIGHT_NOT_DEFAULT_VALUES.contains(value)) { fontWeightValue = value; } else if (slashSymbolIndex > 0) { fontSizeValue = value.substring(0, slashSymbolIndex); lineHeightValue = value.substring(slashSymbolIndex + 1, value.length()); } else if (FONT_SIZE_VALUES.contains(value) || CssTypesValidationUtils.isMetricValue(value) || CssTypesValidationUtils.isNumber(value) || CssTypesValidationUtils.isRelativeValue(value)) { fontSizeValue = value; } else { fontFamilyValue = value; } } List cssDeclarations = Arrays.asList( new CssDeclaration(CommonCssConstants.FONT_STYLE, fontStyleValue == null ? CommonCssConstants.INITIAL : fontStyleValue), new CssDeclaration(CommonCssConstants.FONT_VARIANT, fontVariantValue == null ? CommonCssConstants.INITIAL : fontVariantValue), new CssDeclaration(CommonCssConstants.FONT_WEIGHT, fontWeightValue == null ? CommonCssConstants.INITIAL : fontWeightValue), new CssDeclaration(CommonCssConstants.FONT_SIZE, fontSizeValue == null ? CommonCssConstants.INITIAL : fontSizeValue), new CssDeclaration(CommonCssConstants.LINE_HEIGHT, lineHeightValue == null ? CommonCssConstants.INITIAL : lineHeightValue), new CssDeclaration(CommonCssConstants.FONT_FAMILY, fontFamilyValue == null ? CommonCssConstants.INITIAL : fontFamilyValue) ); return cssDeclarations; }","Fix possible DoS due to using of regex DEVSIX-7108",https://github.com/itext/itext-java/commit/01486efbaccacad78dc093df0d337c4bad407326,,,styled-xml-parser/src/main/java/com/itextpdf/styledxmlparser/css/resolve/shorthand/impl/FontShorthandResolver.java,3,java,False,2022-11-16T08:44:04Z "@Override public boolean compare(SkinSiteProfile ssp0, SkinSiteProfile ssp1) { return true; }","@Override public boolean compare(SkinSiteProfile ssp0, SkinSiteProfile ssp1) { return (!StringUtils.isNoneEmpty(ssp0.apiRoot) || ssp0.apiRoot.equalsIgnoreCase(ssp1.apiRoot)) || (!StringUtils.isNoneEmpty(ssp0.sessionRoot) || ssp0.sessionRoot.equalsIgnoreCase(ssp1.sessionRoot)); }",Prevent authlib-injector from modifying urls. (#159),https://github.com/xfl03/MCCustomSkinLoader/commit/2a4226527dbd8e75a17a89882695a4148e7444f1,,,Common/source/customskinloader/loader/MojangAPILoader.java,3,java,False,2021-05-01T14:46:02Z "private void acceptIncomingCallFromNotification() { showNotification(); if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M && Build.VERSION.SDK_INT < Build.VERSION_CODES.R && (checkSelfPermission(Manifest.permission.RECORD_AUDIO) != PackageManager.PERMISSION_GRANTED || privateCall.video && checkSelfPermission(Manifest.permission.CAMERA) != PackageManager.PERMISSION_GRANTED)) { try { //intent.addFlags(Intent.FLAG_ACTIVITY_NEW_DOCUMENT); PendingIntent.getActivity(VoIPService.this, 0, new Intent(VoIPService.this, VoIPPermissionActivity.class).addFlags(Intent.FLAG_ACTIVITY_NEW_TASK), PendingIntent.FLAG_ONE_SHOT | PendingIntent.FLAG_IMMUTABLE).send(); } catch (Exception x) { if (BuildVars.LOGS_ENABLED) { FileLog.e(""Error starting permission activity"", x); } } return; } acceptIncomingCall(); try { PendingIntent.getActivity(VoIPService.this, 0, new Intent(VoIPService.this, getUIActivityClass()).setAction(""voip""), PendingIntent.FLAG_IMMUTABLE).send(); } catch (Exception x) { if (BuildVars.LOGS_ENABLED) { FileLog.e(""Error starting incall activity"", x); } } }","private void acceptIncomingCallFromNotification() { showNotification(); if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M && Build.VERSION.SDK_INT < Build.VERSION_CODES.R && (checkSelfPermission(Manifest.permission.RECORD_AUDIO) != PackageManager.PERMISSION_GRANTED || privateCall.video && checkSelfPermission(Manifest.permission.CAMERA) != PackageManager.PERMISSION_GRANTED) || Build.VERSION.SDK_INT >= 31 && checkSelfPermission(Manifest.permission.BLUETOOTH_CONNECT) != PackageManager.PERMISSION_GRANTED) { try { //intent.addFlags(Intent.FLAG_ACTIVITY_NEW_DOCUMENT); PendingIntent.getActivity(VoIPService.this, 0, new Intent(VoIPService.this, VoIPPermissionActivity.class).addFlags(Intent.FLAG_ACTIVITY_NEW_TASK), PendingIntent.FLAG_ONE_SHOT | PendingIntent.FLAG_IMMUTABLE).send(); } catch (Exception x) { if (BuildVars.LOGS_ENABLED) { FileLog.e(""Error starting permission activity"", x); } } return; } acceptIncomingCall(); try { PendingIntent.getActivity(VoIPService.this, 0, new Intent(VoIPService.this, getUIActivityClass()).setAction(""voip""), PendingIntent.FLAG_IMMUTABLE).send(); } catch (Exception x) { if (BuildVars.LOGS_ENABLED) { FileLog.e(""Error starting incall activity"", x); } } }",Fix Android 12 Calls Crash,https://github.com/OwlGramDev/OwlGram/commit/5ffeb69a41aa93fbb20abd8c93d49288e87c97aa,,,TMessagesProj/src/main/java/org/telegram/messenger/voip/VoIPService.java,3,java,False,2022-04-29T13:33:56Z "public boolean contains(EObject object) { if (object instanceof Action) { return contains((Action)object); } else if (object instanceof Reaction) { return contains((Reaction)object); } else if (object instanceof Timer) { return contains((Timer)object); } else if (object instanceof ReactorDecl) { return contains((ReactorDecl)object); } else if (object instanceof Import) { return contains((Import)object); } else if (object instanceof Parameter) { return contains((Parameter)object); } throw new UnsupportedOperationException(""EObject class ""+object.eClass().getName()+"" not supported.""); }","public boolean contains(EObject object) { if (object instanceof Action) { return contains((Action)object); } else if (object instanceof Reaction) { return contains((Reaction)object); } else if (object instanceof Timer) { return contains((Timer)object); } else if (object instanceof ReactorDecl) { return contains(this.instantiation, (ReactorDecl)object); } else if (object instanceof Import) { return contains((Import)object); } else if (object instanceof Parameter) { return contains((Parameter)object); } throw new UnsupportedOperationException(""EObject class ""+object.eClass().getName()+"" not supported.""); }",Fixed stackoverflow reported by @ByeongGil-Jun,https://github.com/lf-lang/lingua-franca/commit/8a26d3c18a8a604860ce18fa49be9bec33ebad0f,,,org.lflang/src/org/lflang/federated/generator/FederateInstance.java,3,java,False,2022-08-10T12:23:38Z "private void readPowerPointStream() throws IOException { final DirectoryNode dir = getDirectory(); if (!dir.hasEntry(POWERPOINT_DOCUMENT) && dir.hasEntry(PP95_DOCUMENT)) { throw new OldPowerPointFormatException(""You seem to have supplied a PowerPoint95 file, which isn't supported""); } // Get the main document stream DocumentEntry docProps = (DocumentEntry)dir.getEntry(POWERPOINT_DOCUMENT); // Grab the document stream int len = docProps.getSize(); try (InputStream is = dir.createDocumentInputStream(docProps)) { _docstream = IOUtils.toByteArray(is, len); } }","private void readPowerPointStream() throws IOException { final DirectoryNode dir = getDirectory(); if (!dir.hasEntry(POWERPOINT_DOCUMENT) && dir.hasEntry(PP95_DOCUMENT)) { throw new OldPowerPointFormatException(""You seem to have supplied a PowerPoint95 file, which isn't supported""); } // Get the main document stream DocumentEntry docProps = (DocumentEntry)dir.getEntry(POWERPOINT_DOCUMENT); // Grab the document stream int len = docProps.getSize(); try (InputStream is = dir.createDocumentInputStream(docProps)) { _docstream = IOUtils.toByteArray(is, len, MAX_DOCUMENT_SIZE); } }","Fix issues found when fuzzing Apache POI via Jazzer Add some additional allocation limits to avoid OOM in some more cases with some broken input files git-svn-id: https://svn.apache.org/repos/asf/poi/trunk@1895922 13f79535-47bb-0310-9956-ffa450edef68",https://github.com/apache/poi/commit/9fa33b2b7e2fafb98fc9f5c784dd21487a14816a,,,poi-scratchpad/src/main/java/org/apache/poi/hslf/usermodel/HSLFSlideShowImpl.java,3,java,False,2021-12-13T19:22:34Z "static Http2Headers h1HeadersToH2Headers(HttpHeaders h1Headers) { if (h1Headers.isEmpty()) { if (h1Headers instanceof NettyH2HeadersToHttpHeaders) { return ((NettyH2HeadersToHttpHeaders) h1Headers).nettyHeaders(); } return new DefaultHttp2Headers(false, 0); } // H2 doesn't support connection headers, so remove each one, and the headers corresponding to the // connection value. // https://tools.ietf.org/html/rfc7540#section-8.1.2.2 Iterator connectionItr = h1Headers.valuesIterator(CONNECTION); if (connectionItr.hasNext()) { do { String connectionHeader = connectionItr.next().toString(); connectionItr.remove(); int i = connectionHeader.indexOf(','); if (i != -1) { int start = 0; do { h1Headers.remove(connectionHeader.substring(start, i)); start = i + 1; } while (start < connectionHeader.length() && (i = connectionHeader.indexOf(',', start)) != -1); h1Headers.remove(connectionHeader.substring(start)); } else { h1Headers.remove(connectionHeader); } } while (connectionItr.hasNext()); } // remove other illegal headers h1Headers.remove(KEEP_ALIVE); h1Headers.remove(TRANSFER_ENCODING); h1Headers.remove(UPGRADE); h1Headers.remove(PROXY_CONNECTION); // TE header is treated specially https://tools.ietf.org/html/rfc7540#section-8.1.2.2 // (only value of ""trailers"" is allowed). Iterator teItr = h1Headers.valuesIterator(TE); boolean addTrailers = false; while (teItr.hasNext()) { String teValue = teItr.next().toString(); int i = teValue.indexOf(','); if (i != -1) { int start = 0; do { if (teValue.substring(start, i).compareToIgnoreCase(TRAILERS.toString()) == 0) { addTrailers = true; break; } } while (start < teValue.length() && (i = teValue.indexOf(',', start)) != -1); teItr.remove(); } else if (teValue.compareToIgnoreCase(TRAILERS.toString()) != 0) { teItr.remove(); } } if (addTrailers) { // add after iteration to avoid concurrent modification. h1Headers.add(TE, TRAILERS); } h1HeadersSplitCookieCrumbs(h1Headers); if (h1Headers instanceof NettyH2HeadersToHttpHeaders) { // Assume header field names are already lowercase if they reside in the Http2Headers. We may want to be // more strict in the future, but that would require iteration. return ((NettyH2HeadersToHttpHeaders) h1Headers).nettyHeaders(); } if (h1Headers.isEmpty()) { return new DefaultHttp2Headers(false, 0); } DefaultHttp2Headers http2Headers = new DefaultHttp2Headers(false); for (Map.Entry h1Entry : h1Headers) { // header field names MUST be converted to lowercase prior to their encoding in HTTP/2 // https://tools.ietf.org/html/rfc7540#section-8.1.2 http2Headers.add(h1Entry.getKey().toString().toLowerCase(), h1Entry.getValue()); } return http2Headers; }","static Http2Headers h1HeadersToH2Headers(HttpHeaders h1Headers) { if (h1Headers.isEmpty()) { if (h1Headers instanceof NettyH2HeadersToHttpHeaders) { return ((NettyH2HeadersToHttpHeaders) h1Headers).nettyHeaders(); } return new DefaultHttp2Headers(false, 0); } // H2 doesn't support connection headers, so remove each one, and the headers corresponding to the // connection value. // https://tools.ietf.org/html/rfc7540#section-8.1.2.2 Iterator connectionItr = h1Headers.valuesIterator(CONNECTION); if (connectionItr.hasNext()) { do { String connectionHeader = connectionItr.next().toString(); connectionItr.remove(); int i = connectionHeader.indexOf(','); if (i != -1) { int start = 0; do { h1Headers.remove(connectionHeader.substring(start, i)); start = i + 1; } while (start < connectionHeader.length() && (i = connectionHeader.indexOf(',', start)) != -1); h1Headers.remove(connectionHeader.substring(start)); } else { h1Headers.remove(connectionHeader); } } while (connectionItr.hasNext()); } // remove other illegal headers h1Headers.remove(KEEP_ALIVE); h1Headers.remove(TRANSFER_ENCODING); h1Headers.remove(UPGRADE); h1Headers.remove(PROXY_CONNECTION); // TE header is treated specially https://tools.ietf.org/html/rfc7540#section-8.1.2.2 // (only value of ""trailers"" is allowed). Iterator teItr = h1Headers.valuesIterator(TE); boolean addTrailers = false; while (teItr.hasNext()) { final CharSequence teSequence = teItr.next(); if (addTrailers) { teItr.remove(); } else { int i = indexOf(teSequence, ',', 0); if (i != -1) { int start = 0; do { if (contentEqualsIgnoreCase(teSequence.subSequence(start, i), TRAILERS)) { addTrailers = true; break; } start = i + 1; // Check if we need to skip OWS // https://www.rfc-editor.org/rfc/rfc9110.html#section-10.1.4 if (start < teSequence.length() && teSequence.charAt(start) == ' ') { ++start; } } while (start < teSequence.length() && (i = indexOf(teSequence, ',', start)) != -1); if (!addTrailers && start < teSequence.length() && contentEqualsIgnoreCase(teSequence.subSequence(start, teSequence.length()), TRAILERS)) { addTrailers = true; } teItr.remove(); } else if (!contentEqualsIgnoreCase(teSequence, TRAILERS)) { teItr.remove(); } } } if (addTrailers) { // add after iteration to avoid concurrent modification. h1Headers.add(TE, TRAILERS); } h1HeadersSplitCookieCrumbs(h1Headers); if (h1Headers instanceof NettyH2HeadersToHttpHeaders) { // Assume header field names are already lowercase if they reside in the Http2Headers. We may want to be // more strict in the future, but that would require iteration. return ((NettyH2HeadersToHttpHeaders) h1Headers).nettyHeaders(); } if (h1Headers.isEmpty()) { return new DefaultHttp2Headers(false, 0); } DefaultHttp2Headers http2Headers = new DefaultHttp2Headers(false); for (Map.Entry h1Entry : h1Headers) { // header field names MUST be converted to lowercase prior to their encoding in HTTP/2 // https://tools.ietf.org/html/rfc7540#section-8.1.2 http2Headers.add(h1Entry.getKey().toString().toLowerCase(), h1Entry.getValue()); } return http2Headers; }","StringIndexOutOfBoundsException while parsing cookies (#2397) Motivation: While splitting cookie crumbs for h2 we may encouter a StringIndexOutOfBoundsException while adding the last cookie crumb.",https://github.com/apple/servicetalk/commit/6b17ccda54672e9ead7f8b37757b6bc129c162f0,,,servicetalk-http-netty/src/main/java/io/servicetalk/http/netty/H2ToStH1Utils.java,3,java,False,2022-10-19T05:49:30Z "public static void preRenderEntities() { ServerCommandSource source = new FakeCommandSource(MinecraftClient.getInstance().player); disabledEntities.clear(); for (var filter : entityRenderSelectors) { List entities = filter.getLeft().getEntities(source).stream().map(Entity::getUuid).collect(Collectors.toList()); if (filter.getRight()) { entities.forEach(disabledEntities::remove); } else { disabledEntities.addAll(entities); } } }","public static void preRenderEntities() { ClientPlayerEntity player = MinecraftClient.getInstance().player; // prevent crash from other mods trying to load entity rendering without a world (usually a fake world and no client player) if (player == null) return; ServerCommandSource source = new FakeCommandSource(player); disabledEntities.clear(); for (var filter : entityRenderSelectors) { List entities = filter.getLeft().getEntities(source).stream().map(Entity::getUuid).collect(Collectors.toList()); if (filter.getRight()) { entities.forEach(disabledEntities::remove); } else { disabledEntities.addAll(entities); } } }","prevent null player from crashing (#355) * prevent null player from crashing (when other mods run the entity renderer without a world) * Update RenderSettings.java",https://github.com/Earthcomputer/clientcommands/commit/b0bd40aa69e383148a780b7450ea30a584fbcb46,,,src/main/java/net/earthcomputer/clientcommands/features/RenderSettings.java,3,java,False,2022-02-04T11:37:36Z "function createTextElement(element) { var textElement = document.createElement('span'); $(textElement).addClass('doublestate-button-text'); $(textElement).html(presenter.isSelected() ? presenter.configuration.selected.text : presenter.configuration.deselected.text); $(element).append(textElement); }","function createTextElement(element) { var textElement = document.createElement('span'); $(textElement).addClass('doublestate-button-text'); const buttonText = presenter.getSanitizedButtonTextValue(); $(textElement).html(buttonText); $(element).append(textElement); }",Merge branch 'master' into test-8601,https://github.com/icplayer/icplayer/commit/2d8719bbfba8b71b4b669bef73b7f2f014b81881,CVE-2022-4929,['CWE-79'],addons/Double_State_Button/src/presenter.js,3,js,False,2022-12-09T09:21:16Z "private void removeObjectiveLines(List scores) { scores.removeIf(s -> TextFormatting.getTextWithoutFormattingCodes(s.getPlayerName()).matches(ObjectivesOverlay.OBJECTIVE_PATTERN.pattern())); scores.removeIf(s -> TextFormatting.getTextWithoutFormattingCodes(s.getPlayerName()).matches(""- All done"")); scores.removeIf(s -> TextFormatting.getTextWithoutFormattingCodes(s.getPlayerName()).matches(ObjectivesOverlay.OBJECTIVE_HEADER_PATTERN.pattern())); scores.removeIf(s -> TextFormatting.getTextWithoutFormattingCodes(s.getPlayerName()).matches(ObjectivesOverlay.GUILD_OBJECTIVE_HEADER_PATTERN.pattern())); scores.removeIf(s -> s.getPlayerName().startsWith(TextFormatting.RED + ""- "")); }","private void removeObjectiveLines(List scores) { scores.removeIf(s -> TextFormatting.getTextWithoutFormattingCodes(s.getPlayerName()).matches(ObjectivesOverlay.OBJECTIVE_PARSER_PATTERN.pattern())); scores.removeIf(s -> TextFormatting.getTextWithoutFormattingCodes(s.getPlayerName()).matches(""- All done"")); scores.removeIf(s -> TextFormatting.getTextWithoutFormattingCodes(s.getPlayerName()).matches(ObjectivesOverlay.OBJECTIVE_HEADER_PATTERN.pattern())); scores.removeIf(s -> TextFormatting.getTextWithoutFormattingCodes(s.getPlayerName()).matches(ObjectivesOverlay.GUILD_OBJECTIVE_HEADER_PATTERN.pattern())); scores.removeIf(s -> s.getPlayerName().startsWith(TextFormatting.RED + ""- "")); }","Fix 14 issues found in ticket backlog (#502) * Fix IndexOutOfBoundsException in QuestBookListPage Signed-off-by: kristofbolyai * Fix crash if OverlayConfig.GameUpdate.INSTANCE.messageMaxLength is 1 Signed-off-by: kristofbolyai * Fix crash related to deleting chat tabs and ChatGUI not updating Signed-off-by: kristofbolyai * Fix crash related to deleting chat tabs and ChatGUI not updating Signed-off-by: kristofbolyai * Fix translation cache becoming null Signed-off-by: kristofbolyai * Fix objective parsing if player is in party Signed-off-by: kristofbolyai * Fix guild objective not being removed upon completion Signed-off-by: kristofbolyai * Fix race condition in ServerEvents Signed-off-by: kristofbolyai * Fix race condition in ClientEvents Signed-off-by: kristofbolyai * Fix NPE in ServerEvents Signed-off-by: kristofbolyai * Fix AreaDPS value not being correct Signed-off-by: kristofbolyai * Fix NPE in fix :) Signed-off-by: kristofbolyai * Fix quest dialogue spoofing Signed-off-by: kristofbolyai * Fix Keyholder related crash Signed-off-by: kristofbolyai * Fix totem tracking Signed-off-by: kristofbolyai * Dialogue Page gets updated correctly Signed-off-by: kristofbolyai * Register ChatGUI correctly Signed-off-by: kristofbolyai * Use MC's GameSettings to check for isKeyDown Signed-off-by: kristofbolyai * Make multi line if have braces Signed-off-by: kristofbolyai ",https://github.com/Wynntils/Wynntils/commit/c8f6effe187ff68f17bcff809d2bc440ec07128d,,,src/main/java/com/wynntils/modules/utilities/overlays/hud/ScoreboardOverlay.java,3,java,False,2022-04-15T17:16:00Z "private void setRegistered(boolean registered) { if (mRegistered == registered) return; if (DEBUG) Slog.d(TAG, ""setRegistered "" + registered); mRegistered = registered; if (mRegistered) { final IntentFilter filter = new IntentFilter(); filter.addAction(Intent.ACTION_TIME_CHANGED); filter.addAction(Intent.ACTION_TIMEZONE_CHANGED); filter.addAction(ACTION_EVALUATE); filter.addAction(AlarmManager.ACTION_NEXT_ALARM_CLOCK_CHANGED); registerReceiver(mReceiver, filter); } else { unregisterReceiver(mReceiver); } }","private void setRegistered(boolean registered) { if (mRegistered == registered) return; if (DEBUG) Slog.d(TAG, ""setRegistered "" + registered); mRegistered = registered; if (mRegistered) { final IntentFilter filter = new IntentFilter(); filter.addAction(Intent.ACTION_TIME_CHANGED); filter.addAction(Intent.ACTION_TIMEZONE_CHANGED); filter.addAction(ACTION_EVALUATE); filter.addAction(AlarmManager.ACTION_NEXT_ALARM_CLOCK_CHANGED); registerReceiver(mReceiver, filter, Context.RECEIVER_EXPORTED_UNAUDITED); } else { unregisterReceiver(mReceiver); } }","Add unaudited exported flag to exposed runtime receivers Android T allows apps to declare a runtime receiver as not exported by invoking registerReceiver with a new RECEIVER_NOT_EXPORTED flag; receivers registered with this flag will only receive broadcasts from the platform and the app itself. However to ensure developers can properly protect their receivers, all apps targeting T or later registering a receiver for non-system broadcasts must specify either the exported or not exported flag when invoking #registerReceiver; if one of these flags is not provided, the platform will throw a SecurityException. This commit updates all the exposed receivers with a new RECEIVER_EXPORTED_UNAUDITED flag to maintain the existing behavior of exporting the receiver while also flagging the receiver for audit before the T release. Bug: 161145287 Test: Build Change-Id: If360077718549a66179175e197817f7315d8c8ca",https://github.com/PixelExperience/frameworks_base/commit/0a46c2f78ca8117680f6d6133db7af306eaea0b9,,,services/core/java/com/android/server/notification/ScheduleConditionProvider.java,3,java,False,2021-12-30T16:28:33Z "@SuppressWarnings({""unchecked"", ""rawtypes""}) private void createFlags(final LiteralCommandNode node, final List flags, @Nullable final SpongeCommandExecutorWrapper wrapper) { final Collection> nodesToAddChildrenTo = new ArrayList<>(); for (final Flag flag : flags) { // first create the literal. final Iterator aliasIterator = flag.getAliases().iterator(); final LiteralArgumentBuilder flagLiteral = LiteralArgumentBuilder.literal(aliasIterator.next()); flagLiteral.requires((Predicate) flag.getRequirement()); final Collection> toBeRedirected; final SpongeFlagLiteralCommandNode flagNode = new SpongeFlagLiteralCommandNode(flagLiteral, flag); if (flag.getAssociatedParameter().isPresent()) { toBeRedirected = this.createAndAttachNode( Collections.singleton(flagNode), Collections.singletonList(flag.getAssociatedParameter().get()), wrapper, node.getCommand() != null, false ); } else { toBeRedirected = Collections.singletonList(flagNode); } for (final CommandNode candidate : toBeRedirected) { if (candidate instanceof SpongeNode && ((SpongeNode) candidate).canForceRedirect()) { ((SpongeNode) candidate).forceRedirect(node); } else { nodesToAddChildrenTo.add(candidate); } } node.addChild(flagNode); while (aliasIterator.hasNext()) { final LiteralArgumentBuilder nextFlag = LiteralArgumentBuilder .literal(aliasIterator.next()) .executes(flagNode.getCommand()); if (flagNode.getRedirect() != null) { nextFlag.redirect(flagNode.getRedirect()); } else { nextFlag.redirect(flagNode); } node.addChild(new SpongeFlagLiteralCommandNode(nextFlag, flag)); } } // Make all terminal nodes return to the parent node's children. node.getChildren().forEach(x -> nodesToAddChildrenTo.forEach(y -> y.addChild(x))); }","@SuppressWarnings({""unchecked"", ""rawtypes""}) private void createFlags(final LiteralCommandNode node, final List flags, @Nullable final SpongeCommandExecutorWrapper wrapper) { final Collection> nodesToAddChildrenTo = new ArrayList<>(); for (final Flag flag : flags) { // first create the literal. final Iterator aliasIterator = flag.getAliases().iterator(); final LiteralArgumentBuilder flagLiteral = LiteralArgumentBuilder.literal(aliasIterator.next()); flagLiteral.requires((Predicate) flag.getRequirement()); final Collection> toBeRedirected; final SpongeFlagLiteralCommandNode flagNode = new SpongeFlagLiteralCommandNode(flagLiteral, flag); if (flag.getAssociatedParameter().isPresent()) { toBeRedirected = this.createAndAttachNode( Collections.singleton(flagNode), Collections.singletonList(flag.getAssociatedParameter().get()), wrapper, node.getCommand() != null, false ); } else { toBeRedirected = Collections.singletonList(flagNode); } for (final CommandNode candidate : toBeRedirected) { if (candidate instanceof SpongeNode && ((SpongeNode) candidate).canForceRedirect()) { ((SpongeNode) candidate).forceRedirect(node); } else { nodesToAddChildrenTo.add(candidate); } } node.addChild(flagNode); while (aliasIterator.hasNext()) { final LiteralArgumentBuilder nextFlag = LiteralArgumentBuilder .literal(aliasIterator.next()) .executes(flagNode.getCommand()); if (flagNode.getRedirect() != null) { nextFlag.redirect(flagNode.getRedirect()); } else { nextFlag.redirect(flagNode); } node.addChild(new SpongeFlagLiteralCommandNode(nextFlag, flag)); } } if (!nodesToAddChildrenTo.isEmpty()) { for (final CommandNode target : node.getChildren()) { if (!target.getChildren().isEmpty() && target instanceof SpongeFlagLiteralCommandNode) { nodesToAddChildrenTo.forEach(x -> x.addChild(((SpongeFlagLiteralCommandNode) target).cloneWithRedirectToThis())); } else { nodesToAddChildrenTo.forEach(x -> x.addChild(target)); } } } }","Fix issue where a stack overflow can occur with optional parameters in flags. ...however, this has uncovered a new issue which is not so easily rectified (but is better than crashing the server). Basically, Brigadier has a faulty equality check where it does not take into account the target redirection of a node. This is especially bad with literals, where the equality operator only takes stock of the literal and any command that might be associated with the node when a redirect is in effect. We can patch this on the server (and in general, we do so that redirects point to the right place), but effectively, on the vanilla client we do not control anything and so vanilla sees two nodes with the same literal, no command and no children as one and the same. Admittedly I thought that what mostly mattered was that we can send the two nodes and don't let the server merge them so the client just takes that - either we're not doing that for literals or the client chews them up. We are currently using literals for flags, so if you have two flags named the same thing anywhere, there is a strong possibility that the client will merge them together. More investigation is needed - but for this, this will prevent server stack overflows.",https://github.com/SpongePowered/Sponge/commit/b831058b752dd60d607fd66b9a799316142130c2,,,src/main/java/org/spongepowered/common/command/brigadier/SpongeParameterTranslator.java,3,java,False,2021-02-27T15:35:14Z "@Override public List getOssVulnerabilityList2(OssMaster ossMaster) { if(""N/A"".equals(ossMaster.getOssVersion()) || isEmpty(ossMaster.getOssVersion())) { ossMaster.setOssVersion(""-""); } List list = null; String[] nicknameList = null; try { if(ossMaster.getOssName().contains("" "")) { ossMaster.setOssNameTemp(ossMaster.getOssName().replaceAll("" "", ""_"")); } nicknameList = getOssNickNameListByOssName(ossMaster.getOssName()); ossMaster.setOssNicknames(nicknameList); list = ossMapper.getOssVulnerabilityList2(ossMaster); ossMaster.setOssNameTemp(null); } catch (Exception e) { log.error(e.getMessage()); } if(list != null) { list = checkVulnData(list, nicknameList); list = list.stream().filter(CommonFunction.distinctByKey(e -> e.getCveId())).collect(Collectors.toList()); } return list; }","@Override public List getOssVulnerabilityList2(OssMaster ossMaster) { if(""N/A"".equals(ossMaster.getOssVersion()) || isEmpty(ossMaster.getOssVersion())) { ossMaster.setOssVersion(""-""); } List list = null; String[] nicknameList = null; List dashOssNameList = new ArrayList<>(); try { if(ossMaster.getOssName().contains("" "")) { ossMaster.setOssNameTemp(ossMaster.getOssName().replaceAll("" "", ""_"")); } if(ossMaster.getOssName().contains(""-"")) { dashOssNameList.add(ossMaster.getOssName()); } nicknameList = getOssNickNameListByOssName(ossMaster.getOssName()); ossMaster.setOssNicknames(nicknameList); for(String nick : nicknameList) { if(nick.contains(""-"")) { dashOssNameList.add(nick); } } if(dashOssNameList.size() > 0) { ossMaster.setDashOssNameList(dashOssNameList.toArray(new String[dashOssNameList.size()])); } list = ossMapper.getOssVulnerabilityList2(ossMaster); ossMaster.setOssNameTemp(null); } catch (Exception e) { log.error(e.getMessage()); } if(list != null) { list = checkVulnData(list, nicknameList); list = list.stream().filter(CommonFunction.distinctByKey(e -> e.getCveId())).collect(Collectors.toList()); } return list; }",Fix vulnerability search condition and when save vendor data,https://github.com/fosslight/fosslight/commit/ff6a9b65bf844fccb371ba6e4f4d9610adb76e85,,,src/main/java/oss/fosslight/service/impl/OssServiceImpl.java,3,java,False,2022-12-20T09:05:48Z "@Inject( method = ""reloadShaders"", at = @At( value = ""INVOKE_ASSIGN"", target = ""Ljava/util/List;add(Ljava/lang/Object;)Z"", ordinal = 53 ), locals = LocalCapture.CAPTURE_FAILSOFT ) private void reloadShaders( ResourceManager manager, CallbackInfo info, List list, List>> list2 ) throws IOException { list2.add( Pair.of( new ShaderInstance( manager, ""terminal"", RenderTypes.TERMINAL_WITHOUT_DEPTH.format() ), shader -> RenderTypes.terminalShader = shader ) ); list2.add( Pair.of( new MonitorTextureBufferShader( manager, ""monitor_tbo"", RenderTypes.MONITOR_TBO.format() ), shader -> RenderTypes.monitorTboShader = (MonitorTextureBufferShader) shader ) ); }","@Inject( method = ""reloadShaders"", at = @At( value = ""INVOKE_ASSIGN"", target = ""Ljava/util/List;add(Ljava/lang/Object;)Z"", ordinal = 53 ), locals = LocalCapture.CAPTURE_FAILSOFT ) private void reloadShaders( ResourceManager manager, CallbackInfo info, List list, List>> list2 ) throws IOException { list2.add( Pair.of( new MonitorTextureBufferShader( manager, ""monitor_tbo"", RenderTypes.MONITOR_TBO.format() ), shader -> RenderTypes.monitorTboShader = (MonitorTextureBufferShader) shader ) ); }","[Iris] Merge Rendering Experiments to 1.18.2 (#78) * Quick and dirty test. - VBO monitor renderer path has been hijacked to test not using VBOs, instead we recreate the terminal geometry every frame. - Add an explicit call the BufferSource.endBatch(). This actually fixes the incompatibility with Batched Entity Rendering. Who knew it was that easy? Results: works with Iris without shaders enabled. * Use entity RenderType for rendering terminals in world. - FixedWidthFontRenderer now emits quads and fills out all the vertex elements needed for the entity vertex format, which is, well, *all* of them. - FixedWidthFontRenderer now takes a PoseStack so it can offset the char quads from the background. - TERMINAL_MODE changed to quads so remaining custom RenderTypes work with FWFR. New progress at this commit: - Iris and Canvas both render the hi-jacked VBO backend properly. Issues: - Char quads have a blacker background than empty quads due to mismatched lightmaps. - Items in hand have improper normals. - TBO renderer is untested. Need to make sure it wasn't broken. * More stuff Progress: - ""VBO"" code path now works fine with shaders. - Printout GUI has lightmap issue. - Pocket computer frames don't have right normals in world. - Pocket computer lights don't work. TODOs: - Investigate whether VBOs can be used again without breaking compat. If not, the code path needs to be renamed and the code for managing VBO resources should be removed. - Make sure TBO code path still works. Wouldn't be surprised if I broke something there. * Found a new rendertype for monitors, fixed normals Progress: - Monitors render fullbright in every direction. - Normals are right on pocket computers and printouts, so lighting effects like directional light and shadow maps looks correct. - BEST monitor renderer settings will detect shader mods and automatically enable shader compatible code path. Details: - The ""textIntensity"" rendertype is exactaly what we need for monitors. It's shader doesn't apply a directional light so monitors look fullbright consistent no matter what direction they're facing. - Consolidated all references to rendertypes into RenderTypes class. - Improved consistency of rendering classes. Methods pass a PoseStack instead of a Matrix4f down the chain where possible so that normals can be calculated, and most rendering classes now fill out all vertex elements so they can be used with any vanilla vertex format. - Rendering methods should prefer to take a VertexConsumer rather than a BufferSource, the caller should provide appropriate buffer as that's where the context for buffer choice is. TODO: - Investigate re-enabling VBOs, and, if not an option, clean up naming and VBO related resource code. * Re-enable vbos Things were extremely slow without them in torture tests. They seem to work fine with Iris. Will need to test with Canvas too. I don't know why that hack with the inverse view rotation uniform works but fog doesn't render correctly without it. Unfortunately, the z-offset method does cause visible artifacts. Background quads can sometimes be seen under the edges of adjacant characters, giving the monitor a stitched together look. Will have to investigate splitting all the background and char quads into two draw calls and using glPolygonOffset on the characters :( which probably means two vbos :( :( Co-authored-by: Toad-Dev <748280+toad-dev@users.noreply.github.com>",https://github.com/cc-tweaked/cc-restitched/commit/d8bb05f30ebc6c4c4ed5ebec71acc644227cff06,,,src/main/java/dan200/computercraft/fabric/mixin/MixinGameRenderer.java,3,java,False,2022-03-27T22:13:53Z "@Override protected void handleProducer(final CommandProducer cmdProducer) { checkArgument(state == State.Connected); final long producerId = cmdProducer.getProducerId(); final long requestId = cmdProducer.getRequestId(); // Use producer name provided by client if present final String producerName = cmdProducer.hasProducerName() ? cmdProducer.getProducerName() : service.generateUniqueProducerName(); final long epoch = cmdProducer.getEpoch(); final boolean userProvidedProducerName = cmdProducer.isUserProvidedProducerName(); final boolean isEncrypted = cmdProducer.isEncrypted(); final Map metadata = CommandUtils.metadataFromCommand(cmdProducer); final SchemaData schema = cmdProducer.hasSchema() ? getSchema(cmdProducer.getSchema()) : null; final ProducerAccessMode producerAccessMode = cmdProducer.getProducerAccessMode(); final Optional topicEpoch = cmdProducer.hasTopicEpoch() ? Optional.of(cmdProducer.getTopicEpoch()) : Optional.empty(); final boolean isTxnEnabled = cmdProducer.isTxnEnabled(); TopicName topicName = validateTopicName(cmdProducer.getTopic(), requestId, cmdProducer); if (topicName == null) { return; } if (invalidOriginalPrincipal(originalPrincipal)) { final String msg = ""Valid Proxy Client role should be provided while creating producer ""; log.warn(""[{}] {} with role {} and proxyClientAuthRole {} on topic {}"", remoteAddress, msg, authRole, originalPrincipal, topicName); commandSender.sendErrorResponse(requestId, ServerError.AuthorizationError, msg); return; } CompletableFuture isAuthorizedFuture = isTopicOperationAllowed( topicName, TopicOperation.PRODUCE ); isAuthorizedFuture.thenApply(isAuthorized -> { if (isAuthorized) { if (log.isDebugEnabled()) { log.debug(""[{}] Client is authorized to Produce with role {}"", remoteAddress, getPrincipal()); } CompletableFuture producerFuture = new CompletableFuture<>(); CompletableFuture existingProducerFuture = producers.putIfAbsent(producerId, producerFuture); if (existingProducerFuture != null) { if (existingProducerFuture.isDone() && !existingProducerFuture.isCompletedExceptionally()) { Producer producer = existingProducerFuture.getNow(null); log.info(""[{}] Producer with the same id is already created:"" + "" producerId={}, producer={}"", remoteAddress, producerId, producer); commandSender.sendProducerSuccessResponse(requestId, producer.getProducerName(), producer.getSchemaVersion()); return null; } else { // There was an early request to create a producer with same producerId. // This can happen when client timeout is lower than the broker timeouts. // We need to wait until the previous producer creation request // either complete or fails. ServerError error = null; if (!existingProducerFuture.isDone()) { error = ServerError.ServiceNotReady; } else { error = getErrorCode(existingProducerFuture); // remove producer with producerId as it's already completed with exception producers.remove(producerId, existingProducerFuture); } log.warn(""[{}][{}] Producer with id is already present on the connection,"" + "" producerId={}"", remoteAddress, topicName, producerId); commandSender.sendErrorResponse(requestId, error, ""Producer is already present on the connection""); return null; } } log.info(""[{}][{}] Creating producer. producerId={}"", remoteAddress, topicName, producerId); service.getOrCreateTopic(topicName.toString()).thenAcceptAsync((Topic topic) -> { // Before creating producer, check if backlog quota exceeded // on topic for size based limit and time based limit for (BacklogQuota.BacklogQuotaType backlogQuotaType : BacklogQuota.BacklogQuotaType.values()) { if (topic.isBacklogQuotaExceeded(producerName, backlogQuotaType)) { IllegalStateException illegalStateException = new IllegalStateException( ""Cannot create producer on topic with backlog quota exceeded""); BacklogQuota.RetentionPolicy retentionPolicy = topic .getBacklogQuota(backlogQuotaType).getPolicy(); if (retentionPolicy == BacklogQuota.RetentionPolicy.producer_request_hold) { commandSender.sendErrorResponse(requestId, ServerError.ProducerBlockedQuotaExceededError, illegalStateException.getMessage()); } else if (retentionPolicy == BacklogQuota.RetentionPolicy.producer_exception) { commandSender.sendErrorResponse(requestId, ServerError.ProducerBlockedQuotaExceededException, illegalStateException.getMessage()); } producerFuture.completeExceptionally(illegalStateException); producers.remove(producerId, producerFuture); return; } } // Check whether the producer will publish encrypted messages or not if ((topic.isEncryptionRequired() || encryptionRequireOnProducer) && !isEncrypted) { String msg = String.format(""Encryption is required in %s"", topicName); log.warn(""[{}] {}"", remoteAddress, msg); commandSender.sendErrorResponse(requestId, ServerError.MetadataError, msg); producers.remove(producerId, producerFuture); return; } disableTcpNoDelayIfNeeded(topicName.toString(), producerName); CompletableFuture schemaVersionFuture = tryAddSchema(topic, schema); schemaVersionFuture.exceptionally(exception -> { String message = exception.getMessage(); if (exception.getCause() != null) { message += ("" caused by "" + exception.getCause()); } commandSender.sendErrorResponse(requestId, BrokerServiceException.getClientErrorCode(exception), message); producers.remove(producerId, producerFuture); return null; }); schemaVersionFuture.thenAccept(schemaVersion -> { topic.checkIfTransactionBufferRecoverCompletely(isTxnEnabled).thenAccept(future -> { buildProducerAndAddTopic(topic, producerId, producerName, requestId, isEncrypted, metadata, schemaVersion, epoch, userProvidedProducerName, topicName, producerAccessMode, topicEpoch, producerFuture); }).exceptionally(exception -> { Throwable cause = exception.getCause(); log.error(""producerId {}, requestId {} : TransactionBuffer recover failed"", producerId, requestId, exception); producers.remove(producerId, producerFuture); commandSender.sendErrorResponse(requestId, ServiceUnitNotReadyException.getClientErrorCode(cause), cause.getMessage()); return null; }); }); }, getBrokerService().getPulsar().getExecutor()).exceptionally(exception -> { Throwable cause = exception.getCause(); if (cause instanceof NoSuchElementException) { cause = new TopicNotFoundException(""Topic Not Found.""); log.info(""[{}] Failed to load topic {}, producerId={}: Topic not found"", remoteAddress, topicName, producerId); } else if (!Exceptions.areExceptionsPresentInChain(cause, ServiceUnitNotReadyException.class, ManagedLedgerException.class)) { // Do not print stack traces for expected exceptions log.error(""[{}] Failed to create topic {}, producerId={}"", remoteAddress, topicName, producerId, exception); } // If client timed out, the future would have been completed // by subsequent close. Send error back to // client, only if not completed already. if (producerFuture.completeExceptionally(exception)) { commandSender.sendErrorResponse(requestId, BrokerServiceException.getClientErrorCode(cause), cause.getMessage()); } producers.remove(producerId, producerFuture); return null; }); } else { String msg = ""Client is not authorized to Produce""; log.warn(""[{}] {} with role {}"", remoteAddress, msg, getPrincipal()); ctx.writeAndFlush(Commands.newError(requestId, ServerError.AuthorizationError, msg)); } return null; }).exceptionally(ex -> { logAuthException(remoteAddress, ""producer"", getPrincipal(), Optional.of(topicName), ex); commandSender.sendErrorResponse(requestId, ServerError.AuthorizationError, ex.getMessage()); return null; }); }","@Override protected void handleProducer(final CommandProducer cmdProducer) { checkArgument(state == State.Connected); final long producerId = cmdProducer.getProducerId(); final long requestId = cmdProducer.getRequestId(); // Use producer name provided by client if present final String producerName = cmdProducer.hasProducerName() ? cmdProducer.getProducerName() : service.generateUniqueProducerName(); final long epoch = cmdProducer.getEpoch(); final boolean userProvidedProducerName = cmdProducer.isUserProvidedProducerName(); final boolean isEncrypted = cmdProducer.isEncrypted(); final Map metadata = CommandUtils.metadataFromCommand(cmdProducer); final SchemaData schema = cmdProducer.hasSchema() ? getSchema(cmdProducer.getSchema()) : null; final ProducerAccessMode producerAccessMode = cmdProducer.getProducerAccessMode(); final Optional topicEpoch = cmdProducer.hasTopicEpoch() ? Optional.of(cmdProducer.getTopicEpoch()) : Optional.empty(); final boolean isTxnEnabled = cmdProducer.isTxnEnabled(); TopicName topicName = validateTopicName(cmdProducer.getTopic(), requestId, cmdProducer); if (topicName == null) { return; } if (invalidOriginalPrincipal(originalPrincipal)) { final String msg = ""Valid Proxy Client role should be provided while creating producer ""; log.warn(""[{}] {} with role {} and proxyClientAuthRole {} on topic {}"", remoteAddress, msg, authRole, originalPrincipal, topicName); commandSender.sendErrorResponse(requestId, ServerError.AuthorizationError, msg); return; } CompletableFuture isAuthorizedFuture = isTopicOperationAllowed( topicName, TopicOperation.PRODUCE, getAuthenticationData() ); isAuthorizedFuture.thenApply(isAuthorized -> { if (isAuthorized) { if (log.isDebugEnabled()) { log.debug(""[{}] Client is authorized to Produce with role {}"", remoteAddress, getPrincipal()); } CompletableFuture producerFuture = new CompletableFuture<>(); CompletableFuture existingProducerFuture = producers.putIfAbsent(producerId, producerFuture); if (existingProducerFuture != null) { if (existingProducerFuture.isDone() && !existingProducerFuture.isCompletedExceptionally()) { Producer producer = existingProducerFuture.getNow(null); log.info(""[{}] Producer with the same id is already created:"" + "" producerId={}, producer={}"", remoteAddress, producerId, producer); commandSender.sendProducerSuccessResponse(requestId, producer.getProducerName(), producer.getSchemaVersion()); return null; } else { // There was an early request to create a producer with same producerId. // This can happen when client timeout is lower than the broker timeouts. // We need to wait until the previous producer creation request // either complete or fails. ServerError error = null; if (!existingProducerFuture.isDone()) { error = ServerError.ServiceNotReady; } else { error = getErrorCode(existingProducerFuture); // remove producer with producerId as it's already completed with exception producers.remove(producerId, existingProducerFuture); } log.warn(""[{}][{}] Producer with id is already present on the connection,"" + "" producerId={}"", remoteAddress, topicName, producerId); commandSender.sendErrorResponse(requestId, error, ""Producer is already present on the connection""); return null; } } log.info(""[{}][{}] Creating producer. producerId={}"", remoteAddress, topicName, producerId); service.getOrCreateTopic(topicName.toString()).thenAcceptAsync((Topic topic) -> { // Before creating producer, check if backlog quota exceeded // on topic for size based limit and time based limit for (BacklogQuota.BacklogQuotaType backlogQuotaType : BacklogQuota.BacklogQuotaType.values()) { if (topic.isBacklogQuotaExceeded(producerName, backlogQuotaType)) { IllegalStateException illegalStateException = new IllegalStateException( ""Cannot create producer on topic with backlog quota exceeded""); BacklogQuota.RetentionPolicy retentionPolicy = topic .getBacklogQuota(backlogQuotaType).getPolicy(); if (retentionPolicy == BacklogQuota.RetentionPolicy.producer_request_hold) { commandSender.sendErrorResponse(requestId, ServerError.ProducerBlockedQuotaExceededError, illegalStateException.getMessage()); } else if (retentionPolicy == BacklogQuota.RetentionPolicy.producer_exception) { commandSender.sendErrorResponse(requestId, ServerError.ProducerBlockedQuotaExceededException, illegalStateException.getMessage()); } producerFuture.completeExceptionally(illegalStateException); producers.remove(producerId, producerFuture); return; } } // Check whether the producer will publish encrypted messages or not if ((topic.isEncryptionRequired() || encryptionRequireOnProducer) && !isEncrypted) { String msg = String.format(""Encryption is required in %s"", topicName); log.warn(""[{}] {}"", remoteAddress, msg); commandSender.sendErrorResponse(requestId, ServerError.MetadataError, msg); producers.remove(producerId, producerFuture); return; } disableTcpNoDelayIfNeeded(topicName.toString(), producerName); CompletableFuture schemaVersionFuture = tryAddSchema(topic, schema); schemaVersionFuture.exceptionally(exception -> { String message = exception.getMessage(); if (exception.getCause() != null) { message += ("" caused by "" + exception.getCause()); } commandSender.sendErrorResponse(requestId, BrokerServiceException.getClientErrorCode(exception), message); producers.remove(producerId, producerFuture); return null; }); schemaVersionFuture.thenAccept(schemaVersion -> { topic.checkIfTransactionBufferRecoverCompletely(isTxnEnabled).thenAccept(future -> { buildProducerAndAddTopic(topic, producerId, producerName, requestId, isEncrypted, metadata, schemaVersion, epoch, userProvidedProducerName, topicName, producerAccessMode, topicEpoch, producerFuture); }).exceptionally(exception -> { Throwable cause = exception.getCause(); log.error(""producerId {}, requestId {} : TransactionBuffer recover failed"", producerId, requestId, exception); producers.remove(producerId, producerFuture); commandSender.sendErrorResponse(requestId, ServiceUnitNotReadyException.getClientErrorCode(cause), cause.getMessage()); return null; }); }); }, getBrokerService().getPulsar().getExecutor()).exceptionally(exception -> { Throwable cause = exception.getCause(); if (cause instanceof NoSuchElementException) { cause = new TopicNotFoundException(""Topic Not Found.""); log.info(""[{}] Failed to load topic {}, producerId={}: Topic not found"", remoteAddress, topicName, producerId); } else if (!Exceptions.areExceptionsPresentInChain(cause, ServiceUnitNotReadyException.class, ManagedLedgerException.class)) { // Do not print stack traces for expected exceptions log.error(""[{}] Failed to create topic {}, producerId={}"", remoteAddress, topicName, producerId, exception); } // If client timed out, the future would have been completed // by subsequent close. Send error back to // client, only if not completed already. if (producerFuture.completeExceptionally(exception)) { commandSender.sendErrorResponse(requestId, BrokerServiceException.getClientErrorCode(cause), cause.getMessage()); } producers.remove(producerId, producerFuture); return null; }); } else { String msg = ""Client is not authorized to Produce""; log.warn(""[{}] {} with role {}"", remoteAddress, msg, getPrincipal()); ctx.writeAndFlush(Commands.newError(requestId, ServerError.AuthorizationError, msg)); } return null; }).exceptionally(ex -> { logAuthException(remoteAddress, ""producer"", getPrincipal(), Optional.of(topicName), ex); commandSender.sendErrorResponse(requestId, ServerError.AuthorizationError, ex.getMessage()); return null; }); }","Avoid AuthenticationDataSource mutation for subscription name (#16065) The `authenticationData` field in `ServerCnx` is being mutated to add the `subscription` field that will be passed on to the authorization plugin. The problem is that `authenticationData` is scoped to the whole connection and it should be getting mutated for each consumer that is created on the connection. The current code leads to a race condition where the subscription name used in the authz plugin is already modified while we're looking at it. Instead, we should create a new object and enforce the final modifier. (cherry picked from commit e6b12c64b043903eb5ff2dc5186fe8030f157cfc)",https://github.com/apache/pulsar/commit/422588782146bc60721f532f8a4f7c2e1a91f1f2,,,pulsar-broker/src/main/java/org/apache/pulsar/broker/service/ServerCnx.java,3,java,False,2022-06-15T07:00:28Z "@GetMapping(value = PROJECT.LIST_AJAX) public @ResponseBody ResponseEntity listAjax(Project project, HttpServletRequest req, HttpServletResponse res, Model model) { int page = Integer.parseInt(req.getParameter(""page"")); int rows = Integer.parseInt(req.getParameter(""rows"")); String sidx = req.getParameter(""sidx""); String sord = req.getParameter(""sord""); project.setCurPage(page); project.setPageListSize(rows); project.setSortField(sidx); project.setSortOrder(sord); if(project.getStatuses() != null) { String statuses = project.getStatuses(); if(!isEmpty(statuses)){ String[] arrStatuses = statuses.split("",""); project.setArrStatuses(arrStatuses); } } project.setPublicYn(isEmpty(project.getPublicYn())?CoConstDef.FLAG_YES:project.getPublicYn()); if (""search"".equals(req.getParameter(""act""))) { // 검색 조건 저장 putSessionObject(SESSION_KEY_SEARCH, project); } else if (getSessionObject(SESSION_KEY_SEARCH) != null) { project = (Project) getSessionObject(SESSION_KEY_SEARCH); } Map map = projectService.getProjectList(project); return makeJsonResponseHeader(map); }","@GetMapping(value = PROJECT.LIST_AJAX) public @ResponseBody ResponseEntity listAjax(Project project, HttpServletRequest req, HttpServletResponse res, Model model) { int page = Integer.parseInt(req.getParameter(""page"")); int rows = Integer.parseInt(req.getParameter(""rows"")); String sidx = req.getParameter(""sidx""); String sord = req.getParameter(""sord""); project.setCurPage(page); project.setPageListSize(rows); project.setSortField(sidx); project.setSortOrder(sord); if(project.getStatuses() != null) { String statuses = project.getStatuses(); if(!isEmpty(statuses)){ String[] arrStatuses = statuses.split("",""); project.setArrStatuses(arrStatuses); } } project.setPublicYn(isEmpty(project.getPublicYn())?CoConstDef.FLAG_YES:project.getPublicYn()); if (""search"".equals(req.getParameter(""act""))) { // 검색 조건 저장 putSessionObject(SESSION_KEY_SEARCH, project); } else if (getSessionObject(SESSION_KEY_SEARCH) != null) { project = (Project) getSessionObject(SESSION_KEY_SEARCH); } Map map = projectService.getProjectList(project); XssFilter.projectFilter((List) map.get(""rows"")); return makeJsonResponseHeader(map); }","Add Xss filter for list.jsp and autocomplete It is so boring work to add a defence code in view. Becaues list.jsp use jqGrid and autocomplete use jQuery, I may have to amend jqGrid and jQuery code to defend Xss attack in view. So I add Xss filter in controller. Signed-off-by: yugeeklab ",https://github.com/fosslight/fosslight/commit/ed045b308b77f7be65030c2b570db882c321c5d9,,,src/main/java/oss/fosslight/controller/ProjectController.java,3,java,False,2021-11-11T06:51:12Z "private void stopListeningForFingerprint() { if (DEBUG) Log.v(TAG, ""stopListeningForFingerprint()""); if (mFingerprintRunningState == BIOMETRIC_STATE_RUNNING) { if (mFingerprintCancelSignal != null) { mFingerprintCancelSignal.cancel(); mFingerprintCancelSignal = null; if (!mHandler.hasCallbacks(mCancelNotReceived)) { mHandler.postDelayed(mCancelNotReceived, DEFAULT_CANCEL_SIGNAL_TIMEOUT); } } setFingerprintRunningState(BIOMETRIC_STATE_CANCELLING); } if (mFingerprintRunningState == BIOMETRIC_STATE_CANCELLING_RESTARTING) { setFingerprintRunningState(BIOMETRIC_STATE_CANCELLING); } }","private void stopListeningForFingerprint() { if (DEBUG) Log.v(TAG, ""stopListeningForFingerprint()""); if (mFingerprintRunningState == BIOMETRIC_STATE_RUNNING) { if (mFingerprintCancelSignal != null) { mFingerprintCancelSignal.cancel(); mFingerprintCancelSignal = null; mHandler.removeCallbacks(mFpCancelNotReceived); mHandler.postDelayed(mFpCancelNotReceived, DEFAULT_CANCEL_SIGNAL_TIMEOUT); } setFingerprintRunningState(BIOMETRIC_STATE_CANCELLING); } if (mFingerprintRunningState == BIOMETRIC_STATE_CANCELLING_RESTARTING) { setFingerprintRunningState(BIOMETRIC_STATE_CANCELLING); } }","Fix KeyguardUpdateMonitor auth lifecycle issues This is split into two high-level issues which together cause strange auth behavior on keyguard: ============= Issue 1 ============= For fingerprint, auth ends when: 1) Success 2) Error For face, auth ends when: 1) Success 2) Reject 3) Error This change ensures that cancellation signal is set to null upon any of these conditions, so that there is never an opportunity of using a stale CancellationSignal. Furthermore, do not invoke stale cancellation signal when starting authentication. In the off chance the bug is re-introduced, or if some other situation can cause a cancellation signal to be non-null when keyguard requests auth again (e.g. bad state management in keyguard), do NOT invoke the stale cancellation signal's cancel method. The framework already handles this case gracefully and will automatically cancel the previous operation. ============= Issue 2 ============= We have a runnable that's scheduled to run after X ms if ERROR_CANCELED is not received after cancel() is requested. However, there are various bugs around that logic: 1) shared runnable for both fp and face, leading to unexpected and incorrect state changes (e.g. face does not respond to cancel within X ms, both fp and face will go to STATE_STOPPED, even though cancel() was never requested of fp 2) Always remove and re-add runnable when requesting cancel() though it should never occur that cancel() is requested in close temporal proximity, it never hurts to have the correct timeout before resetting the state. Bug: 195365422 Bug: 193477749 Test: manual Change-Id: I3702f41c8af7e870798f19c43012a26281a6632a",https://github.com/omnirom/android_frameworks_base/commit/a04d57070d780ca5d93e9af93c25c5c6dd36ab3a,,,packages/SystemUI/src/com/android/keyguard/KeyguardUpdateMonitor.java,3,java,False,2021-08-05T22:31:13Z "private void scheduleReceiverColdLocked(@NonNull BroadcastProcessQueue queue) { checkState(queue.isActive(), ""isActive""); final BroadcastRecord r = queue.getActive(); final Object receiver = queue.getActiveReceiver(); final ApplicationInfo info = ((ResolveInfo) receiver).activityInfo.applicationInfo; final ComponentName component = ((ResolveInfo) receiver).activityInfo.getComponentName(); final int intentFlags = r.intent.getFlags() | Intent.FLAG_FROM_BACKGROUND; final HostingRecord hostingRecord = new HostingRecord(HostingRecord.HOSTING_TYPE_BROADCAST, component, r.intent.getAction(), r.getHostingRecordTriggerType()); final boolean isActivityCapable = (r.options != null && r.options.getTemporaryAppAllowlistDuration() > 0); final int zygotePolicyFlags = isActivityCapable ? ZYGOTE_POLICY_FLAG_LATENCY_SENSITIVE : ZYGOTE_POLICY_FLAG_EMPTY; final boolean allowWhileBooting = (r.intent.getFlags() & Intent.FLAG_RECEIVER_BOOT_UPGRADE) != 0; if (DEBUG_BROADCAST) logv(""Scheduling "" + r + "" to cold "" + queue); queue.app = mService.startProcessLocked(queue.processName, info, true, intentFlags, hostingRecord, zygotePolicyFlags, allowWhileBooting, false); if (queue.app == null) { mRunningColdStart = null; finishReceiverLocked(queue, BroadcastRecord.DELIVERY_FAILURE); } }","private void scheduleReceiverColdLocked(@NonNull BroadcastProcessQueue queue) { checkState(queue.isActive(), ""isActive""); // Remember that active broadcast was scheduled via a cold start queue.setActiveViaColdStart(true); final BroadcastRecord r = queue.getActive(); final Object receiver = queue.getActiveReceiver(); final ApplicationInfo info = ((ResolveInfo) receiver).activityInfo.applicationInfo; final ComponentName component = ((ResolveInfo) receiver).activityInfo.getComponentName(); final int intentFlags = r.intent.getFlags() | Intent.FLAG_FROM_BACKGROUND; final HostingRecord hostingRecord = new HostingRecord(HostingRecord.HOSTING_TYPE_BROADCAST, component, r.intent.getAction(), r.getHostingRecordTriggerType()); final boolean isActivityCapable = (r.options != null && r.options.getTemporaryAppAllowlistDuration() > 0); final int zygotePolicyFlags = isActivityCapable ? ZYGOTE_POLICY_FLAG_LATENCY_SENSITIVE : ZYGOTE_POLICY_FLAG_EMPTY; final boolean allowWhileBooting = (r.intent.getFlags() & Intent.FLAG_RECEIVER_BOOT_UPGRADE) != 0; if (DEBUG_BROADCAST) logv(""Scheduling "" + r + "" to cold "" + queue); queue.app = mService.startProcessLocked(queue.processName, info, true, intentFlags, hostingRecord, zygotePolicyFlags, allowWhileBooting, false); if (queue.app != null) { notifyStartedRunning(queue); } else { mRunningColdStart = null; finishReceiverLocked(queue, BroadcastRecord.DELIVERY_FAILURE); } }","BroadcastQueue: misc bookkeeping events for OS. This change brings over the remaining bookkeeping events that other parts of the OS expects, such as allowing background activity starts, temporary allowlisting for power, more complete OOM adjustments, thawing apps before dispatch, and metrics events. Fixes bug so that apps aren't able to abort broadcasts marked with NO_ABORT flag. Tests to confirm all the above behaviors are identical between both broadcast stack implementations. Bug: 245771249 Test: atest FrameworksMockingServicesTests:BroadcastQueueTest Change-Id: If3532d335c94c8138a9ebcf8d11bf3674d1c42aa",https://github.com/LineageOS/android_frameworks_base/commit/6a6e2295915440e17104151160a4b4ce21796962,,,services/core/java/com/android/server/am/BroadcastQueueModernImpl.java,3,java,False,2022-09-22T22:04:12Z "private void removeHeatSinks() { int location = 0; for (; location < equipmentList.getRowCount();) { Mounted mount = (Mounted) equipmentList.getValueAt(location, CriticalTableModel.EQUIPMENT); EquipmentType eq = mount.getType(); if ((eq instanceof MiscType) && (UnitUtil.isHeatSink(mount))) { try { equipmentList.removeCrit(location); } catch (ArrayIndexOutOfBoundsException aioobe) { return; } catch (Exception ex) { ex.printStackTrace(); } } else { location++; } } }","private void removeHeatSinks() { for (int location = 0; location < equipmentList.getRowCount(); ) { Mounted mount = (Mounted) equipmentList.getValueAt(location, CriticalTableModel.EQUIPMENT); EquipmentType eq = mount.getType(); if ((eq instanceof MiscType) && (UnitUtil.isHeatSink(mount))) { try { equipmentList.removeCrit(location); } catch (IndexOutOfBoundsException ignored) { return; } catch (Exception e) { MegaMekLab.getLogger().error(e); return; } } else { location++; } } }",913: Preventing infinite loops in remove heat sink,https://github.com/MegaMek/megameklab/commit/95ec5a3fc34db6863ef8f48f6e4deefc316a08a6,,,src/megameklab/com/ui/Aero/tabs/EquipmentTab.java,3,java,False,2021-06-02T17:58:21Z "private void renderMuzzleFlash(LivingEntity entity, PoseStack poseStack, MultiBufferSource buffer, ItemStack weapon, ItemTransforms.TransformType transformType, float partialTicks) { Gun modifiedGun = ((GunItem) weapon.getItem()).getModifiedGun(weapon); if(modifiedGun.getDisplay().getFlash() == null) return; if(transformType != ItemTransforms.TransformType.FIRST_PERSON_RIGHT_HAND && transformType != ItemTransforms.TransformType.THIRD_PERSON_RIGHT_HAND && transformType != ItemTransforms.TransformType.FIRST_PERSON_LEFT_HAND && transformType != ItemTransforms.TransformType.THIRD_PERSON_LEFT_HAND) return; if(!this.entityIdForMuzzleFlash.contains(entity.getId())) return; float randomValue = this.entityIdToRandomValue.get(entity.getId()); this.drawMuzzleFlash(weapon, modifiedGun, randomValue, randomValue >= 0.5F, poseStack, buffer, partialTicks); }","private void renderMuzzleFlash(@Nullable LivingEntity entity, PoseStack poseStack, MultiBufferSource buffer, ItemStack weapon, ItemTransforms.TransformType transformType, float partialTicks) { Gun modifiedGun = ((GunItem) weapon.getItem()).getModifiedGun(weapon); if(modifiedGun.getDisplay().getFlash() == null) return; if(transformType != ItemTransforms.TransformType.FIRST_PERSON_RIGHT_HAND && transformType != ItemTransforms.TransformType.THIRD_PERSON_RIGHT_HAND && transformType != ItemTransforms.TransformType.FIRST_PERSON_LEFT_HAND && transformType != ItemTransforms.TransformType.THIRD_PERSON_LEFT_HAND) return; if(entity == null || !this.entityIdForMuzzleFlash.contains(entity.getId())) return; float randomValue = this.entityIdToRandomValue.get(entity.getId()); this.drawMuzzleFlash(weapon, modifiedGun, randomValue, randomValue >= 0.5F, poseStack, buffer, partialTicks); }",🐛 Fixed potential crash when player is null,https://github.com/MrCrayfish/MrCrayfishGunMod/commit/0916fe277c5633f9d4062e4d0fa3f2b25f940c60,,,src/main/java/com/mrcrayfish/guns/client/handler/GunRenderingHandler.java,3,java,False,2022-07-13T14:05:31Z "public void run() { List auths = new ArrayList(); for (ClientStateListener stateListener : context.getStateListeners()) { stateListener.authenticate(AuthenticationProtocolClient.this, transport.getConnection(), supportedAuths, partial, auths); authenticators.addAll(auths); } if(canAuthenticate()) { try { doNextAuthentication(); } catch (IOException | SshException e) { Log.error(""I/O error during authentication"", e); transport.disconnect(TransportProtocolClient.BY_APPLICATION, ""I/O error during authentication""); } } }","public void run() { List auths = new ArrayList(); for (ClientStateListener stateListener : context.getStateListeners()) { stateListener.authenticate(AuthenticationProtocolClient.this, transport.getConnection(), supportedAuths, partial, auths); try { addAuthentication(context.getAuthenticators()); } catch (IOException | SshException e) { Log.error(""I/O error during authentication"", e); transport.disconnect(TransportProtocolClient.BY_APPLICATION, ""I/O error during authentication""); } } }","Added prefer keyboard-interactive over password setting. Fixed race condition with none authenticator.",https://github.com/sshtools/maverick-synergy/commit/5421a5cb4c6b5f5174bcfb2c15d78f3acd706d86,,,maverick-synergy-client/src/main/java/com/sshtools/client/AuthenticationProtocolClient.java,3,java,False,2021-03-07T16:54:01Z "private void doSendBatchPut(BackOffer backOffer, Map kvPairs, long ttl) { ExecutorCompletionService completionService = new ExecutorCompletionService<>(batchPutThreadPool); Map> groupKeys = groupKeysByRegion(kvPairs.keySet()); List batches = new ArrayList<>(); for (Map.Entry> entry : groupKeys.entrySet()) { appendBatches( batches, entry.getKey(), entry.getValue(), entry.getValue().stream().map(kvPairs::get).collect(Collectors.toList()), RAW_BATCH_PUT_SIZE); } for (Batch batch : batches) { BackOffer singleBatchBackOffer = ConcreteBackOffer.create(backOffer); completionService.submit( () -> doSendBatchPutInBatchesWithRetry(singleBatchBackOffer, batch, ttl)); } getTasks(completionService, batches, BackOffer.RAWKV_MAX_BACKOFF); }","private void doSendBatchPut(BackOffer backOffer, Map kvPairs, long ttl) { ExecutorCompletionService> completionService = new ExecutorCompletionService<>(batchPutThreadPool); Map> groupKeys = groupKeysByRegion(kvPairs.keySet()); List batches = new ArrayList<>(); for (Map.Entry> entry : groupKeys.entrySet()) { appendBatches( batches, entry.getKey(), entry.getValue(), entry.getValue().stream().map(kvPairs::get).collect(Collectors.toList()), RAW_BATCH_PUT_SIZE); } Queue> taskQueue = new LinkedList<>(); taskQueue.offer(batches); while (!taskQueue.isEmpty()) { List task = taskQueue.poll(); for (Batch batch : task) { BackOffer singleBatchBackOffer = ConcreteBackOffer.create(backOffer); completionService.submit( () -> doSendBatchPutInBatchesWithRetry(singleBatchBackOffer, batch, ttl)); } getTasks(completionService, taskQueue, task, BackOffer.RAWKV_MAX_BACKOFF); } }","Fix batch put StackOverflow (#134) * fix batch put stack overflow Signed-off-by: birdstorm ",https://github.com/tikv/client-java/commit/ce1a95780c6fe3eb6cc9b3a2f8802d5dccdf75e0,,,src/main/java/org/tikv/raw/RawKVClient.java,3,java,False,2021-02-27T10:37:03Z "@Transactional @Override public void deregisterDatatable(final String datatable) { validateDatatableName(datatable); final String permissionList = ""('CREATE_"" + datatable + ""', 'CREATE_"" + datatable + ""_CHECKER', 'READ_"" + datatable + ""', 'UPDATE_"" + datatable + ""', 'UPDATE_"" + datatable + ""_CHECKER', 'DELETE_"" + datatable + ""', 'DELETE_"" + datatable + ""_CHECKER')""; final String deleteRolePermissionsSql = ""delete from m_role_permission where m_role_permission.permission_id in (select id from m_permission where code in "" + permissionList + "")""; final String deletePermissionsSql = ""delete from m_permission where code in "" + permissionList; final String deleteRegisteredDatatableSql = ""delete from x_registered_table where registered_table_name = '"" + datatable + ""'""; final String deleteFromConfigurationSql = ""delete from c_configuration where name ='"" + datatable + ""'""; String[] sqlArray = new String[4]; sqlArray[0] = deleteRolePermissionsSql; sqlArray[1] = deletePermissionsSql; sqlArray[2] = deleteRegisteredDatatableSql; sqlArray[3] = deleteFromConfigurationSql; this.jdbcTemplate.batchUpdate(sqlArray); }","@Transactional @Override public void deregisterDatatable(final String datatable) { String validatedDatatable = this.preventSqlInjectionService.encodeSql(datatable); final String permissionList = ""('CREATE_"" + validatedDatatable + ""', 'CREATE_"" + validatedDatatable + ""_CHECKER', 'READ_"" + validatedDatatable + ""', 'UPDATE_"" + validatedDatatable + ""', 'UPDATE_"" + validatedDatatable + ""_CHECKER', 'DELETE_"" + validatedDatatable + ""', 'DELETE_"" + validatedDatatable + ""_CHECKER')""; final String deleteRolePermissionsSql = ""delete from m_role_permission where m_role_permission.permission_id in (select id from m_permission where code in "" + permissionList + "")""; final String deletePermissionsSql = ""delete from m_permission where code in "" + permissionList; final String deleteRegisteredDatatableSql = ""delete from x_registered_table where registered_table_name = '"" + validatedDatatable + ""'""; final String deleteFromConfigurationSql = ""delete from c_configuration where name ='"" + validatedDatatable + ""'""; String[] sqlArray = new String[4]; sqlArray[0] = deleteRolePermissionsSql; sqlArray[1] = deletePermissionsSql; sqlArray[2] = deleteRegisteredDatatableSql; sqlArray[3] = deleteFromConfigurationSql; this.jdbcTemplate.batchUpdate(sqlArray); // NOSONAR }",FINERACT-1562: Excluding persistence.xml from being picked up by Spring,https://github.com/apache/fineract/commit/f22807b9442dafa0ca07d0fad4e24c2de84e8e33,,,fineract-provider/src/main/java/org/apache/fineract/infrastructure/dataqueries/service/ReadWriteNonCoreDataServiceImpl.java,3,java,False,2022-03-17T13:12:10Z "public static void unzip(InputStream src, File dest) { //buffer for read and write data to file byte[] buffer = new byte[1024]; try { ZipInputStream zis = new ZipInputStream(src); ZipEntry ze = zis.getNextEntry(); while (ze != null) { if (!ze.isDirectory()) { String fileName = ze.getName(); File newFile = new File(dest, fileName); //create directories for sub directories in zip new File(newFile.getParent()).mkdirs(); FileOutputStream fos = new FileOutputStream(newFile); int len; while ((len = zis.read(buffer)) > 0) { fos.write(buffer, 0, len); } fos.close(); } //close this ZipEntry zis.closeEntry(); ze = zis.getNextEntry(); } //close last ZipEntry zis.closeEntry(); zis.close(); } catch (IOException e) { e.printStackTrace(); } }","public static void unzip(InputStream src, File dest) { //buffer for read and write data to file byte[] buffer = new byte[1024]; try { ZipInputStream zis = new ZipInputStream(src); ZipEntry ze = zis.getNextEntry(); while (ze != null) { if (!ze.isDirectory()) { String fileName = ze.getName(); File newFile = new File(dest, fileName); if (!isInTree(dest, newFile)) { throw new RuntimeException(""Not Enough Updates detected an invalid zip file. This is a potential security risk, please report this in the Moulberry discord.""); } //create directories for sub directories in zip new File(newFile.getParent()).mkdirs(); FileOutputStream fos = new FileOutputStream(newFile); int len; while ((len = zis.read(buffer)) > 0) { fos.write(buffer, 0, len); } fos.close(); } //close this ZipEntry zis.closeEntry(); ze = zis.getNextEntry(); } //close last ZipEntry zis.closeEntry(); zis.close(); } catch (IOException e) { e.printStackTrace(); } }","Recipe Reloading should no longer duplicate recipes (#65) * Remove potential RCE only exploitable by Moulberry himself, i still want my cape tho * no more recipe dupes",https://github.com/Moulberry/NotEnoughUpdates/commit/6107995ad7892807bf6ba098548754fea439cee4,,,src/main/java/io/github/moulberry/notenoughupdates/NEUManager.java,3,java,False,2022-01-17T15:15:53Z "public void deserialize(@NotNull final FriendlyByteBuf buf) { final int ranksSize = buf.readVarInt(); for (int i = 0; i < ranksSize; ++i) { final int id = buf.readVarInt(); final Rank rank = new Rank(id, buf.readUtf(32767), buf.readBoolean(), buf.readBoolean(), buf.readBoolean(), buf.readBoolean()); ranks.put(id, rank); } userRank = ranks.get(buf.readVarInt()); // Owners players.clear(); final int numOwners = buf.readVarInt(); for (int i = 0; i < numOwners; ++i) { final UUID id = PacketUtils.readUUID(buf); final String name = buf.readUtf(32767); final Rank rank = ranks.get(buf.readVarInt()); if (rank.getId() == OWNER_RANK_ID) { colonyOwner = id; } players.put(id, new ColonyPlayer(id, name, rank)); } //Permissions permissions.clear(); final int numPermissions = buf.readVarInt(); for (int i = 0; i < numPermissions; ++i) { final Rank rank = ranks.get(buf.readVarInt()); final long flags = buf.readVarLong(); permissions.put(rank, flags); } }","public void deserialize(@NotNull final FriendlyByteBuf buf) { final int ranksSize = buf.readVarInt(); for (int i = 0; i < ranksSize; ++i) { final int id = buf.readVarInt(); final Rank rank = new Rank(id, buf.readLong(), buf.readUtf(32767), buf.readBoolean(), buf.readBoolean(), buf.readBoolean(), buf.readBoolean()); ranks.put(id, rank); } userRank = ranks.get(buf.readVarInt()); // Owners players.clear(); final int numOwners = buf.readVarInt(); for (int i = 0; i < numOwners; ++i) { final UUID id = PacketUtils.readUUID(buf); final String name = buf.readUtf(32767); final Rank rank = ranks.get(buf.readVarInt()); if (rank.getId() == OWNER_RANK_ID) { colonyOwner = id; } players.put(id, new ColonyPlayer(id, name, rank)); } }","Fix permission issues (#7972) Ranks are no longer a static map, which was used as a per-colony map thus causing crashes and desyncs. If the last colony loaded had a custom rank, all other colonies would crash out due to not matching permissions for that rank. Permission/Rank seperation is removed, permission flag is now part of the rank instead of an externally synced map, which also auto-corrects bad stored data to default permissions. UI now has non-changeable permission buttons disabled.",https://github.com/ldtteam/minecolonies/commit/b1b86dffe64dd4c0f9d3060769fc418fd5d2869a,,,src/main/java/com/minecolonies/coremod/colony/permissions/PermissionsView.java,3,java,False,2022-01-23T12:23:45Z "public void process(WebXml webXml, WebApplication webApplication) { LOGGER.log(TRACE, ""Started WebXmlProcessor.process""); processContextParameters(webApplication, webXml); processDefaultContextPath(webApplication, webXml); processDenyUncoveredHttpMethods(webApplication, webXml); processDisplayName(webApplication, webXml); processDistributable(webApplication, webXml); processErrorPages(webApplication, webXml); processFilters(webApplication, webXml); processFilterMappings(webApplication, webXml); processListeners(webApplication, webXml); processMimeMappings(webApplication, webXml); processRequestCharacterEncoding(webApplication, webXml); processResponseCharacterEncoding(webApplication, webXml); processRoleNames(webApplication, webXml); processServlets(webApplication, webXml); processServletMappings(webApplication, webXml); processWebApp(webApplication, webXml); processWelcomeFiles(webApplication, webXml); processLocaleEncodingMapping(webApplication, webXml); processSessionConfig(webApplication, webXml); LOGGER.log(TRACE, ""Finished WebXmlProcessor.process""); }","public void process(WebXml webXml, WebApplication webApplication) { LOGGER.log(TRACE, ""Started WebXmlProcessor.process""); processContextParameters(webApplication, webXml); processDefaultContextPath(webApplication, webXml); processDenyUncoveredHttpMethods(webApplication, webXml); processDisplayName(webApplication, webXml); processDistributable(webApplication, webXml); processErrorPages(webApplication, webXml); processFilters(webApplication, webXml); processFilterMappings(webApplication, webXml); processListeners(webApplication, webXml); processMimeMappings(webApplication, webXml); processRequestCharacterEncoding(webApplication, webXml); processResponseCharacterEncoding(webApplication, webXml); processRoleNames(webApplication, webXml); processSecurityConstraints(webApplication, webXml); processServlets(webApplication, webXml); processServletMappings(webApplication, webXml); processWebApp(webApplication, webXml); processWelcomeFiles(webApplication, webXml); processLocaleEncodingMapping(webApplication, webXml); processSessionConfig(webApplication, webXml); LOGGER.log(TRACE, ""Finished WebXmlProcessor.process""); }",Fixes issue #1894 - Add addSecurityMapping to AuthenticationManager,https://github.com/piranhacloud/piranha/commit/07f1b4d5544f478e62f8805e525b4a94f15d6600,,,extension/webxml/src/main/java/cloud/piranha/extension/webxml/WebXmlProcessor.java,3,java,False,2021-09-11T23:33:08Z "private void updateScrollTo(float delta) { if (scrollTo == null) { return; } RenderNode scrollToNode = scrollTo.getTargetRenderNode(); if (scrollToNode == null) { scrollToNode = getElementById(scrollTo.getTargetElement().getId()); if (scrollToNode == null) { scrollTo = null; return; } } float currentScrollY = getInnerY() + scrollTranslationY; float scrollFactor = ((ScrollBox) element).getScrollFactor() * contentHeight; if (scrollToNode.getOuterY() + scrollToNode.getOuterHeight() > currentScrollY + getInnerHeight()) { if (scrollTo.isImmediate()) { // TODO: Optimise this while (scrollToNode.getOuterY() + scrollToNode.getOuterHeight() > currentScrollY + getInnerHeight() + scrollFactor) { setScrollThumbPosition(scrollThumbPosition + ((ScrollBox) element).getScrollFactor()); currentScrollY = getInnerY() + scrollTranslationY; } if (scrollToNode.getOuterY() + scrollToNode.getOuterHeight() > currentScrollY + getInnerHeight()){ float scrollAmount = (scrollToNode.getOuterY() + scrollToNode.getOuterHeight()) - (currentScrollY + getInnerHeight()); setScrollThumbPosition(scrollThumbPosition + (scrollAmount / contentHeight)); } } else { setScrollThumbPosition(scrollThumbPosition + ((ScrollBox) element).getScrollFactor()); } } else if (scrollToNode.getOuterY() < currentScrollY) { if (scrollTo.isImmediate()) { // TODO: Optimise this while (scrollToNode.getOuterY() < currentScrollY - scrollFactor) { setScrollThumbPosition(scrollThumbPosition - ((ScrollBox) element).getScrollFactor()); currentScrollY = getInnerY() + scrollTranslationY; } if (scrollToNode.getOuterY() < currentScrollY){ float scrollAmount = currentScrollY - scrollToNode.getOuterY(); setScrollThumbPosition(scrollThumbPosition - (scrollAmount / contentHeight)); } } else { setScrollThumbPosition(scrollThumbPosition - ((ScrollBox) element).getScrollFactor()); } } else { scrollTo = null; } }","private void updateScrollTo(float delta) { if (scrollTo == null) { return; } RenderNode scrollToNode = scrollTo.getTargetRenderNode(); if (scrollToNode == null) { scrollToNode = getElementById(scrollTo.getTargetElement().getId()); if (scrollToNode == null) { scrollTo = null; return; } } float currentScrollY = getInnerY() + scrollTranslationY; float scrollFactor = ((ScrollBox) element).getScrollFactor() * contentHeight; if (scrollToNode.getOuterY() + scrollToNode.getOuterHeight() > currentScrollY + getInnerHeight()) { if (scrollTo.isImmediate()) { // TODO: Optimise this int previousScrollTranslationY = Integer.MAX_VALUE; while (scrollToNode.getOuterY() + scrollToNode.getOuterHeight() > currentScrollY + getInnerHeight() + scrollFactor) { if(previousScrollTranslationY == scrollTranslationY) { break; } setScrollThumbPosition(scrollThumbPosition + ((ScrollBox) element).getScrollFactor()); currentScrollY = getInnerY() + scrollTranslationY; previousScrollTranslationY = scrollTranslationY; } if (scrollToNode.getOuterY() + scrollToNode.getOuterHeight() > currentScrollY + getInnerHeight()){ float scrollAmount = (scrollToNode.getOuterY() + scrollToNode.getOuterHeight()) - (currentScrollY + getInnerHeight()); setScrollThumbPosition(scrollThumbPosition + (scrollAmount / contentHeight)); } } else { setScrollThumbPosition(scrollThumbPosition + ((ScrollBox) element).getScrollFactor()); } } else if (scrollToNode.getOuterY() < currentScrollY) { if (scrollTo.isImmediate()) { // TODO: Optimise this int previousScrollTranslationY = Integer.MAX_VALUE; while (scrollToNode.getOuterY() < currentScrollY - scrollFactor) { if(previousScrollTranslationY == scrollTranslationY) { break; } setScrollThumbPosition(scrollThumbPosition - ((ScrollBox) element).getScrollFactor()); currentScrollY = getInnerY() + scrollTranslationY; previousScrollTranslationY = scrollTranslationY; } if (scrollToNode.getOuterY() < currentScrollY){ float scrollAmount = currentScrollY - scrollToNode.getOuterY(); setScrollThumbPosition(scrollThumbPosition - (scrollAmount / contentHeight)); } } else { setScrollThumbPosition(scrollThumbPosition - ((ScrollBox) element).getScrollFactor()); } } else { scrollTo = null; } }",Fix rare infinite loop in ScrollBoxRenderNode,https://github.com/mini2Dx/mini2Dx/commit/37ed37dbb7187b0c758e4fe80b8ad11139fc0c68,,,ui/src/main/java/org/mini2Dx/ui/render/ScrollBoxRenderNode.java,3,java,False,2022-10-22T10:20:00Z "public static VoxelShape rotateDirection(VoxelShape shape, Direction facing) { VoxelShape[] temp = new VoxelShape[] { shape.move(-0.5, 0, -0.5), Shapes.empty() }; for (int i = 0; i < facing.get2DDataValue(); i++) { temp[0].forAllBoxes((x1, y1, z1, x2, y2, z2) -> temp[1] = Shapes.or(temp[1], Shapes.box(-z1, y1, x1, -z2, y2, x2))); temp[0] = temp[1]; temp[1] = Shapes.empty(); } return temp[0].move(0.5, 0, 0.5); }","public static VoxelShape rotateDirection(VoxelShape shape, Direction facing) { VoxelShape[] temp = new VoxelShape[] { shape.move(-0.5, 0, -0.5), Shapes.empty() }; for (int i = 0; i < facing.get2DDataValue(); i++) { temp[0].forAllBoxes((x1, y1, z1, x2, y2, z2) -> temp[1] = Shapes.or(temp[1], Shapes.box(Math.min(-z1, -z2), y1, Math.min(x1, x2), Math.max(-z1, -z2), y2, Math.max(x1, x2)))); temp[0] = temp[1]; temp[1] = Shapes.empty(); } return temp[0].move(0.5, 0, 0.5); }",fixed bounding box crashes,https://github.com/mickelus/tetra/commit/7f3ce103fd90f20bc4642f0e6368a4d5eebd681e,,,src/main/java/se/mickelus/tetra/util/RotationHelper.java,3,java,False,2021-12-04T22:22:54Z "public void playRandomSong() { File[] files = MeteorClient.FOLDER.toPath().resolve(""notebot"").toFile().listFiles(); File randomSong = files[ThreadLocalRandom.current().nextInt(files.length)]; if (SongDecoders.hasDecoder(randomSong)) { loadSong(randomSong); } else { playRandomSong(); } }","public void playRandomSong() { File[] files = MeteorClient.FOLDER.toPath().resolve(""notebot"").toFile().listFiles(); if (files == null) return; File randomSong = files[ThreadLocalRandom.current().nextInt(files.length)]; if (SongDecoders.hasDecoder(randomSong)) { loadSong(randomSong); } else { playRandomSong(); } }",Fix notebot random song null files crash,https://github.com/MeteorDevelopment/meteor-client/commit/68ec0dc461d8afd4421c816e8df826f9db8c1cf0,,,src/main/java/meteordevelopment/meteorclient/systems/modules/misc/Notebot.java,3,java,False,2022-10-15T13:39:21Z "public void getPlayerUUID(String name, Consumer uuidCallback) { String nameF = name.toLowerCase(); if (nameToUuid.containsKey(nameF)) { uuidCallback.accept(nameToUuid.get(nameF)); return; } manager.hypixelApi.getApiAsync( ""https://api.mojang.com/users/profiles/minecraft/"" + nameF, jsonObject -> { if (jsonObject.has(""id"") && jsonObject.get(""id"").isJsonPrimitive() && ((JsonPrimitive) jsonObject.get(""id"")).isString()) { String uuid = jsonObject.get(""id"").getAsString(); nameToUuid.put(nameF, uuid); uuidCallback.accept(uuid); return; } uuidCallback.accept(null); }, () -> uuidCallback.accept(null) ); }","public void getPlayerUUID(String name, Consumer uuidCallback) { String nameF = name.toLowerCase(); if (nameToUuid.containsKey(nameF)) { uuidCallback.accept(nameToUuid.get(nameF)); return; } manager.apiUtils .request() .url(""https://api.mojang.com/users/profiles/minecraft/"" + nameF) .requestJson() .thenAccept(jsonObject -> { if (jsonObject.has(""id"") && jsonObject.get(""id"").isJsonPrimitive() && ((JsonPrimitive) jsonObject.get(""id"")).isString()) { String uuid = jsonObject.get(""id"").getAsString(); nameToUuid.put(nameF, uuid); uuidCallback.accept(uuid); return; } uuidCallback.accept(null); }); }","Add custom keystore and refactor HypixelApi.java (#318) * Add custom keystore and refactor HypixelApi.java * Fix inputstream leak (+ less console spam) * Fix HOTM crash * Use api selected variable to find best profile * Number formatting * Make old profiles show again Co-authored-by: nopo ",https://github.com/Moulberry/NotEnoughUpdates/commit/2dd4a2b36211c380c0bf4e231859dfafd3c04a5b,,,src/main/java/io/github/moulberry/notenoughupdates/profileviewer/ProfileViewer.java,3,java,False,2022-09-29T15:25:37Z "private void fetchBluetoothDeviceName() { if (fetchingBluetoothDeviceName) { return; } try { currentBluetoothDeviceName = null; fetchingBluetoothDeviceName = true; BluetoothAdapter.getDefaultAdapter().getProfileProxy(this, serviceListener, BluetoothProfile.HEADSET); } catch (Throwable e) { FileLog.e(e); } }","private void fetchBluetoothDeviceName() { if (Build.VERSION.SDK_INT >= 31 && ApplicationLoader.applicationContext.checkSelfPermission(Manifest.permission.BLUETOOTH_CONNECT) != PackageManager.PERMISSION_GRANTED) { return; } if (fetchingBluetoothDeviceName) { return; } try { currentBluetoothDeviceName = null; fetchingBluetoothDeviceName = true; BluetoothAdapter.getDefaultAdapter().getProfileProxy(this, serviceListener, BluetoothProfile.HEADSET); } catch (Throwable e) { FileLog.e(e); } }",Fix Android 12 Calls Crash,https://github.com/OwlGramDev/OwlGram/commit/5ffeb69a41aa93fbb20abd8c93d49288e87c97aa,,,TMessagesProj/src/main/java/org/telegram/messenger/voip/VoIPService.java,3,java,False,2022-04-29T13:33:56Z "@Override public void channelInactive(ChannelHandlerContext ctx) throws Exception { super.channelInactive(ctx); connectionController.decreaseConnection(ctx.channel().remoteAddress()); isActive = false; log.info(""Closed connection from {}"", remoteAddress); if (brokerInterceptor != null) { brokerInterceptor.onConnectionClosed(this); } cnxsPerThread.get().remove(this); // Connection is gone, close the producers immediately producers.forEach((__, producerFuture) -> { // prevent race conditions in completing producers if (!producerFuture.isDone() && producerFuture.completeExceptionally(new IllegalStateException(""Connection closed.""))) { return; } if (producerFuture.isDone() && !producerFuture.isCompletedExceptionally()) { Producer producer = producerFuture.getNow(null); producer.closeNow(true); if (brokerInterceptor != null) { brokerInterceptor.producerClosed(this, producer, producer.getMetadata()); } } }); consumers.forEach((__, consumerFuture) -> { // prevent race conditions in completing consumers if (!consumerFuture.isDone() && consumerFuture.completeExceptionally(new IllegalStateException(""Connection closed.""))) { return; } if (consumerFuture.isDone() && !consumerFuture.isCompletedExceptionally()) { Consumer consumer = consumerFuture.getNow(null); try { consumer.close(); if (brokerInterceptor != null) { brokerInterceptor.consumerClosed(this, consumer, consumer.getMetadata()); } } catch (BrokerServiceException e) { log.warn(""Consumer {} was already closed: {}"", consumer, e); } } }); this.topicListService.inactivate(); this.service.getPulsarStats().recordConnectionClose(); }","@Override public void channelInactive(ChannelHandlerContext ctx) throws Exception { super.channelInactive(ctx); connectionController.decreaseConnection(ctx.channel().remoteAddress()); isActive = false; log.info(""Closed connection from {}"", remoteAddress); if (brokerInterceptor != null) { brokerInterceptor.onConnectionClosed(this); } cnxsPerThread.get().remove(this); if (authRefreshTask != null) { authRefreshTask.cancel(false); } // Connection is gone, close the producers immediately producers.forEach((__, producerFuture) -> { // prevent race conditions in completing producers if (!producerFuture.isDone() && producerFuture.completeExceptionally(new IllegalStateException(""Connection closed.""))) { return; } if (producerFuture.isDone() && !producerFuture.isCompletedExceptionally()) { Producer producer = producerFuture.getNow(null); producer.closeNow(true); if (brokerInterceptor != null) { brokerInterceptor.producerClosed(this, producer, producer.getMetadata()); } } }); consumers.forEach((__, consumerFuture) -> { // prevent race conditions in completing consumers if (!consumerFuture.isDone() && consumerFuture.completeExceptionally(new IllegalStateException(""Connection closed.""))) { return; } if (consumerFuture.isDone() && !consumerFuture.isCompletedExceptionally()) { Consumer consumer = consumerFuture.getNow(null); try { consumer.close(); if (brokerInterceptor != null) { brokerInterceptor.consumerClosed(this, consumer, consumer.getMetadata()); } } catch (BrokerServiceException e) { log.warn(""Consumer {} was already closed: {}"", consumer, e); } } }); this.topicListService.inactivate(); this.service.getPulsarStats().recordConnectionClose(); }","[fix][broker] Make authentication refresh threadsafe (#19506) Co-authored-by: Lari Hotari ",https://github.com/apache/pulsar/commit/153e4d4cc3b56aaee224b0a68e0186c08125c975,,,pulsar-broker/src/main/java/org/apache/pulsar/broker/service/ServerCnx.java,3,java,False,2023-02-14T09:09:55Z "@Override public void onCommand(@NotNull Player sender, @NotNull String commandLabel, @NotNull String[] cmdArg) { if (cmdArg.length < 1) { MsgUtil.sendMessage(sender, ""command.bulk-size-not-set""); return; } int amount; try { amount = Integer.parseInt(cmdArg[0]); } catch (NumberFormatException e) { MsgUtil.sendMessage(sender, ""not-a-integer"", cmdArg[0]); return; } final BlockIterator bIt = new BlockIterator(sender, 10); // Loop through every block they're looking at upto 10 blocks away if (!bIt.hasNext()) { MsgUtil.sendMessage(sender, ""not-looking-at-shop""); return; } while (bIt.hasNext()) { final Block b = bIt.next(); final Shop shop = plugin.getShopManager().getShop(b.getLocation()); if (shop != null) { if (shop.getModerator().isModerator(sender.getUniqueId()) || sender.hasPermission(""quickshop.other.amount"")) { if (amount <= 0 || amount > Util.getItemMaxStackSize(shop.getItem().getType())) { MsgUtil.sendMessage(sender, ""command.invalid-bulk-amount"", Integer.toString(amount)); return; } shop.getItem().setAmount(amount); shop.refresh(); MsgUtil.sendMessage(sender, ""command.bulk-size-now"", Integer.toString(shop.getItem().getAmount()), Util.getItemStackName(shop.getItem())); return; } else { MsgUtil.sendMessage(sender, ""not-managed-shop""); } } } MsgUtil.sendMessage(sender, ""not-looking-at-shop""); }","@Override public void onCommand(@NotNull Player sender, @NotNull String commandLabel, @NotNull String[] cmdArg) { if (cmdArg.length < 1) { MsgUtil.sendMessage(sender, ""command.bulk-size-not-set""); return; } int amount; try { amount = Integer.parseInt(cmdArg[0]); } catch (NumberFormatException e) { MsgUtil.sendMessage(sender, ""not-a-integer"", cmdArg[0]); return; } final BlockIterator bIt = new BlockIterator(sender, 10); // Loop through every block they're looking at upto 10 blocks away if (!bIt.hasNext()) { MsgUtil.sendMessage(sender, ""not-looking-at-shop""); return; } while (bIt.hasNext()) { final Block b = bIt.next(); final Shop shop = plugin.getShopManager().getShop(b.getLocation()); if (shop != null) { if (shop.getModerator().isModerator(sender.getUniqueId()) || sender.hasPermission(""quickshop.other.amount"")) { if (amount <= 0 || amount > Util.getItemMaxStackSize(shop.getItem().getType())) { MsgUtil.sendMessage(sender, ""command.invalid-bulk-amount"", Integer.toString(amount)); return; } ItemStack pendingItemStack = shop.getItem().clone(); pendingItemStack.setAmount(amount); PriceLimiter limiter = new PriceLimiter( plugin.getConfig().getDouble(""shop.minimum-price""), plugin.getConfig().getInt(""shop.maximum-price""), plugin.getConfig().getBoolean(""shop.allow-free-shop""), plugin.getConfig().getBoolean(""whole-number-prices-only"")); PriceLimiter.CheckResult checkResult = limiter.check(pendingItemStack, shop.getPrice()); if (checkResult.getStatus() != PriceLimiter.Status.PASS) { MsgUtil.sendMessage(sender, ""restricted-prices"", Util.getItemStackName(shop.getItem()), String.valueOf(checkResult.getMin()), String.valueOf(checkResult.getMax())); return; } shop.setItem(pendingItemStack); MsgUtil.sendMessage(sender, ""command.bulk-size-now"", Integer.toString(shop.getItem().getAmount()), Util.getItemStackName(shop.getItem())); return; } else { MsgUtil.sendMessage(sender, ""not-managed-shop""); } } } MsgUtil.sendMessage(sender, ""not-looking-at-shop""); }",Fix size command bypassing price,https://github.com/Ghost-chu/QuickShop-Hikari/commit/f443721169b72db5f721191df0ba421614035d7c,,,src/main/java/org/maxgamer/quickshop/command/subcommand/SubCommand_Size.java,3,java,False,2021-08-26T02:23:22Z "private void writeHiddenInputs(StringBuilder buf, HttpServletRequest req, String action) { buf.append(""\n""); String peerParam = req.getParameter(""p""); if (peerParam != null) { buf.append(""\n""); } String stParam = req.getParameter(""st""); if (stParam != null) { buf.append(""\n""); } String soParam = req.getParameter(""sort""); if (soParam != null) { buf.append(""\n""); } if (action != null) { buf.append(""\n""); } else { // for buttons, keep the search term String sParam = req.getParameter(""s""); if (sParam != null) { buf.append(""\n""); } } }","private void writeHiddenInputs(StringBuilder buf, HttpServletRequest req, String action) { buf.append(""\n""); String peerParam = req.getParameter(""p""); if (peerParam != null) { buf.append(""\n""); } String stParam = req.getParameter(""st""); if (stParam != null) { buf.append(""\n""); } String soParam = req.getParameter(""sort""); if (soParam != null) { buf.append(""\n""); } if (action != null) { buf.append(""\n""); } else { // for buttons, keep the search term String sParam = req.getParameter(""nf_s""); if (sParam != null) { buf.append(""\n""); } } }","i2psnark: Rename search param to bypass the XSS filter Fix encode/decode search param Copy CSS to non-default themes, not tweaked yet Add support for shorter nf_ prefix to XSS filter Remove unneeded float_right, reported by drzed",https://github.com/i2p/i2p.i2p/commit/0cbbe6297e2f2079fcb33b7b1da23b94c8f83f4f,,,apps/i2psnark/java/src/org/klomp/snark/web/I2PSnarkServlet.java,3,java,False,2023-01-18T17:21:29Z "private void extractAndStoreEventCheckins(SubmissionPayload submissionPayload) { try { List checkins = checkinsDataFilter.filter(submissionPayload.getCheckInsList()); traceTimeIntervalWarningSevice.saveCheckinData(checkins); } catch (final Exception e) { // Any check-in data processing related error must not interrupt the submission flow or interfere // with storing of the diagnosis keys logger.error(""An error has occured while trying to store the event checkin data"", e); } }","private void extractAndStoreEventCheckins(SubmissionPayload submissionPayload) { try { List checkins = checkinsDataFilter.filter(submissionPayload.getCheckInsList()); traceTimeIntervalWarningSevice.saveCheckinsWithFakeData(checkins, submissionServiceConfig.getRandomCheckinsPaddingMultiplier(), submissionServiceConfig.getRandomCheckinsPaddingPepperAsByteArray()); } catch (final Exception e) { // Any check-in data processing related error must not interrupt the submission flow or interfere // with storing of the diagnosis keys logger.error(""An error has occured while trying to store the event checkin data"", e); } }","Random checkin data padding during submission (#1302) * Add @Component annotation for TraceTimeIntervalWarningsPackageBundler (#1292) * Create V13__createPermissionsForEventRegistrationDistribution.sql (#1295) * Create V13__createPermissionsForEventRegistrationDistribution.sql * Update V13__createPermissionsForEventRegistrationDistribution.sql * Add random checkins multiplier config * Implement the fake checkins generation flow at the service level * Generate fake checkins during submission based on configurable multiplier * Resolve security vulnerability and add test coverage * Sonar fix * Switch implementations for interval generation * fix: use hash for inserting trace time intervals * PR feedback changes * invalidCheckinData --> validCheckinData * fix: add additional test for contract between server and client regarding hashing Co-authored-by: ioangut <67064882+ioangut@users.noreply.github.com> Co-authored-by: FelixRottler Co-authored-by: Pit Humke Co-authored-by: FelixRottler <72494737+FelixRottler@users.noreply.github.com>",https://github.com/corona-warn-app/cwa-server/commit/455103b17e18d6de18c45f848fa86799658aa192,,,services/submission/src/main/java/app/coronawarn/server/services/submission/controller/SubmissionController.java,3,java,False,2021-04-06T16:53:54Z "public void sensitiveWallfilter(String name, String[] values,AttackContext attackContext) { String[] wallfilterrules = this.getSensitiveFilterrules(); if (wallfilterrules == null || wallfilterrules.length == 0 || values == null || values.length == 0 || isSensitiveWhilename(name)) return; int j = 0; for (String value : values) { if (value == null || value.equals("""")) { j++; continue; } for (int i = 0; i < wallfilterrules.length; i++) { if (value.indexOf(wallfilterrules[i]) >= 0) { attackContext.setParamName(name); attackContext.setValues(values); attackContext.setPosition(j); attackContext.setAttackRule(wallfilterrules[i]); attackFielterPolicy.attackHandle(attackContext); break; } } j++; } }","public void sensitiveWallfilter(String name, String[] values,AttackContext attackContext) { if(attackFielterPolicy.isDisable()){ return; } String[] wallfilterrules = this.getSensitiveFilterrules(); if (wallfilterrules == null || wallfilterrules.length == 0 || values == null || values.length == 0 || isSensitiveWhilename(name)) return; int j = 0; for (String value : values) { if (value == null || value.equals("""")) { j++; continue; } for (int i = 0; i < wallfilterrules.length; i++) { if (value.indexOf(wallfilterrules[i]) >= 0) { attackContext.setParamName(name); attackContext.setValues(values); attackContext.setPosition(j); attackContext.setAttackRule(wallfilterrules[i]); attackContext.setAttackType(AttackContext.SENSITIVE_ATTACK); attackFielterPolicy.attackHandle(attackContext); break; } } j++; } }","xss和敏感词攻击过滤功能添加 作业启停功能完善",https://github.com/bbossgroups/bboss/commit/c581475ddcb4548aeb168ac05711c911d80042cb,,,bboss-util/src/org/frameworkset/util/ReferHelper.java,3,java,False,2021-12-02T06:13:40Z "private void handleUserStateDetails(UserStateDetails userStateDetails, io.literal.lib.Callback callback) { if (userStateDetails.getUserState().equals(UserState.SIGNED_IN)) { String identityId = AuthenticationRepository.getIdentityId(); final String[] username = new String[1]; final Map[] userAttributes = new Map[1]; final Tokens[] tokens = new Tokens[1]; ManyCallback manyCallback = new ManyCallback<>(3, (e, _void) -> { String aliasedUsername = username[0] != null && userAttributes[0] != null ? username[0].startsWith(""Google"") ? username[0] : userAttributes[0].get(""sub"") : null; User inst = new User( userStateDetails.getUserState(), tokens[0], aliasedUsername, identityId, userAttributes[0] ); user.postValue(inst); callback.invoke(e, inst); }); AuthenticationRepository.getUsername((e, data) -> { username[0] = data; manyCallback.getCallback(0).invoke(null, true); }); AuthenticationRepository.getUserAttributes((e, data) -> { userAttributes[0] = data; manyCallback.getCallback(1).invoke(null, true); }); AuthenticationRepository.getTokens((e, data) -> { tokens[0] = data; manyCallback.getCallback(2).invoke(null, true); }); } else { User inst = new User(userStateDetails.getUserState()); user.postValue(inst); callback.invoke(null, inst); } }","private void handleUserStateDetails(UserStateDetails userStateDetails, io.literal.lib.Callback callback) { if (userStateDetails.getUserState().equals(UserState.SIGNED_IN)) { Box didReceiveSignedOutState = new Box(false); UserStateListener userStateListener = new UserStateListener() { @Override public void onUserStateChanged(UserStateDetails details) { if (details.getUserState().equals(UserState.SIGNED_OUT_FEDERATED_TOKENS_INVALID) || details.getUserState().equals(UserState.SIGNED_OUT_USER_POOLS_TOKENS_INVALID) || details.getUserState().equals(UserState.SIGNED_OUT)) { didReceiveSignedOutState.set(true); User inst = new User(details.getUserState()); user.postValue(inst); callback.invoke(null, inst); AWSMobileClient.getInstance().releaseSignInWait(); AWSMobileClient.getInstance().removeUserStateListener(this); } } }; AWSMobileClient.getInstance().addUserStateListener(userStateListener); String identityId = AuthenticationRepository.getIdentityId(); final String[] username = new String[1]; final Map[] userAttributes = new Map[1]; final Tokens[] tokens = new Tokens[1]; ManyCallback manyCallback = new ManyCallback<>(3, (e, _void) -> { AWSMobileClient.getInstance().removeUserStateListener(userStateListener); if (didReceiveSignedOutState.get()) { // userStateListener already received invalidation state return; } String aliasedUsername = username[0] != null && userAttributes[0] != null ? username[0].startsWith(""Google"") ? username[0] : userAttributes[0].get(""sub"") : null; User inst = new User( userStateDetails.getUserState(), tokens[0], aliasedUsername, identityId, userAttributes[0] ); user.postValue(inst); callback.invoke(e, inst); }); AuthenticationRepository.getUsername((e, data) -> { username[0] = data; manyCallback.getCallback(0).invoke(null, true); }); AuthenticationRepository.getUserAttributes((e, data) -> { userAttributes[0] = data; manyCallback.getCallback(1).invoke(null, true); }); AuthenticationRepository.getTokens((e, data) -> { tokens[0] = data; manyCallback.getCallback(2).invoke(null, true); }); } else { User inst = new User(userStateDetails.getUserState()); user.postValue(inst); callback.invoke(null, inst); } }",fix: handle user authentication state transitions during user initialization,https://github.com/literal-io/literal/commit/42fbd450fc1199e5237406f2a37fb3e72c999130,,,packages/android/app/src/main/java/io/literal/viewmodel/AuthenticationViewModel.java,3,java,False,2021-04-26T12:40:50Z "@Override public RedisResponse executeCommand(Command command, ExecutionHandlerContext context) { SecurityService securityService = context.getSecurityService(); // We're deviating from Redis here in that any AUTH requests, without security explicitly // set up, will fail. if (!securityService.isIntegratedSecurity()) { return RedisResponse.error(ERROR_AUTH_CALLED_WITHOUT_SECURITY_CONFIGURED); } Properties props = getSecurityProperties(command, context); try { Subject subject = securityService.login(props); context.setSubject(subject); } catch (AuthenticationFailedException | AuthenticationExpiredException ex) { return RedisResponse.wrongpass(ERROR_INVALID_USERNAME_OR_PASSWORD); } return RedisResponse.ok(); }","@Override public RedisResponse executeCommand(Command command, ExecutionHandlerContext context) { // We're deviating from Redis here in that any AUTH requests, without security explicitly // set up, will fail. if (!context.isSecurityEnabled()) { return RedisResponse.error(ERROR_AUTH_CALLED_WITHOUT_SECURITY_CONFIGURED); } Properties props = getSecurityProperties(command, context); try { context.login(props); } catch (AuthenticationFailedException | AuthenticationExpiredException ex) { return RedisResponse.wrongpass(ERROR_INVALID_USERNAME_OR_PASSWORD); } return RedisResponse.ok(); }","GEODE-9676: Limit array and string sizes for unauthenticated Radish connections (#6994) - This applies the same fix as introduced by CVE-2021-32675 for Redis. When security is enabled, unuauthenticated requests limit the size of arrays and bulk strings to 10 and 16384 respectively. Once connections are authenticated, the size restriction is not applied. - When security is not enabled, this restriction does not apply. - Re-enable the relevant Redis TCL test.",https://github.com/apache/geode/commit/4398bec6eac70ee7bfa3b296655a8326543fc3b7,,,geode-for-redis/src/main/java/org/apache/geode/redis/internal/executor/connection/AuthExecutor.java,3,java,False,2021-10-19T15:29:54Z "@Override @Transactional(rollbackFor = Exception.class) public Result onlineCreateResource(User loginUser, ResourceType type, String fileName, String fileSuffix, String desc, String content,int pid,String currentDir) { Result result = checkResourceUploadStartupState(); if (!result.getCode().equals(Status.SUCCESS.getCode())) { return result; } //check file suffix String nameSuffix = fileSuffix.trim(); String resourceViewSuffixs = FileUtils.getResourceViewSuffixs(); if (StringUtils.isNotEmpty(resourceViewSuffixs)) { List strList = Arrays.asList(resourceViewSuffixs.split("","")); if (!strList.contains(nameSuffix)) { logger.error(""resource suffix {} not support create"", nameSuffix); putMsg(result, Status.RESOURCE_SUFFIX_NOT_SUPPORT_VIEW); return result; } } String name = fileName.trim() + ""."" + nameSuffix; String fullName = currentDir.equals(""/"") ? String.format(""%s%s"",currentDir,name) : String.format(""%s/%s"",currentDir,name); result = verifyResource(loginUser, type, fullName, pid); if (!result.getCode().equals(Status.SUCCESS.getCode())) { return result; } // save data Date now = new Date(); Resource resource = new Resource(pid,name,fullName,false,desc,name,loginUser.getId(),type,content.getBytes().length,now,now); resourcesMapper.insert(resource); updateParentResourceSize(resource, resource.getSize()); putMsg(result, Status.SUCCESS); Map dataMap = new BeanMap(resource); Map resultMap = new HashMap<>(); for (Map.Entry entry: dataMap.entrySet()) { if (!Constants.CLASS.equalsIgnoreCase(entry.getKey().toString())) { resultMap.put(entry.getKey().toString(), entry.getValue()); } } result.setData(resultMap); String tenantCode = tenantMapper.queryById(loginUser.getTenantId()).getTenantCode(); result = uploadContentToHdfs(fullName, tenantCode, content); if (!result.getCode().equals(Status.SUCCESS.getCode())) { throw new ServiceException(result.getMsg()); } return result; }","@Override @Transactional(rollbackFor = Exception.class) public Result onlineCreateResource(User loginUser, ResourceType type, String fileName, String fileSuffix, String desc, String content,int pid,String currentDir) { Result result = checkResourceUploadStartupState(); if (!result.getCode().equals(Status.SUCCESS.getCode())) { return result; } if (FileUtils.directoryTraversal(fileName)) { putMsg(result, Status.VERIFY_PARAMETER_NAME_FAILED); return result; } //check file suffix String nameSuffix = fileSuffix.trim(); String resourceViewSuffixs = FileUtils.getResourceViewSuffixs(); if (StringUtils.isNotEmpty(resourceViewSuffixs)) { List strList = Arrays.asList(resourceViewSuffixs.split("","")); if (!strList.contains(nameSuffix)) { logger.error(""resource suffix {} not support create"", nameSuffix); putMsg(result, Status.RESOURCE_SUFFIX_NOT_SUPPORT_VIEW); return result; } } String name = fileName.trim() + ""."" + nameSuffix; String fullName = currentDir.equals(""/"") ? String.format(""%s%s"",currentDir,name) : String.format(""%s/%s"",currentDir,name); result = verifyResource(loginUser, type, fullName, pid); if (!result.getCode().equals(Status.SUCCESS.getCode())) { return result; } // save data Date now = new Date(); Resource resource = new Resource(pid,name,fullName,false,desc,name,loginUser.getId(),type,content.getBytes().length,now,now); resourcesMapper.insert(resource); updateParentResourceSize(resource, resource.getSize()); putMsg(result, Status.SUCCESS); Map dataMap = new BeanMap(resource); Map resultMap = new HashMap<>(); for (Map.Entry entry: dataMap.entrySet()) { if (!Constants.CLASS.equalsIgnoreCase(entry.getKey().toString())) { resultMap.put(entry.getKey().toString(), entry.getValue()); } } result.setData(resultMap); String tenantCode = tenantMapper.queryById(loginUser.getTenantId()).getTenantCode(); result = uploadContentToHdfs(fullName, tenantCode, content); if (!result.getCode().equals(Status.SUCCESS.getCode())) { throw new ServiceException(result.getMsg()); } return result; }","[fix] Enhance name pre checker in resource center (#10094) (#10759) * [fix] Enhance name pre checker in resource center (#10094) * [fix] Enhance name pre checker in resource center Add file name and directory checker to avoid directory traversal * add some missing change and change docs * change var name in directoryTraversal * Fix ci (cherry picked from commit 63f835715f8ca8bff79c0e7177ebfa5917ebb3bd) * Add new constants",https://github.com/apache/dolphinscheduler/commit/23fae510dfdde1753e0a161f747c30ae5171fba1,,,dolphinscheduler-api/src/main/java/org/apache/dolphinscheduler/api/service/impl/ResourcesServiceImpl.java,3,java,False,2022-07-04T06:04:23Z "public static CompletableFuture lookupTopicAsync(PulsarService pulsarService, TopicName topicName, boolean authoritative, String clientAppId, AuthenticationDataSource authenticationData, long requestId, final String advertisedListenerName) { final CompletableFuture validationFuture = new CompletableFuture<>(); final CompletableFuture lookupfuture = new CompletableFuture<>(); final String cluster = topicName.getCluster(); // (1) validate cluster getClusterDataIfDifferentCluster(pulsarService, cluster, clientAppId).thenAccept(differentClusterData -> { if (differentClusterData != null) { if (log.isDebugEnabled()) { log.debug(""[{}] Redirecting the lookup call to {}/{} cluster={}"", clientAppId, differentClusterData.getBrokerServiceUrl(), differentClusterData.getBrokerServiceUrlTls(), cluster); } validationFuture.complete(newLookupResponse(differentClusterData.getBrokerServiceUrl(), differentClusterData.getBrokerServiceUrlTls(), true, LookupType.Redirect, requestId, false)); } else { // (2) authorize client try { checkAuthorization(pulsarService, topicName, clientAppId, authenticationData); } catch (RestException authException) { log.warn(""Failed to authorized {} on cluster {}"", clientAppId, topicName.toString()); validationFuture.complete(newLookupErrorResponse(ServerError.AuthorizationError, authException.getMessage(), requestId)); return; } catch (Exception e) { log.warn(""Unknown error while authorizing {} on cluster {}"", clientAppId, topicName.toString()); validationFuture.completeExceptionally(e); return; } // (3) validate global namespace checkLocalOrGetPeerReplicationCluster(pulsarService, topicName.getNamespaceObject()) .thenAccept(peerClusterData -> { if (peerClusterData == null) { // (4) all validation passed: initiate lookup validationFuture.complete(null); return; } // if peer-cluster-data is present it means namespace is owned by that peer-cluster and // request should be redirect to the peer-cluster if (StringUtils.isBlank(peerClusterData.getBrokerServiceUrl()) && StringUtils.isBlank(peerClusterData.getBrokerServiceUrlTls())) { validationFuture.complete(newLookupErrorResponse(ServerError.MetadataError, ""Redirected cluster's brokerService url is not configured"", requestId)); return; } validationFuture.complete(newLookupResponse(peerClusterData.getBrokerServiceUrl(), peerClusterData.getBrokerServiceUrlTls(), true, LookupType.Redirect, requestId, false)); }).exceptionally(ex -> { validationFuture.complete( newLookupErrorResponse(ServerError.MetadataError, ex.getMessage(), requestId)); return null; }); } }).exceptionally(ex -> { validationFuture.completeExceptionally(ex); return null; }); // Initiate lookup once validation completes validationFuture.thenAccept(validationFailureResponse -> { if (validationFailureResponse != null) { lookupfuture.complete(validationFailureResponse); } else { LookupOptions options = LookupOptions.builder() .authoritative(authoritative) .advertisedListenerName(advertisedListenerName) .loadTopicsInBundle(true) .build(); pulsarService.getNamespaceService().getBrokerServiceUrlAsync(topicName, options) .thenAccept(lookupResult -> { if (log.isDebugEnabled()) { log.debug(""[{}] Lookup result {}"", topicName.toString(), lookupResult); } if (!lookupResult.isPresent()) { lookupfuture.complete(newLookupErrorResponse(ServerError.ServiceNotReady, ""No broker was available to own "" + topicName, requestId)); return; } LookupData lookupData = lookupResult.get().getLookupData(); if (lookupResult.get().isRedirect()) { boolean newAuthoritative = lookupResult.get().isAuthoritativeRedirect(); lookupfuture.complete( newLookupResponse(lookupData.getBrokerUrl(), lookupData.getBrokerUrlTls(), newAuthoritative, LookupType.Redirect, requestId, false)); } else { ServiceConfiguration conf = pulsarService.getConfiguration(); lookupfuture.complete(newLookupResponse(lookupData.getBrokerUrl(), lookupData.getBrokerUrlTls(), true /* authoritative */, LookupType.Connect, requestId, shouldRedirectThroughServiceUrl(conf, lookupData))); } }).exceptionally(ex -> { if (ex instanceof CompletionException && ex.getCause() instanceof IllegalStateException) { log.info(""Failed to lookup {} for topic {} with error {}"", clientAppId, topicName.toString(), ex.getCause().getMessage()); } else { log.warn(""Failed to lookup {} for topic {} with error {}"", clientAppId, topicName.toString(), ex.getMessage(), ex); } lookupfuture.complete( newLookupErrorResponse(ServerError.ServiceNotReady, ex.getMessage(), requestId)); return null; }); } }).exceptionally(ex -> { if (ex instanceof CompletionException && ex.getCause() instanceof IllegalStateException) { log.info(""Failed to lookup {} for topic {} with error {}"", clientAppId, topicName.toString(), ex.getCause().getMessage()); } else { log.warn(""Failed to lookup {} for topic {} with error {}"", clientAppId, topicName.toString(), ex.getMessage(), ex); } lookupfuture.complete(newLookupErrorResponse(ServerError.ServiceNotReady, ex.getMessage(), requestId)); return null; }); return lookupfuture; }","public static CompletableFuture lookupTopicAsync(PulsarService pulsarService, TopicName topicName, boolean authoritative, String clientAppId, AuthenticationDataSource authenticationData, long requestId, final String advertisedListenerName) { final CompletableFuture validationFuture = new CompletableFuture<>(); final CompletableFuture lookupfuture = new CompletableFuture<>(); final String cluster = topicName.getCluster(); // (1) validate cluster getClusterDataIfDifferentCluster(pulsarService, cluster, clientAppId).thenAccept(differentClusterData -> { if (differentClusterData != null) { if (log.isDebugEnabled()) { log.debug(""[{}] Redirecting the lookup call to {}/{} cluster={}"", clientAppId, differentClusterData.getBrokerServiceUrl(), differentClusterData.getBrokerServiceUrlTls(), cluster); } validationFuture.complete(newLookupResponse(differentClusterData.getBrokerServiceUrl(), differentClusterData.getBrokerServiceUrlTls(), true, LookupType.Redirect, requestId, false)); } else { // (2) authorize client checkAuthorizationAsync(pulsarService, topicName, clientAppId, authenticationData).thenRun(() -> { // (3) validate global namespace checkLocalOrGetPeerReplicationCluster(pulsarService, topicName.getNamespaceObject()).thenAccept(peerClusterData -> { if (peerClusterData == null) { // (4) all validation passed: initiate lookup validationFuture.complete(null); return; } // if peer-cluster-data is present it means namespace is owned by that peer-cluster and // request should be redirect to the peer-cluster if (StringUtils.isBlank(peerClusterData.getBrokerServiceUrl()) && StringUtils.isBlank(peerClusterData.getBrokerServiceUrlTls())) { validationFuture.complete(newLookupErrorResponse(ServerError.MetadataError, ""Redirected cluster's brokerService url is not configured"", requestId)); return; } validationFuture.complete(newLookupResponse(peerClusterData.getBrokerServiceUrl(), peerClusterData.getBrokerServiceUrlTls(), true, LookupType.Redirect, requestId, false)); }).exceptionally(ex -> { validationFuture.complete( newLookupErrorResponse(ServerError.MetadataError, FutureUtil.unwrapCompletionException(ex).getMessage(), requestId)); return null; }); }) .exceptionally(e -> { Throwable throwable = FutureUtil.unwrapCompletionException(e); if (throwable instanceof RestException) { log.warn(""Failed to authorized {} on cluster {}"", clientAppId, topicName); validationFuture.complete(newLookupErrorResponse(ServerError.AuthorizationError, throwable.getMessage(), requestId)); } else { log.warn(""Unknown error while authorizing {} on cluster {}"", clientAppId, topicName); validationFuture.completeExceptionally(throwable); } return null; }); } }).exceptionally(ex -> { validationFuture.completeExceptionally(FutureUtil.unwrapCompletionException(ex)); return null; }); // Initiate lookup once validation completes validationFuture.thenAccept(validationFailureResponse -> { if (validationFailureResponse != null) { lookupfuture.complete(validationFailureResponse); } else { LookupOptions options = LookupOptions.builder() .authoritative(authoritative) .advertisedListenerName(advertisedListenerName) .loadTopicsInBundle(true) .build(); pulsarService.getNamespaceService().getBrokerServiceUrlAsync(topicName, options) .thenAccept(lookupResult -> { if (log.isDebugEnabled()) { log.debug(""[{}] Lookup result {}"", topicName.toString(), lookupResult); } if (!lookupResult.isPresent()) { lookupfuture.complete(newLookupErrorResponse(ServerError.ServiceNotReady, ""No broker was available to own "" + topicName, requestId)); return; } LookupData lookupData = lookupResult.get().getLookupData(); if (lookupResult.get().isRedirect()) { boolean newAuthoritative = lookupResult.get().isAuthoritativeRedirect(); lookupfuture.complete( newLookupResponse(lookupData.getBrokerUrl(), lookupData.getBrokerUrlTls(), newAuthoritative, LookupType.Redirect, requestId, false)); } else { ServiceConfiguration conf = pulsarService.getConfiguration(); lookupfuture.complete(newLookupResponse(lookupData.getBrokerUrl(), lookupData.getBrokerUrlTls(), true /* authoritative */, LookupType.Connect, requestId, shouldRedirectThroughServiceUrl(conf, lookupData))); } }).exceptionally(ex -> { if (ex instanceof CompletionException && ex.getCause() instanceof IllegalStateException) { log.info(""Failed to lookup {} for topic {} with error {}"", clientAppId, topicName.toString(), ex.getCause().getMessage()); } else { log.warn(""Failed to lookup {} for topic {} with error {}"", clientAppId, topicName.toString(), ex.getMessage(), ex); } lookupfuture.complete( newLookupErrorResponse(ServerError.ServiceNotReady, ex.getMessage(), requestId)); return null; }); } }).exceptionally(ex -> { if (ex instanceof CompletionException && ex.getCause() instanceof IllegalStateException) { log.info(""Failed to lookup {} for topic {} with error {}"", clientAppId, topicName.toString(), ex.getCause().getMessage()); } else { log.warn(""Failed to lookup {} for topic {} with error {}"", clientAppId, topicName.toString(), ex.getMessage(), ex); } lookupfuture.complete(newLookupErrorResponse(ServerError.ServiceNotReady, ex.getMessage(), requestId)); return null; }); return lookupfuture; }",[fix][security] Add timeout of sync methods and avoid call sync method for AuthoriationService (#15694),https://github.com/apache/pulsar/commit/6af365e36aed74e95ca6e088f453d9513094bb36,,,pulsar-broker/src/main/java/org/apache/pulsar/broker/lookup/TopicLookupBase.java,3,java,False,2022-06-09T01:06:28Z "private void free() { if (connection != null) { if(Log.isTraceEnabled()) { log(""Freeing"" ,""channel""); } } if (eventListeners != null) { eventListeners.clear(); } onChannelFree(); }","private void free() { if (connection != null) { if(Log.isTraceEnabled()) { log(""Freeing"" ,""channel""); } } if (eventListeners != null) { eventListeners.clear(); } IOUtils.closeStream(channelIn); this.channelIn = null; this.channelOut = null; if(Objects.nonNull(cache)) { cache.close(); } this.cache = null; onChannelFree(); }",HOTFIX: Additional logging to determine where a channel EOF comes from and clean up of cache buffer to help prevent OOM.,https://github.com/sshtools/maverick-synergy/commit/29e57f89c4eb06df5f33ad67a632aea8fc0f5d21,,,maverick-synergy-common/src/main/java/com/sshtools/synergy/ssh/ChannelNG.java,3,java,False,2022-08-24T11:34:14Z "private GitReaderApi buildGitLabApi(final String gitReaderUrlRoot) { return new ApiBuilder<>(GitReaderApi.class, gitReaderUrlRoot, null, DATA_FORMAT).build(); }","private GitReaderApi buildGitLabApi(final String gitReaderUrlRoot) { return new ApiBuilder<>(GitReaderApi.class, gitReaderUrlRoot, AUTHORIZATION, userJwtToken.toHeader(), DATA_FORMAT).build(); }","issue 1805 Git Reader auth (#1941) * issue 1805 health pod check, auth for gitreader service, auto fill system preference for gitreader when deploying with pipectl * issue 1805 change destenation of CP_API_JWT_PUB_KEY * issue 1805 fix checkstyle * issue 1805 refactor auth schema, using flask auth, other fixes regarding review",https://github.com/epam/cloud-pipeline/commit/49dfcc59a097d04b13396ec54bc9184f29e0d299,,,api/src/main/java/com/epam/pipeline/manager/git/GitReaderClient.java,3,java,False,2021-05-13T18:25:08Z "private void performInstall(final Uri uri, final CharSequence app_description, final @Nullable String base_pkg) { final boolean is_scheme_package = SCHEME_PACKAGE.equals(uri.getScheme()); if (is_scheme_package && base_pkg != null) throw new IllegalArgumentException(""Scheme \""package\"" could never be installed as split""); final Map input_streams = new LinkedHashMap<>(); final String stream_name = ""Island["" + mCallerPackage + ""]""; try { if (is_scheme_package) { final String pkg = uri.getSchemeSpecificPart(); ApplicationInfo info = Apps.of(this).getAppInfo(pkg); if (info == null && (info = getIntent().getParcelableExtra(InstallerExtras.EXTRA_APP_INFO)) == null) { Log.e(TAG, ""Cannot query app info for "" + pkg); finish(); // Do not fall-back to default package installer, since it will fail too. return; } // TODO: Reject forward-locked package input_streams.put(stream_name, new FileInputStream(info.publicSourceDir)); if (info.splitPublicSourceDirs != null) for (int i = 0, num_splits = info.splitPublicSourceDirs.length; i < num_splits; i ++) { final String split = info.splitPublicSourceDirs[i]; input_streams.put(SDK_INT >= O ? info.splitNames[i] : ""split"" + i, new FileInputStream(split)); } } else input_streams.put(stream_name, requireNonNull(getContentResolver().openInputStream(uri))); } catch(final IOException | RuntimeException e) { // SecurityException may be thrown by ContentResolver.openInputStream(). Log.w(TAG, ""Error opening "" + uri + "" for reading.\nTo launch Island app installer, "" + ""please ensure data URI is accessible by Island, either exposed by content provider or world-readable (on pre-N)"", e); fallbackToSystemPackageInstaller(""stream_error"", e); // Default system package installer may have privilege to access the content that we can't. for (final Map.Entry entry : input_streams.entrySet()) IoUtils.closeQuietly(entry.getValue()); return; } final PackageInstaller installer = getPackageManager().getPackageInstaller(); final SessionParams params = new SessionParams(base_pkg != null ? SessionParams.MODE_INHERIT_EXISTING : SessionParams.MODE_FULL_INSTALL); if (base_pkg != null) params.setAppPackageName(base_pkg); final int session_id; try { mSession = installer.openSession(session_id = installer.createSession(params)); for (final Map.Entry entry : input_streams.entrySet()) try (final OutputStream out = mSession.openWrite(entry.getKey(), 0, - 1)) { final byte[] buffer = new byte[STREAM_BUFFER_SIZE]; final InputStream input = entry.getValue(); int count; while ((count = input.read(buffer)) != - 1) out.write(buffer, 0, count); mSession.fsync(out); } } catch (final IOException | RuntimeException e) { Log.e(TAG, ""Error preparing installation"", e); fallbackToSystemPackageInstaller(""session"", e); return; } finally { for (final Map.Entry entry : input_streams.entrySet()) IoUtils.closeQuietly(entry.getValue()); } final Intent callback = new Intent(""INSTALL_STATUS"").setPackage(getPackageName()); registerReceiver(mStatusCallback, new IntentFilter(callback.getAction())); mResultNeeded = getIntent().getBooleanExtra(Intent.EXTRA_RETURN_RESULT, false); mSession.commit(PendingIntent.getBroadcast(this, session_id, callback, FLAG_UPDATE_CURRENT).getIntentSender()); final String progress_text = getString(mUpdateOrInstall == null ? R.string.progress_dialog_cloning : mUpdateOrInstall ? R.string.progress_dialog_updating : R.string.progress_dialog_installing, mCallerAppLabel.get(), app_description); try { mProgressDialog = Dialogs.buildProgress(this, progress_text).indeterminate().nonCancelable().start(); } catch (final WindowManager.BadTokenException ignored) {} // Activity may no longer visible. }","private void performInstall(final Uri uri, final CharSequence app_description, final @Nullable String base_pkg) { final boolean is_scheme_package = SCHEME_PACKAGE.equals(uri.getScheme()); if (is_scheme_package && base_pkg != null) throw new IllegalArgumentException(""Scheme \""package\"" could never be installed as split""); final Map input_streams = new LinkedHashMap<>(); final String stream_name = ""Island["" + mCallerPackage + ""]""; try { if (is_scheme_package) { final String pkg = uri.getSchemeSpecificPart(); ApplicationInfo info = Apps.of(this).getAppInfo(pkg); if (info == null && (info = getIntent().getParcelableExtra(InstallerExtras.EXTRA_APP_INFO)) == null) { Log.e(TAG, ""Cannot query app info for "" + pkg); finish(); // Do not fall-back to default package installer, since it will fail too. return; } // TODO: Reject forward-locked package input_streams.put(stream_name, new FileInputStream(info.publicSourceDir)); if (info.splitPublicSourceDirs != null) for (int i = 0, num_splits = info.splitPublicSourceDirs.length; i < num_splits; i ++) { final String split = info.splitPublicSourceDirs[i]; input_streams.put(SDK_INT >= O ? info.splitNames[i] : ""split"" + i, new FileInputStream(split)); } } else input_streams.put(stream_name, requireNonNull(getContentResolver().openInputStream(uri))); } catch(final IOException | RuntimeException e) { // SecurityException may be thrown by ContentResolver.openInputStream(). Log.w(TAG, ""Error opening "" + uri + "" for reading.\nTo launch Island app installer, "" + ""please ensure data URI is accessible by Island, either exposed by content provider or world-readable (on pre-N)"", e); fallbackToSystemPackageInstaller(""stream_error"", e); // Default system package installer may have privilege to access the content that we can't. for (final Map.Entry entry : input_streams.entrySet()) IoUtils.closeQuietly(entry.getValue()); return; } final PackageInstaller installer = getPackageManager().getPackageInstaller(); final SessionParams params = new SessionParams(base_pkg != null ? SessionParams.MODE_INHERIT_EXISTING : SessionParams.MODE_FULL_INSTALL); if (base_pkg != null) params.setAppPackageName(base_pkg); final int session_id; try { mSession = installer.openSession(session_id = installer.createSession(params)); for (final Map.Entry entry : input_streams.entrySet()) try (final OutputStream out = mSession.openWrite(entry.getKey(), 0, - 1)) { final byte[] buffer = new byte[STREAM_BUFFER_SIZE]; final InputStream input = entry.getValue(); int count; while ((count = input.read(buffer)) != - 1) out.write(buffer, 0, count); mSession.fsync(out); } } catch (final IOException | RuntimeException e) { Log.e(TAG, ""Error preparing installation"", e); fallbackToSystemPackageInstaller(""session"", e); return; } finally { for (final Map.Entry entry : input_streams.entrySet()) IoUtils.closeQuietly(entry.getValue()); } final Intent callback = new Intent(""INSTALL_STATUS"").setPackage(getPackageName()); registerReceiver(mStatusCallback, new IntentFilter(callback.getAction()), SELF_PERMISSION, null); mResultNeeded = getIntent().getBooleanExtra(Intent.EXTRA_RETURN_RESULT, false); mSession.commit(PendingIntent.getBroadcast(this, session_id, callback, FLAG_UPDATE_CURRENT).getIntentSender()); final String progress_text = getString(mUpdateOrInstall == null ? R.string.progress_dialog_cloning : mUpdateOrInstall ? R.string.progress_dialog_updating : R.string.progress_dialog_installing, mCallerAppLabel.get(), app_description); try { mProgressDialog = Dialogs.buildProgress(this, progress_text).indeterminate().nonCancelable().start(); } catch (final WindowManager.BadTokenException ignored) {} // Activity may no longer visible. }",FIX: Use permission to guard against potentially malicious broadcast during app install.,https://github.com/oasisfeng/island/commit/5ac174ee12827c8ebca32ce838cc3ec744178da9,,,installer/src/main/java/com/oasisfeng/island/installer/AppInstallerActivity.java,3,java,False,2021-02-10T03:24:21Z "@SubscribeEvent public void onJoinServer(WynncraftServerEvent.Login e) { if (WebManager.isAthenaOnline()) return; TextComponentString msg = new TextComponentString(""The Wynntils servers are currently down! You can still use Wynntils, but some features may not work. Our servers should be back soon.""); msg.getStyle().setColor(TextFormatting.RED); msg.getStyle().setBold(true); new Delay(() -> McIf.player().sendMessage(msg), 30); // delay so the player actually loads in }","@SubscribeEvent public void onJoinServer(WynncraftServerEvent.Login e) { if (WebManager.isAthenaOnline()) return; TextComponentString msg = new TextComponentString(""The Wynntils servers are currently down! You can still use Wynntils, but some features may not work. Our servers should be back soon.""); msg.getStyle().setColor(TextFormatting.RED); msg.getStyle().setBold(true); new Delay(() -> { if (McIf.player() != null) McIf.player().sendMessage(msg); }, 30); // delay so the player actually loads in }","Fix 14 issues found in ticket backlog (#502) * Fix IndexOutOfBoundsException in QuestBookListPage Signed-off-by: kristofbolyai * Fix crash if OverlayConfig.GameUpdate.INSTANCE.messageMaxLength is 1 Signed-off-by: kristofbolyai * Fix crash related to deleting chat tabs and ChatGUI not updating Signed-off-by: kristofbolyai * Fix crash related to deleting chat tabs and ChatGUI not updating Signed-off-by: kristofbolyai * Fix translation cache becoming null Signed-off-by: kristofbolyai * Fix objective parsing if player is in party Signed-off-by: kristofbolyai * Fix guild objective not being removed upon completion Signed-off-by: kristofbolyai * Fix race condition in ServerEvents Signed-off-by: kristofbolyai * Fix race condition in ClientEvents Signed-off-by: kristofbolyai * Fix NPE in ServerEvents Signed-off-by: kristofbolyai * Fix AreaDPS value not being correct Signed-off-by: kristofbolyai * Fix NPE in fix :) Signed-off-by: kristofbolyai * Fix quest dialogue spoofing Signed-off-by: kristofbolyai * Fix Keyholder related crash Signed-off-by: kristofbolyai * Fix totem tracking Signed-off-by: kristofbolyai * Dialogue Page gets updated correctly Signed-off-by: kristofbolyai * Register ChatGUI correctly Signed-off-by: kristofbolyai * Use MC's GameSettings to check for isKeyDown Signed-off-by: kristofbolyai * Make multi line if have braces Signed-off-by: kristofbolyai ",https://github.com/Wynntils/Wynntils/commit/c8f6effe187ff68f17bcff809d2bc440ec07128d,,,src/main/java/com/wynntils/modules/core/events/ServerEvents.java,3,java,False,2022-04-15T17:16:00Z "public void updatePackageVersionAndCallables(String ecosystem, String packageName, String version) { if(metadataUtility == null) setMetadataUtility(); setDbContext(ecosystem); var vulnerabilities = metadataUtility.getVulnerabilitiesForPurl(ecosystem, packageName, version, context); logger.info(""Found the following vulnerabilities for "" + packageName + "":"" + version + "": "" + vulnerabilities.toString()); vulnerabilities.forEach(vulnerabilityId -> { var jsonStatement = metadataUtility.getVulnerabilityStatement(vulnerabilityId, context); updatePackageVersionsAndCallables(gson.fromJson(jsonStatement, Vulnerability.class), vulnerabilityId); }); }","public void updatePackageVersionAndCallables(String ecosystem, String packageName, String version) { if(metadataUtility == null) setMetadataUtility(); setDbContext(ecosystem); var vulnerabilities = metadataUtility.getVulnerabilitiesForPurl(ecosystem, packageName, version, context); logger.info(""Found the following vulnerabilities for "" + packageName + "":"" + version + "": "" + vulnerabilities.toString()); vulnerabilities.forEach(vulnerabilityId -> { var jsonStatement = metadataUtility.getVulnerabilityStatement(vulnerabilityId, context); this.vulnerability = gson.fromJson(jsonStatement, Vulnerability.class); this.vulnerabilityId = vulnerabilityId; updatePackageVersionsAndCallables(getPurlsForPackage(vulnerability.getValidatedPurls(), packageName), version); }); }","Changed the vulnerability statements processor to only update specific package-versions if known.",https://github.com/fasten-project/fasten/commit/9c2c902980fe8cd610e21d9d963fd0f96ce887fd,,,analyzer/vulnerability-statements-processor/src/main/java/eu/fasten/analyzer/vulnerabilitystatementsprocessor/VulnerabilityStatementsProcessor.java,3,java,False,2021-11-28T21:02:40Z "@Override public void respawn(TabPlayer viewer) { viewer.sendCustomPacket(destroyPacket, TabConstants.PacketCategory.UNLIMITED_NAMETAGS_DESPAWN); Runnable spawn = () -> spawn(viewer); if (viewer.getVersion().getMinorVersion() == 8) { //1.8.0 client sided bug TAB.getInstance().getCPUManager().runTaskLater(50, manager, TabConstants.CpuUsageCategory.V1_8_0_BUG_COMPENSATION, spawn); } else { spawn.run(); } }","@Override public void respawn(TabPlayer viewer) { viewer.sendCustomPacket(destroyPacket, TabConstants.PacketCategory.UNLIMITED_NAMETAGS_DESPAWN); // 1.8.0 will not see entity that respawned in the same tick // creating new delayed task every time someone sneaks can be abused and cause OOM spawn(viewer); }",Unlimited Nametags - Do not delay respawn by 1 tick anymore to fix OOM,https://github.com/NEZNAMY/TAB/commit/79f4bdb86912d47a8cbfc580ecf0fdbf5a199005,,,bukkit/src/main/java/me/neznamy/tab/platforms/bukkit/features/unlimitedtags/BukkitArmorStand.java,3,java,False,2022-05-01T11:07:42Z "def static(path): """""" Create a page handler to serve static files. Disable authentication. """""" assert isinstance(path, str) assert os.path.exists(path), ""%r doesn't exists"" % path content_type = None if os.path.isfile(path): # Set content-type based on filename extension ext = """" i = path.rfind('.') if i != -1: ext = path[i:].lower() content_type = mimetypes.types_map.get(ext, None) # @UndefinedVariable @cherrypy.expose @cherrypy.tools.auth_form(on=False) @cherrypy.tools.sessions(on=False) def handler(*args, **kwargs): if cherrypy.request.method not in ('GET', 'HEAD'): return None filename = os.path.join(path, *args) assert filename.startswith(path) if not os.path.isfile(filename): return None return serve_file(filename, content_type) return handler","def static(path): """""" Create a page handler to serve static files. Disable authentication. """""" assert isinstance(path, str) assert os.path.exists(path), ""%r doesn't exists"" % path content_type = None if os.path.isfile(path): # Set content-type based on filename extension ext = """" i = path.rfind('.') if i != -1: ext = path[i:].lower() content_type = mimetypes.types_map.get(ext, None) # @UndefinedVariable @cherrypy.expose @cherrypy.tools.auth_form(on=False) @cherrypy.tools.sessions(on=False) @cherrypy.tools.secure_headers(on=False) def handler(*args, **kwargs): if cherrypy.request.method not in ('GET', 'HEAD'): return None filename = os.path.join(path, *args) assert filename.startswith(path) if not os.path.isfile(filename): return None return serve_file(filename, content_type) return handler","Add more secure headers: Cache-control, Referrer-Policy, X-Content-Type-Options, X-XSS-Protection",https://github.com/ikus060/rdiffweb/commit/2406780831618405a13113377a784f3102465f40,,,rdiffweb/controller/dispatch.py,3,py,False,2022-09-26T17:02:00Z "private void rebuildFormFieldParent(PdfDictionary field, PdfDictionary newField, PdfDocument toDocument) { if (newField.containsKey(PdfName.Parent)) { return; } PdfDictionary oldParent = field.getAsDictionary(PdfName.Parent); if (oldParent != null) { PdfDictionary newParent = oldParent.copyTo(toDocument, Arrays.asList(PdfName.P, PdfName.Kids, PdfName.Parent), false, NullCopyFilter.getInstance()); if (newParent.isFlushed()) { newParent = oldParent.copyTo(toDocument, Arrays.asList(PdfName.P, PdfName.Kids, PdfName.Parent), true, NullCopyFilter.getInstance()); } rebuildFormFieldParent(oldParent, newParent, toDocument); PdfArray kids = newParent.getAsArray(PdfName.Kids); if (kids == null) { // no kids are added here, since we do not know at this point which pages are to be copied, // hence we do not know which annotations we should copy newParent.put(PdfName.Kids, new PdfArray()); } newField.put(PdfName.Parent, newParent); } }","private void rebuildFormFieldParent(PdfDictionary field, PdfDictionary newField, PdfDocument toDocument) { if (newField.containsKey(PdfName.Parent)) { return; } PdfDictionary oldParent = field.getAsDictionary(PdfName.Parent); if (oldParent != null) { PdfDictionary newParent = oldParent.copyTo(toDocument, Arrays.asList(PdfName.P, PdfName.Kids, PdfName.Parent), false, NullCopyFilter.getInstance()); if (newParent.isFlushed()) { newParent = oldParent.copyTo(toDocument, Arrays.asList(PdfName.P, PdfName.Kids, PdfName.Parent), true, NullCopyFilter.getInstance()); } if (oldParent == oldParent.getAsDictionary(PdfName.Parent)) { return; } rebuildFormFieldParent(oldParent, newParent, toDocument); PdfArray kids = newParent.getAsArray(PdfName.Kids); if (kids == null) { // no kids are added here, since we do not know at this point which pages are to be copied, // hence we do not know which annotations we should copy newParent.put(PdfName.Kids, new PdfArray()); } newField.put(PdfName.Parent, newParent); } }","Fix stackoverflow exception during form field copying DEVSIX-7267",https://github.com/itext/itext-java/commit/fabfac0ac5bca5b91df3cf5559ebcd78d8b4d13a,,,kernel/src/main/java/com/itextpdf/kernel/pdf/PdfPage.java,3,java,False,2022-12-21T09:06:23Z "@Override public Lua newThread() { LuaInstances.Token token = instances.add(); long K = C.luaJ_newthread(L, token.id); Lua lua = newThread(K, token.id, this.mainThread); mainThread.addSubThread(lua); token.setter.accept(lua); return lua; }","@Override public Lua newThread() { checkStack(1); LuaInstances.Token token = instances.add(); long K = C.luaJ_newthread(L, token.id); Lua lua = newThread(K, token.id, this.mainThread); mainThread.addSubThread(lua); token.setter.accept(lua); return lua; }",Fixed Lua stack overflow: causing memory corruption,https://github.com/gudzpoz/luajava/commit/83505ac0aaba37ed1b6434677bd4fd681b391926,,,luajava/src/main/java/party/iroiro/luajava/AbstractLua.java,3,java,False,2022-06-27T15:20:47Z "public int getInt(int col) throws SQLException { DB db = getDatabase(); return db.column_int(stmt.pointer, markCol(col)); }","public int getInt(int col) throws SQLException { return stmt.pointer.safeRunInt((db, ptr) -> db.column_int(ptr, markCol(col))); }",Wrap Statement Pointers to prevent use after free race,https://github.com/xerial/sqlite-jdbc/commit/e1d282cb2887ef427c7ad93d4fe7dd05a6c11473,,,src/main/java/org/sqlite/jdbc3/JDBC3ResultSet.java,3,java,False,2022-07-29T03:54:01Z "public void close() { if (mNativeContext != 0) { mEndpoint = null; mConnection = null; native_close(); mCloseGuard.close(); } }","public void close() { synchronized (mLock) { if (mNativeContext != 0) { mEndpoint = null; mConnection = null; native_close(); mCloseGuard.close(); } } }","Add protections against queueing a UsbRequest when the underlying UsbDeviceConnection is closed. Bug: 204584366 Test: CTS Verifier: USB Accessory Test & USB Device Test Test: No HWASan use-after-free reports with a test app Change-Id: Ia3a9b10349efc0236b1539c81465f479cb32e02b",https://github.com/aosp-mirror/platform_frameworks_base/commit/1691b54b1fda4239249a3871d2c17ed1ec753061,,,core/java/android/hardware/usb/UsbRequest.java,3,java,False,2022-09-23T09:05:39Z "def log_request(handler): """"""log a bit more information about each request than tornado's default - move static file get success to debug-level (reduces noise) - get proxied IP instead of proxy IP - log referer for redirect and failed requests - log user-agent for failed requests """""" status = handler.get_status() request = handler.request try: logger = handler.log except AttributeError: logger = access_log if status < 300 or status == 304: # Successes (or 304 FOUND) are debug-level log_method = logger.debug elif status < 400: log_method = logger.info elif status < 500: log_method = logger.warning else: log_method = logger.error request_time = 1000.0 * handler.request.request_time() ns = dict( status=status, method=request.method, ip=request.remote_ip, uri=request.uri, request_time=request_time, ) msg = ""{status} {method} {uri} ({ip}) {request_time:.2f}ms"" if status >= 400: # log bad referers ns[""referer""] = request.headers.get(""Referer"", ""None"") msg = msg + "" referer={referer}"" if status >= 500 and status != 502: # log all headers if it caused an error log_method(json.dumps(dict(request.headers), indent=2)) log_method(msg.format(**ns)) prometheus_log_method(handler)","def log_request(handler): """"""log a bit more information about each request than tornado's default - move static file get success to debug-level (reduces noise) - get proxied IP instead of proxy IP - log referer for redirect and failed requests - log user-agent for failed requests """""" status = handler.get_status() request = handler.request try: logger = handler.log except AttributeError: logger = access_log if status < 300 or status == 304: # Successes (or 304 FOUND) are debug-level log_method = logger.debug elif status < 400: log_method = logger.info elif status < 500: log_method = logger.warning else: log_method = logger.error request_time = 1000.0 * handler.request.request_time() ns = dict( status=status, method=request.method, ip=request.remote_ip, uri=request.uri, request_time=request_time, ) msg = ""{status} {method} {uri} ({ip}) {request_time:.2f}ms"" if status >= 400: # log bad referers ns[""referer""] = request.headers.get(""Referer"", ""None"") msg = msg + "" referer={referer}"" if status >= 500 and status != 502: # Log a subset of the headers if it caused an error. headers = {} for header in ['Host', 'Accept', 'Referer', 'User-Agent']: if header in request.headers: headers[header] = request.headers[header] log_method(json.dumps(headers, indent=2)) log_method(msg.format(**ns)) prometheus_log_method(handler)",Merge pull request from GHSA-p737-p57g-4cpr,https://github.com/jupyter-server/jupyter_server/commit/a5683aca0b0e412672ac6218d09f74d44ca0de5a,,,jupyter_server/log.py,3,py,False,2022-03-15T15:34:29Z "public static void destroyAreaLightning(World world, BlockPos center, EntityDragonBase destroyer) { if (MinecraftForge.EVENT_BUS.post(new DragonFireDamageWorldEvent(destroyer, center.getX(), center.getY(), center.getZ()))) return; int stage = destroyer.getDragonStage(); double damageRadius = 3.5D; float dmgScale = (float) IafConfig.dragonAttackDamageLightning; if (stage <= 3) { BlockPos.getAllInBox(center.add(-1, -1, -1), center.add(1, 1, 1)).forEach(pos -> { if (world.getTileEntity(pos) instanceof TileEntityDragonforgeInput) { ((TileEntityDragonforgeInput) world.getTileEntity(pos)).onHitWithFlame(); } if (IafConfig.dragonGriefing != 2 && world.rand.nextBoolean()) { if (!(world.getBlockState(pos).getBlock() instanceof IDragonProof) && DragonUtils.canDragonBreak(world.getBlockState(pos).getBlock())) { BlockState transformState = transformBlockLightning(world.getBlockState(pos)); if(transformState.getBlock() != world.getBlockState(pos).getBlock()){ world.setBlockState(pos, transformState); } } } }); } else { int radius = stage == 4 ? 2 : 3; int j = radius + world.rand.nextInt(1); int k = radius + world.rand.nextInt(1); int l = radius + world.rand.nextInt(1); float f = (float) (j + k + l) * 0.333F + 0.5F; final float ff = f * f; final double ffDouble = (double) ff; damageRadius = 2.5F + f * 1.2F; BlockPos.getAllInBox(center.add(-j, -k, -l), center.add(j, k, l)).forEach(blockpos -> { if (world.getTileEntity(blockpos) instanceof TileEntityDragonforgeInput) { ((TileEntityDragonforgeInput) world.getTileEntity(blockpos)).onHitWithFlame(); } if (blockpos.distanceSq(center) <= ffDouble) { if (IafConfig.dragonGriefing != 2 && world.rand.nextFloat() > (float) blockpos.distanceSq(center) / ff) { if (!(world.getBlockState(blockpos).getBlock() instanceof IDragonProof) && DragonUtils.canDragonBreak(world.getBlockState(blockpos).getBlock())) { BlockState transformState = transformBlockLightning(world.getBlockState(blockpos)); world.setBlockState(blockpos, transformState); } } } }); } final float stageDmg = stage * dmgScale; world.getEntitiesWithinAABB( LivingEntity.class, new AxisAlignedBB( (double) center.getX() - damageRadius, (double) center.getY() - damageRadius, (double) center.getZ() - damageRadius, (double) center.getX() + damageRadius, (double) center.getY() + damageRadius, (double) center.getZ() + damageRadius ) ).stream().forEach(livingEntity -> { if (!DragonUtils.onSameTeam(destroyer, livingEntity) && !destroyer.isEntityEqual(livingEntity) && destroyer.canEntityBeSeen(livingEntity)) { livingEntity.attackEntityFrom(IafDamageRegistry.DRAGON_LIGHTNING, stageDmg); double d1 = destroyer.getPosX() - livingEntity.getPosX(); double d0 = destroyer.getPosZ() - livingEntity.getPosZ(); livingEntity.applyKnockback(0.3F, d1, d0); } }); }","public static void destroyAreaLightning(World world, BlockPos center, EntityDragonBase destroyer) { if (MinecraftForge.EVENT_BUS.post(new DragonFireDamageWorldEvent(destroyer, center.getX(), center.getY(), center.getZ()))) return; Entity cause = destroyer.getRidingPlayer() != null ? destroyer.getRidingPlayer() : destroyer; DamageSource source = IafDamageRegistry.causeDragonLightningDamage(cause); int stage = destroyer.getDragonStage(); double damageRadius = 3.5D; float dmgScale = (float) IafConfig.dragonAttackDamageLightning; if (stage <= 3) { BlockPos.getAllInBox(center.add(-1, -1, -1), center.add(1, 1, 1)).forEach(pos -> { if (world.getTileEntity(pos) instanceof TileEntityDragonforgeInput) { ((TileEntityDragonforgeInput) world.getTileEntity(pos)).onHitWithFlame(); return; } if (IafConfig.dragonGriefing != 2 && world.rand.nextBoolean()) { lightningAttackBlock(world, pos); } }); } else { int radius = stage == 4 ? 2 : 3; int j = radius + world.rand.nextInt(1); int k = radius + world.rand.nextInt(1); int l = radius + world.rand.nextInt(1); float f = (float) (j + k + l) * 0.333F + 0.5F; final float ff = f * f; damageRadius = 2.5F + f * 1.2F; BlockPos.getAllInBox(center.add(-j, -k, -l), center.add(j, k, l)).forEach(pos -> { if (world.getTileEntity(pos) instanceof TileEntityDragonforgeInput) { ((TileEntityDragonforgeInput) world.getTileEntity(pos)).onHitWithFlame(); return; } if (center.distanceSq(pos) <= ff) { if (IafConfig.dragonGriefing != 2 && world.rand.nextFloat() > (float) center.distanceSq(pos) / ff) { lightningAttackBlock(world, pos); } } }); } final float stageDmg = stage * dmgScale; world.getEntitiesWithinAABB( LivingEntity.class, new AxisAlignedBB( (double) center.getX() - damageRadius, (double) center.getY() - damageRadius, (double) center.getZ() - damageRadius, (double) center.getX() + damageRadius, (double) center.getY() + damageRadius, (double) center.getZ() + damageRadius ) ).stream().forEach(livingEntity -> { if (!DragonUtils.onSameTeam(destroyer, livingEntity) && !destroyer.isEntityEqual(livingEntity) && destroyer.canEntityBeSeen(livingEntity)) { livingEntity.attackEntityFrom(source, stageDmg); double d1 = destroyer.getPosX() - livingEntity.getPosX(); double d0 = destroyer.getPosZ() - livingEntity.getPosZ(); livingEntity.applyKnockback(0.3F, d1, d0); } }); }","Updated IafDamageRegistry to use EntityDamageSource. - Attacking someone while riding a dragon now identifies the rider as the source of the damage/attack Cleaned up code related to entity charge attacks. - The various dragon charges now all inherit from the same abstract class - Charge attacks now no longer raytrace twice - Removed duplicate code Cleaned up and improved code regarding dragons breath attacks Dragons don't break blocks anymore that they shouldn't. Fixes #4475",https://github.com/AlexModGuy/Ice_and_Fire/commit/3c52775ad166dd8ee77da768881444db1b89512a,,,src/main/java/com/github/alexthe666/iceandfire/entity/IafDragonDestructionManager.java,3,java,False,2022-05-10T16:42:49Z "@EventHandler(ignoreCancelled = true) public void onPistonExtend(BlockPistonExtendEvent event) { Block piston = event.getBlock(); Block block = piston.getRelative(event.getDirection()); // See if this block is going to get pushed or broken or what PistonMoveReaction reaction = block.getPistonMoveReaction(); if (reaction == PistonMoveReaction.BLOCK) { return; } UndoList undoList = controller.getPendingUndo(block.getLocation()); if (undoList == null) { undoList = controller.getPendingUndo(piston.getLocation()); } if (undoList != null) { // This block stores the state of the piston, maybe undoList.add(piston); // We need to store the final air block since we'll be pushing a block into that // But after that, we can quit final int MAX_BLOCKS = 14; while (block != null) { block = handleMovedBlock(undoList, block, event.getDirection(), reaction, MAX_BLOCKS); // Determine the reaction for the new block type if (block != null) { reaction = block.getPistonMoveReaction(); } } } }","@EventHandler(ignoreCancelled = true) public void onPistonExtend(BlockPistonExtendEvent event) { Block piston = event.getBlock(); Block block = piston.getRelative(event.getDirection()); // See if this block is going to get pushed or broken or what PistonMoveReaction reaction = block.getPistonMoveReaction(); // Ignore blocked moves if (reaction == PistonMoveReaction.BLOCK) { return; } UndoList undoList = controller.getPendingUndo(block.getLocation()); if (undoList == null) { undoList = controller.getPendingUndo(piston.getLocation()); } // If either the block or the piston is magical, mark the piston for undo if (undoList != null) { undoList.add(piston); } // Determine how many blocks ahead we may need to look, minecraft will move up to 13 // blocks by default. // TODO: Can we get this number programatically from somewhere? // We need to store the final air block since we'll be pushing a block into that // But after that, we can quit final int MAX_BLOCKS = 14; // Look ahead to see if any part of the blocks moving in this chain have been modified magically while (block != null) { block = handleMovedBlock(undoList, block, event.getDirection(), reaction, MAX_BLOCKS); // If we n eed to keep looking, update state given new target block if (block != null) { // Determine the reaction for the new block type reaction = block.getPistonMoveReaction(); // Look for new modification source UndoList newUndo = controller.getPendingUndo(block.getLocation()); if (newUndo != null) { undoList = newUndo; } } } }","Walk through all changed blocks in a chain .. this fixed yet another exploit, but causes us to lose blocks. Committing this for now since it does fix the exploit, still needs work though and I'm going to try some other things.",https://github.com/elBukkit/MagicPlugin/commit/a4554df73e1df27753fc71bfde1a84829c2bf7f0,,,Magic/src/main/java/com/elmakers/mine/bukkit/magic/listener/BlockController.java,3,java,False,2021-10-04T21:50:32Z "public RspDownload getSolcFile(String fileNameParam) { // format filename end with js String fileName = formatFileName(fileNameParam); checkSolcInfoExist(fileName); File solcDir = getSolcDir(); try { String solcLocate = solcDir.getAbsolutePath() + File.separator + fileName; File file = new File(solcLocate); InputStream targetStream = Files.newInputStream(Paths.get(file.getPath())); return new RspDownload(fileName, targetStream); } catch (FileNotFoundException e) { log.error(""getSolcFile: file not found:{}, e:{}"", fileName, e.getMessage()); throw new FrontException(ConstantCode.READ_SOLC_FILE_ERROR); } catch (IOException e) { log.error(""getSolcFile: file not found:{}"", e.getMessage()); throw new FrontException(ConstantCode.READ_SOLC_FILE_ERROR); } }","public RspDownload getSolcFile(String fileNameParam) { // format filename end with js String fileName = formatFileName(fileNameParam); checkSolcInfoExist(fileName); File solcDir = getSolcDir(); try { String solcLocate = solcDir.getAbsolutePath() + File.separator + fileName; File file = new File(CleanPathUtil.cleanString(solcLocate)); InputStream targetStream = Files.newInputStream(Paths.get(CleanPathUtil.cleanString(file.getPath()))); return new RspDownload(fileName, targetStream); } catch (FileNotFoundException e) { log.error(""getSolcFile: file not found:{}, e:{}"", fileName, e.getMessage()); throw new FrontException(ConstantCode.READ_SOLC_FILE_ERROR); } catch (IOException e) { log.error(""getSolcFile: file not found:{}"", e.getMessage()); throw new FrontException(ConstantCode.READ_SOLC_FILE_ERROR); } }",fix security scan,https://github.com/WeBankBlockchain/WeBASE-Front/commit/7c14dcde8af19c79357bfb337e00c948fe62d673,,,src/main/java/com/webank/webase/front/solc/SolcService.java,3,java,False,2021-04-01T09:17:57Z "public static void destroyAreaLightningCharge(World world, BlockPos center, EntityDragonBase destroyer) { if (destroyer != null) { if (MinecraftForge.EVENT_BUS.post(new DragonFireDamageWorldEvent(destroyer, center.getX(), center.getY(), center.getZ()))) return; int stage = destroyer.getDragonStage(); int j = 2; int k = 2; int l = 2; if (stage <= 3) { BlockPos.getAllInBox(center.add(-j, -k, -l), center.add(j, k, l)).forEach(pos -> { if (world.rand.nextFloat() * 7F > Math.sqrt(center.distanceSq(pos)) && !(world.getBlockState(pos).getBlock() instanceof IDragonProof) && DragonUtils.canDragonBreak(world.getBlockState(pos).getBlock())) { world.setBlockState(pos, Blocks.AIR.getDefaultState()); } }); BlockPos.getAllInBox(center.add(-j, -k, -l), center.add(j, k, l)).forEach(pos -> { if (world.rand.nextFloat() * 7F > Math.sqrt(center.distanceSq(pos)) && !(world.getBlockState(pos).getBlock() instanceof IDragonProof) && DragonUtils.canDragonBreak(world.getBlockState(pos).getBlock())) { BlockState transformState = transformBlockLightning(world.getBlockState(pos)); world.setBlockState(pos, transformState); } }); } else { int radius = stage == 4 ? 2 : 3; j = radius + world.rand.nextInt(2); k = radius + world.rand.nextInt(2); l = radius + world.rand.nextInt(2); float f = (float) (j + k + l) * 0.333F + 0.5F; final float ff = f * f; final double ffDouble = (double) ff; BlockPos.getAllInBox(center.add(-j, -k, -l), center.add(j, k, l)).forEach(blockpos -> { if (blockpos.distanceSq(center) <= ffDouble) { if (world.rand.nextFloat() * 3 > (float) blockpos.distanceSq(center) / ff && !(world.getBlockState(blockpos).getBlock() instanceof IDragonProof) && DragonUtils.canDragonBreak(world.getBlockState(blockpos).getBlock())) { world.setBlockState(blockpos, Blocks.AIR.getDefaultState()); } } }); j++; k++; l++; BlockPos.getAllInBox(center.add(-j, -k, -l), center.add(j, k, l)).forEach(blockpos -> { if (blockpos.distanceSq(center) <= ffDouble) { if (!(world.getBlockState(blockpos).getBlock() instanceof IDragonProof) && DragonUtils.canDragonBreak(world.getBlockState(blockpos).getBlock())) { BlockState transformState = transformBlockLightning(world.getBlockState(blockpos)); world.setBlockState(blockpos, transformState); } } }); } final float stageDmg = Math.max(1, stage - 1) * 2F; world.getEntitiesWithinAABB( LivingEntity.class, new AxisAlignedBB( (double) center.getX() - j, (double) center.getY() - k, (double) center.getZ() - l, (double) center.getX() + j, (double) center.getY() + k, (double) center.getZ() + l ) ).stream().forEach(livingEntity -> { if (!destroyer.isOnSameTeam(livingEntity) && !destroyer.isEntityEqual(livingEntity) && destroyer.canEntityBeSeen(livingEntity)) { livingEntity.attackEntityFrom(IafDamageRegistry.DRAGON_LIGHTNING, stageDmg); double d1 = destroyer.getPosX() - livingEntity.getPosX(); double d0 = destroyer.getPosZ() - livingEntity.getPosZ(); livingEntity.applyKnockback(0.9F, d1, d0); } }); if (IafConfig.explosiveDragonBreath) { BlockLaunchExplosion explosion = new BlockLaunchExplosion(world, destroyer, center.getX(), center.getY(), center.getZ(), Math.min(2, stage - 2)); explosion.doExplosionA(); explosion.doExplosionB(true); } } }","public static void destroyAreaLightningCharge(World world, BlockPos center, EntityDragonBase destroyer) { if (destroyer != null) { if (MinecraftForge.EVENT_BUS.post(new DragonFireDamageWorldEvent(destroyer, center.getX(), center.getY(), center.getZ()))) return; Entity cause = destroyer.getRidingPlayer() != null ? destroyer.getRidingPlayer() : destroyer; DamageSource source = IafDamageRegistry.causeDragonLightningDamage(cause); int stage = destroyer.getDragonStage(); int j = 2; int k = 2; int l = 2; if (stage <= 3) { BlockPos.getAllInBox(center.add(-j, -k, -l), center.add(j, k, l)).forEach(pos -> { if (Math.pow(world.rand.nextFloat() * 7F, 2) > center.distanceSq(pos) && !(world.getBlockState(pos).getBlock() instanceof IDragonProof) && DragonUtils.canDragonBreak(world.getBlockState(pos).getBlock())) { world.setBlockState(pos, Blocks.AIR.getDefaultState()); } if (Math.pow(world.rand.nextFloat() * 7F, 2) > center.distanceSq(pos) && !(world.getBlockState(pos).getBlock() instanceof IDragonProof) && DragonUtils.canDragonBreak(world.getBlockState(pos).getBlock())) { BlockState transformState = transformBlockLightning(world.getBlockState(pos)); world.setBlockState(pos, transformState); } }); } else { int radius = stage == 4 ? 2 : 3; j = radius + world.rand.nextInt(2); k = radius + world.rand.nextInt(2); l = radius + world.rand.nextInt(2); float f = (float) (j + k + l) * 0.333F + 0.5F; final float ff = f * f; destroyBlocks(world, center, j, k, l, ff); j++; k++; l++; BlockPos.getAllInBox(center.add(-j, -k, -l), center.add(j, k, l)).forEach(pos -> { if (center.distanceSq(pos) <= ff) { if (!(world.getBlockState(pos).getBlock() instanceof IDragonProof) && DragonUtils.canDragonBreak(world.getBlockState(pos).getBlock())) { BlockState transformState = transformBlockLightning(world.getBlockState(pos)); world.setBlockState(pos, transformState); } } }); } final float stageDmg = Math.max(1, stage - 1) * 2F; world.getEntitiesWithinAABB( LivingEntity.class, new AxisAlignedBB( (double) center.getX() - j, (double) center.getY() - k, (double) center.getZ() - l, (double) center.getX() + j, (double) center.getY() + k, (double) center.getZ() + l ) ).stream().forEach(livingEntity -> { if (!destroyer.isOnSameTeam(livingEntity) && !destroyer.isEntityEqual(livingEntity) && destroyer.canEntityBeSeen(livingEntity)) { livingEntity.attackEntityFrom(source, stageDmg); double d1 = destroyer.getPosX() - livingEntity.getPosX(); double d0 = destroyer.getPosZ() - livingEntity.getPosZ(); livingEntity.applyKnockback(0.9F, d1, d0); } }); if (IafConfig.explosiveDragonBreath) causeExplosion(world, center, destroyer, source, stage); } }","Updated IafDamageRegistry to use EntityDamageSource. - Attacking someone while riding a dragon now identifies the rider as the source of the damage/attack Cleaned up code related to entity charge attacks. - The various dragon charges now all inherit from the same abstract class - Charge attacks now no longer raytrace twice - Removed duplicate code Cleaned up and improved code regarding dragons breath attacks Dragons don't break blocks anymore that they shouldn't. Fixes #4475",https://github.com/AlexModGuy/Ice_and_Fire/commit/3c52775ad166dd8ee77da768881444db1b89512a,,,src/main/java/com/github/alexthe666/iceandfire/entity/IafDragonDestructionManager.java,3,java,False,2022-05-10T16:42:49Z "private void createInitialGrid(Envelope env, PriorityQueue cellQueue) { double minX = env.getMinX(); double maxX = env.getMaxX(); double minY = env.getMinY(); double maxY = env.getMaxY(); double width = env.getWidth(); double height = env.getHeight(); double cellSize = Math.min(width, height); double hSide = cellSize / 2.0; // compute initial grid of cells to cover area for (double x = minX; x < maxX; x += cellSize) { for (double y = minY; y < maxY; y += cellSize) { cellQueue.add(createCell(x + hSide, y + hSide, hSide)); } } }","private void createInitialGrid(Envelope env, PriorityQueue cellQueue) { double minX = env.getMinX(); double maxX = env.getMaxX(); double minY = env.getMinY(); double maxY = env.getMaxY(); double width = env.getWidth(); double height = env.getHeight(); double cellSize = Math.min(width, height); // Check for flat collapsed input and if so short-circuit // Result will just be centroid if (cellSize == 0) return; double hSide = cellSize / 2.0; // compute initial grid of cells to cover area for (double x = minX; x < maxX; x += cellSize) { for (double y = minY; y < maxY; y += cellSize) { cellQueue.add(createCell(x + hSide, y + hSide, hSide)); } } }","Fix MaximumInscribedCircle to avoid infinite loop (#807) Signed-off-by: Martin Davis ",https://github.com/locationtech/jts/commit/428f7ff492e337f219514bdd6fb3bb80151038db,,,modules/core/src/main/java/org/locationtech/jts/algorithm/construct/MaximumInscribedCircle.java,3,java,False,2021-11-25T20:20:32Z "@Override public Element[] supStreamFeatures(XMPPResourceConnection session) { if (log.isLoggable(Level.FINEST) && (session != null)) { log.finest(""VHostItem: "" + session.getDomain()); } if ((session != null) && session.getDomain().isRegisterEnabled()) { return FEATURES; } else { return null; } }","@Override public Element[] supStreamFeatures(XMPPResourceConnection session) { if (log.isLoggable(Level.FINEST) && (session != null)) { log.finest(""VHostItem: "" + session.getDomain()); } if ((session != null) && session.getDomain().isRegisterEnabled()) { if (session.isTlsRequired() && !session.isEncrypted()) { return null; } return FEATURES; } else { return null; } }",Fixed advertisement stream features for unauthorized stream #server-1334,https://github.com/tigase/tigase-server/commit/b9bc6f1db3891f1b4c80d28281cf7678f284892f,,,src/main/java/tigase/xmpp/impl/JabberIqRegister.java,3,java,False,2022-10-07T14:16:48Z "@Override public void setWriteListener(WriteListener writeListener) { }","@Override public void setWriteListener(WriteListener writeListener) { throw new UnsupportedOperationException(); }","Issue 225 do head content length (#405) Issue #225 doHead contentLength + converting the contentLength field to a long + checking against bufferSize before setting a content length to simulate a buffer overflow + support flush and close + pass through async IO listener * Issue #225 doHead contentLength + check content-length against buffer size on every write * Improved clarity of the writer flush mechanism * Added unit test * Alternate approach + fixed some definite bugs in Nobody response + made the use of Nobody response optional. * + use SC init parameter to enable legacy doHead handling * Deprecated legacy mode and added text in spec * format Signed-off-by: Greg Wilkins * format Signed-off-by: Greg Wilkins * merged and updated for deprecated and new methods.",https://github.com/jakartaee/servlet/commit/75647ca7284df416278bf7cc2c2b344d54cd3ae1,,,api/src/main/java/jakarta/servlet/http/HttpServlet.java,3,java,False,2021-10-08T00:21:40Z "public static List splitValueList(String value) { List result = new ArrayList<>(); if (value != null && value.length() > 0) { value = value.trim(); String[] list = value.split(""\\s*(,|\\s)\\s*""); result.addAll(Arrays.asList(list)); } return result; }","public static List splitValueList(String value) { List result = new ArrayList<>(); if (value != null && value.length() > 0) { value = value.trim(); String[] list = value.split(""[,|\\s]""); for (String element: list) { if (!element.isEmpty()) { result.add(element); } } } return result; }","Fix possible DoS due to using of regex DEVSIX-7108",https://github.com/itext/itext-java/commit/01486efbaccacad78dc093df0d337c4bad407326,,,svg/src/main/java/com/itextpdf/svg/utils/SvgCssUtils.java,3,java,False,2022-11-16T08:44:04Z "public void sendIntent(Context context, int code, Intent intent, OnFinished onFinished, Handler handler, String requiredPermission) throws SendIntentException { try { String resolvedType = intent != null ? intent.resolveTypeIfNeeded(context.getContentResolver()) : null; final IApplicationThread app = ActivityThread.currentActivityThread() .getApplicationThread(); int res = ActivityManager.getService().sendIntentSender(app, mTarget, mWhitelistToken, code, intent, resolvedType, onFinished != null ? new FinishedDispatcher(this, onFinished, handler) : null, requiredPermission, null); if (res < 0) { throw new SendIntentException(); } } catch (RemoteException e) { throw new SendIntentException(); } }","public void sendIntent(Context context, int code, Intent intent, OnFinished onFinished, Handler handler, String requiredPermission) throws SendIntentException { sendIntent(context, code, intent, onFinished, handler, requiredPermission, null /* options */); }","Fix bypass BG-FGS and BAL via package manager APIs Opt-in for BAL of PendingIntent for following APIs: * PackageInstaller.uninstall() * PackageInstaller.installExistingPackage() * PackageInstaller.uninstallExistingPackage() * PackageInstaller.waitForInstallConstraints() * PackageInstaller.Session.commit() * PackageInstaller.Session.commitTransferred() * PackageInstaller.Session.requestUserPreapproval() * PackageManager.freeStorage() Bug: 230492955 Bug: 243377226 Test: atest android.security.cts.PackageInstallerTest Test: atest CtsStagedInstallHostTestCases Change-Id: I9b6f801d69ea6d2244a38dbe689e81afa4e798bf",https://github.com/PixelExperience/frameworks_base/commit/2be553067f56f21c0cf599ffa6b1ff24052a12fd,,,core/java/android/content/IntentSender.java,3,java,False,2023-01-11T08:02:27Z "@Path(""/{group-id}/schemas/{schema-id}"") @POST @Produces({""application/json;format=avro"", ""application/json;format=protobuf""}) @Consumes(""application/json;format=avro"") CompletionStage createSchema(@PathParam(""group-id"") String groupId, @PathParam(""schema-id"") String schemaId, InputStream data);","@Path(""/{group-id}/schemas/{schema-id}"") @POST @Produces({""application/json;format=avro"", ""application/json;format=protobuf""}) @Consumes(""application/json;format=avro"") @Authorized CompletionStage createSchema(@PathParam(""group-id"") String groupId, @PathParam(""schema-id"") String schemaId, InputStream data);","Implement owner-only authorization support (optional, enabled via appication.properties) (#1407) * trying to implement simple authorization using CDI interceptors * added @Authorized to appropriate methods * updated the auth test * Removed some debugging statements * Improved and applied authn/z to other APIs (v1, cncf, etc) * Fixed some issues with GroupOnly authorization * Disable the IBM API by default due to authorization issues * fix the IBM api test",https://github.com/Apicurio/apicurio-registry/commit/90a856197b104c99032163fa26c04d01465bf487,,,app/src/main/java/io/apicurio/registry/cncf/schemaregistry/SchemagroupsResource.java,3,java,False,2021-04-13T09:08:58Z "private void saveLocalParents(ModuleRevisionId baseMrevId, ModuleDescriptor md, File mdFile, Properties paths) throws ParseException, IOException { for (ExtendsDescriptor parent : md.getInheritedDescriptors()) { if (!parent.isLocal()) { // we store only local parents in the cache! continue; } ModuleDescriptor parentMd = parent.getParentMd(); ModuleRevisionId pRevId = ModuleRevisionId.newInstance(baseMrevId, baseMrevId.getRevision() + ""-parent."" + paths.size()); File parentFile = getResolvedIvyFileInCache(pRevId); parentMd.toIvyFile(parentFile); paths.setProperty(mdFile.getName() + ""|"" + parent.getLocation(), parentFile.getAbsolutePath()); saveLocalParents(baseMrevId, parentMd, parentFile, paths); } }","private void saveLocalParents(ModuleRevisionId baseMrevId, ModuleDescriptor md, File mdFile, Properties paths) throws ParseException, IOException { for (ExtendsDescriptor parent : md.getInheritedDescriptors()) { if (!parent.isLocal()) { // we store only local parents in the cache! continue; } ModuleDescriptor parentMd = parent.getParentMd(); ModuleRevisionId pRevId = ModuleRevisionId.newInstance(baseMrevId, baseMrevId.getRevision() + ""-parent."" + paths.size()); File parentFile = getResolvedIvyFileInCache(pRevId); assertInsideCache(parentFile); parentMd.toIvyFile(parentFile); paths.setProperty(mdFile.getName() + ""|"" + parent.getLocation(), parentFile.getAbsolutePath()); saveLocalParents(baseMrevId, parentMd, parentFile, paths); } }",CVE-2022-37865 ZipPacking allows overwriting arbitrary files,https://github.com/apache/ant-ivy/commit/3f374602d4d63691398951b9af692960d019f4d9,,,src/java/org/apache/ivy/core/cache/DefaultResolutionCacheManager.java,3,java,False,2022-08-21T16:54:43Z "private void setBanner(@Nullable View view) { mBanner = view; if (view != null) { setupAndAddBanner(); setBannerOutline(); } }","private void setBanner(@Nullable View view) { mBanner = view; if (view != null && mTaskView.getRecentsView() != null) { setupAndAddBanner(); setBannerOutline(); } }","Fix crash condition by adding a null check in DigitalWellBeingToast Fixes a crash condition where TaskView#getRecentsView() could return null when being called from DigitalWellBeingToast#setBanner(), resulting in a crash. Fixes: 217671133 Test: Manual Change-Id: I964384d97d26336e9a5e8e4c025f66ab78c63e0a",https://github.com/LawnchairLauncher/lawnchair/commit/64212c5439dd40204256630dd7c01cf68a02047f,,,quickstep/src/com/android/quickstep/views/DigitalWellBeingToast.java,3,java,False,2022-03-18T23:55:17Z "public Completable execute(KeyT key, Completable task, boolean force) { return Completable.fromSingle( cache.execute(key, task.toSingleDefault(Optional.empty()), force)); }","public Completable execute(KeyT key, Completable task, boolean force) { return execute(key, task, () -> {}, force); }","Remote: Fix crashes by InterruptedException when dynamic execution is enabled. Fixes #14433. The root cause is, inside `RemoteExecutionCache`, the result of `FindMissingDigests` is shared with other threads without considering error handling. For example, if there are two or more threads uploading the same input and one thread got interrupted when waiting for the result of `FindMissingDigests` call, the call is cancelled and others threads still waiting for the upload will receive upload error due to the cancellation which is wrong. This PR fixes this by effectively applying reference count to the result of `FindMissingDigests` call so that if one thread got interrupted, as long as there are other threads depending on the result, the call won't be cancelled and the upload can continue. Closes #15001. PiperOrigin-RevId: 436180205",https://github.com/bazelbuild/bazel/commit/702df847cf32789ffe6c0a7c7679e92a7ccccb8d,,,src/main/java/com/google/devtools/build/lib/remote/util/AsyncTaskCache.java,3,java,False,2022-03-21T12:37:13Z "@Override public void updateState(Preference preference) { if (mFragment == null) { return; } final int simSlot = getSimSlotIndex(); if (mSimChangeObserver == null) { mSimChangeObserver = x -> updateStateBySlot(preference, simSlot); mFragment.getViewLifecycleOwnerLiveData().observeForever(lifecycleOwner -> { mSlotSimStatus.observe(lifecycleOwner, mSimChangeObserver); }); } else { updateStateBySlot(preference, simSlot); } }","@Override public void updateState(Preference preference) { if (mFragment == null) { return; } if (mLifecycleOwnerObserver == null) { final LiveData dataLifecycleOwner = mFragment.getViewLifecycleOwnerLiveData(); mLifecycleOwnerObserver = owner -> { if (owner != null) { final int simSlot = getSimSlotIndex(); mSimChangeObserver = x -> updateStateBySlot(preference, simSlot); mSlotSimStatus.observe(owner, mSimChangeObserver); } else { if (mSimChangeObserver != null) { mSlotSimStatus.removeObserver(mSimChangeObserver); mSimChangeObserver = null; } dataLifecycleOwner.removeObserver(mLifecycleOwnerObserver); } }; dataLifecycleOwner.observeForever(mLifecycleOwnerObserver); } else if (mSimChangeObserver != null) { final int simSlot = getSimSlotIndex(); updateStateBySlot(preference, simSlot); } }","[Settings] Fix about phone crash no leave Avoid from crash when LifecycleOwnerLiveData reports null during destroy. Bug: 267513122 Test: local Change-Id: Ie541b0e5b81aa14bd064087c5343716b6bc066a3",https://github.com/LineageOS/android_packages_apps_Settings/commit/211920bc7c4548c8efd64d78d469755539c06911,,,src/com/android/settings/deviceinfo/simstatus/SimStatusPreferenceController.java,3,java,False,2023-02-02T06:09:05Z "@Override public AWSCredentials run() { return getCredentials(); }","@Override public Void run() throws Exception { if (signOutOptions.isSignOutGlobally()) { final GlobalSignOutRequest globalSignOutRequest = new GlobalSignOutRequest(); globalSignOutRequest.setAccessToken(getTokens().getAccessToken().getTokenString()); userpoolLL.globalSignOut(globalSignOutRequest); } if (signOutOptions.isInvalidateTokens()) { if (userpool != null) { userpool.getCurrentUser().revokeTokens(); } if (hostedUI != null) { if (signOutOptions.getBrowserPackage() != null) { hostedUI.setBrowserPackage(signOutOptions.getBrowserPackage()); } hostedUI.signOut(); } else if (mOAuth2Client != null) { final CountDownLatch latch = new CountDownLatch(1); final JSONObject hostedUIJSON = getHostedUIJSON(); final String signOutUriString = hostedUIJSON.getString(""SignOutURI""); final Uri.Builder uriBuilder = Uri.parse(signOutUriString).buildUpon(); if (getHostedUIJSON().optString(""SignOutRedirectURI"", null) != null) { uriBuilder.appendQueryParameter(""redirect_uri"", getHostedUIJSON().getString( ""SignOutRedirectURI"")); } final JSONObject signOutQueryParametersJSON = hostedUIJSON.getJSONObject( ""SignOutQueryParameters""); if (signOutQueryParametersJSON != null) { final Iterator keysIterator = signOutQueryParametersJSON.keys(); while (keysIterator.hasNext()) { String key = keysIterator.next(); uriBuilder.appendQueryParameter(key, signOutQueryParametersJSON.getString(key)); } } final Exception[] signOutError = new Exception[1]; mOAuth2Client.signOut(uriBuilder.build(), new Callback() { @Override public void onResult(Void result) { latch.countDown(); } @Override public void onError(Exception e) { signOutError[0] = e; latch.countDown(); } }); latch.await(); if (signOutError[0] != null) { throw signOutError[0]; } } } signOut(); return null; }","feat: revoke tokens during auth sign out (#2415) * feature: user pool token revocation model updates * feature: revoke tokens if invalidate tokens specified * Token revocation (#2532) * feat(aws-android-sdk-cognitoidentityprovider): support custom endpoint * feat(aws-android-sdk-cognitoidentityprovider): support custom endpoint unit tests * feat(aws-android-sdk-cognitoidentityprovider): support custom endpoint unit tests * feat(aws-android-sdk-machinelearning): update models to latest (#2407) Co-authored-by: Richard McClellan * feat(aws-android-sdk-iot): update models to latest (#2408) Co-authored-by: Richard McClellan * feat(aws-android-sdk-comprehend): update models to latest (#2409) Co-authored-by: Richard McClellan * feat(aws-android-sdk-transcribe): update models to latest (#2410) Co-authored-by: Richard McClellan * feat(aws-android-sdk-lex): update models to latest (#2413) Co-authored-by: Richard McClellan * chore(lex): update service name for lex runtime (#2424) * feat(aws-android-sdk-kinesisvideo-archivedmedia): update models to latest (#2422) * Revert ""feat(aws-android-sdk-cognitoidentityprovider): support custom endpoint"" (#2425) Co-authored-by: Richard McClellan * release: 2.22.6 (#2426) * fix(mobile-client): missing optional dependency warning removed (#2427) * fix(mobile-client): missing optional dependency warning removed * make comment more descriptive * chore: add fastlane scripts for release automation (#2428) * fix: change protocol for github import (#2429) * fix(s3): remove eTag validation logic (#2419) * chore(build): use in-memory key in CI (#2449) * change the time offset precision from int to long (#2448) **Notes:** The clockskew auto-correct logic in the SDK relies on the `int` primitive type when calculating the offset. When the offset is converted from milliseconds to days, the ms represented as an `int` have the boundaries as -24 and +24 days. Changing it to long (64-bit precision) fixes the limit. * fix(s3): force upload part tasks to be serial (#2447) * feat(aws-android-sdk-core): update models to latest (#2445) Co-authored-by: Richard McClellan * release: AWS SDK for Android 2.22.7 (#2451) * release: AWS SDK for Android 2.23.0 * Update CHANGELOG.md Co-authored-by: Richard McClellan * Update CHANGELOG.md * Update gradle.properties * Update CHANGELOG.md * Update CHANGELOG.md Co-authored-by: awsmobilesdk-dev+ghops Co-authored-by: Chang Xu <42978935+changxu0306@users.noreply.github.com> Co-authored-by: Richard McClellan * ""feat(aws-android-sdk-cognitoidentityprovider): support custom endpoint"" (#2455) * fix(pinpoint): add campaign attributes to push events (#2458) * release: AWS SDK for Android 2.23.0 (#2459) * release: AWS SDK for Android 2.22.8 * Update CHANGELOG.md * Update CHANGELOG.md * Update CHANGELOG.md * Update gradle.properties Co-authored-by: awsmobilesdk-dev+ghops Co-authored-by: Chang Xu <42978935+changxu0306@users.noreply.github.com> * feat(aws-android-sdk-sns): update models to latest (#2461) * feat(aws-android-sdk-cognitoidentityprovider): update models to latest (#2456) Co-authored-by: Raphael Kim <52714340+raphkim@users.noreply.github.com> * chore(build): set region in circleci script (#2467) * fix: launch hosted-ui sign-out using custom tabs manager (#2472) * feat(mobile-client): hosted-ui auth response handler is now built into redirect activity (#2473) * feat(mobile-client): auth response handler is now built into redirect activity * add javadocs for redirect activities * add signout latch conditionally * add no history flag to auth signout flow * feat(aws-android-sdk-connect): update models to latest (#2469) Co-authored-by: Raphael Kim <52714340+raphkim@users.noreply.github.com> * feat(aws-android-sdk-transcribe): update models to latest (#2476) Co-authored-by: Raphael Kim <52714340+raphkim@users.noreply.github.com> * feat(aws-android-sdk-rekognition): update models to latest (#2487) Co-authored-by: Raphael Kim <52714340+raphkim@users.noreply.github.com> * feat(aws-android-sdk-iot): update models to latest (#2490) Co-authored-by: Raphael Kim <52714340+raphkim@users.noreply.github.com> Co-authored-by: Rafael Juliano * feat(aws-android-sdk-location): update models to latest (#2494) Co-authored-by: Raphael Kim <52714340+raphkim@users.noreply.github.com> * feat(aws-android-sdk-sns): update models to latest (#2496) Co-authored-by: Raphael Kim <52714340+raphkim@users.noreply.github.com> * feat(aws-android-sdk-polly): update models to latest (#2497) Co-authored-by: Raphael Kim <52714340+raphkim@users.noreply.github.com> * chore(sts): add support for regionalizing sts client (#2493) * feat(sts): add support for regionalizing sts client * feat(aws-android-sdk-mobile-client): adds signature with user attributes in confirmSignIn (#2492) * feat(aws-android-sdk-mobile-client): adds signature with user attributes in confirmSignIn * code review suggestion Co-authored-by: Noyes * release: AWS SDK for Android 2.24.0 (#2500) * release: AWS SDK for Android 2.24.0 * Reword the changelog * include instruction for applying fix Co-authored-by: awsmobilesdk-dev+ghops Co-authored-by: Raphael Kim <52714340+raphkim@users.noreply.github.com> * fix(aws-android-sdk-lex): prioritize custom lex signer for all regions (#2506) * fix(aws-android-sdk-lex): prioritize custom lex signer for all regions * add tests * fix(mobileclient): Honor auth flow setting from config (#2499) * fix(mobileclient): Honor auth flow setting from config * PR feedback * fix(aws-android-sdk-polly): use correct SignerConfig in all regions (#2505) Co-authored-by: Raphael Kim <52714340+raphkim@users.noreply.github.com> * feat(aws-android-sdk-cognitoidentityprovider): update models to latest (#2510) * release: AWS SDK for Android 2.25.0 (#2512) Co-authored-by: awsmobilesdk-dev+ghops * chore(docs): releases not pushed to S3 anymore (#2514) * fix(aws-android-sdk-s3): implement retry mechanism for upload part (#2504) * implement retry mechanism for upload part * reduce backoff time and max attempts * lgtm warning * feat(aws-android-sdk-connect): update models to latest (#2516) * feat(aws-android-sdk-kms): update models to latest (#2518) * release: AWS SDK for Android 2.26.0 (#2525) Co-authored-by: awsmobilesdk-dev+ghops * feat(aws-android-sdk-connect): update models to latest (#2526) Co-authored-by: Abhash Kumar Singh Co-authored-by: Abhash Kumar Singh Co-authored-by: Jameson Williams Co-authored-by: AWS Mobile SDK Team <46607340+awsmobilesdk@users.noreply.github.com> Co-authored-by: Richard McClellan Co-authored-by: Raphael Kim <52714340+raphkim@users.noreply.github.com> Co-authored-by: Rafael Juliano Co-authored-by: Daniel Rochetti Co-authored-by: github-actions[bot] <41898282+github-actions[bot]@users.noreply.github.com> Co-authored-by: awsmobilesdk-dev+ghops Co-authored-by: Chang Xu <42978935+changxu0306@users.noreply.github.com> Co-authored-by: Dustin Noyes Co-authored-by: Noyes Co-authored-by: tllauda <85560392+tllauda@users.noreply.github.com> * Update UserPoolClientType.java remove duplicate vars. * delete code for removed API * fixes: - use access token to check claim - check for origin_jti claim - clientSecret is optional * Update aws-android-sdk-cognitoidentityprovider/src/main/java/com/amazonaws/mobileconnectors/cognitoidentityprovider/CognitoUser.java Co-authored-by: Richard McClellan * swallow exceptions * update test mock classes with latest model changes * add unit tests * return revoketoken response result Co-authored-by: Divyesh Chitroda Co-authored-by: Abhash Kumar Singh Co-authored-by: Abhash Kumar Singh Co-authored-by: AWS Mobile SDK Team <46607340+awsmobilesdk@users.noreply.github.com> Co-authored-by: Richard McClellan Co-authored-by: Raphael Kim <52714340+raphkim@users.noreply.github.com> Co-authored-by: Rafael Juliano Co-authored-by: Daniel Rochetti Co-authored-by: github-actions[bot] <41898282+github-actions[bot]@users.noreply.github.com> Co-authored-by: awsmobilesdk-dev+ghops Co-authored-by: Chang Xu <42978935+changxu0306@users.noreply.github.com> Co-authored-by: Dustin Noyes Co-authored-by: Noyes Co-authored-by: tllauda <85560392+tllauda@users.noreply.github.com> Co-authored-by: poojamat ",https://github.com/aws-amplify/aws-sdk-android/commit/1940e0500f50e34b5096e4635a4b60beb0fa8284,,,aws-android-sdk-mobile-client/src/main/java/com/amazonaws/mobile/client/AWSMobileClient.java,3,java,False,2021-07-30T18:05:35Z "@Override public NodeStateEntryTraverser create(LastModifiedRange lastModifiedRange) { IndexingProgressReporter progressReporterPerTask = new IndexingProgressReporter(IndexUpdateCallback.NOOP, NodeTraversalCallback.NOOP); String entryTraverserID = TRAVERSER_ID_PREFIX + traverserInstanceCounter.incrementAndGet(); //As first traversal is for dumping change the message prefix progressReporterPerTask.setMessagePrefix(""Dumping from "" + entryTraverserID); NodeStateEntryTraverser nsep = new NodeStateEntryTraverser(entryTraverserID, rootRevision, documentNodeStore, documentStore, lastModifiedRange) .withProgressCallback((id) -> { try { progressReporterPerTask.traversedNode(() -> id); } catch (CommitFailedException e) { throw new RuntimeException(e); } traversalLogger.trace(id); }) .withPathPredicate(indexer::shouldInclude); closer.register(nsep); return nsep; }","@Override public NodeStateEntryTraverser create(LastModifiedRange lastModifiedRange) { IndexingProgressReporter progressReporterPerTask = new IndexingProgressReporter(IndexUpdateCallback.NOOP, NodeTraversalCallback.NOOP); String entryTraverserID = TRAVERSER_ID_PREFIX + traverserInstanceCounter.incrementAndGet(); //As first traversal is for dumping change the message prefix progressReporterPerTask.setMessagePrefix(""Dumping from "" + entryTraverserID); return new NodeStateEntryTraverser(entryTraverserID, rootRevision, documentNodeStore, documentStore, lastModifiedRange) .withProgressCallback((id) -> { try { progressReporterPerTask.traversedNode(() -> id); } catch (CommitFailedException e) { throw new RuntimeException(e); } traversalLogger.trace(id); }) .withPathPredicate(indexer::shouldInclude); }","OAK-9576: Multithreaded download synchronization issues (#383) * OAK-9576 - Multithreaded download synchronization issues * Fixing a problem with test * OAK-9576: Multithreaded download synchronization issues * Fixing synchronization issues * Fixing OOM issue * Adding delay between download retries * OAK-9576: Multithreaded download synchronization issues * Using linkedlist in tasks for freeing memory early * Dumping if data is greater than one MB * OAK-9576: Multithreaded download synchronization issues * Closing node state entry traversors using try with * trivial - removing unused object * OAK-9576: Multithreaded download synchronization issues * Incorporating some feedback from review comments * OAK-9576: Multithreaded download synchronization issues * Replacing explicit synchronization with atomic operations * OAK-9576: Multithreaded download synchronization issues * Using same memory manager across retries * trivial - removing unwanted method * OAK-9576: Multithreaded download synchronization issues * Moving retry delay to exception block * trivial - correcting variable name Co-authored-by: amrverma ",https://github.com/apache/jackrabbit-oak/commit/c04aff5d970beccd41ff15c1c907f7ea6d0720fb,,,oak-run-commons/src/main/java/org/apache/jackrabbit/oak/index/indexer/document/DocumentStoreIndexerBase.java,3,java,False,2021-12-01T07:03:04Z "private String toExampleValueRecursive(String modelName, Schema schema, Object objExample, int indentationLevel, String prefix, Integer exampleLine, List includedSchemas) { boolean couldHaveCycle = includedSchemas.size() > 0 && potentiallySelfReferencingSchema(schema); // If we have seen the ContextAwareSchemaNode more than once before, we must be in a cycle. boolean cycleFound = false; if (couldHaveCycle) { cycleFound = includedSchemas.subList(0, includedSchemas.size()-1).stream().anyMatch(s -> schema.equals(s)); } final String indentionConst = "" ""; String currentIndentation = """"; String closingIndentation = """"; for (int i = 0; i < indentationLevel; i++) currentIndentation += indentionConst; if (exampleLine.equals(0)) { closingIndentation = currentIndentation; currentIndentation = """"; } else { closingIndentation = currentIndentation; } String openChars = """"; String closeChars = """"; if (modelName != null) { openChars = modelName + ""(""; closeChars = "")""; } String fullPrefix = currentIndentation + prefix + openChars; String example = null; if (objExample != null) { example = objExample.toString(); } if (null != schema.get$ref()) { Map allDefinitions = ModelUtils.getSchemas(this.openAPI); String ref = ModelUtils.getSimpleRef(schema.get$ref()); Schema refSchema = allDefinitions.get(ref); if (null == refSchema) { LOGGER.warn(""Unable to find referenced schema "" + schema.get$ref() + ""\n""); return fullPrefix + ""None"" + closeChars; } String refModelName = getModelName(schema); return toExampleValueRecursive(refModelName, refSchema, objExample, indentationLevel, prefix, exampleLine, includedSchemas); } else if (ModelUtils.isNullType(schema)) { // The 'null' type is allowed in OAS 3.1 and above. It is not supported by OAS 3.0.x, // though this tooling supports it. return fullPrefix + ""None"" + closeChars; } else if (ModelUtils.isAnyType(schema)) { /* This schema may be a composed schema TODO generate examples for some of these use cases in the future like only oneOf without a discriminator */ Boolean hasProperties = (schema.getProperties() != null && !schema.getProperties().isEmpty()); CodegenDiscriminator disc = createDiscriminator(modelName, schema, openAPI); if (ModelUtils.isComposedSchema(schema)) { // complex composed object type schemas not yet handled and the code returns early if (hasProperties) { // what if this composed schema defined properties + allOf? // or items + properties, both a ist and a dict could be accepted as payloads return fullPrefix + ""{}"" + closeChars; } ComposedSchema cs = (ComposedSchema) schema; Integer allOfExists = 0; if (cs.getAllOf() != null && !cs.getAllOf().isEmpty()) { allOfExists = 1; } Integer anyOfExists = 0; if (cs.getAnyOf() != null && !cs.getAnyOf().isEmpty()) { anyOfExists = 1; } Integer oneOfExists = 0; if (cs.getOneOf() != null && !cs.getOneOf().isEmpty()) { oneOfExists = 1; } if (allOfExists + anyOfExists + oneOfExists > 1) { // what if it needs one oneOf schema, one anyOf schema, and two allOf schemas? return fullPrefix + ""None"" + closeChars; } // for now only oneOf with discriminator is supported if (oneOfExists == 1 && disc != null) { ; } else { return fullPrefix + ""None"" + closeChars; } } if (disc != null) { // a discriminator means that the type must be object MappedModel mm = getDiscriminatorMappedModel(disc); if (mm == null) { return fullPrefix + ""None"" + closeChars; } String discPropNameValue = mm.getMappingName(); String chosenModelName = mm.getModelName(); Schema modelSchema = getModelNameToSchemaCache().get(chosenModelName); CodegenProperty cp = new CodegenProperty(); cp.setName(disc.getPropertyName()); cp.setExample(discPropNameValue); return exampleForObjectModel(modelSchema, fullPrefix, closeChars, cp, indentationLevel, exampleLine, closingIndentation, includedSchemas); } return fullPrefix + ""None"" + closeChars; } else if (ModelUtils.isBooleanSchema(schema)) { if (example == null) { example = ""True""; } else { if (""false"".equalsIgnoreCase(objExample.toString())) { example = ""False""; } else { example = ""True""; } } return fullPrefix + example + closeChars; } else if (ModelUtils.isStringSchema(schema)) { if (example != null) { return fullPrefix + ensureQuotes(processStringValue(example)) + closeChars; } if (ModelUtils.isDateSchema(schema)) { if (objExample == null) { example = pythonDate(""1970-01-01""); } else { example = pythonDate(objExample); } } else if (ModelUtils.isDateTimeSchema(schema)) { if (objExample == null) { example = pythonDateTime(""1970-01-01T00:00:00.00Z""); } else { example = pythonDateTime(objExample); } } else if (ModelUtils.isBinarySchema(schema)) { if (example == null) { example = ""/path/to/file""; } example = ""open('"" + example + ""', 'rb')""; return fullPrefix + example + closeChars; } else if (ModelUtils.isByteArraySchema(schema)) { if (objExample == null) { example = ""'YQ=='""; } } else if (""Number"".equalsIgnoreCase(schema.getFormat())) { // a BigDecimal: example = ""2""; } else if (StringUtils.isNotBlank(schema.getPattern())) { String pattern = schema.getPattern(); /* RxGen does not support our ECMA dialect https://github.com/curious-odd-man/RgxGen/issues/56 So strip off the leading / and trailing / and turn on ignore case if we have it */ Pattern valueExtractor = Pattern.compile(""^/?(.+?)/?(.?)$""); Matcher m = valueExtractor.matcher(pattern); RgxGen rgxGen = null; if (m.find()) { int groupCount = m.groupCount(); if (groupCount == 1) { // only pattern found String isolatedPattern = m.group(1); rgxGen = new RgxGen(isolatedPattern); } else if (groupCount == 2) { // patterns and flag found String isolatedPattern = m.group(1); String flags = m.group(2); if (flags.contains(""i"")) { rgxGen = new RgxGen(isolatedPattern); RgxGenProperties properties = new RgxGenProperties(); RgxGenOption.CASE_INSENSITIVE.setInProperties(properties, true); rgxGen.setProperties(properties); } else { rgxGen = new RgxGen(isolatedPattern); } } } else { rgxGen = new RgxGen(pattern); } // this seed makes it so if we have [a-z] we pick a Random random = new Random(18); if (rgxGen != null) { example = rgxGen.generate(random); } else { throw new RuntimeException(""rgxGen cannot be null. Please open an issue in the openapi-generator github repo.""); } } else if (schema.getMinLength() != null) { example = """"; int len = schema.getMinLength().intValue(); for (int i = 0; i < len; i++) example += ""a""; } else if (ModelUtils.isUUIDSchema(schema)) { example = ""046b6c7f-0b8a-43b9-b35d-6489e6daee91""; } else { example = ""string_example""; } return fullPrefix + ensureQuotes(example) + closeChars; } else if (ModelUtils.isIntegerSchema(schema)) { if (objExample == null) { if (schema.getMinimum() != null) { example = schema.getMinimum().toString(); } else { example = ""1""; } } return fullPrefix + example + closeChars; } else if (ModelUtils.isNumberSchema(schema)) { if (objExample == null) { if (schema.getMinimum() != null) { example = schema.getMinimum().toString(); } else { example = ""3.14""; } } return fullPrefix + example + closeChars; } else if (ModelUtils.isArraySchema(schema)) { if (objExample instanceof Iterable) { // If the example is already a list, return it directly instead of wrongly wrap it in another list return fullPrefix + objExample.toString() + closeChars; } if (ModelUtils.isComposedSchema(schema)) { // complex composed array type schemas not yet handled and the code returns early return fullPrefix + ""[]"" + closeChars; } ArraySchema arrayschema = (ArraySchema) schema; Schema itemSchema = arrayschema.getItems(); String itemModelName = getModelName(itemSchema); includedSchemas.add(schema); String itemExample = toExampleValueRecursive(itemModelName, itemSchema, objExample, indentationLevel + 1, """", exampleLine + 1, includedSchemas); if (StringUtils.isEmpty(itemExample) || cycleFound) { return fullPrefix + ""[]"" + closeChars; } else { return fullPrefix + ""["" + ""\n"" + itemExample + ""\n"" + closingIndentation + ""]"" + closeChars; } } else if (ModelUtils.isTypeObjectSchema(schema)) { if (modelName == null) { fullPrefix += ""dict(""; closeChars = "")""; } if (cycleFound) { return fullPrefix + closeChars; } Boolean hasProperties = (schema.getProperties() != null && !schema.getProperties().isEmpty()); CodegenDiscriminator disc = createDiscriminator(modelName, schema, openAPI); if (ModelUtils.isComposedSchema(schema)) { // complex composed object type schemas not yet handled and the code returns early if (hasProperties) { // what if this composed schema defined properties + allOf? return fullPrefix + closeChars; } ComposedSchema cs = (ComposedSchema) schema; Integer allOfExists = 0; if (cs.getAllOf() != null && !cs.getAllOf().isEmpty()) { allOfExists = 1; } Integer anyOfExists = 0; if (cs.getAnyOf() != null && !cs.getAnyOf().isEmpty()) { anyOfExists = 1; } Integer oneOfExists = 0; if (cs.getOneOf() != null && !cs.getOneOf().isEmpty()) { oneOfExists = 1; } if (allOfExists + anyOfExists + oneOfExists > 1) { // what if it needs one oneOf schema, one anyOf schema, and two allOf schemas? return fullPrefix + closeChars; } // for now only oneOf with discriminator is supported if (oneOfExists == 1 && disc != null) { ; } else { return fullPrefix + closeChars; } } if (disc != null) { MappedModel mm = getDiscriminatorMappedModel(disc); if (mm == null) { return fullPrefix + closeChars; } String discPropNameValue = mm.getMappingName(); String chosenModelName = mm.getModelName(); Schema modelSchema = getModelNameToSchemaCache().get(chosenModelName); CodegenProperty cp = new CodegenProperty(); cp.setName(disc.getPropertyName()); cp.setExample(discPropNameValue); return exampleForObjectModel(modelSchema, fullPrefix, closeChars, cp, indentationLevel, exampleLine, closingIndentation, includedSchemas); } Object addPropsObj = schema.getAdditionalProperties(); if (hasProperties) { return exampleForObjectModel(schema, fullPrefix, closeChars, null, indentationLevel, exampleLine, closingIndentation, includedSchemas); } else if (addPropsObj instanceof Schema) { // TODO handle true case for additionalProperties Schema addPropsSchema = (Schema) addPropsObj; String key = ""key""; Object addPropsExample = getObjectExample(addPropsSchema); if (addPropsSchema.getEnum() != null && !addPropsSchema.getEnum().isEmpty()) { key = addPropsSchema.getEnum().get(0).toString(); } addPropsExample = exampleFromStringOrArraySchema(addPropsSchema, addPropsExample, key); String addPropPrefix = key + ""=""; if (modelName == null) { addPropPrefix = ensureQuotes(key) + "": ""; } String addPropsModelName = getModelName(addPropsSchema); includedSchemas.add(schema); example = fullPrefix + ""\n"" + toExampleValueRecursive(addPropsModelName, addPropsSchema, addPropsExample, indentationLevel + 1, addPropPrefix, exampleLine + 1, includedSchemas) + "",\n"" + closingIndentation + closeChars; } else { example = fullPrefix + closeChars; } } else { LOGGER.warn(""Type "" + schema.getType() + "" not handled properly in toExampleValue""); } return example; }","private String toExampleValueRecursive(String modelName, Schema schema, Object objExample, int indentationLevel, String prefix, Integer exampleLine, List includedSchemas) { boolean couldHaveCycle = includedSchemas.size() > 0 && potentiallySelfReferencingSchema(schema); // If we have seen the ContextAwareSchemaNode more than once before, we must be in a cycle. boolean cycleFound = false; if (couldHaveCycle) { cycleFound = includedSchemas.subList(0, includedSchemas.size()-1).stream().anyMatch(s -> schema.equals(s)); } final String indentionConst = "" ""; String currentIndentation = """"; String closingIndentation = """"; for (int i = 0; i < indentationLevel; i++) currentIndentation += indentionConst; if (exampleLine.equals(0)) { closingIndentation = currentIndentation; currentIndentation = """"; } else { closingIndentation = currentIndentation; } String openChars = """"; String closeChars = """"; if (modelName != null) { openChars = modelName + ""(""; closeChars = "")""; } String fullPrefix = currentIndentation + prefix + openChars; String example = null; if (objExample != null) { example = objExample.toString(); } if (null != schema.get$ref()) { Map allDefinitions = ModelUtils.getSchemas(this.openAPI); String ref = ModelUtils.getSimpleRef(schema.get$ref()); Schema refSchema = allDefinitions.get(ref); if (null == refSchema) { LOGGER.warn(""Unable to find referenced schema "" + schema.get$ref() + ""\n""); return fullPrefix + ""None"" + closeChars; } String refModelName = getModelName(schema); return toExampleValueRecursive(refModelName, refSchema, objExample, indentationLevel, prefix, exampleLine, includedSchemas); } else if (ModelUtils.isNullType(schema)) { // The 'null' type is allowed in OAS 3.1 and above. It is not supported by OAS 3.0.x, // though this tooling supports it. return fullPrefix + ""None"" + closeChars; } else if (ModelUtils.isAnyType(schema)) { /* This schema may be a composed schema TODO generate examples for some of these use cases in the future like only oneOf without a discriminator */ if (cycleFound) { return """"; } Boolean hasProperties = (schema.getProperties() != null && !schema.getProperties().isEmpty()); CodegenDiscriminator disc = createDiscriminator(modelName, schema, openAPI); if (ModelUtils.isComposedSchema(schema)) { addSchemaToIncludedSchemaList(includedSchemas, schema); // complex composed object type schemas not yet handled and the code returns early if (hasProperties) { // what if this composed schema defined properties + allOf? // or items + properties, both a ist and a dict could be accepted as payloads return fullPrefix + ""{}"" + closeChars; } ComposedSchema cs = (ComposedSchema) schema; Integer allOfExists = 0; if (cs.getAllOf() != null && !cs.getAllOf().isEmpty()) { allOfExists = 1; } Integer anyOfExists = 0; if (cs.getAnyOf() != null && !cs.getAnyOf().isEmpty()) { anyOfExists = 1; } Integer oneOfExists = 0; if (cs.getOneOf() != null && !cs.getOneOf().isEmpty()) { oneOfExists = 1; } if (allOfExists + anyOfExists + oneOfExists > 1) { // what if it needs one oneOf schema, one anyOf schema, and two allOf schemas? return fullPrefix + ""None"" + closeChars; } // for now only oneOf with discriminator is supported if (oneOfExists == 1 && disc != null) { ; } else { return fullPrefix + ""None"" + closeChars; } } if (disc != null) { // a discriminator means that the type must be object MappedModel mm = getDiscriminatorMappedModel(disc); if (mm == null) { return fullPrefix + ""None"" + closeChars; } String discPropNameValue = mm.getMappingName(); String chosenModelName = mm.getModelName(); Schema modelSchema = getModelNameToSchemaCache().get(chosenModelName); CodegenProperty cp = new CodegenProperty(); cp.setName(disc.getPropertyName()); cp.setExample(discPropNameValue); return exampleForObjectModel(modelSchema, fullPrefix, closeChars, cp, indentationLevel, exampleLine, closingIndentation, includedSchemas); } return fullPrefix + ""None"" + closeChars; } else if (ModelUtils.isBooleanSchema(schema)) { if (example == null) { example = ""True""; } else { if (""false"".equalsIgnoreCase(objExample.toString())) { example = ""False""; } else { example = ""True""; } } return fullPrefix + example + closeChars; } else if (ModelUtils.isStringSchema(schema)) { if (example != null) { return fullPrefix + ensureQuotes(processStringValue(example)) + closeChars; } if (ModelUtils.isDateSchema(schema)) { if (objExample == null) { example = pythonDate(""1970-01-01""); } else { example = pythonDate(objExample); } } else if (ModelUtils.isDateTimeSchema(schema)) { if (objExample == null) { example = pythonDateTime(""1970-01-01T00:00:00.00Z""); } else { example = pythonDateTime(objExample); } } else if (ModelUtils.isBinarySchema(schema)) { if (example == null) { example = ""/path/to/file""; } example = ""open('"" + example + ""', 'rb')""; return fullPrefix + example + closeChars; } else if (ModelUtils.isByteArraySchema(schema)) { if (objExample == null) { example = ""'YQ=='""; } } else if (""Number"".equalsIgnoreCase(schema.getFormat())) { // a BigDecimal: example = ""2""; } else if (StringUtils.isNotBlank(schema.getPattern())) { String pattern = schema.getPattern(); /* RxGen does not support our ECMA dialect https://github.com/curious-odd-man/RgxGen/issues/56 So strip off the leading / and trailing / and turn on ignore case if we have it */ Pattern valueExtractor = Pattern.compile(""^/?(.+?)/?(.?)$""); Matcher m = valueExtractor.matcher(pattern); RgxGen rgxGen = null; if (m.find()) { int groupCount = m.groupCount(); if (groupCount == 1) { // only pattern found String isolatedPattern = m.group(1); rgxGen = new RgxGen(isolatedPattern); } else if (groupCount == 2) { // patterns and flag found String isolatedPattern = m.group(1); String flags = m.group(2); if (flags.contains(""i"")) { rgxGen = new RgxGen(isolatedPattern); RgxGenProperties properties = new RgxGenProperties(); RgxGenOption.CASE_INSENSITIVE.setInProperties(properties, true); rgxGen.setProperties(properties); } else { rgxGen = new RgxGen(isolatedPattern); } } } else { rgxGen = new RgxGen(pattern); } // this seed makes it so if we have [a-z] we pick a Random random = new Random(18); if (rgxGen != null) { example = rgxGen.generate(random); } else { throw new RuntimeException(""rgxGen cannot be null. Please open an issue in the openapi-generator github repo.""); } } else if (schema.getMinLength() != null) { example = """"; int len = schema.getMinLength().intValue(); for (int i = 0; i < len; i++) example += ""a""; } else if (ModelUtils.isUUIDSchema(schema)) { example = ""046b6c7f-0b8a-43b9-b35d-6489e6daee91""; } else { example = ""string_example""; } return fullPrefix + ensureQuotes(example) + closeChars; } else if (ModelUtils.isIntegerSchema(schema)) { if (objExample == null) { if (schema.getMinimum() != null) { example = schema.getMinimum().toString(); } else { example = ""1""; } } return fullPrefix + example + closeChars; } else if (ModelUtils.isNumberSchema(schema)) { if (objExample == null) { if (schema.getMinimum() != null) { example = schema.getMinimum().toString(); } else { example = ""3.14""; } } return fullPrefix + example + closeChars; } else if (ModelUtils.isArraySchema(schema)) { if (objExample instanceof Iterable) { // If the example is already a list, return it directly instead of wrongly wrap it in another list return fullPrefix + objExample.toString() + closeChars; } if (ModelUtils.isComposedSchema(schema)) { // complex composed array type schemas not yet handled and the code returns early return fullPrefix + ""[]"" + closeChars; } ArraySchema arrayschema = (ArraySchema) schema; Schema itemSchema = arrayschema.getItems(); String itemModelName = getModelName(itemSchema); addSchemaToIncludedSchemaList(includedSchemas, schema); String itemExample = toExampleValueRecursive(itemModelName, itemSchema, objExample, indentationLevel + 1, """", exampleLine + 1, includedSchemas); if (StringUtils.isEmpty(itemExample) || cycleFound) { return fullPrefix + ""[]"" + closeChars; } else { return fullPrefix + ""["" + ""\n"" + itemExample + ""\n"" + closingIndentation + ""]"" + closeChars; } } else if (ModelUtils.isTypeObjectSchema(schema)) { if (modelName == null) { fullPrefix += ""dict(""; closeChars = "")""; } if (cycleFound) { return fullPrefix + closeChars; } Boolean hasProperties = (schema.getProperties() != null && !schema.getProperties().isEmpty()); CodegenDiscriminator disc = createDiscriminator(modelName, schema, openAPI); if (ModelUtils.isComposedSchema(schema)) { // complex composed object type schemas not yet handled and the code returns early if (hasProperties) { // what if this composed schema defined properties + allOf? return fullPrefix + closeChars; } ComposedSchema cs = (ComposedSchema) schema; Integer allOfExists = 0; if (cs.getAllOf() != null && !cs.getAllOf().isEmpty()) { allOfExists = 1; } Integer anyOfExists = 0; if (cs.getAnyOf() != null && !cs.getAnyOf().isEmpty()) { anyOfExists = 1; } Integer oneOfExists = 0; if (cs.getOneOf() != null && !cs.getOneOf().isEmpty()) { oneOfExists = 1; } if (allOfExists + anyOfExists + oneOfExists > 1) { // what if it needs one oneOf schema, one anyOf schema, and two allOf schemas? return fullPrefix + closeChars; } // for now only oneOf with discriminator is supported if (oneOfExists == 1 && disc != null) { ; } else { return fullPrefix + closeChars; } } if (disc != null) { MappedModel mm = getDiscriminatorMappedModel(disc); if (mm == null) { return fullPrefix + closeChars; } String discPropNameValue = mm.getMappingName(); String chosenModelName = mm.getModelName(); Schema modelSchema = getModelNameToSchemaCache().get(chosenModelName); CodegenProperty cp = new CodegenProperty(); cp.setName(disc.getPropertyName()); cp.setExample(discPropNameValue); return exampleForObjectModel(modelSchema, fullPrefix, closeChars, cp, indentationLevel, exampleLine, closingIndentation, includedSchemas); } Object addPropsObj = schema.getAdditionalProperties(); if (hasProperties) { return exampleForObjectModel(schema, fullPrefix, closeChars, null, indentationLevel, exampleLine, closingIndentation, includedSchemas); } else if (addPropsObj instanceof Schema) { // TODO handle true case for additionalProperties Schema addPropsSchema = (Schema) addPropsObj; String key = ""key""; Object addPropsExample = getObjectExample(addPropsSchema); if (addPropsSchema.getEnum() != null && !addPropsSchema.getEnum().isEmpty()) { key = addPropsSchema.getEnum().get(0).toString(); } addPropsExample = exampleFromStringOrArraySchema(addPropsSchema, addPropsExample, key); String addPropPrefix = key + ""=""; if (modelName == null) { addPropPrefix = ensureQuotes(key) + "": ""; } String addPropsModelName = getModelName(addPropsSchema); addSchemaToIncludedSchemaList(includedSchemas, schema); example = fullPrefix + ""\n"" + toExampleValueRecursive(addPropsModelName, addPropsSchema, addPropsExample, indentationLevel + 1, addPropPrefix, exampleLine + 1, includedSchemas) + "",\n"" + closingIndentation + closeChars; } else { example = fullPrefix + closeChars; } } else { LOGGER.warn(""Type "" + schema.getType() + "" not handled properly in toExampleValue""); } return example; }","[python experimental] Issue 13043: fixes toExampleValueRecursive stackoverflow (#13062) Fixes an issue in python-experimental that was causing a stackoverflow error. * Fixed by adding composed schemas to the list of 'includedSchemas' * Fixed an additional issue that was causing a schema to be added to the 'includedSchemas' list * Added a unit test with a minimal GeoJson spec to confirm results",https://github.com/OpenAPITools/openapi-generator/commit/4da8176b04d56741a636b9afb163d20026d255e0,,,modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/PythonExperimentalClientCodegen.java,3,java,False,2022-08-03T14:28:33Z "public static String readFile(File f,Charset charset) throws IOException { if(f==null || !f.exists()) { logger.warn(f +"" doesn't exist""); return """"; } logger.debug(""opening file "" + f); return FileUtils.readFileToString(f,charset); }","public static String readFile(File f,Charset charset) throws IOException { if(f==null || !f.exists()) { logger.warn(f.getAbsolutePath().replaceAll(""[\n\r\t]"", ""_"") +"" doesn't exist""); return """"; } logger.debug(""opening file "" + f.getAbsolutePath().replaceAll(""[\n\r\t]"", ""_"")); return FileUtils.readFileToString(f,charset); }",security fixes,https://github.com/nicho92/MtgDesktopCompanion/commit/6b46d264645f778218a8ca83c5806a51d525fd28,,,src/main/java/org/magic/tools/FileTools.java,3,java,False,2022-03-28T10:12:56Z "@Override public void onFailure(@NonNull Call call, @NonNull IOException exception) { onFailure.accept(new ApiException( ""OkHttp client request failed."", exception, ""See attached exception for more details."" )); }","@Override public void onFailure(@NonNull Call call, @NonNull IOException exception) { if (!call.isCanceled()) { onFailure.accept(new ApiException( ""OkHttp client request failed."", exception, ""See attached exception for more details."" )); } }",fix: check for canceled call to fix RxJava crash (#1441),https://github.com/aws-amplify/amplify-android/commit/60e7330a16e3da88316708a3b8480936d8907c89,,,aws-api/src/main/java/com/amplifyframework/api/aws/AppSyncGraphQLOperation.java,3,java,False,2021-08-05T21:29:11Z "def __init__(self, message=""Error Message not found."", *items): """""" Exception initializer. Arguments --------- message : str Error message to display with the exception. *items : VyperNode | Tuple[str, VyperNode], optional Vyper ast node(s), or tuple of (description, node) indicating where the exception occured. Source annotations are generated in the order the nodes are given. A single tuple of (lineno, col_offset) is also understood to support the old API, but new exceptions should not use this approach. """""" self.message = message self.lineno = None self.col_offset = None if len(items) == 1 and isinstance(items[0], tuple) and isinstance(items[0][0], int): # support older exceptions that don't annotate - remove this in the future! self.lineno, self.col_offset = items[0][:2] else: self.annotations = items","def __init__(self, message=""Error Message not found."", *items): """""" Exception initializer. Arguments --------- message : str Error message to display with the exception. *items : VyperNode | Tuple[str, VyperNode], optional Vyper ast node(s), or tuple of (description, node) indicating where the exception occured. Source annotations are generated in the order the nodes are given. A single tuple of (lineno, col_offset) is also understood to support the old API, but new exceptions should not use this approach. """""" self.message = message self.lineno = None self.col_offset = None if len(items) == 1 and isinstance(items[0], tuple) and isinstance(items[0][0], int): # support older exceptions that don't annotate - remove this in the future! self.lineno, self.col_offset = items[0][:2] else: # strip out None sources so that None can be passed as a valid # annotation (in case it is only available optionally) self.annotations = [k for k in items if k is not None]","fix: only allow valid identifiers to be nonreentrant keys disallow invalid identifiers like `"" ""`, `""123abc""` from being keys for non-reentrant locks. this commit also refactors the `validate_identifiers` helper function to be in the `ast/` subdirectory, and slightly improves the VyperException constructor by allowing None (optional) annotations.",https://github.com/vyperlang/vyper/commit/3c701654b4a067c19b723d019965275622aed033,,,vyper/exceptions.py,3,py,False,2023-09-15T12:38:42Z "@Override public Empire bestVictim() { if(searchedVictimThisTurn) { return bestVictim; } searchedVictimThisTurn = true; float highestScore = 0; Empire archEnemy = null; if(empire.contactedEmpires().isEmpty()) { bestVictim = archEnemy; return bestVictim; } int opponentsInRange = 1; for(Empire emp : empire.contactedEmpires()) { if(empire.inShipRange(emp.id)) opponentsInRange++; } for(Empire emp : empire.contactedEmpires()) { //Since there's allied victory, there's no reason to ever break up with our alliance if(empire.alliedWith(emp.id)) continue; if(!empire.inShipRange(emp.id)) continue; //The bigger we are, the more careful we are about whom to pick if(!empire.warEnemies().contains(emp)) { int upToWhatRank = 1 + opponentsInRange - empire.diplomatAI().popCapRank(true); //System.out.println(galaxy().currentTurn()+"" ""+empire.name()+"" my popcaprank: ""+empire.diplomatAI().popCapRank(true)+"" ""+emp.name()+"" military-rank: ""+empire.diplomatAI().militaryRank(emp, true) +"" threshold: ""+upToWhatRank+"" / ""+opponentsInRange); if(empire.diplomatAI().militaryRank(emp, true) < upToWhatRank) { //System.out.println(galaxy().currentTurn()+"" ""+empire.name()+"" skips ""+emp.name()+"" as potential enemy because military-rank: ""+empire.diplomatAI().militaryRank(emp, true) +"" is better than ""+upToWhatRank); continue; } } boolean incomingInvasion = false; float currentScore = 1 / fleetCenter(empire).distanceTo(colonyCenter(emp)); if(incomingInvasion) currentScore *= 2; //System.out.println(galaxy().currentTurn()+"" ""+empire.name()+"" vs ""+emp.name()+"" dist: ""+fleetCenter(empire).distanceTo(colonyCenter(emp))+"" score: ""+currentScore); if(currentScore > highestScore) { highestScore = currentScore; archEnemy = emp; } } /*if(archEnemy != null) System.out.println(galaxy().currentTurn()+"" ""+empire.name()+"" => ""+archEnemy.name()+"" score: ""+highestScore);*/ bestVictim = archEnemy; return bestVictim; }","@Override public Empire bestVictim() { if(searchedVictimThisTurn) { return bestVictim; } searchedVictimThisTurn = true; float highestScore = 0; Empire archEnemy = null; if(empire.contactedEmpires().isEmpty()) { bestVictim = archEnemy; return bestVictim; } int opponentsInRange = 1; for(Empire emp : empire.contactedEmpires()) { if(empire.inShipRange(emp.id)) opponentsInRange++; } for(Empire emp : empire.contactedEmpires()) { //Since there's allied victory, there's no reason to ever break up with our alliance if(empire.alliedWith(emp.id)) continue; if(!empire.inShipRange(emp.id)) continue; float currentScore = ((float)empire.diplomatAI().militaryRank(emp, true) / (float)empire.diplomatAI().popCapRank(emp, true)) * (fleetCenter(emp).distanceTo(colonyCenter(empire)) / fleetCenter(empire).distanceTo(colonyCenter(emp))); //System.out.println(galaxy().currentTurn()+"" ""+empire.name()+"" vs ""+emp.name()+"" dist: ""+fleetCenter(empire).distanceTo(colonyCenter(emp))+"" rev-dist: ""+fleetCenter(emp).distanceTo(colonyCenter(empire))+"" milrank: ""+empire.diplomatAI().militaryRank(emp, true)+"" poprank: ""+empire.diplomatAI().popCapRank(emp, true)+"" score: ""+currentScore); if(currentScore > highestScore) { highestScore = currentScore; archEnemy = emp; } } /*if(archEnemy != null) System.out.println(galaxy().currentTurn()+"" ""+empire.name()+"" => ""+archEnemy.name()+"" score: ""+highestScore);*/ bestVictim = archEnemy; return bestVictim; }","New algorithm to determine whom to go to war with (#71) * Update AIScientist.java Adjusted values of a bunch of techs. * Update AIShipCaptain.java Fixed accidental removal of range-adjustment in new target-selection-formula and removed unused code. * Update NewShipTemplate.java Allowing missiles to be used again under certain circumstances, taking ECM into account and basing weapon-decision on actual shield-levels rather than best possible. * Update TechMissileWeapon.java Fixed that 2-rack-missiles didn't have +1 speed as they should have according to official strategy-guide. * Update AIScientist.java Tech-Slider-Allocations now depend on racial-bonuses, not leader-personality. * Immersive Xilmi-AI When set to AI: Selectable, the Xilmi AI now goes in immersive-mode, once again making numerous uses of leader-traits. * Update CombatStackColony.java Fixed a bug, that planets without missile-bases always absorbed damage as if they already had a shield-built, even if they had none and even if they were in a nebula. * Tactical combat improvements Can now detect when someone protects another stack with repulsor-beams and retreats, when it cannot counter it with long-range-weapons. Optimal range for firing missiles increased by repulsor-radius so missile-ships won't be affected by the can't counter repulsors-detection. Missiles will now be held back until getting closer to prevent target from dodging them easily. Unused specials like Repulsor will no longer prevent ships from kiting. * Update AIShipCaptain.java Only kite when there's either repulsor-beam or missile-weapons installed on the ship. * Update AIFleetCommander.java Defending is only half as desirable as attacking now. * Immersive Xilmi-AI Lot's of changes for the personality-mode of Xilmi-AI. * Update DiplomaticEmbassy.java Fix for one empire still holding a grudge against the other when signing a peace-treaty. * Update AIShipCaptain.java Somehow the Xilmi-AI must have had conquered a system with a missile-base on it against another type of AI and then crashed at this place, I didn't even think it would get to for a colony. * Update AISpyMaster.java No longer consider computer-advantage for how much to spend into counter-espionage. * Race-fitting-playstyles implemented and leader-specfic-self-restrictions removed. * Update AIGeneral.java Invader-AI back to normal victim-selection. * Update AIGovernor.java Turns out espionage didn't work like I thought it would. So Darlok just building ships and relying on stealing techs was a bad idea. (You can only steal techs below your highest level in any given tree!) * Update AIDiplomat.java Fixed issue where AI wouldn't allow the player to ask for tech-trades and where they would take deals that are horrible for themselves when trading with other AIs. Trades are now usually all done within a 66%-150% tech-cost-range. * Update AIGeneral.java Giving themselves a personality/objective-combination that fits their behavior. * Update AIDiplomat.java Tech exchange only will work within same tier now. * Update AIGeneral.java Removed setting of personalities as this causes issue with missing texts. * Update AIScientist.java Fixed issue for Silicoids trading for Eco-restoration-techs. * Update ColonyDefense.java * Update ColonyDefense.java Shield will now only be built automatically under the following circumstances: There's missile-bases existing There's missile-bases needing to be upgraded There's missile-bases to be built * Update AIDiplomat.java Avoid false positives in war-declaration for incoming fleets when the system in question was only recently colonized. * Update AIShipCaptain.java Fixed a rare but not impossible crash. * Update AIDiplomat.java No longer accept joint-war-proposals from empires we like less than who they propose as victim. * Update AIGovernor.java Now building missile-bases... under very specific and rare circumstances. * Update AIShipCaptain.java Fixed crash when handling missile-bases. Individual stacks that can't find a target to attack no longer automatically retreat and instead let their behavior be governed by whether the whole fleet would want to retreat. * Update ColonyDefense.java Reverted previous changes which also happened to prevent AI from building shields. * Update CombatStackShip.java Fixed issue where multi-shot-weapons weren't reported as used when they were used. * Update AIFleetCommander.java Fleets now are split depending on their warp-speed unless they are on the way to their final-attack-target. * Update AIDiplomat.java Knowing about uncolonized systems no longer prevents wars. * Update CombatStackShip.java Revert change to shipComponentIsUsed * Update AIShipCaptain.java Moved logic that detects if a weapon has been used to this file. * Update AIScientist.java Try to avoid researching techs we know our neighbors already have since we can trade for it or steal it. * Update AIFleetCommander.java Colony ships now only ignore distance if they are huge as otherwise ignoring distance was horrible in late-game with hyperspace-communications. Keeping scout-designs around for longer. * Fixed a very annoying issue that caused eco-spending to become... insufficient and thus people to die when adjusting espionage- or security-spending. * Reserve-management-improvements Rich and Ultra-Rich planets now put their production into reserve when they would otherwise conduct research. Reserve will now try to keep an emergency-reserve for dealing with events like Supernova. Exceeding twice the amount of that reserve will always be spent so the money doesn't just lie around unused, when there's no new colonies that still need industry. * Update AIShipCaptain.java Removed an unneccessary white line 8[ * Update AIFleetCommander.java Reversed keeping scouts for longer * Update AIGovernor.java no industry, when under siege * Update AIGovernor.java Small fixed to sieged colonies building industry when they shouldn't. * Update Rotp.java Versioning 0.93a * Update RacesUI.java Race-selector no longer jumps after selecting a race. Race-selector scroll-speed when dragging is no longer amplified like the scroll-bar but instead moves 1:1 the distance dragged. * Update AIFleetCommander.java Smart-Path will no longer path over systems further away than the target-system. Fleets will now always be split by speed if more than 2/3rd of the fleet have the fastest speed possible. * Update AIGovernor.java Build more fleet when fighting someone who has no or extremely little fleet. * Update AIShipCaptain.java Kiting no longer uses path-finding during auto-resolve. Ships with repulsor and long-range will no longer get closer than 2 tiles before firing against ships that don't have long range. Will only retreat to system with enemy fleets when there's no system without enemy fleets to retreat to. * Update CombatStackColony.java Added override for optimal firing-range for missile-bases. It is 9. * Update CombatStackShip.java Optimal firing-range for ship-stacks with missiles will now be at least two when they have repulsors. * Update NewShipTemplate.java The willingness of the AI to use repulsor-beam now scales with how many opponent ships have long range. It will be higher if there's only a few but drop down to 0 if all opponent ships use them. * Update AI.java Improved logic for shuttling around population within the empire. * Update ShipBattleUI.java Fixed a bug where remaining commands were transferred from one stack to another, which could also cause a crash when missile-bases were involved. * Update Colony.java currentProductionCapacity now correctly takes into consideration how many factories are actually operated. * Update NewShipTemplate.java Fixes and improvements to special-selection. Mainly bigger emphasis on using cloaking-device and stasis-field. * Update AIShipDesigner.java Consider getting an important special like cloaking, stasis or black-hole-generator as reason to immediately make a new design. * Update SystemView.java Systems with enemy-fleets will now flash the Alert. Especially usefull when under siege by cloaked enemy fleets. * Update AIShipCaptain.java Added check whether retreat was possible when retreating for the reason that nothing can be done. * Update AIGovernor.java Taking natural pop-growth and the cost of terraforming into account when deciding to build factories or population. This usually results to prefering factories almost always when they can be operated. * War- and Peace-making changes. Prevent war-declaration when there's barely any fleet to attack with. Smarter selection of preferred victim. In particular taking their diplomatic status with others into account. Toned down overall aggressiveness. Several personalities now are taken into account for determining behavior. * Update General.java Don't attack too early. * Update AIFleetCommander.java Colony ships will now always prefer undefended targets instead of waiting for help if they want to colonize a defended system. * Update Rotp.java Version 0.93b * Update NewShipTemplate.java Not needing ranged weapon, when we have cloaking-device. * Improved behavior when using missiles to act according to expectations of /u/bot39lvl * Showing pop-growth at clean-eco. * New Version with u/bot39lvl recommended changes to missile-boat-handling * Fixed issue that caused ships being scrapped after loading a game, no longer taking incoming enemy fleets into consideration that are more than one turn away from reaching their target. * Stacks that want to retreat will now also try and damage their target if it is more than one space away as long as they don't use up all movement-points. Planets with no missile-bases will not become a target unless all non-bomb-weapons were used. * Fixed an issue where a new design would override a similar existing one. * When defending or when having better movement-speed now shall always try to get the 1st strike. * Not keeping a defensive fleet on duty when the incoming opponent attack will overwhelm them anyways. * Using more unique ship-names * Avoid ship-information being cut off by drawing ship-button-overlay into the upper direction as soon as a stack is below the middle of the screen. * Fixed exploit that allowed player to ignore enemy repulsor-beams via auto-resolve. * Fixed issue that caused missile-ships to sometimes retreat when they shouldn't. * Calling beam/missileDefense() method instead of looking at the member since the function also takes stealth into account which we want to do for better decision-making. * Ships with limited shot-weapons no longer think they can land all hits at once. * Best tech of each type no longer gets it's research-value reduced. * Halfed inertial-value again as it otherwise may suppress vital range-tech. * Prevent overbuilding colony-ships in lategame by taking into consideration when systems can build more than one per turn. * Design-names now use name of a system that is actually owned and add a number to make sure they are unique. * Fixed some issues with no longer firing before retreating after rework and now ignoring stacks in stasis for whether to retreat or not. * Evenly distributing population across the empire led to an increase of almost 30% productivity at a reference turn in tests and thus turned out to be a much better population-distribution-strategy when compared to the ""bring new colonies to 25%""-rule-of-thumb as suggested in the official-strategy-guide. * Last defending stacks in stasis are now also made to autoretreat as otherwise this would result in 100 turns of ""you can't do anything but watch"". * Avoid having more than two designs with Stasis-Field as it doesn't stack. * Should fix an issue that caused usage of Hyper-Space-Communications to be inefficient. * Futher optimization on population-shuttling. * Fixed possible crash from trying to make peace while being involved in a final war. * Fixed infinite loop when trying to scrap the last existing design. * Making much better use of natural growth. * Some further slight adjustments to economy-handling that lead to an even better result in my test. * Fix for ""Hyperspace Communications: can't reroute back to the starting planet - bug"" by setting system to null, when leaving the orbit. In this vein no longer check for a stargate-connection when a fleet isn't at a system anymore. * Only the victor and the owner of the colony fought over get a scan on the system. Not all participants. Especially not someone who fled from the orion-guardian and wanted to exploit this bug to get free high-end-techs! * Prepare next version number since Ray hasn't commited anything yet since the beginning of June. :( * Presumably a better fix to the issue of carrying over button-presses to the next stack. But I don't have a good save to test it. * Fixed that for certain techs the inherited baseValue method either had no override or the override did not reference to the corresponding AI-method. * Reverted fix for redirecting ships with hyperspace-communications to their source-system because it could crash the game when trying to redirect ships using rally-points. * Using same ship-design-naming-pattern for all types of ships so player can't idintify colony-ships by looking at the name. * Added missing override for baseValue from AI. * Made separate method for upgradeCost so it can be used from outside, like AI for example. * Fixed an issue where ships wouldn't retreat when they couldn't path to their preferred target. * Changed how much the AI values certain technologies. Most notably will it like warp-speed-improvements more. * Introduced an algorithm that guesses how long it will take to kill another empire and how long it would take the other empire to kill ourselves. This is used in target-selection and also in order to decide on whether we should go all in with our military. If we think the other empire can kill us more quickly than what it takes to benefit from investments into economy, we go all-in with building military. * Fixed an issue that prevented ships being sent back to where they came from while in space via using hyperspace-communications. Note: The intention of that code is already handled by the ""CanSendTo""-check just above of it. At this place the differientiation between beeing in transit is made, so that code was redundant for it's intended use-case. * Production- and reseach-modifier now considered in decision to build ships non-stop or not. Fixed bug that caused AI-colonies to not build ships when they should. Consider incoming transports in decision whether to build population or not. * Big revamp of dimplomatic AI-behavior. AI should now make much more sophisticated decisions about when to go to war. * No longer bolstering population of low-pop-systems during war as this is pretty exploitable and detracts from producting military. * Version * Fixed a weird issue that prevented AIs from bombarding each other unless the player had knowledge about who the owner of the system to be bombarded is. * Less willing to go to war, when there's other ways to expand. * Fixed issue with colonizers and hyper-space-communications, that I thought I had fixed before. When there's other possible targets to attack, a fleet waiting for invasion-forces, that can glass the system it is orbiting will split up and continue its attack. * Only building excess colonizers, when someone we know (including ourselves) is at war and there's potential to colonize systems that are freed up by that war. * At 72% and higher population a system wanting to build a colonizer will go all-in on it. This mostly affects Sakkra and Meklar, so they expand quicker and make more use of fast pop-growth. * Fixed extremely rare crash. * 0.93g * Guessing travel-time and impact of nebulae instead of actually calculating the correct travel-times including nebulae to improve turn-times. * No longer using bestVictim in ship-Design-Code. * Lower limit from transport-size removed. * Yet another big revamp about when to go to war. It's much more simple now. * Transports sent towards someone who we don't want to have a war with now will be set to surrender on arrival. Travel-distance-calculation simplified in favor of turn-processing. Fixed dysfunctional defense-code that was recently broken. * Pop-growth now plays a role in invasion-decisionmaking. Invasions now can occur without a fleet in orbit. Code for estimating kill-time now takes invasions into account. Drastically simplified victim-selection. * Due to the changes in how the AI handles it's fleets during the wait time for invasions the amount of bombers built was increased. * Changed how it is determined whether to retreat against fleets with repulsors. Fixed issue with not firing missiles under certain circumstances. Stacks of smaller ships fighting against stacks of bigger ships are now more likely to retreat, when they can't kill at least one of the bigger ships per turn. * Moved accidental-stargate-building-prevention-workaround to where it actually is effective. * Fixed an issue where a combat would end prematurely when missiles were fired but still on their way to their target. * Removed commented-out code * Removed actual war-weariness from the reasons to make peace as there's now other and better reasons to make peace. * Bombers are now more specialized as in better at bombing and worse at actual combat. * Bomb-Percentage now considers all opponents, not just the current enemy. * The usage of designs is now recognized by their loadout and not by what role it was assigned to it during design. * No longer super-heavy commitment to ship-production in war. Support of hybrid-playstyle. * Fixed issue that sometimes prevented shooting missiles. * Lowered counter-espionage by no longer looking at average tech-level of opponents but instead at tech-level of highest opponent. * Support for hybrid ship-designs and many tweaks- and fixes in scrapping-logic. * Setting eco-slider with a popup that promts for a percentage now uses the percentage of the amount that isn't required to keep clean. * Fixed previously integrated potential dead-lock. * Indentation * Fix for becoming enemy of others before they are in range in the always-war-mode. * Version-number for next inofficial build. * No security-spending when no contact. But luckily that actually makes no difference between it only actually gets detracted from income when there's contacts. * Revert ""Setting eco-slider with a popup that promts for a percentage now uses the percentage of the amount that isn't required to keep clean."" This reverts commit a2fe5dce3c1be344b6c96b6bfa1b5d16b321fafa. * Taught AI to use divert-reserve to research-checkbox * I don't know how it can happen but I've seen rare cases of colonies with negative-population. This is a workaround that changes them back to 1 pop. * Skip AI turn when corresponing empire is dead. * Fixed possible endless-loop from scrapping last existing ship-design. * Fixed issue where AI would build colonizers as bombers after having scrapped their last existing bomber-design. * Removed useless code. * Removed useless code. * Xilmi AI now capable of deciding when to use bio-weapons. * Bioweapon-support * New voting behavior: Xilmi Ai now votes for whoever they are most scared of but aren't at war with. * Fixed for undecisive behavior of launching an assault but retreating until transports arrive because developmentPct is no longer maxxed after sending transports. (War would still get triggered by the invasion but the fleet sent to accompany the invasion would retreat) * No longer escorting colony-ships on their way to presumably undefended systems. Reason: This oftentimes used a good portion of the fleet for no good reason, when they could be better used for attacking/defending. * Requiring closer range to fire missiles. * Lower score for using bio-weapons depending on how many missile-bases are seen. * No longer altering tech-allocations based on war-state. * New, more diverse and supposedly more interesting diplomatic behavior for AI. * Pick weapon to counter best enemy shield in use rather than average to avoid situations where lasers or scatterpack-V are countered too hard. Also: Make sure that there is a design with the most current bomb before considering bio-weapons. * Weapons that allow heavy-mounts don't get their value decreased so AI doesn't end up without decent repulsor-counter. * Moved negative-population workaround to a place where it is actually called. * Smarter decision-making about when to bomb or not to bomb during on-going invasions. * Incoming invasions of oneself should be slightly better covered but without tying too much of the fleet to it. * Choose target by distance from fleet. * Giving more cover to incoming invasions. * Made rank-check-functions available outside of diplomat too. * Always abstain if not both candidates are known. Superpowers should avoid wars. * Fixed an issue where defenders wouldn't always stay back when they should. * Don't hold back full power when in war anymore. * Quality of ships now more important for scrapping than before. * Reversed prior change in retreat-logic for smaller ships: Yes, the enemy could retreat but control over the system is probably more important than preserving some ships. * Fixed issue where AI would retreat from repulsors when they had missiles. * Minimum speed-requirement for missiles now takes repulsor-beams and diagonals into account. * AI will prepare their wars a little better and also take having to prepare into account before invadion. * No longer voting until both candidates are met. AI now knows much better to capitalize on an advantage and actually win the game instead of throwing it in a risky way. * Moved a debug-output to another place. * 0.93l * Better preparations before going to war. Removed alliances again. * Pick war-target by population-center rather than potential population center. * Fixed a bunch of issued leading to bad colony-ship-management in the lategame. * The better an AI is doing, the more careful they are about how to pick their enemies. * Increased minimum ship-maintenance-threshold for the early-game. * New version * Forgot to remove a debug-message. * Fixed issue reported by u/Individual_Act289: Transports launched before final war disappear on arrival. * Fixed logical error in maxFiringRange-method which could cause unwanted retreats. * When at war, AI will not make so many colony-ships, fixed issue where invasions wouldn't happen against partially built missile-bases, build more bombers when there's a high military-superiority * Willingness to defend now scales with defense-ratio. * Holding back before going to war as long as techs can still be easily researched. * AI will get a bit more tech when it's opportune instead of going for war. * Smart path will avoid paths where the detour would be longer than 50%, fleets that would otherwise go to a staging-point while they are orbiting an enemy will instead stay in orbit of the enemy. * Yet unused methor determining the required count of fighters to shoo scouts away. * Techs that are more than 5 levels behind the average will now be researched even if they are low priority. * Handling for enemy missile-frigates. * No longer scrap ships while at war. * Shields are seen as more useful, new way of determining what size ships should be. * enemyTransportsInTransit now also returns transports of neutral/cold-war-opponents * Created separate method unfriendlyTransportsInTransit * Improved algorithm to determine ship-design-size, reduction in score for hybrids without bombs * Run from missile code should no longer try to outrun missiles that are too close already * New method for unfriendlyTransportsInTransit used * Taught AI to protect their systems against scouting * Taught AI to protect their systems against scouting * Fixed issue that prevented scouts from being sent to long-range-targets when they were part of a fleet with other ships. * Xilmi-AI now declaring war at any poploss, not just at 30+ * Sanity check for fleeing from missiles: Only do it when something could actually be lost. * Prepare better for potential attacks. * Some code cleanup * Fixed issue where other ships than destroyers could be built as scout-repellers. * Avoid downsizing of weapons in non-destroyer-ships. * Distances need to be recalculated immediately after obtaining new system as otherwise AI would act on outdated information. In this case it led to the AI offering peace due to losing range on an opponent whos colony it just conquered despite that act bringing lots of new systems into range. * Fixed an issue where AI would consider an opponents contacts instead of their own when determining the opponents relative standing. Also no longer looking at empires outside of ship-range for potential wars. * Priority for my purpose needs to be above 1000 and below 1400. Below 1000 it gets into conflict with scouts and above 1400 it will rush out the ships under all circumstances. * The widespread usage of scout-repellers makes adding a weapon to a colony-ship much more important. * Added missing override for maxFiringRange * Fixed that after capturing a colony the default for max-bases was not used from the settings of the new owner. * Default for bases on new systems and whether excess-spending goes to research can now be changed in Remnants.cfg * Fixed issue that allowed ship-designs without weapons to be considered the best design. * Fixed a rare crash I had never seen before and can't really explain. * Now taking into account if a weapon would cause a lot of overkill and reduce it's score if it is the case. Most likely will only affect Death-Ray and maybe Mauler-Device. * Fixed an issue with negative-fleets and error-messages. Fixed an issue where systems of empires without income wouldn't be attacked when they had stealth-ships or were out of sensor-range. * Improved detection on whether scout-repellers are needed. Also forbid scout-repellers when unlimited range is available. * Removed code that would consistently scrap unused designs, which sometimes had unintended side-effects when building bigger ships. Replaced what it was meant for by something vastly better: A design-rotation that happens based on how much the design contributes to the maintenance-cost. When there's 4 available slots for combat-designs and one design takes up more than 1/3rd of the maintenance, a new design is enforced, even if it is the same as before. * Fixed issue where ships wouldn't shoot at nearby targets when they couldn't reach their preferred target. Rewrote combat-outcome-expectation to much better guess the expected outcome, which now also consideres auto-repair. * New algorithm to determine who is the best target for a war. * New algorithm to determine the ratio of bombers vs. fighters respectively bombs vs. anti-ship-weapons on a hybrid. * Fixed issue where huge colonizers wouldn't be built when Orion was reachable. * The slots for scouts and scout-repellers are no longer used during wars. * Improved strategic target-selection to better take ship-roles into account. * Fixed issue in bcValue not recognizing scouts of non-AI-player * Fixed several issues with design-scoring. (possible zero-division and using size instead of space) * Much more dedicated and better adapted defending-techniques. * Improved estimate on how many troops need to stay back in order to shoot down transports.",https://github.com/rayfowler/rotp-public/commit/2ec066ab66098db56a37be9f35ccf980ce38866b,,,src/rotp/model/ai/xilmi/AIGeneral.java,3,java,False,2021-10-12T17:22:38Z "function onCHANNEL_OPEN(self, info) { // the server is trying to open a channel with us, this is usually when // we asked the server to forward us connections on some port and now they // are asking us to accept/deny an incoming connection on their side var localChan = false; var reason; function accept() { var chaninfo = { type: info.type, incoming: { id: localChan, window: Channel.MAX_WINDOW, packetSize: Channel.PACKET_SIZE, state: 'open' }, outgoing: { id: info.sender, window: info.window, packetSize: info.packetSize, state: 'open' } }; var stream = new Channel(chaninfo, self); self._sshstream.channelOpenConfirm(info.sender, localChan, Channel.MAX_WINDOW, Channel.PACKET_SIZE); return stream; } function reject() { if (reason === undefined) { if (localChan === false) reason = consts.CHANNEL_OPEN_FAILURE.RESOURCE_SHORTAGE; else reason = consts.CHANNEL_OPEN_FAILURE.CONNECT_FAILED; } self._sshstream.channelOpenFail(info.sender, reason, '', ''); } if (info.type === 'forwarded-tcpip' || info.type === 'x11' || info.type === 'auth-agent@openssh.com' || info.type === 'forwarded-streamlocal@openssh.com') { // check for conditions for automatic rejection var rejectConn = ( (info.type === 'forwarded-tcpip' && self._forwarding[info.data.destIP + ':' + info.data.destPort] === undefined) || (info.type === 'forwarded-streamlocal@openssh.com' && self._forwardingUnix[info.data.socketPath] === undefined) || (info.type === 'x11' && self._acceptX11 === 0) || (info.type === 'auth-agent@openssh.com' && !self._agentFwdEnabled) ); if (!rejectConn) { localChan = nextChannel(self); if (localChan === false) { self.config.debug('DEBUG: Client: Automatic rejection of incoming channel open: no channels available'); rejectConn = true; } else self._channels[localChan] = true; } else { reason = consts.CHANNEL_OPEN_FAILURE.ADMINISTRATIVELY_PROHIBITED; self.config.debug('DEBUG: Client: Automatic rejection of incoming channel open: unexpected channel open for: ' + info.type); } // TODO: automatic rejection after some timeout? if (rejectConn) reject(); if (localChan !== false) { if (info.type === 'forwarded-tcpip') { if (info.data.destPort === 0) { info.data.destPort = self._forwarding[info.data.destIP + ':' + info.data.destPort]; } self.emit('tcp connection', info.data, accept, reject); } else if (info.type === 'x11') { self.emit('x11', info.data, accept, reject); } else if (info.type === 'forwarded-streamlocal@openssh.com') { self.emit('unix connection', info.data, accept, reject); } else { agentQuery(self.config.agent, accept, reject); } } } else { // automatically reject any unsupported channel open requests self.config.debug('DEBUG: Client: Automatic rejection of incoming channel open: unsupported type: ' + info.type); reason = consts.CHANNEL_OPEN_FAILURE.UNKNOWN_CHANNEL_TYPE; reject(); } }","function onCHANNEL_OPEN(self, info) { // The server is trying to open a channel with us, this is usually when // we asked the server to forward us connections on some port and now they // are asking us to accept/deny an incoming connection on their side let localChan = -1; let reason; const accept = () => { const chanInfo = { type: info.type, incoming: { id: localChan, window: MAX_WINDOW, packetSize: PACKET_SIZE, state: 'open' }, outgoing: { id: info.sender, window: info.window, packetSize: info.packetSize, state: 'open' } }; const stream = new Channel(self, chanInfo); self._chanMgr.update(localChan, stream); self._protocol.channelOpenConfirm(info.sender, localChan, MAX_WINDOW, PACKET_SIZE); return stream; }; const reject = () => { if (reason === undefined) { if (localChan === -1) reason = CHANNEL_OPEN_FAILURE.RESOURCE_SHORTAGE; else reason = CHANNEL_OPEN_FAILURE.CONNECT_FAILED; } self._protocol.channelOpenFail(info.sender, reason, ''); }; const reserveChannel = () => { localChan = self._chanMgr.add(); if (localChan === -1) { reason = CHANNEL_OPEN_FAILURE.RESOURCE_SHORTAGE; if (self.config.debug) { self.config.debug( 'Client: Automatic rejection of incoming channel open: ' + 'no channels available' ); } } return (localChan !== -1); }; const data = info.data; switch (info.type) { case 'forwarded-tcpip': { const val = self._forwarding[`${data.destIP}:${data.destPort}`]; if (val !== undefined && reserveChannel()) { if (data.destPort === 0) data.destPort = val; self.emit('tcp connection', data, accept, reject); return; } break; } case 'forwarded-streamlocal@openssh.com': if (self._forwardingUnix[data.socketPath] !== undefined && reserveChannel()) { self.emit('unix connection', data, accept, reject); return; } break; case 'auth-agent@openssh.com': if (self._agentFwdEnabled && reserveChannel()) { agentQuery(self.config.agent, accept, reject); return; } break; case 'x11': if (self._acceptX11 !== 0 && reserveChannel()) { self.emit('x11', data, accept, reject); return; } break; default: // Automatically reject any unsupported channel open requests reason = CHANNEL_OPEN_FAILURE.UNKNOWN_CHANNEL_TYPE; if (self.config.debug) { self.config.debug( 'Client: Automatic rejection of unsupported incoming channel open ' + `type: ${info.type}` ); } } if (reason === undefined) { reason = CHANNEL_OPEN_FAILURE.ADMINISTRATIVELY_PROHIBITED; if (self.config.debug) { self.config.debug( 'Client: Automatic rejection of unexpected incoming channel open for: ' + info.type ); } } reject(); }","examples,lib,test: switch to code rewrite For more information see: https://github.com/mscdex/ssh2/issues/935",https://github.com/mscdex/ssh2/commit/f763271f41320e71d5cbee02ea5bc6a2ded3ca21,CVE-2020-26301,['CWE-78'],lib/client.js,3,js,False,2020-10-07T19:57:49Z "@Override @Transactional(rollbackFor = Exception.class) public Result createDirectory(User loginUser, String name, String description, ResourceType type, int pid, String currentDir) { Result result = checkResourceUploadStartupState(); if (!result.getCode().equals(Status.SUCCESS.getCode())) { return result; } String fullName = currentDir.equals(""/"") ? String.format(""%s%s"",currentDir,name) : String.format(""%s/%s"",currentDir,name); result = verifyResource(loginUser, type, fullName, pid); if (!result.getCode().equals(Status.SUCCESS.getCode())) { return result; } if (checkResourceExists(fullName, 0, type.ordinal())) { logger.error(""resource directory {} has exist, can't recreate"", fullName); putMsg(result, Status.RESOURCE_EXIST); return result; } Date now = new Date(); Resource resource = new Resource(pid,name,fullName,true,description,name,loginUser.getId(),type,0,now,now); try { resourcesMapper.insert(resource); putMsg(result, Status.SUCCESS); Map dataMap = new BeanMap(resource); Map resultMap = new HashMap<>(); for (Map.Entry entry: dataMap.entrySet()) { if (!""class"".equalsIgnoreCase(entry.getKey().toString())) { resultMap.put(entry.getKey().toString(), entry.getValue()); } } result.setData(resultMap); } catch (DuplicateKeyException e) { logger.error(""resource directory {} has exist, can't recreate"", fullName); putMsg(result, Status.RESOURCE_EXIST); return result; } catch (Exception e) { logger.error(""resource already exists, can't recreate "", e); throw new ServiceException(""resource already exists, can't recreate""); } //create directory in hdfs createDirectory(loginUser,fullName,type,result); return result; }","@Override @Transactional(rollbackFor = Exception.class) public Result createDirectory(User loginUser, String name, String description, ResourceType type, int pid, String currentDir) { Result result = checkResourceUploadStartupState(); if (!result.getCode().equals(Status.SUCCESS.getCode())) { return result; } if (FileUtils.directoryTraversal(name)) { putMsg(result, Status.VERIFY_PARAMETER_NAME_FAILED); return result; } String fullName = currentDir.equals(""/"") ? String.format(""%s%s"",currentDir,name) : String.format(""%s/%s"",currentDir,name); result = verifyResource(loginUser, type, fullName, pid); if (!result.getCode().equals(Status.SUCCESS.getCode())) { return result; } if (checkResourceExists(fullName, 0, type.ordinal())) { logger.error(""resource directory {} has exist, can't recreate"", fullName); putMsg(result, Status.RESOURCE_EXIST); return result; } Date now = new Date(); Resource resource = new Resource(pid,name,fullName,true,description,name,loginUser.getId(),type,0,now,now); try { resourcesMapper.insert(resource); putMsg(result, Status.SUCCESS); Map dataMap = new BeanMap(resource); Map resultMap = new HashMap<>(); for (Map.Entry entry: dataMap.entrySet()) { if (!""class"".equalsIgnoreCase(entry.getKey().toString())) { resultMap.put(entry.getKey().toString(), entry.getValue()); } } result.setData(resultMap); } catch (DuplicateKeyException e) { logger.error(""resource directory {} has exist, can't recreate"", fullName); putMsg(result, Status.RESOURCE_EXIST); return result; } catch (Exception e) { logger.error(""resource already exists, can't recreate "", e); throw new ServiceException(""resource already exists, can't recreate""); } //create directory in hdfs createDirectory(loginUser,fullName,type,result); return result; }","[fix] Enhance name pre checker in resource center (#10094) (#10759) * [fix] Enhance name pre checker in resource center (#10094) * [fix] Enhance name pre checker in resource center Add file name and directory checker to avoid directory traversal * add some missing change and change docs * change var name in directoryTraversal * Fix ci (cherry picked from commit 63f835715f8ca8bff79c0e7177ebfa5917ebb3bd) * Add new constants",https://github.com/apache/dolphinscheduler/commit/23fae510dfdde1753e0a161f747c30ae5171fba1,,,dolphinscheduler-api/src/main/java/org/apache/dolphinscheduler/api/service/impl/ResourcesServiceImpl.java,3,java,False,2022-07-04T06:04:23Z "private static void syncCurios(LivingEntity livingEntity, ItemStack stack, LazyOptional currentCurio, LazyOptional prevCurio, String identifier, int index, HandlerType type) { boolean syncable = currentCurio.map(curio -> curio.canSync(identifier, index, livingEntity)).orElse(false) || prevCurio.map(curio -> curio.canSync(identifier, index, livingEntity)).orElse(false); CompoundNBT syncTag = syncable ? currentCurio.map(ICurio::writeSyncData).orElse(new CompoundNBT()) : new CompoundNBT(); NetworkHandler.INSTANCE .send(PacketDistributor.TRACKING_ENTITY_AND_SELF.with(() -> livingEntity), new SPacketSyncStack(livingEntity.getEntityId(), identifier, index, stack, type, syncTag)); }","private static void syncCurios(LivingEntity livingEntity, ItemStack stack, LazyOptional currentCurio, LazyOptional prevCurio, String identifier, int index, HandlerType type) { boolean syncable = currentCurio.map(curio -> curio.canSync(identifier, index, livingEntity)).orElse(false) || prevCurio.map(curio -> curio.canSync(identifier, index, livingEntity)).orElse(false); CompoundNBT syncTag = syncable ? currentCurio.map(curio -> { CompoundNBT tag = curio.writeSyncData(); return tag != null ? tag : new CompoundNBT(); }).orElse(new CompoundNBT()) : new CompoundNBT(); NetworkHandler.INSTANCE .send(PacketDistributor.TRACKING_ENTITY_AND_SELF.with(() -> livingEntity), new SPacketSyncStack(livingEntity.getEntityId(), identifier, index, stack, type, syncTag)); }","fix null nbt tag crash, closes #152",https://github.com/TheIllusiveC4/Curios/commit/ade9786152f9a4b02c1f184f250ca8208a0b343f,,,src/main/java/top/theillusivec4/curios/common/event/CuriosEventHandler.java,3,java,False,2021-09-11T21:56:32Z "public List findAll(String path, S conf) { Preconditions.checkArgument(path != null, ""path may not be null""); List factories = new ArrayList<>(mFactories); String libDir = PathUtils.concatPath(conf.getString(PropertyKey.HOME), ""lib""); String extensionDir = conf.getString(PropertyKey.EXTENSIONS_DIR); scanLibs(factories, libDir); scanExtensions(factories, extensionDir); List eligibleFactories = new ArrayList<>(); for (T factory : factories) { if (factory.supportsPath(path, conf)) { LOG.debug(""Factory implementation {} is eligible for path {}"", factory, path); eligibleFactories.add(factory); } } if (eligibleFactories.isEmpty()) { LOG.warn(""No factory implementation supports the path {}"", path); } return eligibleFactories; }","public List findAll(String path, S conf) { Preconditions.checkArgument(path != null, ""path may not be null""); List eligibleFactories = scanRegistered(path, conf); if (!eligibleFactories.isEmpty()) { LOG.debug(""Find {} eligible items from registered factories for path {}"", eligibleFactories.size(), path); return eligibleFactories; } List factories = new ArrayList<>(mFactories); String libDir = PathUtils.concatPath(conf.getString(PropertyKey.HOME), ""lib""); String extensionDir = conf.getString(PropertyKey.EXTENSIONS_DIR); scanLibs(factories, libDir); scanExtensions(factories, extensionDir); for (T factory : factories) { if (factory.supportsPath(path, conf)) { LOG.debug(""Factory implementation {} is eligible for path {}"", factory, path); eligibleFactories.add(factory); } } if (eligibleFactories.isEmpty()) { LOG.warn(""No factory implementation supports the path {}"", path); } return eligibleFactories; }","Save the registered factories and look up from this collection first Fixes https://github.com/Alluxio/alluxio/issues/16001 ### What changes are proposed in this pull request? Save the registered factories and look up from this collection first. ### Why are the changes needed? Reduce the memory consumption of metaspace and avoid master crash due to OutOfMemory of metaspace. ### Does this PR introduce any user facing changes? No. pr-link: Alluxio/alluxio#16145 change-id: cid-74e8604d1d4e1458c3c37378b7a67e1d5d264f3c",https://github.com/Alluxio/alluxio/commit/b544e6fe6b86ca65882eacbd2297c48b475a122c,,,core/common/src/main/java/alluxio/extensions/ExtensionFactoryRegistry.java,3,java,False,2022-09-23T07:37:50Z "static Document loadXmlDoc(String uri) throws Exception { DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance(); DocumentBuilder db = dbf.newDocumentBuilder(); Document doc = db.parse(uri); return doc; }","static Document loadXmlDoc(String uri) throws Exception { DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance(); dbf.setFeature(""http://apache.org/xml/features/disallow-doctype-decl"", true); DocumentBuilder db = dbf.newDocumentBuilder(); Document doc = db.parse(uri); return doc; }",rt,https://github.com/variflight/feeyo-redisproxy/commit/ce9d394cd2e0066d5520c4a1f75bf9915445454e,,,src/main/java/com/feeyo/kafka/config/loader/KafkaConfigLoader.java,3,java,False,2022-08-05T10:02:22Z "def on_header_end(self) -> None: message = (MultiPartMessage.HEADER_END, b"""") self.messages.append(message)","def on_header_end(self) -> None: field = self._current_partial_header_name.lower() if field == b""content-disposition"": self._current_part.content_disposition = self._current_partial_header_value self._current_part.item_headers.append( (field, self._current_partial_header_value) ) self._current_partial_header_name = b"""" self._current_partial_header_value = b""""","Merge pull request from GHSA-74m5-2c7w-9w3x * ♻️ Refactor multipart parser logic to support limiting max fields and files * ✨ Add support for new request.form() parameters max_files and max_fields * ✅ Add tests for limiting max fields and files in form data * 📝 Add docs about request.form() with new parameters max_files and max_fields * 📝 Update `docs/requests.md` Co-authored-by: Marcelo Trylesinski * 📝 Tweak docs for request.form() * ✏ Fix typo in `starlette/formparsers.py` Co-authored-by: Adrian Garcia Badaracco <1755071+adriangb@users.noreply.github.com> --------- Co-authored-by: Marcelo Trylesinski Co-authored-by: Adrian Garcia Badaracco <1755071+adriangb@users.noreply.github.com>",https://github.com/encode/starlette/commit/8c74c2c8dba7030154f8af18e016136bea1938fa,,,starlette/formparsers.py,3,py,False,2023-02-14T08:01:32Z "private void sendWithUser( Transport.Connection connection, String action, TransportRequest request, TransportRequestOptions options, TransportResponseHandler handler, AsyncSender sender ) { if (securityContext.getAuthentication() == null) { // we use an assertion here to ensure we catch this in our testing infrastructure, but leave the ISE for cases we do not catch // in tests and may be hit by a user assertNoAuthentication(action); throw new IllegalStateException(""there should always be a user when sending a message for action ["" + action + ""]""); } try { sender.sendRequest(connection, action, request, options, handler); } catch (Exception e) { handler.handleException(new SendRequestTransportException(connection.getNode(), action, e)); } }","private void sendWithUser( Transport.Connection connection, String action, TransportRequest request, TransportRequestOptions options, TransportResponseHandler handler, AsyncSender sender ) { if (securityContext.getAuthentication() == null) { // we use an assertion here to ensure we catch this in our testing infrastructure, but leave the ISE for cases we do not catch // in tests and may be hit by a user assertNoAuthentication(action); throw new IllegalStateException(""there should always be a user when sending a message for action ["" + action + ""]""); } assert securityContext.getParentAuthorization() == null || remoteClusterAliasResolver.apply(connection).isPresent() == false : ""parent authorization header should not be set for remote cluster requests""; try { sender.sendRequest(connection, action, request, options, handler); } catch (Exception e) { handler.handleException(new SendRequestTransportException(connection.getNode(), action, e)); } }","Pre-authorize child search transport actions (#91886) This PR aims to improve authorization performance of `indices:data/read/search` action by avoiding authorizing the transport child actions on every node. The focus is on index search child actions since they are accessing just a subset of parent's indices. Some optimizations already exist which allow the children of authorized parent actions on the same node to skip authorization (#77221). This PR adds ability to do the same optimization, but for search child actions that are executed on remote nodes in the same cluster. The optimization is realized through ""parent"" authorization header. The header is set in the thread context when parent action is successfully authorized and removed after it has been used to skip child authorization. It's worth noting that a parent authorization header is removed in two other cases: - before request is sent to a remote cluster - when transport action being sent is not a child of a parent for which authorization exists in thread context",https://github.com/elastic/elasticsearch/commit/8bccf664b0c3d8814c485256a475e6a1857ede5c,,,x-pack/plugin/security/src/main/java/org/elasticsearch/xpack/security/transport/SecurityServerTransportInterceptor.java,3,java,False,2022-12-19T15:33:02Z "public SavingsAccountTransactionData findLastTransaction(final LocalDate date) { SavingsAccountTransactionData savingsTransaction = null; List trans = getTransactions(); for (final SavingsAccountTransactionData transaction : trans) { if (transaction.isNotReversed() && transaction.occursOn(date)) { savingsTransaction = transaction; break; } } return savingsTransaction; }","public SavingsAccountTransactionData findLastTransaction(final LocalDate date) { SavingsAccountTransactionData savingsTransaction = null; List trans = getTransactions(); for (final SavingsAccountTransactionData transaction : trans) { if (transaction.isNotReversed() && !transaction.isReversalTransaction() && transaction.occursOn(date)) { savingsTransaction = transaction; break; } } return savingsTransaction; }","fineract-1646 and fineract-1638 combined fix (#2457) authored-by: Dhaval Maniyar ",https://github.com/apache/fineract/commit/a80f589ad4ad91a7b1c8abbd864e6a5129e8e2cf,,,fineract-provider/src/main/java/org/apache/fineract/portfolio/savings/data/SavingsAccountData.java,3,java,False,2022-07-28T08:30:15Z "public void validate(@Nullable TokenBinding clientDataTokenBinding, @Nullable byte[] serverTokenBindingId) { if (clientDataTokenBinding != null) { byte[] clientDataTokenBindingId; if (clientDataTokenBinding.getId() == null) { clientDataTokenBindingId = null; } else { clientDataTokenBindingId = Base64UrlUtil.decode(clientDataTokenBinding.getId()); } TokenBindingStatus tokenBindingStatus = clientDataTokenBinding.getStatus(); switch (tokenBindingStatus) { case NOT_SUPPORTED: case SUPPORTED: break; case PRESENT: if (!Arrays.equals(clientDataTokenBindingId, serverTokenBindingId)) { throw new TokenBindingException(""TokenBinding id does not match""); } } } }","public void validate(@Nullable TokenBinding clientDataTokenBinding, @Nullable byte[] serverTokenBindingId) { if (clientDataTokenBinding != null) { byte[] clientDataTokenBindingId; if (clientDataTokenBinding.getId() == null) { clientDataTokenBindingId = null; } else { clientDataTokenBindingId = Base64UrlUtil.decode(clientDataTokenBinding.getId()); } TokenBindingStatus tokenBindingStatus = clientDataTokenBinding.getStatus(); switch (tokenBindingStatus) { case NOT_SUPPORTED: case SUPPORTED: break; case PRESENT: if (!MessageDigest.isEqual(clientDataTokenBindingId, serverTokenBindingId)) { throw new TokenBindingException(""TokenBinding id does not match""); } } } }","Rewrite Arrays.equals to MessageDigest.isEqual to protect from timing attack Note: It was already protected by message signing, there was no security vulnerability. This change is for improvement.",https://github.com/webauthn4j/webauthn4j/commit/875509e170a5f7475773bad9240634c7e0453821,,,webauthn4j-core/src/main/java/com/webauthn4j/validator/TokenBindingValidator.java,3,java,False,2021-08-13T11:21:00Z "Uri updateMediaProvider(@NonNull ContentProviderClient mediaProvider, @NonNull ContentValues mediaValues) { final String filePath = mediaValues.getAsString(MediaStore.DownloadColumns.DATA); Uri mediaStoreUri = getMediaStoreUri(mediaProvider, filePath); try { if (mediaStoreUri == null) { mediaStoreUri = mediaProvider.insert( Helpers.getContentUriForPath(getContext(), filePath), mediaValues); if (mediaStoreUri == null) { Log.e(Constants.TAG, ""Error inserting into mediaProvider: "" + mediaValues); } return mediaStoreUri; } else { if (mediaProvider.update(mediaStoreUri, mediaValues, null, null) != 1) { Log.e(Constants.TAG, ""Error updating MediaProvider, uri: "" + mediaStoreUri + "", values: "" + mediaValues); } return mediaStoreUri; } } catch (RemoteException e) { // Should not happen } return null; }","Uri updateMediaProvider(@NonNull ContentProviderClient mediaProvider, @NonNull ContentValues mediaValues) { final String filePath = mediaValues.getAsString(MediaStore.DownloadColumns.DATA); Uri mediaStoreUri = getMediaStoreUri(mediaProvider, filePath); try { if (mediaStoreUri == null) { mediaStoreUri = mediaProvider.insert( Helpers.getContentUriForPath(getContext(), filePath), mediaValues); if (mediaStoreUri == null) { Log.e(Constants.TAG, ""Error inserting into mediaProvider: "" + mediaValues); } return mediaStoreUri; } else { if (mediaProvider.update(mediaStoreUri, mediaValues, null, null) != 1) { Log.e(Constants.TAG, ""Error updating MediaProvider, uri: "" + mediaStoreUri + "", values: "" + mediaValues); } return mediaStoreUri; } } catch (IllegalArgumentException ignored) { // Insert or update MediaStore failed. At this point we can't do // much here. If the file belongs to MediaStore collection, it will // get added to MediaStore collection during next scan, and we will // obtain the uri to the file in the next MediaStore#scanFile // initiated by us Log.w(Constants.TAG, ""Couldn't update MediaStore for "" + filePath, ignored); } catch (RemoteException e) { // Should not happen } return null; }","Ignore IllegalArgumentException from MediaProvider operations Inserting new MediaStore entries for files in app private directories leads to IllegalArgumentException in Android S-OS and above. DownloadProvider tries to insert MediaStore entry for files in app external directories when doing sync after OS upgrade from Android P to Android S. To avoid crashing DownloadProvider, we ignore the IllegalArgumentException. Bug: 195185812 Test: Tests will be added as part of b/196028977 Change-Id: Idf95a75c8101246a2650fe69f476f9372b9cebd7",https://github.com/aosp-mirror/platform_packages_providers_downloadprovider/commit/4cc6f519fd4e9b12fb688e20364a92dc3f4e5dc9,,,src/com/android/providers/downloads/DownloadProvider.java,3,java,False,2021-08-09T16:30:11Z "public ItemStack finishUsing(ItemStack stack, World world, LivingEntity entity) { ailment.get(entity).ifPresent(ailment -> ailment.effect().afflict((PlayerEntity)entity, stack)); return stack; }","public ItemStack finishUsing(ItemStack stack, World world, LivingEntity entity) { if (entity instanceof PlayerEntity player) { ailment.get(entity).ifPresent(ailment -> ailment.effect().afflict(player, stack)); } return stack; }",Fixed crash when an entity other than the player tries to eat,https://github.com/Sollace/Unicopia/commit/64be265c04328223bb148c752792b70912e54fd7,,,src/main/java/com/minelittlepony/unicopia/item/toxin/Toxic.java,3,java,False,2022-10-03T21:44:48Z "public AuthResult auth(final HttpServletRequest request, final String scope, final String responseType, final String clientId, final String redirectUri, @Nullable final String nonce, @Nullable final String state, @Nullable final String prompt) { URI result; AuthStatus authStatus = null; OpenIdClient oAuth2Client = openIdClientDetailsFactory.getClient(clientId); final Pattern pattern = Pattern.compile(oAuth2Client.getUriPattern()); if (!pattern.matcher(redirectUri).matches()) { throw new BadRequestException(UNKNOWN_SUBJECT, AuthenticateOutcomeReason.OTHER.value(), ""Redirect URI is not allowed""); } // If the prompt is 'login' then we always want to prompt the user to login in with username and password. final boolean requireLoginPrompt = prompt != null && prompt.equalsIgnoreCase(""login""); if (requireLoginPrompt) { LOGGER.info(""Relying party requested a user login page by using 'prompt=login'""); } if (requireLoginPrompt) { LOGGER.debug(""Login has been requested by the RP""); result = authenticationService.createSignInUri(redirectUri); } else { // We need to make sure our understanding of the session is correct authStatus = authenticationService.currentAuthState(request); if (authStatus.getError().isPresent()) { LOGGER.error(""Error authenticating request {} got {}"", request.getRequestURI(), authStatus.getError().get()); result = UriBuilder.fromUri(uriFactory.uiUri(AuthenticationService.UNAUTHORISED_URL_PATH)).build(); } else if (authStatus.getAuthState().isPresent()) { // If we have an authenticated session then the user is logged in final AuthState authState = authStatus.getAuthState().get(); // If the users password still needs tp be changed then send them back to the login page. if (authState.isRequirePasswordChange()) { result = authenticationService.createSignInUri(redirectUri); } else { LOGGER.debug(""User has a session, sending them back to the RP""); // We need to make sure we record this access code request. final String accessCode = createAccessCode(); final String token = createIdToken(clientId, authState.getSubject(), nonce, state); final AccessCodeRequest accessCodeRequest = new AccessCodeRequest( scope, responseType, clientId, redirectUri, nonce, state, prompt, token); accessCodeCache.put(accessCode, accessCodeRequest); result = buildRedirectionUrl(redirectUri, accessCode, state); } } else { LOGGER.debug(""User has no session and no certificate - sending them to login.""); result = authenticationService.createSignInUri(redirectUri); } } return new AuthResult(result, authStatus); }","public AuthResult auth(final HttpServletRequest request, final String scope, final String responseType, final String clientId, final String redirectUri, @Nullable final String nonce, @Nullable final String state, @Nullable final String prompt) { URI result; AuthStatus authStatus = null; OpenIdClient oAuth2Client = openIdClientDetailsFactory.getClient(clientId); final Pattern pattern = Pattern.compile(oAuth2Client.getUriPattern()); if (!pattern.matcher(redirectUri).matches()) { authStatus = new AuthStatus(){ @Override public Optional getAuthState() { return Optional.empty(); } @Override public Optional getError() { return Optional.of (new BadRequestException(UNKNOWN_SUBJECT, AuthenticateOutcomeReason.OTHER.value(), ""Redirect URI is not allowed"")); } @Override public boolean isNew() { return true; } }; result = authenticationService.createSignInUri(redirectUri); } else { // If the prompt is 'login' then we always want to prompt the user to login in with username and password. final boolean requireLoginPrompt = prompt != null && prompt.equalsIgnoreCase(""login""); if (requireLoginPrompt) { LOGGER.info(""Relying party requested a user login page by using 'prompt=login'""); } if (requireLoginPrompt) { LOGGER.debug(""Login has been requested by the RP""); result = authenticationService.createSignInUri(redirectUri); } else { // We need to make sure our understanding of the session is correct authStatus = authenticationService.currentAuthState(request); if (authStatus.getError().isPresent()) { LOGGER.error(""Error authenticating request {} for {} got {} - {}"", request.getRequestURI(), authStatus.getError().get().getSubject(), authStatus.getError().get().getReason(), authStatus.getError().get().getMessage()); //Send back to log in with username/password result = authenticationService.createSignInUri(redirectUri); } else if (authStatus.getAuthState().isPresent()) { // If we have an authenticated session then the user is logged in final AuthState authState = authStatus.getAuthState().get(); // If the users password still needs tp be changed then send them back to the login page. if (authState.isRequirePasswordChange()) { result = authenticationService.createSignInUri(redirectUri); } else { LOGGER.debug(""User has a session, sending them back to the RP""); // We need to make sure we record this access code request. final String accessCode = createAccessCode(); final String token = createIdToken(clientId, authState.getSubject(), nonce, state); final AccessCodeRequest accessCodeRequest = new AccessCodeRequest( scope, responseType, clientId, redirectUri, nonce, state, prompt, token); accessCodeCache.put(accessCode, accessCodeRequest); result = buildRedirectionUrl(redirectUri, accessCode, state); } } else { LOGGER.debug(""User has no session and no certificate - sending them to login.""); result = authenticationService.createSignInUri(redirectUri); } } } return new AuthResult(result, authStatus); }",Redirect unauthorised users to username/password login page,https://github.com/gchq/stroom/commit/3a976a8a4779245d311269c943af4c06a02245be,,,stroom-security/stroom-security-identity/src/main/java/stroom/security/identity/openid/OpenIdService.java,3,java,False,2021-04-01T13:11:41Z "@Override public AuthenticationContext authenticate(RequestContext requestContext) throws APISecurityException { String jwtToken = retrieveAuthHeaderValue(requestContext); String splitToken[] = jwtToken.split(""\\s""); // Extract the token when it is sent as bearer token. i.e Authorization: Bearer if (splitToken.length > 1) { jwtToken = splitToken[1]; } String context = requestContext.getMatchedAPI().getAPIConfig().getBasePath(); String name = requestContext.getMatchedAPI().getAPIConfig().getName(); String version = requestContext.getMatchedAPI().getAPIConfig().getVersion(); context = context + ""/"" + version; ResourceConfig matchingResource = requestContext.getMatchedResourcePath(); String httpMethod = requestContext.getMatchedResourcePath().getMethod().toString(); SignedJWTInfo signedJWTInfo; try { signedJWTInfo = getSignedJwt(jwtToken); } catch (ParseException | IllegalArgumentException e) { throw new SecurityException(""Not a JWT token. Failed to decode the token header."", e); } JWTClaimsSet claims = signedJWTInfo.getJwtClaimsSet(); String jwtTokenIdentifier = getJWTTokenIdentifier(signedJWTInfo); String jwtHeader = signedJWTInfo.getSignedJWT().getHeader().toString(); if (StringUtils.isNotEmpty(jwtTokenIdentifier)) { if (RevokedJWTDataHolder.isJWTTokenSignatureExistsInRevokedMap(jwtTokenIdentifier)) { if (log.isDebugEnabled()) { log.debug(""Token retrieved from the revoked jwt token map. Token: "" + FilterUtils.getMaskedToken(jwtHeader)); } log.error(""Invalid JWT token. "" + FilterUtils.getMaskedToken(jwtHeader)); throw new APISecurityException(APIConstants.StatusCodes.UNAUTHENTICATED.getCode(), APISecurityConstants.API_AUTH_INVALID_CREDENTIALS, ""Invalid JWT token""); } } JWTValidationInfo validationInfo = getJwtValidationInfo(signedJWTInfo, jwtTokenIdentifier); if (validationInfo != null) { if (validationInfo.isValid()) { // Validate subscriptions APIKeyValidationInfoDTO apiKeyValidationInfoDTO = null; EnforcerConfig configuration = ConfigHolder.getInstance().getConfig(); ExtendedTokenIssuerDto issuerDto = configuration.getIssuersMap().get(validationInfo.getIssuer()); //TODO: enable subscription validation if (issuerDto.isValidateSubscriptions()) { JSONObject api = validateSubscriptionFromClaim(name, version, claims, splitToken, true); if (api == null) { if (log.isDebugEnabled()) { log.debug(""Begin subscription validation via Key Manager: "" + validationInfo.getKeyManager()); } apiKeyValidationInfoDTO = validateSubscriptionUsingKeyManager(requestContext, validationInfo); // set endpoint security SecurityInfo securityInfo; if (apiKeyValidationInfoDTO != null && apiKeyValidationInfoDTO.getType() != null && requestContext.getMatchedAPI().getAPIConfig().getEndpointSecurity() != null) { if (apiKeyValidationInfoDTO.getType().equals(APIConstants.API_KEY_TYPE_PRODUCTION)) { securityInfo = requestContext.getMatchedAPI().getAPIConfig().getEndpointSecurity(). getProductionSecurityInfo(); } else { securityInfo = requestContext.getMatchedAPI().getAPIConfig().getEndpointSecurity(). getSandBoxSecurityInfo(); } if (securityInfo.getEnabled() && APIConstants.AUTHORIZATION_HEADER_BASIC. equalsIgnoreCase(securityInfo.getSecurityType())) { // use constants requestContext.addResponseHeaders(APIConstants.AUTHORIZATION_HEADER_DEFAULT, APIConstants.AUTHORIZATION_HEADER_BASIC + "" "" + Base64.getEncoder().encodeToString((securityInfo.getUsername() + "":"" + securityInfo.getPassword()).getBytes())); } } if (log.isDebugEnabled()) { log.debug(""Subscription validation via Key Manager. Status: "" + apiKeyValidationInfoDTO .isAuthorized()); } if (!apiKeyValidationInfoDTO.isAuthorized()) { throw new APISecurityException(APIConstants.StatusCodes.UNAUTHORIZED.getCode(), apiKeyValidationInfoDTO.getValidationStatus(), ""User is NOT authorized to access the Resource. "" + ""API Subscription validation failed.""); } } } // Validate scopes validateScopes(context, version, matchingResource, validationInfo, signedJWTInfo); log.debug(""JWT authentication successful.""); String endUserToken = null; // Get jwtConfigurationDto JWTConfigurationDto jwtConfigurationDto = ConfigHolder.getInstance().getConfig(). getJwtConfigurationDto(); if (jwtConfigurationDto.isEnabled()) { // Set ttl jwtConfigurationDto.setTtl(JWTUtil.getTTL()); JWTInfoDto jwtInfoDto = FilterUtils .generateJWTInfoDto(null, validationInfo, apiKeyValidationInfoDTO, requestContext); endUserToken = generateAndRetrieveJWTToken(jwtTokenIdentifier, jwtInfoDto); // Set generated jwt token as a response header requestContext.addResponseHeaders(jwtConfigurationDto.getJwtHeader(), endUserToken); } AuthenticationContext authenticationContext = FilterUtils .generateAuthenticationContext(requestContext, jwtTokenIdentifier, validationInfo, apiKeyValidationInfoDTO, endUserToken, true); //TODO: (VirajSalaka) Place the keytype population logic properly for self contained token if (claims.getClaim(""keytype"") != null) { authenticationContext.setKeyType(claims.getClaim(""keytype"").toString()); } return authenticationContext; } else { throw new APISecurityException(APIConstants.StatusCodes.UNAUTHENTICATED.getCode(), validationInfo.getValidationCode(), APISecurityConstants.getAuthenticationFailureMessage(validationInfo.getValidationCode())); } } else { throw new APISecurityException(APIConstants.StatusCodes.UNAUTHENTICATED.getCode(), APISecurityConstants.API_AUTH_GENERAL_ERROR, APISecurityConstants.API_AUTH_GENERAL_ERROR_MESSAGE); } }","@Override public AuthenticationContext authenticate(RequestContext requestContext) throws APISecurityException { String jwtToken = retrieveAuthHeaderValue(requestContext); if (jwtToken == null || !jwtToken.toLowerCase().contains(JWTConstants.BEARER)) { throw new SecurityException(""Authorization header is not in correct format. Authorization: Bearer ""); } String[] splitToken = jwtToken.split(""\\s""); // Extract the token when it is sent as bearer token. i.e Authorization: Bearer if (splitToken.length > 1) { jwtToken = splitToken[1]; } String context = requestContext.getMatchedAPI().getAPIConfig().getBasePath(); String name = requestContext.getMatchedAPI().getAPIConfig().getName(); String version = requestContext.getMatchedAPI().getAPIConfig().getVersion(); context = context + ""/"" + version; ResourceConfig matchingResource = requestContext.getMatchedResourcePath(); String httpMethod = requestContext.getMatchedResourcePath().getMethod().toString(); SignedJWTInfo signedJWTInfo; try { signedJWTInfo = getSignedJwt(jwtToken); } catch (ParseException | IllegalArgumentException e) { throw new SecurityException(""Not a JWT token. Failed to decode the token header."", e); } JWTClaimsSet claims = signedJWTInfo.getJwtClaimsSet(); String jwtTokenIdentifier = getJWTTokenIdentifier(signedJWTInfo); String jwtHeader = signedJWTInfo.getSignedJWT().getHeader().toString(); if (StringUtils.isNotEmpty(jwtTokenIdentifier)) { if (RevokedJWTDataHolder.isJWTTokenSignatureExistsInRevokedMap(jwtTokenIdentifier)) { if (log.isDebugEnabled()) { log.debug(""Token retrieved from the revoked jwt token map. Token: "" + FilterUtils.getMaskedToken(jwtHeader)); } log.error(""Invalid JWT token. "" + FilterUtils.getMaskedToken(jwtHeader)); throw new APISecurityException(APIConstants.StatusCodes.UNAUTHENTICATED.getCode(), APISecurityConstants.API_AUTH_INVALID_CREDENTIALS, ""Invalid JWT token""); } } JWTValidationInfo validationInfo = getJwtValidationInfo(signedJWTInfo, jwtTokenIdentifier); if (validationInfo != null) { if (validationInfo.isValid()) { // Validate subscriptions APIKeyValidationInfoDTO apiKeyValidationInfoDTO = null; EnforcerConfig configuration = ConfigHolder.getInstance().getConfig(); ExtendedTokenIssuerDto issuerDto = configuration.getIssuersMap().get(validationInfo.getIssuer()); //TODO: enable subscription validation if (issuerDto.isValidateSubscriptions()) { JSONObject api = validateSubscriptionFromClaim(name, version, claims, splitToken, true); if (api == null) { if (log.isDebugEnabled()) { log.debug(""Begin subscription validation via Key Manager: "" + validationInfo.getKeyManager()); } apiKeyValidationInfoDTO = validateSubscriptionUsingKeyManager(requestContext, validationInfo); // set endpoint security SecurityInfo securityInfo; if (apiKeyValidationInfoDTO != null && apiKeyValidationInfoDTO.getType() != null && requestContext.getMatchedAPI().getAPIConfig().getEndpointSecurity() != null) { if (apiKeyValidationInfoDTO.getType().equals(APIConstants.API_KEY_TYPE_PRODUCTION)) { securityInfo = requestContext.getMatchedAPI().getAPIConfig().getEndpointSecurity(). getProductionSecurityInfo(); } else { securityInfo = requestContext.getMatchedAPI().getAPIConfig().getEndpointSecurity(). getSandBoxSecurityInfo(); } if (securityInfo.getEnabled() && APIConstants.AUTHORIZATION_HEADER_BASIC. equalsIgnoreCase(securityInfo.getSecurityType())) { // use constants requestContext.addResponseHeaders(APIConstants.AUTHORIZATION_HEADER_DEFAULT, APIConstants.AUTHORIZATION_HEADER_BASIC + "" "" + Base64.getEncoder().encodeToString((securityInfo.getUsername() + "":"" + securityInfo.getPassword()).getBytes())); } } if (log.isDebugEnabled()) { log.debug(""Subscription validation via Key Manager. Status: "" + apiKeyValidationInfoDTO .isAuthorized()); } if (!apiKeyValidationInfoDTO.isAuthorized()) { throw new APISecurityException(APIConstants.StatusCodes.UNAUTHORIZED.getCode(), apiKeyValidationInfoDTO.getValidationStatus(), ""User is NOT authorized to access the Resource. "" + ""API Subscription validation failed.""); } } } // Validate scopes validateScopes(context, version, matchingResource, validationInfo, signedJWTInfo); log.debug(""JWT authentication successful.""); String endUserToken = null; // Get jwtConfigurationDto JWTConfigurationDto jwtConfigurationDto = ConfigHolder.getInstance().getConfig(). getJwtConfigurationDto(); if (jwtConfigurationDto.isEnabled()) { // Set ttl jwtConfigurationDto.setTtl(JWTUtil.getTTL()); JWTInfoDto jwtInfoDto = FilterUtils .generateJWTInfoDto(null, validationInfo, apiKeyValidationInfoDTO, requestContext); endUserToken = generateAndRetrieveJWTToken(jwtTokenIdentifier, jwtInfoDto); // Set generated jwt token as a response header requestContext.addResponseHeaders(jwtConfigurationDto.getJwtHeader(), endUserToken); } AuthenticationContext authenticationContext = FilterUtils .generateAuthenticationContext(requestContext, jwtTokenIdentifier, validationInfo, apiKeyValidationInfoDTO, endUserToken, true); //TODO: (VirajSalaka) Place the keytype population logic properly for self contained token if (claims.getClaim(""keytype"") != null) { authenticationContext.setKeyType(claims.getClaim(""keytype"").toString()); } return authenticationContext; } else { throw new APISecurityException(APIConstants.StatusCodes.UNAUTHENTICATED.getCode(), validationInfo.getValidationCode(), APISecurityConstants.getAuthenticationFailureMessage(validationInfo.getValidationCode())); } } else { throw new APISecurityException(APIConstants.StatusCodes.UNAUTHENTICATED.getCode(), APISecurityConstants.API_AUTH_GENERAL_ERROR, APISecurityConstants.API_AUTH_GENERAL_ERROR_MESSAGE); } }",Fix token validation when Authorization header is malformed,https://github.com/wso2/product-microgateway/commit/8d316ccd784f0ccad47935f56b05e0601a4d0e97,,,enforcer/src/main/java/org/wso2/choreo/connect/enforcer/security/jwt/JWTAuthenticator.java,3,java,False,2021-04-06T18:52:13Z "protected final double _parseDoublePrimitive(JsonParser p, DeserializationContext ctxt) throws IOException { String text; switch (p.currentTokenId()) { case JsonTokenId.ID_STRING: text = p.getText(); break; case JsonTokenId.ID_NUMBER_INT: case JsonTokenId.ID_NUMBER_FLOAT: return p.getDoubleValue(); case JsonTokenId.ID_NULL: _verifyNullForPrimitive(ctxt); return 0.0; // 29-Jun-2020, tatu: New! ""Scalar from Object"" (mostly for XML) case JsonTokenId.ID_START_OBJECT: text = ctxt.extractScalarFromObject(p, this, Double.TYPE); break; case JsonTokenId.ID_START_ARRAY: if (ctxt.isEnabled(DeserializationFeature.UNWRAP_SINGLE_VALUE_ARRAYS)) { p.nextToken(); final double parsed = _parseDoublePrimitive(p, ctxt); _verifyEndArrayForSingle(p, ctxt); return parsed; } // fall through default: return ((Number) ctxt.handleUnexpectedToken(Double.TYPE, p)).doubleValue(); } // 18-Nov-2020, tatu: Special case, Not-a-Numbers as String need to be // considered ""native"" representation as JSON does not allow as numbers, // and hence not bound by coercion rules { Double nan = this._checkDoubleSpecialValue(text); if (nan != null) { return nan.doubleValue(); } } final CoercionAction act = _checkFromStringCoercion(ctxt, text, LogicalType.Integer, Double.TYPE); if (act == CoercionAction.AsNull) { // 03-May-2021, tatu: Might not be allowed (should we do ""empty"" check?) _verifyNullForPrimitive(ctxt); return 0.0; } if (act == CoercionAction.AsEmpty) { return 0.0; } text = text.trim(); if (_hasTextualNull(text)) { _verifyNullForPrimitiveCoercion(ctxt, text); return 0.0; } return _parseDoublePrimitive(ctxt, text); }","protected final double _parseDoublePrimitive(JsonParser p, DeserializationContext ctxt) throws IOException { String text; switch (p.currentTokenId()) { case JsonTokenId.ID_STRING: text = p.getText(); break; case JsonTokenId.ID_NUMBER_INT: case JsonTokenId.ID_NUMBER_FLOAT: return p.getDoubleValue(); case JsonTokenId.ID_NULL: _verifyNullForPrimitive(ctxt); return 0.0; // 29-Jun-2020, tatu: New! ""Scalar from Object"" (mostly for XML) case JsonTokenId.ID_START_OBJECT: text = ctxt.extractScalarFromObject(p, this, Double.TYPE); break; case JsonTokenId.ID_START_ARRAY: if (ctxt.isEnabled(DeserializationFeature.UNWRAP_SINGLE_VALUE_ARRAYS)) { if (p.nextToken() == JsonToken.START_ARRAY) { return (double) handleNestedArrayForSingle(p, ctxt); } final double parsed = _parseDoublePrimitive(p, ctxt); _verifyEndArrayForSingle(p, ctxt); return parsed; } // fall through default: return ((Number) ctxt.handleUnexpectedToken(Double.TYPE, p)).doubleValue(); } // 18-Nov-2020, tatu: Special case, Not-a-Numbers as String need to be // considered ""native"" representation as JSON does not allow as numbers, // and hence not bound by coercion rules { Double nan = this._checkDoubleSpecialValue(text); if (nan != null) { return nan.doubleValue(); } } final CoercionAction act = _checkFromStringCoercion(ctxt, text, LogicalType.Integer, Double.TYPE); if (act == CoercionAction.AsNull) { // 03-May-2021, tatu: Might not be allowed (should we do ""empty"" check?) _verifyNullForPrimitive(ctxt); return 0.0; } if (act == CoercionAction.AsEmpty) { return 0.0; } text = text.trim(); if (_hasTextualNull(text)) { _verifyNullForPrimitiveCoercion(ctxt, text); return 0.0; } return _parseDoublePrimitive(ctxt, text); }","update release notes wrt #3582, [CVE-2022-42004]",https://github.com/FasterXML/jackson-databind/commit/2c4a601c626f7790cad9d3c322d244e182838288,,,src/main/java/com/fasterxml/jackson/databind/deser/std/StdDeserializer.java,3,java,False,2022-10-12T01:42:40Z "@Override public List getPaths() { return fromComponent.getPrefixPaths(); }","@Override public List getPaths() { Set authPaths = new HashSet<>(); List prefixPaths = fromComponent.getPrefixPaths(); List resultColumns = selectComponent.getResultColumns(); for (ResultColumn resultColumn : resultColumns) { Expression expression = resultColumn.getExpression(); authPaths.addAll(ExpressionAnalyzer.concatExpressionWithSuffixPaths(expression, prefixPaths)); } return new ArrayList<>(authPaths); }",[IOTDB-4242] Fix inconsistency of auth check between old standalone and new standalone (#7158),https://github.com/apache/iotdb/commit/edc81cc361841efcfd7991269db4c40ac48a22dc,,,server/src/main/java/org/apache/iotdb/db/mpp/plan/statement/crud/QueryStatement.java,3,java,False,2022-08-31T08:36:18Z "@Override public void readNBT(Tag nbt) { super.readNBT(nbt); CompoundTag compound = (CompoundTag) nbt; whichHand = InteractionHand.values()[compound.getInt(""whichHand"")]; }","@Override public void readNBT(Tag nbt) { super.readNBT(nbt); if (isUsing()) { CompoundTag compound = (CompoundTag) nbt; whichHand = InteractionHand.values()[compound.getInt(""whichHand"")]; } }",Fix another tunneling crash,https://github.com/BobMowzie/MowziesMobs/commit/14366b89fd081619fccc6661cafefff5a05cec75,,,src/main/java/com/bobmowzie/mowziesmobs/server/ability/abilities/TunnelingAbility.java,3,java,False,2022-07-26T17:40:06Z "@Override public void registerMap() { map(Type.INT); handler(packetWrapper -> { byte status = packetWrapper.read(Type.BYTE); if (status > 23) { packetWrapper.cancel(); return; } packetWrapper.write(Type.BYTE, status); }); }","@Override public void registerMap() { map(Type.VAR_INT); handler(packetWrapper -> { // todo check if this is correct for the own player int slot = packetWrapper.read(Type.VAR_INT); if (slot == 1) { packetWrapper.cancel(); } else if (slot > 1) { slot -= 1; } packetWrapper.write(Type.SHORT, (short) slot); }); map(Type.ITEM); handler(packetWrapper -> packetWrapper.set(Type.ITEM, 0, ItemRewriter.toClient(packetWrapper.get(Type.ITEM, 0)))); }","fix #306 death crash (#411) * untested equipment slots crash fix * save uuid in 1.7 on join and check limit",https://github.com/ViaVersion/ViaRewind/commit/e6b8b6937ebd80dcbeaa8670fc960b3d4164baf6,,,core/src/main/java/de/gerrygames/viarewind/protocol/protocol1_8to1_9/packets/EntityPackets.java,3,java,False,2022-09-04T15:12:57Z "function at(target, path, update) { path = pathToArray(path); if (! path.length) { return update(target, null); } const key = path[0]; if (isNumber(key)) { if (! Array.isArray(target)) { target = []; } } else if (! isObject(target)) { target = {}; } if (path.length > 1) { target[key] = at(target[key], path.slice(1), update); } else { target = update(target, key); } return target; }","function at(target, path, update) { path = pathToArray(path); if (! path.length) { return update(target, null); } const key = path[0]; if (isNumber(key)) { if (! Array.isArray(target)) { target = []; } } else if (! isObject(target)) { target = {}; } validateKey(key); if (path.length > 1) { target[key] = at(target[key], path.slice(1), update); } else { target = update(target, key); } return target; }","[v,src,deps,spec,doc] v2.3.0 - Fix vulnerabilities. - Update outdated deps. - Increase coverage to 100%.",https://github.com/rumkin/keyget/commit/17d15b6c75036eb429075a8cfeccfc18094dd2e2,CVE-2020-28272,['NVD-CWE-noinfo'],index.js,3,js,False,2020-11-22T14:24:49Z "public Response revokeCert(CertId id, CertRevokeRequest request, boolean caCert) { if (id == null) { logger.warn(""Unable to revoke cert: Missing certificate ID""); throw new BadRequestException(""Unable to revoke cert: Missing certificate ID""); } if (request == null) { logger.warn(""revokeCert: request is null""); throw new BadRequestException(""Unable to revoke cert: invalid request""); } // check cert actually exists. This will throw a CertNotFoundException // if the cert does not exist @SuppressWarnings(""unused"") CertData data = getCertData(id); RevocationReason revReason = RevocationReason.valueOf(request.getReason()); if (revReason == RevocationReason.REMOVE_FROM_CRL) { return unrevokeCert(id); } String caIssuerDN = null; X500Name caX500DN = null; RevocationProcessor processor; try { processor = new RevocationProcessor(""caDoRevoke-agent"", getLocale(headers)); processor.setStartTime(new Date().getTime()); // TODO: set initiative based on auth info processor.setInitiative(AuditFormat.FROMAGENT); processor.setSerialNumber(id); processor.setRevocationReason(revReason); processor.setRequestType(revReason == RevocationReason.CERTIFICATE_HOLD ? RevocationProcessor.ON_HOLD : RevocationProcessor.REVOKE); processor.setInvalidityDate(request.getInvalidityDate()); processor.setComments(request.getComments()); processor.setAuthority(authority); caX500DN = (X500Name) authority.getCACert().getIssuerDN(); } catch (EBaseException e) { logger.error(""Unable to revoke certificate: "" + e.getMessage(), e); throw new PKIException(""Unable to revoke certificate: "" + e.getMessage(), e); } try { X509Certificate clientCert = null; try { clientCert = CAProcessor.getSSLClientCertificate(servletRequest); } catch (EBaseException e) { // No client certificate, ignore. } CertRecord clientRecord = null; BigInteger clientSerialNumber = null; String clientSubjectDN = null; if (clientCert != null) { clientSerialNumber = clientCert.getSerialNumber(); clientSubjectDN = clientCert.getSubjectDN().toString(); X500Name x500issuerDN = (X500Name) clientCert.getIssuerDN(); /* * internal revocation check only to be conducted for certs * issued by this CA * For client certs issued by external CAs, TLS mutual auth * would have completed the authenticaton/verification if * OCSP was enabled; * Furthermore, prior to the actual revocation, client cert * is mapped against the agent group database for proper * privilege regardless of the issuer. */ if (x500issuerDN.equals(caX500DN)) { logger.info(""CertService.revokeCert: client cert issued by this CA""); clientRecord = processor.getCertificateRecord(clientSerialNumber); // Verify client cert is not revoked. // TODO: This should be checked during authentication. if (clientRecord.getStatus().equals(CertRecord.STATUS_REVOKED)) { throw new UnauthorizedException(CMS.getLogMessage(""CMSGW_UNAUTHORIZED"")); } } else { logger.info(""CertService.revokeCert: client cert not issued by this CA""); if (!authority.allowExtCASignedAgentCerts()) { logger.error(""CertService.revokeCert: allowExtCASignedAgentCerts false;""); throw new UnauthorizedException(CMS.getLogMessage(""CMSGW_UNAUTHORIZED"")); } else { logger.info(""CertService.revokeCert: allowExtCASignedAgentCerts true;""); } } } if (authority.noncesEnabled() && !processor.isMemberOfSubsystemGroup(clientCert)) { processor.validateNonce(servletRequest, ""cert-revoke"", id.toBigInteger(), request.getNonce()); } // Find target cert record if different from client cert. CertRecord targetRecord = id.equals(clientSerialNumber) ? clientRecord : processor.getCertificateRecord(id); X509CertImpl targetCert = targetRecord.getCertificate(); processor.createCRLExtension(); // TODO remove hardcoded role names and consult authzmgr // (so that we can handle externally-authenticated principals) GenericPrincipal principal = (GenericPrincipal) servletRequest.getUserPrincipal(); String subjectDN = principal.hasRole(""Certificate Manager Agents"") ? null : clientSubjectDN; processor.validateCertificateToRevoke(subjectDN, targetRecord, caCert); processor.addCertificateToRevoke(targetCert); processor.createRevocationRequest(); processor.auditChangeRequest(ILogger.SUCCESS); } catch (PKIException e) { logger.warn(""Unable to pre-process revocation request: "" + e.getMessage()); processor.auditChangeRequest(ILogger.FAILURE); throw e; } catch (EBaseException e) { logger.error(""Unable to pre-process revocation request: "" + e.getMessage(), e); processor.auditChangeRequest(ILogger.FAILURE); throw new PKIException(""Unable to revoke cert: "" + e.getMessage(), e); } catch (IOException e) { logger.error(""Unable to pre-process revocation request: "" + e.getMessage(), e); processor.auditChangeRequest(ILogger.FAILURE); throw new PKIException(""Unable to revoke cert: "" + e.getMessage(), e); } // change audit processing from ""REQUEST"" to ""REQUEST_PROCESSED"" // to distinguish which type of signed audit log message to save // as a failure outcome in case an exception occurs try { processor.processRevocationRequest(); processor.auditChangeRequestProcessed(ILogger.SUCCESS); } catch (EBaseException e) { logger.error(""Unable to process revocation request: "" + e.getMessage(), e); processor.auditChangeRequestProcessed(ILogger.FAILURE); throw new PKIException(""Unable to revoke certificate: "" + e.getMessage(), e); } try { IRequest certRequest = processor.getRequest(); CertRequestDAO dao = new CertRequestDAO(); CertRequestInfo requestInfo = dao.getRequest(certRequest.getRequestId(), uriInfo); return createOKResponse(requestInfo); } catch (EBaseException e) { logger.error(""Unable to create revocation response: "" + e.getMessage(), e); throw new PKIException(""Unable to create revocation response: "" + e.getMessage(), e); } }","public Response revokeCert(CertId id, CertRevokeRequest request, boolean caCert) { if (id == null) { logger.warn(""Unable to revoke cert: Missing certificate ID""); throw new BadRequestException(""Unable to revoke cert: Missing certificate ID""); } if (request == null) { logger.warn(""revokeCert: request is null""); throw new BadRequestException(""Unable to revoke cert: invalid request""); } // check cert actually exists. This will throw a CertNotFoundException // if the cert does not exist @SuppressWarnings(""unused"") CertData data = getCertData(id); RevocationReason revReason = RevocationReason.valueOf(request.getReason()); if (revReason == RevocationReason.REMOVE_FROM_CRL) { return unrevokeCert(id); } String caIssuerDN = null; X500Name caX500DN = null; RevocationProcessor processor; try { processor = new RevocationProcessor(""caDoRevoke-agent"", getLocale(headers)); processor.setStartTime(new Date().getTime()); // TODO: set initiative based on auth info processor.setInitiative(AuditFormat.FROMAGENT); processor.setSerialNumber(id); processor.setRevocationReason(revReason); processor.setRequestType(revReason == RevocationReason.CERTIFICATE_HOLD ? RevocationProcessor.ON_HOLD : RevocationProcessor.REVOKE); processor.setInvalidityDate(request.getInvalidityDate()); processor.setComments(request.getComments()); processor.setAuthority(authority); caX500DN = (X500Name) authority.getCACert().getSubjectDN(); } catch (EBaseException e) { logger.error(""Unable to revoke certificate: "" + e.getMessage(), e); throw new PKIException(""Unable to revoke certificate: "" + e.getMessage(), e); } try { X509Certificate clientCert = null; try { clientCert = CAProcessor.getSSLClientCertificate(servletRequest); } catch (EBaseException e) { // No client certificate, ignore. } CertRecord clientRecord = null; BigInteger clientSerialNumber = null; String clientSubjectDN = null; if (clientCert != null) { clientSerialNumber = clientCert.getSerialNumber(); clientSubjectDN = clientCert.getSubjectDN().toString(); X500Name x500issuerDN = (X500Name) clientCert.getIssuerDN(); /* * internal revocation check only to be conducted for certs * issued by this CA * For client certs issued by external CAs, TLS mutual auth * would have completed the authenticaton/verification if * OCSP was enabled; * Furthermore, prior to the actual revocation, client cert * is mapped against the agent group database for proper * privilege regardless of the issuer. */ if (x500issuerDN.equals(caX500DN)) { logger.info(""CertService.revokeCert: client cert issued by this CA""); clientRecord = processor.getCertificateRecord(clientSerialNumber); // Verify client cert is not revoked. // TODO: This should be checked during authentication. if (clientRecord.getStatus().equals(CertRecord.STATUS_REVOKED)) { throw new UnauthorizedException(CMS.getLogMessage(""CMSGW_UNAUTHORIZED"")); } } else { logger.info(""CertService.revokeCert: client cert not issued by this CA""); if (!authority.allowExtCASignedAgentCerts()) { logger.error(""CertService.revokeCert: allowExtCASignedAgentCerts false;""); throw new UnauthorizedException(CMS.getLogMessage(""CMSGW_UNAUTHORIZED"")); } else { logger.info(""CertService.revokeCert: allowExtCASignedAgentCerts true;""); } } } if (authority.noncesEnabled() && !processor.isMemberOfSubsystemGroup(clientCert)) { processor.validateNonce(servletRequest, ""cert-revoke"", id.toBigInteger(), request.getNonce()); } // Find target cert record if different from client cert. CertRecord targetRecord = id.equals(clientSerialNumber) ? clientRecord : processor.getCertificateRecord(id); X509CertImpl targetCert = targetRecord.getCertificate(); processor.createCRLExtension(); // TODO remove hardcoded role names and consult authzmgr // (so that we can handle externally-authenticated principals) GenericPrincipal principal = (GenericPrincipal) servletRequest.getUserPrincipal(); String subjectDN = principal.hasRole(""Certificate Manager Agents"") ? null : clientSubjectDN; processor.validateCertificateToRevoke(subjectDN, targetRecord, caCert); processor.addCertificateToRevoke(targetCert); processor.createRevocationRequest(); processor.auditChangeRequest(ILogger.SUCCESS); } catch (PKIException e) { logger.warn(""Unable to pre-process revocation request: "" + e.getMessage()); processor.auditChangeRequest(ILogger.FAILURE); throw e; } catch (EBaseException e) { logger.error(""Unable to pre-process revocation request: "" + e.getMessage(), e); processor.auditChangeRequest(ILogger.FAILURE); throw new PKIException(""Unable to revoke cert: "" + e.getMessage(), e); } catch (IOException e) { logger.error(""Unable to pre-process revocation request: "" + e.getMessage(), e); processor.auditChangeRequest(ILogger.FAILURE); throw new PKIException(""Unable to revoke cert: "" + e.getMessage(), e); } // change audit processing from ""REQUEST"" to ""REQUEST_PROCESSED"" // to distinguish which type of signed audit log message to save // as a failure outcome in case an exception occurs try { processor.processRevocationRequest(); processor.auditChangeRequestProcessed(ILogger.SUCCESS); } catch (EBaseException e) { logger.error(""Unable to process revocation request: "" + e.getMessage(), e); processor.auditChangeRequestProcessed(ILogger.FAILURE); throw new PKIException(""Unable to revoke certificate: "" + e.getMessage(), e); } try { IRequest certRequest = processor.getRequest(); CertRequestDAO dao = new CertRequestDAO(); CertRequestInfo requestInfo = dao.getRequest(certRequest.getRequestId(), uriInfo); return createOKResponse(requestInfo); } catch (EBaseException e) { logger.error(""Unable to create revocation response: "" + e.getMessage(), e); throw new PKIException(""Unable to create revocation response: "" + e.getMessage(), e); } }","Bug1990105- TPS Not properly enforcing Token Profile Separation This patch addresses the issue that TPS agent operations on tokens, activities, and profiles are not limited by the types (profiles) permmtted to the agent (as described in the documentation). This is a regression from 8.x. The affected operations are: - findProfiles - getProfiles - updateProfile - changeStatus (of a profile) - retrieveTokens - getToken - modifyToken - changeTokenStatus - retrieveActivities - getActivity Note that some operations that seem like should be affected are not due to the fact that they are TPS admin operations and are shielded from entering the TPS service at the activity level. For example, deleting a token would be such a case. The authorization enforcement added in this patch should affect both access from the web UI as well as access from PKI CLI. Reference: https://github.com/dogtagpki/pki/wiki/PKI-TPS-CLI Another note: the VLV complicates the resulting page. If the returned entries on the page are all restricted then nothing would be shown. To add a bit more clarity, an entry is added to reflect such effect so that it would be less confusing to the role user. The entries are left with the epoch date. This would affect both WEB UI and PKI CLI. Also, a list minute addition to address an issue with 1911472 in CertService.java where the subject DN of the CA signing cert should be used instead of the issuer. fixes https://bugzilla.redhat.com/show_bug.cgi?id=1990105",https://github.com/dogtagpki/pki/commit/52af304b76e6eb7c216476480a3dee0afc65fdde,,,base/ca/src/main/java/org/dogtagpki/server/ca/rest/CertService.java,3,java,False,2021-08-11T16:15:48Z "@Override public PulsarAdminBuilder loadConf(Map config) { conf = ConfigurationDataUtils.loadData(config, conf, ClientConfigurationData.class); return this; }","@Override public PulsarAdminBuilder loadConf(Map config) { conf = ConfigurationDataUtils.loadData(config, conf, ClientConfigurationData.class); setAuthenticationFromPropsIfAvailable(conf); return this; }",[fix][client] Set authentication when using loadConf in client and admin client (#18358),https://github.com/apache/pulsar/commit/0f72a822dd8aa21fa3d86bb6f62ea4482fc3b907,,,pulsar-client-admin/src/main/java/org/apache/pulsar/client/admin/internal/PulsarAdminBuilderImpl.java,3,java,False,2023-02-04T20:03:23Z "public synchronized void encode(final ByteBuf buffer) { if (properties == null || size == 0) { buffer.writeByte(DataConstants.NULL); } else { buffer.writeByte(DataConstants.NOT_NULL); buffer.writeInt(properties.size()); //uses internal iteration to allow inlining/loop unrolling properties.forEach((key, value) -> { final byte[] data = key.getData(); buffer.writeInt(data.length); buffer.writeBytes(data); value.write(buffer); }); } }","public synchronized int encode(final ByteBuf buffer) { final int encodedSize; // it's a trick to not pay the cost of buffer.writeIndex without assertions enabled int writerIndex = 0; assert (writerIndex = buffer.writerIndex()) >= 0 : ""Always true""; if (properties == null || size == 0) { encodedSize = DataConstants.SIZE_BYTE; ensureExactWritable(buffer, encodedSize); buffer.writeByte(DataConstants.NULL); } else { encodedSize = DataConstants.SIZE_BYTE + DataConstants.SIZE_INT + size; ensureExactWritable(buffer, encodedSize); buffer.writeByte(DataConstants.NOT_NULL); buffer.writeInt(properties.size()); //uses internal iteration to allow inlining/loop unrolling properties.forEach((key, value) -> { final byte[] data = key.getData(); buffer.writeInt(data.length); buffer.writeBytes(data); value.write(buffer); }); } assert buffer.writerIndex() == (writerIndex + encodedSize) : ""Bad encode size estimation""; return encodedSize; }",ARTEMIS-3021 OOM due to wrong CORE clustered message memory estimation,https://github.com/apache/activemq-artemis/commit/ad4f6a133af9130f206a78e43ad387d4e3ee5f8f,,,artemis-commons/src/main/java/org/apache/activemq/artemis/utils/collections/TypedProperties.java,3,java,False,2020-12-05T23:07:29Z "private byte[] getImage(String host, byte[] defaultImage) { // If we've already attempted to get the favicon twice and failed, // return the default image. if (missesCache.get(host) != null && missesCache.get(host) > 1) { // Domain does not have a favicon so return default icon return defaultImage; } // See if we've cached the favicon. if (hitsCache.containsKey(host)) { return hitsCache.get(host); } byte[] bytes = getImage(""http://"" + host + ""/favicon.ico""); if (bytes == null) { // Cache that the requested domain does not have a favicon. Check if this // is the first cache miss or the second. if (missesCache.get(host) != null) { missesCache.put(host, 2); } else { missesCache.put(host, 1); } // Return byte of default icon bytes = defaultImage; } // Cache the favicon. else { hitsCache.put(host, bytes); } return bytes; }","private byte[] getImage(String host, byte[] defaultImage) { // If we've already attempted to get the favicon twice and failed, // return the default image. if (missesCache.get(host) != null && missesCache.get(host) > 1) { // Domain does not have a favicon so return default icon return defaultImage; } // See if we've cached the favicon. if (hitsCache.containsKey(host)) { return hitsCache.get(host); } byte[] bytes = getImage(host); if (bytes == null) { // Cache that the requested domain does not have a favicon. Check if this // is the first cache miss or the second. if (missesCache.get(host) != null) { missesCache.put(host, 2); } else { missesCache.put(host, 1); } // Return byte of default icon bytes = defaultImage; } // Cache the favicon. else { hitsCache.put(host, bytes); } return bytes; }","OF-2518: Attempt to load favicon over HTTPS This adds an additional attempt to load the favicon. With this, both HTTPS and HTTP are attempted. Additionally, the URL that's used is now being constructed through a builder, which should further reduce the attack vector of using 'user-provided input'.",https://github.com/igniterealtime/Openfire/commit/664f6704aef73b9e15617a03c54acc9b17afcf1c,,,xmppserver/src/main/java/org/jivesoftware/util/FaviconServlet.java,3,java,False,2022-10-04T18:46:22Z "@Override public NegotiationResult requested(ClaimToken token, ContractOfferRequest request) { var negotiation = ContractNegotiation.Builder.newInstance() .id(UUID.randomUUID().toString()) .correlationId(request.getCorrelationId()) .counterPartyId(request.getConnectorId()) .counterPartyAddress(request.getConnectorAddress()) .protocol(request.getProtocol()) .state(0) .stateCount(0) .stateTimestamp(Instant.now().toEpochMilli()) .type(ContractNegotiation.Type.PROVIDER) .build(); negotiationStore.save(negotiation); invokeForEach(l -> l.requested(negotiation)); monitor.debug(String.format(""[Provider] ContractNegotiation initiated. %s is now in state %s."", negotiation.getId(), ContractNegotiationStates.from(negotiation.getState()))); return processIncomingOffer(negotiation, token, request.getContractOffer()); }","@Override public NegotiationResult requested(ClaimToken token, ContractOfferRequest request) { var negotiation = ContractNegotiation.Builder.newInstance() .id(UUID.randomUUID().toString()) .correlationId(request.getCorrelationId()) .counterPartyId(request.getConnectorId()) .counterPartyAddress(request.getConnectorAddress()) .protocol(request.getProtocol()) .type(ContractNegotiation.Type.PROVIDER) .build(); negotiation.transitionRequested(); negotiationStore.save(negotiation); invokeForEach(l -> l.requested(negotiation)); monitor.debug(String.format(""[Provider] ContractNegotiation initiated. %s is now in state %s."", negotiation.getId(), ContractNegotiationStates.from(negotiation.getState()))); return processIncomingOffer(negotiation, token, request.getContractOffer()); }","Feature/538 avoid negotiation loop (#545) * core: avoid infinite loop on contract negotiation manager introducing a new INITIAL state * core: add new contract negotiation state to avoid loop",https://github.com/eclipse-edc/Connector/commit/5c0ca0d401ea56176beaefcb7ac553776c30bee1,,,core/contract/src/main/java/org/eclipse/dataspaceconnector/contract/negotiation/ProviderContractNegotiationManagerImpl.java,3,java,False,2022-01-28T13:16:10Z "private void write() { if (this.getString(""config-version"") == null || Integer.valueOf(this.getString(""config-version"")) < configVersion) { System.out.println(""Converting to Config Version: "" + configVersion); convertToNewConfig(); } //Main generateConfigOption(""config-version"", 2); //Setting generateConfigOption(""settings.allow-graceful-uuids"", true); generateConfigOption(""settings.delete-duplicate-uuids"", false); generateConfigOption(""settings.save-playerdata-by-uuid"", true); generateConfigOption(""settings.per-day-logfile"", false); generateConfigOption(""settings.fetch-uuids-from"", ""https://api.mojang.com/profiles/minecraft""); generateConfigOption(""settings.enable-watchdog"", true); generateConfigOption(""settings.remove-join-leave-debug"", true); generateConfigOption(""settings.enable-tpc-nodelay"", false); generateConfigOption(""settings.use-get-for-uuids.enabled"", false); generateConfigOption(""settings.use-get-for-uuids.info"", ""This setting causes the server to use the GET method for Username to UUID conversion. This is useful incase the POST method goes offline.""); //Packet Events generateConfigOption(""settings.packet-events.enabled"", false); generateConfigOption(""settings.packet-events.info"", ""This setting causes the server to fire a Bukkit event for each packet received and sent to a player once they have finished the initial login process. This only needs to be enabled if you have a plugin that uses this specific feature.""); //Statistics generateConfigOption(""settings.statistics.key"", UUID.randomUUID().toString()); generateConfigOption(""settings.statistics.enabled"", true); //Word Settings generateConfigOption(""world-settings.optimized-explosions"", false); generateConfigOption(""world-settings.randomize-spawn"", true); generateConfigOption(""world-settings.teleport-to-highest-safe-block"", true); generateConfigOption(""world-settings.use-modern-fence-bounding-boxes"", false); //TODO: Actually implement the tree growth functionality stuff generateConfigOption(""world.settings.block-tree-growth.enabled"", true); generateConfigOption(""world.settings.block-tree-growth.list"", ""54,63,68""); generateConfigOption(""world.settings.block-tree-growth.info"", ""This setting allows for server owners to easily block trees growing from automatically destroying certain blocks. The list must be a string with numerical item ids separated by commas.""); //Release2Beta Settings generateConfigOption(""settings.release2beta.enable-ip-pass-through"", false); generateConfigOption(""settings.release2beta.proxy-ip"", ""127.0.0.1""); //Modded Jar Support generateConfigOption(""settings.support.modloader.enable"", false); generateConfigOption(""settings.support.modloader.info"", ""EXPERIMENTAL support for ModloaderMP.""); //Offline Username Check generateConfigOption(""settings.check-username-validity.enabled"", true); generateConfigOption(""settings.check-username-validity.info"", ""If enabled, verifies the validity of a usernames of cracked players.""); generateConfigOption(""settings.check-username-validity.regex"", ""[a-zA-Z0-9_?]*""); generateConfigOption(""settings.check-username-validity.max-length"", 16); generateConfigOption(""settings.check-username-validity.min-length"", 3); //Tree Leave Destroy Blacklist if (Boolean.valueOf(String.valueOf(getConfigOption(""world.settings.block-tree-growth.enabled"", true)))) { if (String.valueOf(this.getConfigOption(""world.settings.block-tree-growth.list"", """")).trim().isEmpty()) { //Empty Blacklist } else { String[] rawBlacklist = String.valueOf(this.getConfigOption(""world.settings.block-tree-growth.list"", """")).trim().split("",""); int blackListCount = 0; for (String stringID : rawBlacklist) { if (Pattern.compile(""-?[0-9]+"").matcher(stringID).matches()) { blackListCount = blackListCount + 1; } else { System.out.println(""The ID "" + stringID + "" for leaf decay blocker has been detected as invalid, and won't be used.""); } } //Loop a second time to get correct array length. I know this is horrible code, but it works and only runs on server startup. treeBlacklistIDs = new Integer[blackListCount]; int i = 0; for (String stringID : rawBlacklist) { if (Pattern.compile(""-?[0-9]+"").matcher(stringID).matches()) { treeBlacklistIDs[i] = Integer.valueOf(stringID); i = i + 1; } } System.out.println(""Leaf blocks can't replace the following block IDs: "" + Arrays.toString(treeBlacklistIDs)); } } else { treeBlacklistIDs = new Integer[0]; } }","private void write() { if (this.getString(""config-version"") == null || Integer.valueOf(this.getString(""config-version"")) < configVersion) { System.out.println(""Converting to Config Version: "" + configVersion); convertToNewConfig(); } //Main generateConfigOption(""config-version"", 2); //Setting generateConfigOption(""settings.allow-graceful-uuids"", true); generateConfigOption(""settings.delete-duplicate-uuids"", false); generateConfigOption(""settings.save-playerdata-by-uuid"", true); generateConfigOption(""settings.per-day-logfile"", false); generateConfigOption(""settings.fetch-uuids-from"", ""https://api.mojang.com/profiles/minecraft""); generateConfigOption(""settings.enable-watchdog"", true); generateConfigOption(""settings.remove-join-leave-debug"", true); generateConfigOption(""settings.enable-tpc-nodelay"", false); generateConfigOption(""settings.use-get-for-uuids.enabled"", false); generateConfigOption(""settings.use-get-for-uuids.info"", ""This setting causes the server to use the GET method for Username to UUID conversion. This is useful incase the POST method goes offline.""); //Packet Events generateConfigOption(""settings.packet-events.enabled"", false); generateConfigOption(""settings.packet-events.info"", ""This setting causes the server to fire a Bukkit event for each packet received and sent to a player once they have finished the initial login process. This only needs to be enabled if you have a plugin that uses this specific feature.""); //Statistics generateConfigOption(""settings.statistics.key"", UUID.randomUUID().toString()); generateConfigOption(""settings.statistics.enabled"", true); //Word Settings generateConfigOption(""world-settings.optimized-explosions"", false); generateConfigOption(""world-settings.randomize-spawn"", true); generateConfigOption(""world-settings.teleport-to-highest-safe-block"", true); generateConfigOption(""world-settings.use-modern-fence-bounding-boxes"", false); //TODO: Actually implement the tree growth functionality stuff generateConfigOption(""world.settings.block-tree-growth.enabled"", true); generateConfigOption(""world.settings.block-tree-growth.list"", ""54,63,68""); generateConfigOption(""world.settings.block-tree-growth.info"", ""This setting allows for server owners to easily block trees growing from automatically destroying certain blocks. The list must be a string with numerical item ids separated by commas.""); generateConfigOption(""world.settings.block-pistons-pushing-furnaces.info"", ""This workaround prevents pistons from pushing furnaces which prevents a malicious server crash.""); generateConfigOption(""world.settings.block-pistons-pushing-furnaces.enabled"", true); //Release2Beta Settings generateConfigOption(""settings.release2beta.enable-ip-pass-through"", false); generateConfigOption(""settings.release2beta.proxy-ip"", ""127.0.0.1""); //Modded Jar Support generateConfigOption(""settings.support.modloader.enable"", false); generateConfigOption(""settings.support.modloader.info"", ""EXPERIMENTAL support for ModloaderMP.""); //Offline Username Check generateConfigOption(""settings.check-username-validity.enabled"", true); generateConfigOption(""settings.check-username-validity.info"", ""If enabled, verifies the validity of a usernames of cracked players.""); generateConfigOption(""settings.check-username-validity.regex"", ""[a-zA-Z0-9_?]*""); generateConfigOption(""settings.check-username-validity.max-length"", 16); generateConfigOption(""settings.check-username-validity.min-length"", 3); //Tree Leave Destroy Blacklist if (Boolean.valueOf(String.valueOf(getConfigOption(""world.settings.block-tree-growth.enabled"", true)))) { if (String.valueOf(this.getConfigOption(""world.settings.block-tree-growth.list"", """")).trim().isEmpty()) { //Empty Blacklist } else { String[] rawBlacklist = String.valueOf(this.getConfigOption(""world.settings.block-tree-growth.list"", """")).trim().split("",""); int blackListCount = 0; for (String stringID : rawBlacklist) { if (Pattern.compile(""-?[0-9]+"").matcher(stringID).matches()) { blackListCount = blackListCount + 1; } else { System.out.println(""The ID "" + stringID + "" for leaf decay blocker has been detected as invalid, and won't be used.""); } } //Loop a second time to get correct array length. I know this is horrible code, but it works and only runs on server startup. treeBlacklistIDs = new Integer[blackListCount]; int i = 0; for (String stringID : rawBlacklist) { if (Pattern.compile(""-?[0-9]+"").matcher(stringID).matches()) { treeBlacklistIDs[i] = Integer.valueOf(stringID); i = i + 1; } } System.out.println(""Leaf blocks can't replace the following block IDs: "" + Arrays.toString(treeBlacklistIDs)); } } else { treeBlacklistIDs = new Integer[0]; } }","Fix a malicious piston + furnace crash that causes a stackoverflow Fixes a possibly publically known crash involving pistons and furnaces which has been observed on RetroMC and BetaLands over the last month or so.",https://github.com/RhysB/Project-Poseidon/commit/1603d5ca0fbc6f62aea1d9ca880161f2e37f312b,,,src/com/legacyminecraft/poseidon/PoseidonConfig.java,3,java,False,2021-12-22T02:23:41Z "BOOL transport_accept_nla(rdpTransport* transport) { freerdp* instance; rdpSettings* settings; if (transport->TlsIn == NULL) transport->TlsIn = tls_new(transport->settings); if (transport->TlsOut == NULL) transport->TlsOut = transport->TlsIn; transport->layer = TRANSPORT_LAYER_TLS; transport->TlsIn->sockfd = transport->TcpIn->sockfd; if (tls_accept(transport->TlsIn, transport->settings->CertificateFile, transport->settings->PrivateKeyFile) != TRUE) return FALSE; /* Network Level Authentication */ if (transport->settings->Authentication != TRUE) return TRUE; settings = transport->settings; instance = (freerdp*) settings->instance; if (transport->credssp == NULL) transport->credssp = credssp_new(instance, transport, settings); if (credssp_authenticate(transport->credssp) < 0) { fprintf(stderr, ""client authentication failure\n""); credssp_free(transport->credssp); return FALSE; } /* don't free credssp module yet, we need to copy the credentials from it first */ return TRUE; }","BOOL transport_accept_nla(rdpTransport* transport) { freerdp* instance; rdpSettings* settings; if (transport->TlsIn == NULL) transport->TlsIn = tls_new(transport->settings); if (transport->TlsOut == NULL) transport->TlsOut = transport->TlsIn; transport->layer = TRANSPORT_LAYER_TLS; transport->TlsIn->sockfd = transport->TcpIn->sockfd; if (tls_accept(transport->TlsIn, transport->settings->CertificateFile, transport->settings->PrivateKeyFile) != TRUE) return FALSE; /* Network Level Authentication */ if (transport->settings->Authentication != TRUE) return TRUE; settings = transport->settings; instance = (freerdp*) settings->instance; if (transport->credssp == NULL) transport->credssp = credssp_new(instance, transport, settings); if (credssp_authenticate(transport->credssp) < 0) { fprintf(stderr, ""client authentication failure\n""); credssp_free(transport->credssp); transport->credssp = NULL; return FALSE; } /* don't free credssp module yet, we need to copy the credentials from it first */ return TRUE; }","nla: invalidate sec handle after creation If sec pointer isn't invalidated after creation it is not possible to check if the upper and lower pointers are valid. This fixes a segfault in the server part if the client disconnects before the authentication was finished.",https://github.com/FreeRDP/FreeRDP/commit/0773bb9303d24473fe1185d85a424dfe159aff53,,,libfreerdp/core/transport.c,3,c,False,2013-07-01T17:24:19Z "private void handleAuthenticationException(AuthenticationException authenticationException, HttpServletResponse response) throws IOException { response.setStatus(HttpStatus.UNAUTHORIZED.value()); if (authenticationException instanceof BadCredentialsException) { mapper.writeValue(response.getWriter(), ThingsboardErrorResponse.of(""Invalid username or password"", ThingsboardErrorCode.AUTHENTICATION, HttpStatus.UNAUTHORIZED)); } else if (authenticationException instanceof DisabledException) { mapper.writeValue(response.getWriter(), ThingsboardErrorResponse.of(""User account is not active"", ThingsboardErrorCode.AUTHENTICATION, HttpStatus.UNAUTHORIZED)); } else if (authenticationException instanceof LockedException) { mapper.writeValue(response.getWriter(), ThingsboardErrorResponse.of(""User account is locked due to security policy"", ThingsboardErrorCode.AUTHENTICATION, HttpStatus.UNAUTHORIZED)); } else if (authenticationException instanceof JwtExpiredTokenException) { mapper.writeValue(response.getWriter(), ThingsboardErrorResponse.of(""Token has expired"", ThingsboardErrorCode.JWT_TOKEN_EXPIRED, HttpStatus.UNAUTHORIZED)); } else if (authenticationException instanceof AuthMethodNotSupportedException) { mapper.writeValue(response.getWriter(), ThingsboardErrorResponse.of(authenticationException.getMessage(), ThingsboardErrorCode.AUTHENTICATION, HttpStatus.UNAUTHORIZED)); } else if (authenticationException instanceof UserPasswordExpiredException) { UserPasswordExpiredException expiredException = (UserPasswordExpiredException) authenticationException; String resetToken = expiredException.getResetToken(); mapper.writeValue(response.getWriter(), ThingsboardCredentialsExpiredResponse.of(expiredException.getMessage(), resetToken)); } else { mapper.writeValue(response.getWriter(), ThingsboardErrorResponse.of(""Authentication failed"", ThingsboardErrorCode.AUTHENTICATION, HttpStatus.UNAUTHORIZED)); } }","private void handleAuthenticationException(AuthenticationException authenticationException, HttpServletResponse response) throws IOException { response.setStatus(HttpStatus.UNAUTHORIZED.value()); if (authenticationException instanceof BadCredentialsException || authenticationException instanceof UsernameNotFoundException) { mapper.writeValue(response.getWriter(), ThingsboardErrorResponse.of(""Invalid username or password"", ThingsboardErrorCode.AUTHENTICATION, HttpStatus.UNAUTHORIZED)); } else if (authenticationException instanceof DisabledException) { mapper.writeValue(response.getWriter(), ThingsboardErrorResponse.of(""User account is not active"", ThingsboardErrorCode.AUTHENTICATION, HttpStatus.UNAUTHORIZED)); } else if (authenticationException instanceof LockedException) { mapper.writeValue(response.getWriter(), ThingsboardErrorResponse.of(""User account is locked due to security policy"", ThingsboardErrorCode.AUTHENTICATION, HttpStatus.UNAUTHORIZED)); } else if (authenticationException instanceof JwtExpiredTokenException) { mapper.writeValue(response.getWriter(), ThingsboardErrorResponse.of(""Token has expired"", ThingsboardErrorCode.JWT_TOKEN_EXPIRED, HttpStatus.UNAUTHORIZED)); } else if (authenticationException instanceof AuthMethodNotSupportedException) { mapper.writeValue(response.getWriter(), ThingsboardErrorResponse.of(authenticationException.getMessage(), ThingsboardErrorCode.AUTHENTICATION, HttpStatus.UNAUTHORIZED)); } else if (authenticationException instanceof UserPasswordExpiredException) { UserPasswordExpiredException expiredException = (UserPasswordExpiredException) authenticationException; String resetToken = expiredException.getResetToken(); mapper.writeValue(response.getWriter(), ThingsboardCredentialsExpiredResponse.of(expiredException.getMessage(), resetToken)); } else { mapper.writeValue(response.getWriter(), ThingsboardErrorResponse.of(""Authentication failed"", ThingsboardErrorCode.AUTHENTICATION, HttpStatus.UNAUTHORIZED)); } }","[PROD-678] Authorization and password reset vulnerability fix (#4569) * Fixed vulnerabilities for password reset and authorization * Improvements to check user and credentials for null * Correct messages and logs * Improvements * Reset Password Test: added delay after resetting password to synchronize test with server * Executor removed from controller * Correct method calling * Formatting cleaned",https://github.com/thingsboard/thingsboard-edge/commit/228fddb8cd92bf4ec89f16760aef7f190a45bb96,,,application/src/main/java/org/thingsboard/server/exception/ThingsboardErrorResponseHandler.java,3,java,False,2021-07-06T14:24:35Z "@Override public void run() { long now = U.currentTimeMillis(); if (lastBalance + balancePeriod < now) { lastBalance = now; long maxRcvd0 = -1, minRcvd0 = -1, maxSent0 = -1, minSent0 = -1; int maxRcvdIdx = -1, minRcvdIdx = -1, maxSentIdx = -1, minSentIdx = -1; for (int i = 0; i < clientWorkers.size(); i++) { GridNioServer.AbstractNioClientWorker worker = clientWorkers.get(i); int sesCnt = worker.workerSessions.size(); if (i % 2 == 0) { // Reader. long bytesRcvd0 = worker.bytesRcvd0; if ((maxRcvd0 == -1 || bytesRcvd0 > maxRcvd0) && bytesRcvd0 > 0 && sesCnt > 1) { maxRcvd0 = bytesRcvd0; maxRcvdIdx = i; } if (minRcvd0 == -1 || bytesRcvd0 < minRcvd0) { minRcvd0 = bytesRcvd0; minRcvdIdx = i; } } else { // Writer. long bytesSent0 = worker.bytesSent0; if ((maxSent0 == -1 || bytesSent0 > maxSent0) && bytesSent0 > 0 && sesCnt > 1) { maxSent0 = bytesSent0; maxSentIdx = i; } if (minSent0 == -1 || bytesSent0 < minSent0) { minSent0 = bytesSent0; minSentIdx = i; } } } if (log.isDebugEnabled()) log.debug(""Balancing data [minSent0="" + minSent0 + "", minSentIdx="" + minSentIdx + "", maxSent0="" + maxSent0 + "", maxSentIdx="" + maxSentIdx + "", minRcvd0="" + minRcvd0 + "", minRcvdIdx="" + minRcvdIdx + "", maxRcvd0="" + maxRcvd0 + "", maxRcvdIdx="" + maxRcvdIdx + ']'); if (maxSent0 != -1 && minSent0 != -1) { GridSelectorNioSessionImpl ses = null; long sentDiff = maxSent0 - minSent0; long delta = sentDiff; double threshold = sentDiff * 0.9; GridConcurrentHashSet sessions = clientWorkers.get(maxSentIdx).workerSessions; for (GridSelectorNioSessionImpl ses0 : sessions) { long bytesSent0 = ses0.bytesSent0(); if (bytesSent0 < threshold && (ses == null || delta > U.safeAbs(bytesSent0 - sentDiff / 2))) { ses = ses0; delta = U.safeAbs(bytesSent0 - sentDiff / 2); } } if (ses != null) { if (log.isDebugEnabled()) log.debug(""Will move session to less loaded writer [ses="" + ses + "", from="" + maxSentIdx + "", to="" + minSentIdx + ']'); moveSession(ses, maxSentIdx, minSentIdx); } else { if (log.isDebugEnabled()) log.debug(""Unable to find session to move for writers.""); } } if (maxRcvd0 != -1 && minRcvd0 != -1) { GridSelectorNioSessionImpl ses = null; long rcvdDiff = maxRcvd0 - minRcvd0; long delta = rcvdDiff; double threshold = rcvdDiff * 0.9; GridConcurrentHashSet sessions = clientWorkers.get(maxRcvdIdx).workerSessions; for (GridSelectorNioSessionImpl ses0 : sessions) { long bytesRcvd0 = ses0.bytesReceived0(); if (bytesRcvd0 < threshold && (ses == null || delta > U.safeAbs(bytesRcvd0 - rcvdDiff / 2))) { ses = ses0; delta = U.safeAbs(bytesRcvd0 - rcvdDiff / 2); } } if (ses != null) { if (log.isDebugEnabled()) log.debug(""Will move session to less loaded reader [ses="" + ses + "", from="" + maxRcvdIdx + "", to="" + minRcvdIdx + ']'); moveSession(ses, maxRcvdIdx, minRcvdIdx); } else { if (log.isDebugEnabled()) log.debug(""Unable to find session to move for readers.""); } } for (int i = 0; i < clientWorkers.size(); i++) { GridNioServer.AbstractNioClientWorker worker = clientWorkers.get(i); worker.reset0(); } } }","@Override public void run() { if (clientWorkers.size() < 2) return; ThreadLocalRandom rnd = ThreadLocalRandom.current(); int w1 = rnd.nextInt(clientWorkers.size()); if (clientWorkers.get(w1).workerSessions.isEmpty()) return; int w2 = rnd.nextInt(clientWorkers.size()); while (w2 == w1) w2 = rnd.nextInt(clientWorkers.size()); GridNioSession ses = randomSession(clientWorkers.get(w1)); if (ses != null) { if (log.isInfoEnabled()) log.info(""Move session [from="" + w1 + "", to="" + w2 + "", ses="" + ses + ']'); moveSession(ses, w1, w2); } }",IGNITE-17779 Fix infinite loop in RandomBalancer (#10276),https://github.com/apache/ignite/commit/98dc8dcf1ebcf2b264e5b3fc18db3c4fdf638b2a,,,modules/core/src/main/java/org/apache/ignite/internal/util/nio/GridNioServer.java,3,java,False,2022-10-03T06:51:55Z "@Override public org.bukkit.inventory.ItemStack getPlayerHead(Player player, org.bukkit.inventory.ItemStack copyTagFrom) { org.bukkit.inventory.ItemStack head = new org.bukkit.inventory.ItemStack(materialPlayerHead()); if (copyTagFrom != null) { ItemStack i = CraftItemStack.asNMSCopy(head); i.c(CraftItemStack.asNMSCopy(copyTagFrom).s()); head = CraftItemStack.asBukkitCopy(i); } SkullMeta headMeta = (SkullMeta) head.getItemMeta(); Field profileField; try { //noinspection ConstantConditions profileField = headMeta.getClass().getDeclaredField(""profile""); profileField.setAccessible(true); profileField.set(headMeta, ((CraftPlayer) player).getProfile()); } catch (NoSuchFieldException | IllegalArgumentException | IllegalAccessException e1) { e1.printStackTrace(); } head.setItemMeta(headMeta); return head; }","@Override public org.bukkit.inventory.ItemStack getPlayerHead(Player player, org.bukkit.inventory.ItemStack copyTagFrom) { org.bukkit.inventory.ItemStack head = new org.bukkit.inventory.ItemStack(materialPlayerHead()); if (copyTagFrom != null) { ItemStack i = CraftItemStack.asNMSCopy(head); i.c(CraftItemStack.asNMSCopy(copyTagFrom).s()); head = CraftItemStack.asBukkitCopy(i); } // SkullMeta headMeta = (SkullMeta) head.getItemMeta(); // FIXME: current hotfix will get rate limited! how the hell do we set head texture now? // wtf is this: SkullOwner:{Id:[I;-1344581477,-1919271229,-1306015584,-647763423],Name:""andrei1058""} // Field profileField; // try { // //noinspection ConstantConditions // profileField = headMeta.getClass().getDeclaredField(""profile""); // profileField.setAccessible(true); // profileField.set(headMeta, ((CraftPlayer) player).getProfile()); // } catch (NoSuchFieldException | IllegalArgumentException | IllegalAccessException e1) { // e1.printStackTrace(); // } // assert headMeta != null; // headMeta.setOwningPlayer(player); // head.setItemMeta(headMeta); return head; }","fix player skull crashing the server (#233) * fix #210 * hotfix for #223 and #210",https://github.com/andrei1058/BedWars1058/commit/927a5858bdbf0271212f0126c57e92be0a255f81,,,versionsupport_v1_18_R1/src/main/java/com/andrei1058/bedwars/support/version/v1_18_R1/v1_18_R1.java,3,java,False,2022-02-02T18:01:07Z "private boolean performAuth(ChannelHandlerContext ctx, String username, String password) { Authenticator authenticator = respServer.getConfiguration().authentication().authenticator(); if (authenticator == null) { return handleAuthResponse(ctx, null); } CompletionStage cs = authenticator.authenticate(username, password.toCharArray()) .thenApply(r -> handleAuthResponse(ctx, r)) .exceptionally(t -> { handleThrowable(ctx, t); return false; }); try { return CompletableFutures.await(cs.toCompletableFuture()); } catch (ExecutionException | InterruptedException e) { handleThrowable(ctx, e); } return false; }","private boolean performAuth(ChannelHandlerContext ctx, String username, String password) { Authenticator authenticator = respServer.getConfiguration().authentication().authenticator(); if (authenticator == null) { return handleAuthResponse(ctx, null); } CompletionStage cs = authenticator.authenticate(username, password.toCharArray()) .thenApply(r -> handleAuthResponse(ctx, r)) .exceptionally(t -> { handleUnauthorized(ctx); return false; }); try { return CompletableFutures.await(cs.toCompletableFuture()); } catch (ExecutionException | InterruptedException e) { handleThrowable(ctx, e); } return false; }","ISPN-14164 Merge basic and vendor registries This should fix the issue",https://github.com/infinispan/infinispan/commit/a4160464dda6e7f8e4f5c86397ece7d425239db2,,,server/resp/src/main/java/org/infinispan/server/resp/Resp3AuthHandler.java,3,java,False,2022-09-21T18:09:53Z "public boolean isOp(String name) { return this.operators.exists(name, true); }","public boolean isOp(String name) { return name != null && this.operators.exists(name, true); }",Fix rare server crash from hack clients trying to connect (#1881),https://github.com/CloudburstMC/Nukkit/commit/51cc75db535a5405ced0ec3b323681bb916d40d8,,,src/main/java/cn/nukkit/Server.java,3,java,False,2021-08-07T07:12:52Z "private TypeDefinitionRegistry parseImpl(Reader schemaInput, ParserOptions parseOptions) { try { if (parseOptions == null) { // for SDL we dont stop how many parser tokens there are - its not the attack vector // to be prevented compared to queries parseOptions = ParserOptions.getDefaultParserOptions().transform(opts -> opts.maxTokens(Integer.MAX_VALUE)); } Parser parser = new Parser(); Document document = parser.parseDocument(schemaInput, parseOptions); return buildRegistry(document); } catch (InvalidSyntaxException e) { throw handleParseException(e.toInvalidSyntaxError()); } }","private TypeDefinitionRegistry parseImpl(Reader schemaInput, ParserOptions parseOptions) { try { if (parseOptions == null) { parseOptions = ParserOptions.getDefaultSdlParserOptions(); } Parser parser = new Parser(); Document document = parser.parseDocument(schemaInput, parseOptions); return buildRegistry(document); } catch (InvalidSyntaxException e) { throw handleParseException(e.toInvalidSyntaxError()); } }","READY - Stop DOS attacks by making the lexer stop early on evil input. (#2892) Port to 18.x",https://github.com/graphql-java/graphql-java/commit/1511839ad6ed7e7ec397b9060926a4d219fc245e,,,src/main/java/graphql/schema/idl/SchemaParser.java,3,java,False,2022-07-26T05:42:20Z "@Override protected void handleLookup(CommandLookupTopic lookup) { final long requestId = lookup.getRequestId(); final boolean authoritative = lookup.isAuthoritative(); final String advertisedListenerName = lookup.hasAdvertisedListenerName() ? lookup.getAdvertisedListenerName() : null; if (log.isDebugEnabled()) { log.debug(""[{}] Received Lookup from {} for {}"", lookup.getTopic(), remoteAddress, requestId); } TopicName topicName = validateTopicName(lookup.getTopic(), requestId, lookup); if (topicName == null) { return; } final Semaphore lookupSemaphore = service.getLookupRequestSemaphore(); if (lookupSemaphore.tryAcquire()) { if (invalidOriginalPrincipal(originalPrincipal)) { final String msg = ""Valid Proxy Client role should be provided for lookup ""; log.warn(""[{}] {} with role {} and proxyClientAuthRole {} on topic {}"", remoteAddress, msg, authRole, originalPrincipal, topicName); ctx.writeAndFlush(newLookupErrorResponse(ServerError.AuthorizationError, msg, requestId)); lookupSemaphore.release(); return; } isTopicOperationAllowed(topicName, TopicOperation.LOOKUP).thenApply(isAuthorized -> { if (isAuthorized) { lookupTopicAsync(getBrokerService().pulsar(), topicName, authoritative, getPrincipal(), getAuthenticationData(), requestId, advertisedListenerName).handle((lookupResponse, ex) -> { if (ex == null) { ctx.writeAndFlush(lookupResponse); } else { // it should never happen log.warn(""[{}] lookup failed with error {}, {}"", remoteAddress, topicName, ex.getMessage(), ex); ctx.writeAndFlush(newLookupErrorResponse(ServerError.ServiceNotReady, ex.getMessage(), requestId)); } lookupSemaphore.release(); return null; }); } else { final String msg = ""Proxy Client is not authorized to Lookup""; log.warn(""[{}] {} with role {} on topic {}"", remoteAddress, msg, getPrincipal(), topicName); ctx.writeAndFlush(newLookupErrorResponse(ServerError.AuthorizationError, msg, requestId)); lookupSemaphore.release(); } return null; }).exceptionally(ex -> { logAuthException(remoteAddress, ""lookup"", getPrincipal(), Optional.of(topicName), ex); final String msg = ""Exception occurred while trying to authorize lookup""; ctx.writeAndFlush(newLookupErrorResponse(ServerError.AuthorizationError, msg, requestId)); lookupSemaphore.release(); return null; }); } else { if (log.isDebugEnabled()) { log.debug(""[{}] Failed lookup due to too many lookup-requests {}"", remoteAddress, topicName); } ctx.writeAndFlush(newLookupErrorResponse(ServerError.TooManyRequests, ""Failed due to too many pending lookup requests"", requestId)); } }","@Override protected void handleLookup(CommandLookupTopic lookup) { final long requestId = lookup.getRequestId(); final boolean authoritative = lookup.isAuthoritative(); final String advertisedListenerName = lookup.hasAdvertisedListenerName() ? lookup.getAdvertisedListenerName() : null; if (log.isDebugEnabled()) { log.debug(""[{}] Received Lookup from {} for {}"", lookup.getTopic(), remoteAddress, requestId); } TopicName topicName = validateTopicName(lookup.getTopic(), requestId, lookup); if (topicName == null) { return; } final Semaphore lookupSemaphore = service.getLookupRequestSemaphore(); if (lookupSemaphore.tryAcquire()) { if (invalidOriginalPrincipal(originalPrincipal)) { final String msg = ""Valid Proxy Client role should be provided for lookup ""; log.warn(""[{}] {} with role {} and proxyClientAuthRole {} on topic {}"", remoteAddress, msg, authRole, originalPrincipal, topicName); ctx.writeAndFlush(newLookupErrorResponse(ServerError.AuthorizationError, msg, requestId)); lookupSemaphore.release(); return; } isTopicOperationAllowed(topicName, TopicOperation.LOOKUP, getAuthenticationData()).thenApply( isAuthorized -> { if (isAuthorized) { lookupTopicAsync(getBrokerService().pulsar(), topicName, authoritative, getPrincipal(), getAuthenticationData(), requestId, advertisedListenerName).handle((lookupResponse, ex) -> { if (ex == null) { ctx.writeAndFlush(lookupResponse); } else { // it should never happen log.warn(""[{}] lookup failed with error {}, {}"", remoteAddress, topicName, ex.getMessage(), ex); ctx.writeAndFlush(newLookupErrorResponse(ServerError.ServiceNotReady, ex.getMessage(), requestId)); } lookupSemaphore.release(); return null; }); } else { final String msg = ""Proxy Client is not authorized to Lookup""; log.warn(""[{}] {} with role {} on topic {}"", remoteAddress, msg, getPrincipal(), topicName); ctx.writeAndFlush(newLookupErrorResponse(ServerError.AuthorizationError, msg, requestId)); lookupSemaphore.release(); } return null; }).exceptionally(ex -> { logAuthException(remoteAddress, ""lookup"", getPrincipal(), Optional.of(topicName), ex); final String msg = ""Exception occurred while trying to authorize lookup""; ctx.writeAndFlush(newLookupErrorResponse(ServerError.AuthorizationError, msg, requestId)); lookupSemaphore.release(); return null; }); } else { if (log.isDebugEnabled()) { log.debug(""[{}] Failed lookup due to too many lookup-requests {}"", remoteAddress, topicName); } ctx.writeAndFlush(newLookupErrorResponse(ServerError.TooManyRequests, ""Failed due to too many pending lookup requests"", requestId)); } }","Avoid AuthenticationDataSource mutation for subscription name (#16065) The `authenticationData` field in `ServerCnx` is being mutated to add the `subscription` field that will be passed on to the authorization plugin. The problem is that `authenticationData` is scoped to the whole connection and it should be getting mutated for each consumer that is created on the connection. The current code leads to a race condition where the subscription name used in the authz plugin is already modified while we're looking at it. Instead, we should create a new object and enforce the final modifier. (cherry picked from commit e6b12c64b043903eb5ff2dc5186fe8030f157cfc)",https://github.com/apache/pulsar/commit/88b51b1e12254ab4feb1e4f0ace5432a330d1eda,,,pulsar-broker/src/main/java/org/apache/pulsar/broker/service/ServerCnx.java,3,java,False,2022-06-15T07:00:28Z "@SuppressWarnings(""unchecked"") private static Connection getConnection0(final Settings settings, final Path configPath, final ClassLoader cl, final boolean needRestore) throws KeyStoreException, NoSuchAlgorithmException, CertificateException, FileNotFoundException, IOException, LdapException { final boolean enableSSL = settings.getAsBoolean(ConfigConstants.LDAPS_ENABLE_SSL, false); final List ldapHosts = settings.getAsList(ConfigConstants.LDAP_HOSTS, Collections.singletonList(""localhost"")); Connection connection = null; Exception lastException = null; final boolean isDebugEnabled = log.isDebugEnabled(); final boolean isTraceEnabled = log.isTraceEnabled(); for (String ldapHost : ldapHosts) { if (isTraceEnabled) { log.trace(""Connect to {}"", ldapHost); } try { final String[] split = ldapHost.split("":""); int port; if (split.length > 1) { port = Integer.parseInt(split[1]); } else { port = enableSSL ? 636 : 389; } final ConnectionConfig config = new ConnectionConfig(); config.setLdapUrl(""ldap"" + (enableSSL ? ""s"" : """") + ""://"" + split[0] + "":"" + port); if (isTraceEnabled) { log.trace(""Connect to {}"", config.getLdapUrl()); } final Map props = configureSSL(config, settings, configPath); final String bindDn = settings.get(ConfigConstants.LDAP_BIND_DN, null); final String password = settings.get(ConfigConstants.LDAP_PASSWORD, null); if (isDebugEnabled) { log.debug(""bindDn {}, password {}"", bindDn, password != null && password.length() > 0 ? ""****"" : """"); } if (bindDn != null && (password == null || password.length() == 0)) { log.error(""No password given for bind_dn {}. Will try to authenticate anonymously to ldap"", bindDn); } final boolean enableClientAuth = settings.getAsBoolean(ConfigConstants.LDAPS_ENABLE_SSL_CLIENT_AUTH, ConfigConstants.LDAPS_ENABLE_SSL_CLIENT_AUTH_DEFAULT); if (isDebugEnabled) { if (enableClientAuth && bindDn == null) { log.debug(""Will perform External SASL bind because client cert authentication is enabled""); } else if (bindDn == null) { log.debug(""Will perform anonymous bind because no bind dn is given""); } else if (enableClientAuth && bindDn != null) { log.debug( ""Will perform simple bind with bind dn because to bind dn is given and overrides client cert authentication""); } else if (!enableClientAuth && bindDn != null) { log.debug(""Will perform simple bind with bind dn""); } } if (bindDn != null && password != null && password.length() > 0) { props.put(JndiConnection.AUTHENTICATION, ""simple""); props.put(JndiConnection.PRINCIPAL, bindDn); props.put(JndiConnection.CREDENTIALS, password.getBytes(StandardCharsets.UTF_8)); } else if (enableClientAuth) { props.put(JndiConnection.AUTHENTICATION, ""EXTERNAL""); } else { props.put(JndiConnection.AUTHENTICATION, ""none""); } DefaultConnectionFactory connFactory = new DefaultConnectionFactory(config); connFactory.getProvider().getProviderConfig().setProperties(props); connection = connFactory.getConnection(); connection.open(); if (connection != null && connection.isOpen()) { break; } else { Utils.unbindAndCloseSilently(connection); if (needRestore) { restoreClassLoader0(cl); } connection = null; } } catch (final Exception e) { lastException = e; log.warn(""Unable to connect to ldapserver {} due to {}. Try next."", ldapHost, e.toString()); Utils.unbindAndCloseSilently(connection); if (needRestore) { restoreClassLoader0(cl); } connection = null; continue; } } if (connection == null || !connection.isOpen()) { Utils.unbindAndCloseSilently(connection); //just in case if (needRestore) { restoreClassLoader0(cl); } connection = null; if (lastException == null) { throw new LdapException(""Unable to connect to any of those ldap servers "" + ldapHosts); } else { throw new LdapException( ""Unable to connect to any of those ldap servers "" + ldapHosts + "" due to "" + lastException, lastException); } } final Connection delegate = connection; if (isDebugEnabled) { log.debug(""Opened a connection, total count is now {}"", CONNECTION_COUNTER.incrementAndGet()); } return new Connection() { @Override public Response reopen(BindRequest request) throws LdapException { if (isDebugEnabled) { log.debug(""Reopened a connection""); } return delegate.reopen(request); } @Override public Response reopen() throws LdapException { if (isDebugEnabled) { log.debug(""Reopened a connection""); } return delegate.reopen(); } @Override public Response open(BindRequest request) throws LdapException { try { if(isDebugEnabled && delegate != null && delegate.isOpen()) { log.debug(""Opened a connection, total count is now {}"", CONNECTION_COUNTER.incrementAndGet()); } } catch (Throwable e) { //ignore } return delegate.open(request); } @Override public Response open() throws LdapException { try { if(isDebugEnabled && delegate != null && delegate.isOpen()) { log.debug(""Opened a connection, total count is now {}"", CONNECTION_COUNTER.incrementAndGet()); } } catch (Throwable e) { //ignore } return delegate.open(); } @Override public boolean isOpen() { return delegate.isOpen(); } @Override public ProviderConnection getProviderConnection() { return delegate.getProviderConnection(); } @Override public ConnectionConfig getConnectionConfig() { return delegate.getConnectionConfig(); } @Override public void close(RequestControl[] controls) { try { if(isDebugEnabled && delegate != null && delegate.isOpen()) { log.debug(""Closed a connection, total count is now {}"", CONNECTION_COUNTER.decrementAndGet()); } } catch (Throwable e) { //ignore } try { delegate.close(controls); } finally { restoreClassLoader(); } } @Override public void close() { try { if(isDebugEnabled && delegate != null && delegate.isOpen()) { log.debug(""Closed a connection, total count is now {}"", CONNECTION_COUNTER.decrementAndGet()); } } catch (Throwable e) { //ignore } try { delegate.close(); } finally { restoreClassLoader(); } } private void restoreClassLoader() { if (needRestore) { restoreClassLoader0(cl); } } }; }","@SuppressWarnings(""unchecked"") private static Connection getConnection0(final Settings settings, final Path configPath, final ClassLoader cl, final boolean needRestore) throws KeyStoreException, NoSuchAlgorithmException, CertificateException, FileNotFoundException, IOException, LdapException { final boolean enableSSL = settings.getAsBoolean(ConfigConstants.LDAPS_ENABLE_SSL, false); final List ldapHosts = settings.getAsList(ConfigConstants.LDAP_HOSTS, Collections.singletonList(""localhost"")); Connection connection = null; Exception lastException = null; final boolean isDebugEnabled = log.isDebugEnabled(); final boolean isTraceEnabled = log.isTraceEnabled(); for (String ldapHost : ldapHosts) { if (isTraceEnabled) { log.trace(""Connect to {}"", ldapHost); } try { final String[] split = ldapHost.split("":""); int port; if (split.length > 1) { port = Integer.parseInt(split[1]); } else { port = enableSSL ? 636 : 389; } final ConnectionConfig config = new ConnectionConfig(); config.setLdapUrl(""ldap"" + (enableSSL ? ""s"" : """") + ""://"" + split[0] + "":"" + port); if (isTraceEnabled) { log.trace(""Connect to {}"", config.getLdapUrl()); } configureSSL(config, settings, configPath); final String bindDn = settings.get(ConfigConstants.LDAP_BIND_DN, null); final String password = settings.get(ConfigConstants.LDAP_PASSWORD, null); if (isDebugEnabled) { log.debug(""bindDn {}, password {}"", bindDn, password != null && password.length() > 0 ? ""****"" : """"); } if (bindDn != null && (password == null || password.length() == 0)) { log.error(""No password given for bind_dn {}. Will try to authenticate anonymously to ldap"", bindDn); } final boolean enableClientAuth = settings.getAsBoolean(ConfigConstants.LDAPS_ENABLE_SSL_CLIENT_AUTH, ConfigConstants.LDAPS_ENABLE_SSL_CLIENT_AUTH_DEFAULT); if (isDebugEnabled) { if (enableClientAuth && bindDn == null) { log.debug(""Will perform External SASL bind because client cert authentication is enabled""); } else if (bindDn == null) { log.debug(""Will perform anonymous bind because no bind dn is given""); } else if (enableClientAuth && bindDn != null) { log.debug( ""Will perform simple bind with bind dn because to bind dn is given and overrides client cert authentication""); } else if (!enableClientAuth && bindDn != null) { log.debug(""Will perform simple bind with bind dn""); } } if (bindDn != null && password != null && password.length() > 0) { config.setConnectionInitializer(new BindConnectionInitializer(bindDn, new Credential(password))); } else if (enableClientAuth) { SaslConfig saslConfig = new SaslConfig(); saslConfig.setMechanism(Mechanism.EXTERNAL); BindConnectionInitializer bindConnectionInitializer = new BindConnectionInitializer(); bindConnectionInitializer.setBindSaslConfig(saslConfig); config.setConnectionInitializer(bindConnectionInitializer); } else { // No authentication } DefaultConnectionFactory connFactory = new DefaultConnectionFactory(config); connection = connFactory.getConnection(); connection.open(); if (connection != null && connection.isOpen()) { break; } else { Utils.unbindAndCloseSilently(connection); if (needRestore) { restoreClassLoader0(cl); } connection = null; } } catch (final Exception e) { lastException = e; log.warn(""Unable to connect to ldapserver {} due to {}. Try next."", ldapHost, e.toString()); Utils.unbindAndCloseSilently(connection); if (needRestore) { restoreClassLoader0(cl); } connection = null; continue; } } if (connection == null || !connection.isOpen()) { Utils.unbindAndCloseSilently(connection); //just in case if (needRestore) { restoreClassLoader0(cl); } connection = null; if (lastException == null) { throw new LdapException(""Unable to connect to any of those ldap servers "" + ldapHosts); } else { throw new LdapException( ""Unable to connect to any of those ldap servers "" + ldapHosts + "" due to "" + lastException, lastException); } } final Connection delegate = connection; if (isDebugEnabled) { log.debug(""Opened a connection, total count is now {}"", CONNECTION_COUNTER.incrementAndGet()); } return new Connection() { @Override public Response reopen(BindRequest request) throws LdapException { if (isDebugEnabled) { log.debug(""Reopened a connection""); } return delegate.reopen(request); } @Override public Response reopen() throws LdapException { if (isDebugEnabled) { log.debug(""Reopened a connection""); } return delegate.reopen(); } @Override public Response open(BindRequest request) throws LdapException { try { if(isDebugEnabled && delegate != null && delegate.isOpen()) { log.debug(""Opened a connection, total count is now {}"", CONNECTION_COUNTER.incrementAndGet()); } } catch (Throwable e) { //ignore } return delegate.open(request); } @Override public Response open() throws LdapException { try { if(isDebugEnabled && delegate != null && delegate.isOpen()) { log.debug(""Opened a connection, total count is now {}"", CONNECTION_COUNTER.incrementAndGet()); } } catch (Throwable e) { //ignore } return delegate.open(); } @Override public boolean isOpen() { return delegate.isOpen(); } @Override public ProviderConnection getProviderConnection() { return delegate.getProviderConnection(); } @Override public ConnectionConfig getConnectionConfig() { return delegate.getConnectionConfig(); } @Override public void close(RequestControl[] controls) { try { if(isDebugEnabled && delegate != null && delegate.isOpen()) { log.debug(""Closed a connection, total count is now {}"", CONNECTION_COUNTER.decrementAndGet()); } } catch (Throwable e) { //ignore } try { delegate.close(controls); } finally { restoreClassLoader(); } } @Override public void close() { try { if(isDebugEnabled && delegate != null && delegate.isOpen()) { log.debug(""Closed a connection, total count is now {}"", CONNECTION_COUNTER.decrementAndGet()); } } catch (Throwable e) { //ignore } try { delegate.close(); } finally { restoreClassLoader(); } } private void restoreClassLoader() { if (needRestore) { restoreClassLoader0(cl); } } }; }","Fix LDAP authentication when using StartTLS (#1415) Update the code to use the same ldaptive API as the one of the working examples. This unbreak LDAP authentification when StartTLS is required. As a bonus, remove the passing of the now useless properties all around the code. Signed-off-by: Romain Tartière ",https://github.com/opensearch-project/security/commit/6483d39678c7fe4b16ecd912f07256455cbd22dc,,,src/main/java/com/amazon/dlic/auth/ldap/backend/LDAPAuthorizationBackend.java,3,java,False,2021-08-23T17:12:55Z "def get_client_uri(self, protocol, host, port, proxied_path): context_path = self._get_context_path(host, port) if self.absolute_url: client_path = url_path_join(context_path, proxied_path) else: client_path = proxied_path # Quote spaces, åäö and such, but only enough to send a valid web # request onwards. To do this, we mark the RFC 3986 specs' ""reserved"" # and ""un-reserved"" characters as safe that won't need quoting. The # un-reserved need to be marked safe to ensure the quote function behave # the same in py36 as py37. # # ref: https://tools.ietf.org/html/rfc3986#section-2.2 client_path = quote(client_path, safe="":/?#[]@!$&'()*+,;=-._~"") client_uri = '{protocol}://{host}:{port}{path}'.format( protocol=protocol, host=host, port=port, path=client_path ) if self.request.query: client_uri += '?' + self.request.query return client_uri","def get_client_uri(self, protocol, host, port, proxied_path): if self.absolute_url: context_path = self._get_context_path(host, port) client_path = url_path_join(context_path, proxied_path) else: client_path = proxied_path # ensure client_path always starts with '/' if not client_path.startswith(""/""): client_path = ""/"" + client_path # Quote spaces, åäö and such, but only enough to send a valid web # request onwards. To do this, we mark the RFC 3986 specs' ""reserved"" # and ""un-reserved"" characters as safe that won't need quoting. The # un-reserved need to be marked safe to ensure the quote function behave # the same in py36 as py37. # # ref: https://tools.ietf.org/html/rfc3986#section-2.2 client_path = quote(client_path, safe="":/?#[]@!$&'()*+,;=-._~"") client_uri = '{protocol}://{host}:{port}{path}'.format( protocol=protocol, host=host, port=port, path=client_path, ) if self.request.query: client_uri += '?' + self.request.query return client_uri","Merge pull request from GHSA-gcv9-6737-pjqw validate proxied paths starting with /",https://github.com/jupyterhub/jupyter-server-proxy/commit/fd31930bacd12188c448c886e0783529436b99eb,,,jupyter_server_proxy/handlers.py,3,py,False,2022-01-24T22:30:00Z "@Override public void allocateReserve() { List allSystems = empire.allColonizedSystems(); List poorSystems = new ArrayList<>(); List richSystems = new ArrayList<>(); // modnar: make richSystem list // remove all systems in rebellion and poor/ultra-poor. None of these // systems will receive reserve. However poor/ultra-poor will be added // back in so we can collect reserve from them. // modnar: (???) poor/ultra-poor should be getting reserve to build factories // they are terrible to collect reserve from... // instead remove rich/ultra-rich from receiving reserves List systems = new ArrayList<>(allSystems); for (StarSystem sys: allSystems) { if (sys.colony().inRebellion()) systems.remove(sys); else { Planet pl = sys.planet(); if (pl.isResourcePoor() || pl.isResourceUltraPoor()) { poorSystems.add(sys); // modnar: still make poorSystems list } if (pl.isResourceRich() || pl.isResourceUltraRich()) { systems.remove(sys); richSystems.add(sys); // modnar: make richSystems list } } } // first, help systems that are fighting plague or supernova research events if (empire.totalReserve() > 0) { List remainingSystems = new ArrayList<>(systems); for (StarSystem sys: remainingSystems) { if (empire.totalReserve() <= 0) break; Colony col = sys.colony(); if (col.research().hasProject()) { int rsvNeeded = (int) col.maxReserveNeeded(); empire.allocateReserve(col, rsvNeeded); systems.remove(sys); } } } // next, give reserve to systems designed as ""rush defense"" by the general if (empire.totalReserve() > 0) { List needDefense = empire.generalAI().rushDefenseSystems(); for (StarSystem sys: needDefense) { if (empire.totalReserve() <= 0) break; Colony col = sys.colony(); int rsvNeeded = (int) col.maxReserveNeeded(); empire.allocateReserve(col, rsvNeeded); systems.remove(sys); } } // next, give reserve to systems designed as ""rush build ships"" by the fleet commander if (empire.totalReserve() > 0) { List needShips = empire.generalAI().rushShipSystems(); for (StarSystem sys: needShips) { if (empire.totalReserve() <= 0) break; Colony col = sys.colony(); int rsvNeeded = (int) col.maxReserveNeeded(); empire.allocateReserve(col, rsvNeeded); systems.remove(sys); } } // sort remaining colonies from smallest to largest // assist in prod to build factories on smaller colonies if (empire.totalReserve() > 0) { List remainingSystems = new ArrayList<>(systems); Collections.sort(remainingSystems,StarSystem.BASE_PRODUCTION); Collections.reverse(remainingSystems); for (StarSystem sys : remainingSystems) { if (empire.totalReserve() <= 0) break; Colony col = sys.colony(); float max = col.industry().maxSpendingNeeded(); float curr = col.maxProduction(); int rsvNeeded = (int) max(0, min(col.maxReserveUseable(), max-curr)); if (rsvNeeded > 0) { empire.allocateReserve(col,rsvNeeded); systems.remove(sys); } } } }","@Override public void allocateReserve() { List allSystems = empire.allColonizedSystems(); List poorSystems = new ArrayList<>(); List richSystems = new ArrayList<>(); // modnar: make richSystem list boolean needToSolveEvent = false; // remove all systems in rebellion and poor/ultra-poor. None of these // systems will receive reserve. However poor/ultra-poor will be added // back in so we can collect reserve from them. // modnar: (???) poor/ultra-poor should be getting reserve to build factories // they are terrible to collect reserve from... // instead remove rich/ultra-rich from receiving reserves List systems = new ArrayList<>(allSystems); for (StarSystem sys: allSystems) { if (sys.colony().inRebellion()) systems.remove(sys); else { if (sys.colony().research().hasProject()) needToSolveEvent = true; Planet pl = sys.planet(); if (pl.isResourcePoor() || pl.isResourceUltraPoor()) { poorSystems.add(sys); // modnar: still make poorSystems list } if (pl.isResourceRich() || pl.isResourceUltraRich()) { //ail: If the system with the event is rich, we mustn't remove it from the list of receivers! if(!sys.colony().research().hasProject()) { systems.remove(sys); richSystems.add(sys); // modnar: make richSystems list } } } } // first, help systems that are fighting plague or supernova research events if (empire.totalReserve() > 0) { List remainingSystems = new ArrayList<>(systems); for (StarSystem sys: remainingSystems) { if (empire.totalReserve() <= 0) break; Colony col = sys.colony(); if (col.research().hasProject()) { needToSolveEvent = true; int rsvNeeded = (int) col.maxReserveNeeded(); empire.allocateReserve(col, rsvNeeded); //ail: might be able to lower it due to more income meaning less percent for clean needed col.lowerECOToCleanIfEcoComplete(); systems.remove(sys); } } } // next, give reserve to systems designed as ""rush defense"" by the general if (empire.totalReserve() > 0) { List needDefense = empire.generalAI().rushDefenseSystems(); for (StarSystem sys: needDefense) { if (empire.totalReserve() <= 0) break; Colony col = sys.colony(); int rsvNeeded = (int) col.maxReserveNeeded(); empire.allocateReserve(col, rsvNeeded); //ail: might be able to lower it due to more income meaning less percent for clean needed col.lowerECOToCleanIfEcoComplete(); systems.remove(sys); } } // next, give reserve to systems designed as ""rush build ships"" by the fleet commander if (empire.totalReserve() > 0) { List needShips = empire.generalAI().rushShipSystems(); for (StarSystem sys: needShips) { if (empire.totalReserve() <= 0) break; Colony col = sys.colony(); int rsvNeeded = (int) col.maxReserveNeeded(); empire.allocateReserve(col, rsvNeeded); //ail: might be able to lower it due to more income meaning less percent for clean needed col.lowerECOToCleanIfEcoComplete(); systems.remove(sys); } } // sort remaining colonies from smallest to largest // assist in prod to build factories on smaller colonies if (empire.totalReserve() > 0) { List remainingSystems = new ArrayList<>(systems); Collections.sort(remainingSystems,StarSystem.BASE_PRODUCTION); Collections.reverse(remainingSystems); for (StarSystem sys : remainingSystems) { if (empire.totalReserve() <= 0) break; Colony col = sys.colony(); float max = col.industry().maxSpendingNeeded(); float curr = col.maxProduction(); int rsvNeeded = (int) max(0, min(col.maxReserveUseable(), max-curr)); if (rsvNeeded > 0) { empire.allocateReserve(col,rsvNeeded); //ail: might be able to lower it due to more income meaning less percent for clean needed col.lowerECOToCleanIfEcoComplete(); systems.remove(sys); } } } //We only gather tax when we need to deal with a nova/plague if(needToSolveEvent) { float totalProd = empire.totalPlanetaryProduction(); float desiredRsv = totalProd * 0.1f; // modnar: reduce reserve collection, less is more efficient in general int maxAlloc = ColonySpendingCategory.MAX_TICKS; if (empire.totalReserve() < desiredRsv) { systems.addAll(richSystems); // modnar: check for richSystems first to collect reserve Collections.reverse(systems); for (StarSystem sys : systems) { Colony col = sys.colony(); //ail: The colony that has the project that we are saving for shouldn't be one of those who are saving! if(col.research().hasProject()) continue; int res = col.research().allocation(); if (res > 0) { Planet pl = sys.planet(); if (pl.isResourceRich() || pl.isResourceUltraRich()) { if (col.population() >= pl.maxSize()) { int eco = col.ecology().allocation(); int ecoAdj = min(res, maxAlloc - eco); // modnar: collect all we can from rich/ultra-rich col.research().adjustValue(-ecoAdj); col.ecology().adjustValue(ecoAdj); } } else if (!pl.isArtifact()) { if (col.industry().factories() >= col.industry().maxFactories()) { int ind = col.industry().allocation(); int indAdj = min(res, maxAlloc - ind)/4; // ail: 1/6 wasn't enough to prevent the nova col.research().adjustValue(-indAdj); col.industry().adjustValue(indAdj); } } } } } } }","2nd pullrequest for 0.9a (#50) * Replaced many isPlayer() by isPlayerControlled() This leads to a more fluent experience on AutoPlay. Note: the council-voting acts weird when you try that there, getting you stuck, and the News-Broadcasts also seem to use a differnt logic and are always shown. * Orion-guard-handling Avoid sending colonization-fleets, when guardian is still alive Increase guardian-power-estimate to 100,000 Don't send and count bombers towards guardian-defeat-force * Fixed Crash from a report on reddit Not sure how that could happen though. Never had this issue in games started on my computer. * Fixed crash after AI defeats orion-guard Tried to access an out-of-bounds-value because it couldn't find the System where the guardian was. So looking to find the Planet with the Orionartifact now, which does find it. * All the forgotten isPlayer()-calls Including the Base- and Modnar-AI-Diplomat * Personalities now play a role in my AI once again Instead of everyone having the same conditions for war, there's now different ones. Some are more aggressive, some are less. * Fixed issue where enemy-fleets weren's seen, when they actually were. Also added a way of guessing when enemy-fleets aren't seen so it shouldn't trickle in tiny fleets that all retreat anymore in the early-game, before they can see the enemy-fleets. And also not later because they now actually can see them. * Update AIDiplomat.java * Delete ShipCombatResults.java * Delete Empire.java * Delete TradeRoute.java * Revert ""Delete TradeRoute.java"" This reverts commit 6e5c5a8604e89bb11a9a6dc63acd5b3f27194c83. * Revert ""Delete Empire.java"" This reverts commit 1a020295e05ebc735dae761f426742eb7bdc8d35. * Revert ""Delete ShipCombatResults.java"" This reverts commit 5f9287289feb666adf1aa809524973c54fbf0cd5. * Update ShipCombatResults.java reverting pull-request... manually because I don't know of a better way 8[ * Update Empire.java * Update TradeRoute.java * Merge with Master * Update TradeRoute.java * Update TradeRoute.java github editor does not allow me to remove a newline oO * AI improvements Added parameter to make the colonizer-function return just the uncolonized planets without substracting the colony-ships. Impelemented a very differnt diplomatic behavior, that supposedly is more suitable to actually winning by waging less war, particularly when big enough to be voted for. Revoked that AI doesn't adjust to enemy-troops when it has a more defensive unit-composition. In lategame going by destructive-power of bombers hasn't much merit, when 1 bombers can pack 60ish neutronium-bombs. Fixed an issue that prevented designing extended-fuel-range-colonizers asap. This once again helps expansion-speed a lot. Security now is only spent against empires actually in range to spy, as it was intended. Contact via council should not increase paranoia. Also Xenophobic-extra-paranoia removed. * Update OrionGuardianShip.java * War-declaration behavior Electible faction will no longer declare war on someone who is at war with the other electible faction. * Fix zero-division on refreshing a trade-route that had been adjusted due to empire-shrinkage. * AI & Bugfix Leader-stuff is now overridden Should now retreat against repulsors, when no counter available Tech-nullifier hit and miss mixup fixed * AI improvements Fixed a rare crash in AutoPlay-Mode Massive overhaul of AI-ship-design Spy master now more catious about avoiding unwanted, dangerous wars due to spying on the wrong people Colony-ship-designs now will only get a weapon, if this doesn't prevent reserve-tanks or reducing their size to medium Fixed an issue where ai wouldn't retreat from ships with repulsor-beam that exploited their range-advantage Increased research-value of cloaking-tech and battle-suits Upon reaching tech-level 99 in every field, AI will produce ships non-stop even in peace-time AI will now retreat fleets from empires it doesn't want to go to war with in order to avoid trespassing-issues Fixed issue where the AI wanted to but couldn't colonize orion before it was cleared and then wouldn't colonize other systems in that time AI will no longer break non-aggression-pacts when it still has a war with someone else AI will only begin wars because of spying, if it actually feels comfortable dealing with the person who spied on them AI will now try and predict whether it will be attacked soon and enact preventive measures * Tackling some combat-issue Skipping specials when it comes to determining optimal-range. Otherwise ships with long-range-specials like warp-dissipator would never close in on their prey. Resetting the selectedWeaponIndex upon reload to consistency start with same weapons every turn. Writing new attack-method that allows to skip certain weapons like for example repulsor-beam at the beginning of the turn and fire them at the end instead. * Update NewShipTemplate.java Fixed incorrect operator ""-="" instead of ""=-"", that prevented weapons being used at all when no weapon that is strong enough for theorethical best enemy shield could be found. Also when range is required an not fitting beam can be found try missiles and when no fitting missile can be found either, try short-range weapon. Should still be better than nothing. * Diplomacy and Ship-Building Reduced suicidal tendencies. No more war-declarations against wastly superior enemies. At most they ought to be 25% stronger. Voting behavior is now deterministic. No more votes based on fear, only on who they actually like and only for those whom they have real-contact. Ship-construction is now based on relative-productivity rather than using a hard cut-off for anything lower than standard-resources. So when the empire only has poor-systems it will try to build at least a few ships still. * Orion prevented war Fixed an issue, where wanting to build a colonizer for Orion prevented wars. * Update AIGeneral.java Don't invade unless you have something in orbit. * Update AIFleetCommander.java No longer using hyperspace-communications... for now. (it produced unintentional results and error-messages) * AI improvements corrected typo in Stellar Converter Fixed trading for techs that have no value by taking the random modifier into account No longer agreeing to or offering alliances Added sophisticated behavior when it comes to offering and agreeing to joint wars Ignore existence of council in diplomatic behavior No longer needing to have positive relations for council vote, the lesser evil is good enough Improved the selection at which planets ships are being built, this time really improved rather than probably making it worse than before No longer using extended fuel-tanks when unlimited-range-tech is researched Avoid designing bombers that can overkill a planet single-handedly, instead replace part of the bombs with other weapons Scoring adjustments for special-devices, primarily no longer taking space into account for score as otherwise miniaturization would always lead to always using the old, weak specials * AI-improvements and combat-estimated fixes No longer wanting to do a NAP with preferred target Divide score for target by 3 if nap is in place, so nap now is really usefull to have with Empires outside of trading range will no longer offer joint wars Logic for whether to declare war on somone who spied on them is now same as if they were their best victim. This prevents suicidal anti-spy-wars. Prevention-war will now also be started upon invasions No longer setting retreat on arrival, as preemtively retreating may prevent retargetting something else, especially important for colony-ships early on Retreats are now also handled after the fleet-manager had the chance to do something else with these ships reduced the percentage of bombers that will be built by about half. So it can't go over 50% anymore and usually will be even lower Fixed an issue with incorrect kill-percentage estimates. After that fix the Valuefactor, which had some correcting attributes, was no longer needed and thus removed. Made sure that bombers are always designed to actually have bombs. Invaders with surrenderOnArrival are no longer considered a threat * AI and damage-simulation-stuff No longer bombing colonies of someone who isn't my enemy Asking others to join a war, when our opponent is stronger than us Agreeing to join-war request when not busy otherwise, together we'd be stronger and the asked-for-faction is our primary target anyways Restricted war over espionage even more, to only do it if we feel ready. Much better to share a few techs than to die. Wars for strategic reasons can now once again be cancelled. Doing a cost:gain-analysis for invasions, that is much more likely to invade, especially if we have previously been invaded and the planet has factories from us. It also takes the savings of not having to build a colony-ship into account. Further reduced the overkill for invasions. We want to do more of them when they are cost-efficient but still not waste our population. More planets will participate in the construction of colony-ships. When we are at war or have others in our range during the phase where we want to churn out colony-ships, we mix in combat-ships to make us less of a juicy target and be able to repel sneak-attacks better. Hostile-planets now get more population sent to. Stacks of strong individual ships about to die in combat, will consider their lessened chances of survival and may now retreat when damaged too much. Reverted change in method that I don't use anyways. Fixed shield-halving-properties of weapons like neutron-pellet-guns not being taken into account in combat-simulations using the firepower-method. Fixed bombers estimating the whole stack sharing a single bomb, which dramatically underestimated the firepower they had. * Mostly things about research Fixed that studyingFutureTech() always returned false. Fixed issue with having more research-allocation-points than possible in base- and modnar-AI when redistributing research-points to avoid researching future techs before other techs are researched Inclusion of faction-specific espionage-replies Maximum ship-maintenance now capped at 45% (5*warp-speed) before all techs are researched, then it is doubled to 90% More bombers will be built when opponents use missile-bases a lot When under siege by enemy bombers will no longer build factories but either population, ships or research depending on how destructive the bombardment is. This is to avoid investing into something that will be lost or not finished anyways. Future techs are now considered lower priority than all non-obsolete techs. Fixed missing override of baseValue for future-techs No longer allocating RP to techs which have a higher percentage to be researched next turn than the percentage of RP attributed to them. This should increase research-output slightly. Ship-stacks that have colony-ships in their fleet will no longer be much more ready to retreat because they consider the low survivability of colony-ships as a threat to themselves. Colony-ships may retreat alone, but won't always do so either. Retreat threshold is now always 1.0, meaning if they think they can win, they will stay, even if the losses equal their own kills. Allowed treasurer to gather taxes in order to save planets from nova or plague. Co-authored-by: rayfowler <58891984+rayfowler@users.noreply.github.com>",https://github.com/rayfowler/rotp-public/commit/2d6b3647a636a7a38600a9f3e9f8597a3a0da2a5,,,src/rotp/model/ai/xilmi/AITreasurer.java,3,java,False,2021-04-09T00:05:05Z "protected Object mapObject(JsonParser p, DeserializationContext ctxt) throws IOException { // will point to FIELD_NAME at this point, guaranteed // 19-Jul-2021, tatu: Was incorrectly using ""getText()"" before 2.13, fixed for 2.13.0 String key1 = p.currentName(); p.nextToken(); Object value1 = deserialize(p, ctxt); String key2 = p.nextFieldName(); if (key2 == null) { // single entry; but we want modifiable LinkedHashMap result = new LinkedHashMap(2); result.put(key1, value1); return result; } p.nextToken(); Object value2 = deserialize(p, ctxt); String key = p.nextFieldName(); if (key == null) { LinkedHashMap result = new LinkedHashMap(4); result.put(key1, value1); if (result.put(key2, value2) != null) { // 22-May-2020, tatu: [databind#2733] may need extra handling return _mapObjectWithDups(p, ctxt, result, key1, value1, value2, key); } return result; } // And then the general case; default map size is 16 LinkedHashMap result = new LinkedHashMap(); result.put(key1, value1); if (result.put(key2, value2) != null) { // 22-May-2020, tatu: [databind#2733] may need extra handling return _mapObjectWithDups(p, ctxt, result, key1, value1, value2, key); } do { p.nextToken(); final Object newValue = deserialize(p, ctxt); final Object oldValue = result.put(key, newValue); if (oldValue != null) { return _mapObjectWithDups(p, ctxt, result, key, oldValue, newValue, p.nextFieldName()); } } while ((key = p.nextFieldName()) != null); return result; }","protected Object mapObject(JsonParser p, DeserializationContext ctxt) throws IOException { String key1; JsonToken t = p.currentToken(); if (t == JsonToken.START_OBJECT) { key1 = p.nextFieldName(); } else if (t == JsonToken.FIELD_NAME) { key1 = p.currentName(); } else { if (t != JsonToken.END_OBJECT) { return ctxt.handleUnexpectedToken(handledType(), p); } key1 = null; } if (key1 == null) { // empty map might work; but caller may want to modify... so better just give small modifiable return new LinkedHashMap<>(2); } // minor optimization; let's handle 1 and 2 entry cases separately // 24-Mar-2015, tatu: Ideally, could use one of 'nextXxx()' methods, but for // that we'd need new method(s) in JsonDeserializer. So not quite yet. p.nextToken(); Object value1 = deserialize(p, ctxt); String key2 = p.nextFieldName(); if (key2 == null) { // has to be END_OBJECT, then // single entry; but we want modifiable LinkedHashMap result = new LinkedHashMap<>(2); result.put(key1, value1); return result; } p.nextToken(); Object value2 = deserialize(p, ctxt); String key = p.nextFieldName(); if (key == null) { LinkedHashMap result = new LinkedHashMap<>(4); result.put(key1, value1); if (result.put(key2, value2) != null) { // 22-May-2020, tatu: [databind#2733] may need extra handling return _mapObjectWithDups(p, ctxt, result, key1, value1, value2, key); } return result; } // And then the general case; default map size is 16 LinkedHashMap result = new LinkedHashMap<>(); result.put(key1, value1); if (result.put(key2, value2) != null) { // 22-May-2020, tatu: [databind#2733] may need extra handling return _mapObjectWithDups(p, ctxt, result, key1, value1, value2, key); } do { p.nextToken(); final Object newValue = deserialize(p, ctxt); final Object oldValue = result.put(key, newValue); if (oldValue != null) { return _mapObjectWithDups(p, ctxt, result, key, oldValue, newValue, p.nextFieldName()); } } while ((key = p.nextFieldName()) != null); return result; }","Throw JsonMappingException for deeply nested JSON (#2816, CVE-2020-36518) (#3416)",https://github.com/FasterXML/jackson-databind/commit/fcfc4998ec23f0b1f7f8a9521c2b317b6c25892b,,,src/main/java/com/fasterxml/jackson/databind/deser/std/UntypedObjectDeserializer.java,3,java,False,2022-03-22T03:24:05Z "public double fromDerivedUnit(double amount) throws ConversionException { if (!(_unit instanceof DerivableUnit)) throw new ConversionException(getDerivedUnit(), this); double value = ((DerivableUnit)getUnit()).fromDerivedUnit(amount)/getScale(); BigDecimal bd = new BigDecimal(value); bd = bd.round(new MathContext(15)); return bd.doubleValue(); }","public double fromDerivedUnit(double amount) throws ConversionException { if (!(_unit instanceof DerivableUnit)) { throw new ConversionException(getDerivedUnit(), this); } double value = ((DerivableUnit)getUnit()).fromDerivedUnit(amount)/getScale(); if(Double.isInfinite(value) || Double.isNaN(value)) { return value; } BigDecimal bd = new BigDecimal(value); bd = bd.round(new MathContext(15)); return bd.doubleValue(); }",Fixed crash when Double evaluates to Infinity or NaN.,https://github.com/virtualcell/vcell/commit/70140d528c7a5712a28a8531b9a46e0e81b5217a,,,vcell-math/src/main/java/ucar/units_vcell/ScaledUnit.java,3,java,False,2022-07-13T17:37:35Z "public @PermissionResult int checkSlicePermission(@NonNull Uri uri, int pid, int uid) { try { return mService.checkSlicePermission(uri, mContext.getPackageName(), null, pid, uid, null); } catch (RemoteException e) { throw e.rethrowFromSystemServer(); } }","public @PermissionResult int checkSlicePermission(@NonNull Uri uri, int pid, int uid) { try { return mService.checkSlicePermission(uri, mContext.getPackageName(), pid, uid, null /* autoGrantPermissions */); } catch (RemoteException e) { throw e.rethrowFromSystemServer(); } }","Resive SliceManagerService#checkSlicePermission The parameter pkg leaves the possibility that malicious code could do a side channel attack. Remove the parameter and use calling UID instead. Bug: 191678586 Test: atest FrameworksUiServicesTests:SliceManagerServiceTest Test: atest CtsSliceTestCases Test: atest CtsSettingsTestCases:WifiSliceTest Test: manually using the PoC in the buganizer to ensure the symptom no longer exists. Change-Id: I8031577cd01027485404441ac4724a7126e395da",https://github.com/LineageOS/android_frameworks_base/commit/c459398f6f1bd1c99c78b914cc1dfe342019c301,,,core/java/android/app/slice/SliceManager.java,3,java,False,2022-03-10T08:11:55Z "@Override public boolean createNotificationChannel(String pkg, int uid, NotificationChannel channel, boolean fromTargetApp, boolean hasDndAccess) { Objects.requireNonNull(pkg); Objects.requireNonNull(channel); Objects.requireNonNull(channel.getId()); Preconditions.checkArgument(!TextUtils.isEmpty(channel.getName())); boolean needsPolicyFileChange = false, wasUndeleted = false; synchronized (mPackagePreferences) { PackagePreferences r = getOrCreatePackagePreferencesLocked(pkg, uid); if (r == null) { throw new IllegalArgumentException(""Invalid package""); } if (channel.getGroup() != null && !r.groups.containsKey(channel.getGroup())) { throw new IllegalArgumentException(""NotificationChannelGroup doesn't exist""); } if (NotificationChannel.DEFAULT_CHANNEL_ID.equals(channel.getId())) { throw new IllegalArgumentException(""Reserved id""); } NotificationChannel existing = r.channels.get(channel.getId()); if (existing != null && fromTargetApp) { // Actually modifying an existing channel - keep most of the existing settings if (existing.isDeleted()) { // The existing channel was deleted - undelete it. existing.setDeleted(false); existing.setDeletedTimeMs(-1); needsPolicyFileChange = true; wasUndeleted = true; // log a resurrected channel as if it's new again MetricsLogger.action(getChannelLog(channel, pkg).setType( com.android.internal.logging.nano.MetricsProto.MetricsEvent.TYPE_OPEN)); mNotificationChannelLogger.logNotificationChannelCreated(channel, uid, pkg); } if (!Objects.equals(channel.getName().toString(), existing.getName().toString())) { existing.setName(channel.getName().toString()); needsPolicyFileChange = true; } if (!Objects.equals(channel.getDescription(), existing.getDescription())) { existing.setDescription(channel.getDescription()); needsPolicyFileChange = true; } if (channel.isBlockable() != existing.isBlockable()) { existing.setBlockable(channel.isBlockable()); needsPolicyFileChange = true; } if (channel.getGroup() != null && existing.getGroup() == null) { existing.setGroup(channel.getGroup()); needsPolicyFileChange = true; } // Apps are allowed to downgrade channel importance if the user has not changed any // fields on this channel yet. final int previousExistingImportance = existing.getImportance(); final int previousLoggingImportance = NotificationChannelLogger.getLoggingImportance(existing); if (existing.getUserLockedFields() == 0 && channel.getImportance() < existing.getImportance()) { existing.setImportance(channel.getImportance()); needsPolicyFileChange = true; } // system apps and dnd access apps can bypass dnd if the user hasn't changed any // fields on the channel yet if (existing.getUserLockedFields() == 0 && hasDndAccess) { boolean bypassDnd = channel.canBypassDnd(); if (bypassDnd != existing.canBypassDnd()) { existing.setBypassDnd(bypassDnd); needsPolicyFileChange = true; if (bypassDnd != mAreChannelsBypassingDnd || previousExistingImportance != existing.getImportance()) { updateChannelsBypassingDnd(mContext.getUserId()); } } } if (existing.getOriginalImportance() == IMPORTANCE_UNSPECIFIED) { existing.setOriginalImportance(channel.getImportance()); needsPolicyFileChange = true; } updateConfig(); if (needsPolicyFileChange && !wasUndeleted) { mNotificationChannelLogger.logNotificationChannelModified(existing, uid, pkg, previousLoggingImportance, false); } return needsPolicyFileChange; } if (r.channels.size() >= NOTIFICATION_CHANNEL_COUNT_LIMIT) { throw new IllegalStateException(""Limit exceed; cannot create more channels""); } needsPolicyFileChange = true; if (channel.getImportance() < IMPORTANCE_NONE || channel.getImportance() > NotificationManager.IMPORTANCE_MAX) { throw new IllegalArgumentException(""Invalid importance level""); } // Reset fields that apps aren't allowed to set. if (fromTargetApp && !hasDndAccess) { channel.setBypassDnd(r.priority == Notification.PRIORITY_MAX); } if (fromTargetApp) { channel.setLockscreenVisibility(r.visibility); channel.setAllowBubbles(existing != null ? existing.getAllowBubbles() : NotificationChannel.DEFAULT_ALLOW_BUBBLE); } clearLockedFieldsLocked(channel); channel.setImportanceLockedByOEM(r.oemLockedImportance); if (!channel.isImportanceLockedByOEM()) { if (r.oemLockedChannels.contains(channel.getId())) { channel.setImportanceLockedByOEM(true); } } channel.setImportanceLockedByCriticalDeviceFunction(r.defaultAppLockedImportance); if (channel.getLockscreenVisibility() == Notification.VISIBILITY_PUBLIC) { channel.setLockscreenVisibility( NotificationListenerService.Ranking.VISIBILITY_NO_OVERRIDE); } if (!r.showBadge) { channel.setShowBadge(false); } channel.setOriginalImportance(channel.getImportance()); // validate parent if (channel.getParentChannelId() != null) { Preconditions.checkArgument(r.channels.containsKey(channel.getParentChannelId()), ""Tried to create a conversation channel without a preexisting parent""); } r.channels.put(channel.getId(), channel); if (channel.canBypassDnd() != mAreChannelsBypassingDnd) { updateChannelsBypassingDnd(mContext.getUserId()); } MetricsLogger.action(getChannelLog(channel, pkg).setType( com.android.internal.logging.nano.MetricsProto.MetricsEvent.TYPE_OPEN)); mNotificationChannelLogger.logNotificationChannelCreated(channel, uid, pkg); } return needsPolicyFileChange; }","@Override public boolean createNotificationChannel(String pkg, int uid, NotificationChannel channel, boolean fromTargetApp, boolean hasDndAccess) { Objects.requireNonNull(pkg); Objects.requireNonNull(channel); Objects.requireNonNull(channel.getId()); Preconditions.checkArgument(!TextUtils.isEmpty(channel.getName())); boolean needsPolicyFileChange = false, wasUndeleted = false; synchronized (mPackagePreferences) { PackagePreferences r = getOrCreatePackagePreferencesLocked(pkg, uid); if (r == null) { throw new IllegalArgumentException(""Invalid package""); } if (channel.getGroup() != null && !r.groups.containsKey(channel.getGroup())) { throw new IllegalArgumentException(""NotificationChannelGroup doesn't exist""); } if (NotificationChannel.DEFAULT_CHANNEL_ID.equals(channel.getId())) { throw new IllegalArgumentException(""Reserved id""); } NotificationChannel existing = r.channels.get(channel.getId()); if (existing != null && fromTargetApp) { // Actually modifying an existing channel - keep most of the existing settings if (existing.isDeleted()) { // The existing channel was deleted - undelete it. existing.setDeleted(false); existing.setDeletedTimeMs(-1); needsPolicyFileChange = true; wasUndeleted = true; // log a resurrected channel as if it's new again MetricsLogger.action(getChannelLog(channel, pkg).setType( com.android.internal.logging.nano.MetricsProto.MetricsEvent.TYPE_OPEN)); mNotificationChannelLogger.logNotificationChannelCreated(channel, uid, pkg); } if (!Objects.equals(channel.getName().toString(), existing.getName().toString())) { existing.setName(channel.getName().toString()); needsPolicyFileChange = true; } if (!Objects.equals(channel.getDescription(), existing.getDescription())) { existing.setDescription(channel.getDescription()); needsPolicyFileChange = true; } if (channel.isBlockable() != existing.isBlockable()) { existing.setBlockable(channel.isBlockable()); needsPolicyFileChange = true; } if (channel.getGroup() != null && existing.getGroup() == null) { existing.setGroup(channel.getGroup()); needsPolicyFileChange = true; } // Apps are allowed to downgrade channel importance if the user has not changed any // fields on this channel yet. final int previousExistingImportance = existing.getImportance(); final int previousLoggingImportance = NotificationChannelLogger.getLoggingImportance(existing); if (existing.getUserLockedFields() == 0 && channel.getImportance() < existing.getImportance()) { existing.setImportance(channel.getImportance()); needsPolicyFileChange = true; } // system apps and dnd access apps can bypass dnd if the user hasn't changed any // fields on the channel yet if (existing.getUserLockedFields() == 0 && hasDndAccess) { boolean bypassDnd = channel.canBypassDnd(); if (bypassDnd != existing.canBypassDnd() || wasUndeleted) { existing.setBypassDnd(bypassDnd); needsPolicyFileChange = true; if (bypassDnd != mAreChannelsBypassingDnd || previousExistingImportance != existing.getImportance()) { updateChannelsBypassingDnd(); } } } if (existing.getOriginalImportance() == IMPORTANCE_UNSPECIFIED) { existing.setOriginalImportance(channel.getImportance()); needsPolicyFileChange = true; } updateConfig(); if (needsPolicyFileChange && !wasUndeleted) { mNotificationChannelLogger.logNotificationChannelModified(existing, uid, pkg, previousLoggingImportance, false); } return needsPolicyFileChange; } if (r.channels.size() >= NOTIFICATION_CHANNEL_COUNT_LIMIT) { throw new IllegalStateException(""Limit exceed; cannot create more channels""); } needsPolicyFileChange = true; if (channel.getImportance() < IMPORTANCE_NONE || channel.getImportance() > NotificationManager.IMPORTANCE_MAX) { throw new IllegalArgumentException(""Invalid importance level""); } // Reset fields that apps aren't allowed to set. if (fromTargetApp && !hasDndAccess) { channel.setBypassDnd(r.priority == Notification.PRIORITY_MAX); } if (fromTargetApp) { channel.setLockscreenVisibility(r.visibility); channel.setAllowBubbles(existing != null ? existing.getAllowBubbles() : NotificationChannel.DEFAULT_ALLOW_BUBBLE); } clearLockedFieldsLocked(channel); channel.setImportanceLockedByOEM(r.oemLockedImportance); if (!channel.isImportanceLockedByOEM()) { if (r.oemLockedChannels.contains(channel.getId())) { channel.setImportanceLockedByOEM(true); } } channel.setImportanceLockedByCriticalDeviceFunction(r.defaultAppLockedImportance); if (channel.getLockscreenVisibility() == Notification.VISIBILITY_PUBLIC) { channel.setLockscreenVisibility( NotificationListenerService.Ranking.VISIBILITY_NO_OVERRIDE); } if (!r.showBadge) { channel.setShowBadge(false); } channel.setOriginalImportance(channel.getImportance()); // validate parent if (channel.getParentChannelId() != null) { Preconditions.checkArgument(r.channels.containsKey(channel.getParentChannelId()), ""Tried to create a conversation channel without a preexisting parent""); } r.channels.put(channel.getId(), channel); if (channel.canBypassDnd() != mAreChannelsBypassingDnd) { updateChannelsBypassingDnd(); } MetricsLogger.action(getChannelLog(channel, pkg).setType( com.android.internal.logging.nano.MetricsProto.MetricsEvent.TYPE_OPEN)); mNotificationChannelLogger.logNotificationChannelCreated(channel, uid, pkg); } return needsPolicyFileChange; }","[Notification] Fix Notification channel Dnd bypass for multiusers -Permission granted for a given package using shell cmd (user system) are not sufficient due to a check of notification uid vs packagepreference uid. -If the packagepreference is deleted then restored, the channel preference are not taken into account. Bug: 178032672 Test: CTS/AudioManagerTest Signed-off-by: Francois Gaffie Change-Id: Ia26467f27b31bc048bdb141beac7d764fcb27f51 Merged-in: Ia26467f27b31bc048bdb141beac7d764fcb27f51 (cherry picked from commit ab74309e89428c469f075a2ebddaa8be4340d588)",https://github.com/omnirom/android_frameworks_base/commit/51cf65124ac0bee7b178f3ab6a9481cf3940c685,,,services/core/java/com/android/server/notification/PreferencesHelper.java,3,java,False,2021-02-24T16:26:29Z "void setDescriptor(final int descIdx) throws MemoryAccessException { this.descIdx = descIdx; address = getDescAddress(descIdx); length = getDescLength(descIdx); position = 0; }","void setDescriptor(final short descIdx) throws MemoryAccessException { this.descIdx = descIdx; address = getDescAddress(descIdx); length = getDescLength(descIdx); position = 0; }","Use shorts where we actually have shorts, fixes potential infinite loop when next available index is exactly the wrap point (0x8000, which as int will never equal a short value).",https://github.com/fnuecke/sedna/commit/ae93820014397840d62f2572e720b710ac368276,,,src/main/java/li/cil/sedna/device/virtio/AbstractVirtIODevice.java,3,java,False,2022-07-19T21:31:56Z "@Override public List searchUsers(String login, Map userPropertiesSearch, boolean userPropertiesAsIntersectionSearch) { SearchIdentityParams params = new SearchIdentityParams(login, userPropertiesSearch, userPropertiesAsIntersectionSearch, null, null, null, null, null, null, null, Identity.STATUS_VISIBLE_LIMIT); params.setOrganisations(getSearchableOrganisations()); params.setRepositoryEntryRole(getRepositoryEntryRole(), false); return identitySearchQueries.getIdentitiesByPowerSearch(params, 0, -1); }","@Override public List searchUsers(String login, Map userPropertiesSearch, boolean userPropertiesAsIntersectionSearch) { SearchIdentityParams params = new SearchIdentityParams(login, userPropertiesSearch, userPropertiesAsIntersectionSearch, null, null, null, null, null, null, null, Identity.STATUS_VISIBLE_LIMIT); params.setOrganisations(getSearchableOrganisations()); params.setRepositoryEntryRole(getRepositoryEntryRole(), false); params.setExcludedRoles(getExcludedRoles()); return identitySearchQueries.getIdentitiesByPowerSearch(params, 0, -1); }",OO-6346: prevent author to add guest/invitee in resources,https://github.com/OpenOLAT/OpenOLAT/commit/5d1fcc6b0100da6b7fc79c1f8ed843125f633652,,,src/main/java/org/olat/admin/user/UserSearchFlexiController.java,3,java,False,2022-08-04T13:52:42Z "static Image *ReadEPTImage(const ImageInfo *image_info,ExceptionInfo *exception) { EPTInfo ept_info; Image *image; ImageInfo *read_info; MagickBooleanType status; MagickOffsetType offset; ssize_t count; /* Open image file. */ assert(image_info != (const ImageInfo *) NULL); assert(image_info->signature == MagickSignature); if (image_info->debug != MagickFalse) (void) LogMagickEvent(TraceEvent,GetMagickModule(),""%s"", image_info->filename); assert(exception != (ExceptionInfo *) NULL); assert(exception->signature == MagickSignature); image=AcquireImage(image_info); status=OpenBlob(image_info,image,ReadBinaryBlobMode,exception); if (status == MagickFalse) { image=DestroyImageList(image); return((Image *) NULL); } ept_info.magick=ReadBlobLSBLong(image); if (ept_info.magick != 0xc6d3d0c5ul) ThrowReaderException(CorruptImageError,""ImproperImageHeader""); ept_info.postscript_offset=(MagickOffsetType) ReadBlobLSBLong(image); ept_info.postscript_length=ReadBlobLSBLong(image); (void) ReadBlobLSBLong(image); (void) ReadBlobLSBLong(image); ept_info.tiff_offset=(MagickOffsetType) ReadBlobLSBLong(image); ept_info.tiff_length=ReadBlobLSBLong(image); (void) ReadBlobLSBShort(image); ept_info.postscript=(unsigned char *) AcquireQuantumMemory( ept_info.postscript_length+1,sizeof(*ept_info.postscript)); if (ept_info.postscript == (unsigned char *) NULL) ThrowReaderException(ResourceLimitError,""MemoryAllocationFailed""); (void) ResetMagickMemory(ept_info.postscript,0,(ept_info.postscript_length+1)* sizeof(*ept_info.postscript)); ept_info.tiff=(unsigned char *) AcquireQuantumMemory(ept_info.tiff_length+1, sizeof(*ept_info.tiff)); if (ept_info.tiff == (unsigned char *) NULL) ThrowReaderException(ResourceLimitError,""MemoryAllocationFailed""); (void) ResetMagickMemory(ept_info.tiff,0,(ept_info.tiff_length+1)* sizeof(*ept_info.tiff)); offset=SeekBlob(image,ept_info.tiff_offset,SEEK_SET); if ((ept_info.tiff_length != 0) && (offset < 30)) ThrowReaderException(CorruptImageError,""ImproperImageHeader""); count=ReadBlob(image,ept_info.tiff_length,ept_info.tiff); if (count != (ssize_t) (ept_info.tiff_length)) (void) ThrowMagickException(exception,GetMagickModule(),CorruptImageWarning, ""InsufficientImageDataInFile"",""`%s'"",image->filename); offset=SeekBlob(image,ept_info.postscript_offset,SEEK_SET); if ((ept_info.postscript_length != 0) && (offset < 30)) ThrowReaderException(CorruptImageError,""ImproperImageHeader""); count=ReadBlob(image,ept_info.postscript_length,ept_info.postscript); if (count != (ssize_t) (ept_info.postscript_length)) (void) ThrowMagickException(exception,GetMagickModule(),CorruptImageWarning, ""InsufficientImageDataInFile"",""`%s'"",image->filename); (void) CloseBlob(image); image=DestroyImage(image); read_info=CloneImageInfo(image_info); (void) CopyMagickString(read_info->magick,""EPS"",MaxTextExtent); image=BlobToImage(read_info,ept_info.postscript,ept_info.postscript_length, exception); if (image == (Image *) NULL) { (void) CopyMagickString(read_info->magick,""TIFF"",MaxTextExtent); image=BlobToImage(read_info,ept_info.tiff,ept_info.tiff_length,exception); } read_info=DestroyImageInfo(read_info); if (image != (Image *) NULL) { (void) CopyMagickString(image->filename,image_info->filename, MaxTextExtent); (void) CopyMagickString(image->magick,""EPT"",MaxTextExtent); } ept_info.tiff=(unsigned char *) RelinquishMagickMemory(ept_info.tiff); ept_info.postscript=(unsigned char *) RelinquishMagickMemory( ept_info.postscript); return(image); }","static Image *ReadEPTImage(const ImageInfo *image_info,ExceptionInfo *exception) { EPTInfo ept_info; Image *image; ImageInfo *read_info; MagickBooleanType status; MagickOffsetType offset; ssize_t count; /* Open image file. */ assert(image_info != (const ImageInfo *) NULL); assert(image_info->signature == MagickSignature); if (image_info->debug != MagickFalse) (void) LogMagickEvent(TraceEvent,GetMagickModule(),""%s"", image_info->filename); assert(exception != (ExceptionInfo *) NULL); assert(exception->signature == MagickSignature); image=AcquireImage(image_info); status=OpenBlob(image_info,image,ReadBinaryBlobMode,exception); if (status == MagickFalse) { image=DestroyImageList(image); return((Image *) NULL); } ept_info.magick=ReadBlobLSBLong(image); if (ept_info.magick != 0xc6d3d0c5ul) ThrowReaderException(CorruptImageError,""ImproperImageHeader""); ept_info.postscript_offset=(MagickOffsetType) ReadBlobLSBLong(image); ept_info.postscript_length=ReadBlobLSBLong(image); (void) ReadBlobLSBLong(image); (void) ReadBlobLSBLong(image); ept_info.tiff_offset=(MagickOffsetType) ReadBlobLSBLong(image); ept_info.tiff_length=ReadBlobLSBLong(image); (void) ReadBlobLSBShort(image); ept_info.postscript=(unsigned char *) AcquireQuantumMemory( ept_info.postscript_length+1,sizeof(*ept_info.postscript)); if (ept_info.postscript == (unsigned char *) NULL) ThrowReaderException(ResourceLimitError,""MemoryAllocationFailed""); (void) ResetMagickMemory(ept_info.postscript,0,(ept_info.postscript_length+1)* sizeof(*ept_info.postscript)); ept_info.tiff=(unsigned char *) AcquireQuantumMemory(ept_info.tiff_length+1, sizeof(*ept_info.tiff)); if (ept_info.tiff == (unsigned char *) NULL) { ept_info.postscript=(unsigned char *) RelinquishMagickMemory( ept_info.postscript); ThrowReaderException(ResourceLimitError,""MemoryAllocationFailed""); } (void) ResetMagickMemory(ept_info.tiff,0,(ept_info.tiff_length+1)* sizeof(*ept_info.tiff)); offset=SeekBlob(image,ept_info.tiff_offset,SEEK_SET); if ((ept_info.tiff_length != 0) && (offset < 30)) { ept_info.tiff=(unsigned char *) RelinquishMagickMemory(ept_info.tiff); ept_info.postscript=(unsigned char *) RelinquishMagickMemory( ept_info.postscript); ThrowReaderException(CorruptImageError,""ImproperImageHeader""); } count=ReadBlob(image,ept_info.tiff_length,ept_info.tiff); if (count != (ssize_t) (ept_info.tiff_length)) (void) ThrowMagickException(exception,GetMagickModule(),CorruptImageWarning, ""InsufficientImageDataInFile"",""`%s'"",image->filename); offset=SeekBlob(image,ept_info.postscript_offset,SEEK_SET); if ((ept_info.postscript_length != 0) && (offset < 30)) { ept_info.tiff=(unsigned char *) RelinquishMagickMemory(ept_info.tiff); ept_info.postscript=(unsigned char *) RelinquishMagickMemory( ept_info.postscript); ThrowReaderException(CorruptImageError,""ImproperImageHeader""); } count=ReadBlob(image,ept_info.postscript_length,ept_info.postscript); if (count != (ssize_t) (ept_info.postscript_length)) (void) ThrowMagickException(exception,GetMagickModule(),CorruptImageWarning, ""InsufficientImageDataInFile"",""`%s'"",image->filename); (void) CloseBlob(image); image=DestroyImage(image); read_info=CloneImageInfo(image_info); (void) CopyMagickString(read_info->magick,""EPS"",MaxTextExtent); image=BlobToImage(read_info,ept_info.postscript,ept_info.postscript_length, exception); if (image == (Image *) NULL) { (void) CopyMagickString(read_info->magick,""TIFF"",MaxTextExtent); image=BlobToImage(read_info,ept_info.tiff,ept_info.tiff_length,exception); } read_info=DestroyImageInfo(read_info); if (image != (Image *) NULL) { (void) CopyMagickString(image->filename,image_info->filename, MaxTextExtent); (void) CopyMagickString(image->magick,""EPT"",MaxTextExtent); } ept_info.tiff=(unsigned char *) RelinquishMagickMemory(ept_info.tiff); ept_info.postscript=(unsigned char *) RelinquishMagickMemory( ept_info.postscript); return(image); }",https://github.com/ImageMagick/ImageMagick/issues/453,https://github.com/ImageMagick/ImageMagick/commit/d340012f201619d57bc418e21b8569403f9453f1,,,coders/ept.c,3,c,False,2017-04-26T21:39:11Z "public static CliContext loadCliContext(String[] args) throws Exception { CliContext cliContext = new CliContext(); // load the parameters - so order doesn't matter for (int i = 0; i < args.length; i++) { if (args[i].equals(VERSION)) { cliContext.setSv(VersionUtilities.getCurrentPackageVersion(args[++i])); } else if (args[i].equals(OUTPUT)) { if (i + 1 == args.length) throw new Error(""Specified -output without indicating output file""); else cliContext.setOutput(args[++i]); } else if (args[i].equals(HTML_OUTPUT)) { if (i + 1 == args.length) throw new Error(""Specified -html-output without indicating output file""); else cliContext.setHtmlOutput(args[++i]); } else if (args[i].equals(PROXY)) { i++; // ignore next parameter } else if (args[i].equals(PROXY_AUTH)) { i++; } else if (args[i].equals(PROFILE)) { String p = null; if (i + 1 == args.length) { throw new Error(""Specified -profile without indicating profile source""); } else { p = args[++i]; cliContext.addProfile(p); } } else if (args[i].equals(BUNDLE)) { String p = null; String r = null; if (i + 1 == args.length) { throw new Error(""Specified -profile without indicating bundle rule ""); } else { r = args[++i]; } if (i + 1 == args.length) { throw new Error(""Specified -profile without indicating profile source""); } else { p = args[++i]; } cliContext.getBundleValidationRules().add(new BundleValidationRule(r, p)); } else if (args[i].equals(QUESTIONNAIRE)) { if (i + 1 == args.length) throw new Error(""Specified -questionnaire without indicating questionnaire mode""); else { String q = args[++i]; cliContext.setQuestionnaireMode(QuestionnaireMode.fromCode(q)); } } else if (args[i].equals(NATIVE)) { cliContext.setDoNative(true); } else if (args[i].equals(ASSUME_VALID_REST_REF)) { cliContext.setAssumeValidRestReferences(true); } else if (args[i].equals(DEBUG)) { cliContext.setDoDebug(true); } else if (args[i].equals(SCT)) { cliContext.setSnomedCT(args[++i]); } else if (args[i].equals(RECURSE)) { cliContext.setRecursive(true); } else if (args[i].equals(SHOW_MESSAGES_FROM_REFERENCES)) { cliContext.setShowMessagesFromReferences(true); } else if (args[i].equals(LOCALE)) { if (i + 1 == args.length) { throw new Error(""Specified -locale without indicating locale""); } else { cliContext.setLocale(new Locale(args[++i])); } } else if (args[i].equals(STRICT_EXTENSIONS)) { cliContext.setAnyExtensionsAllowed(false); } else if (args[i].equals(NO_INTERNAL_CACHING)) { cliContext.setNoInternalCaching(true); } else if (args[i].equals(NO_EXTENSIBLE_BINDING_WARNINGS)) { cliContext.setNoExtensibleBindingMessages(true); } else if (args[i].equals(NO_INVARIANTS)) { cliContext.setNoInvariants(true); } else if (args[i].equals(WANT_INVARIANTS_IN_MESSAGES)) { cliContext.setWantInvariantsInMessages(true); } else if (args[i].equals(HINT_ABOUT_NON_MUST_SUPPORT)) { cliContext.setHintAboutNonMustSupport(true); } else if (args[i].equals(TO_VERSION)) { cliContext.setTargetVer(args[++i]); cliContext.setMode(EngineMode.VERSION); } else if (args[i].equals(DO_NATIVE)) { cliContext.setCanDoNative(true); } else if (args[i].equals(NO_NATIVE)) { cliContext.setCanDoNative(false); } else if (args[i].equals(TRANSFORM)) { cliContext.setMap(args[++i]); cliContext.setMode(EngineMode.TRANSFORM); } else if (args[i].equals(NARRATIVE)) { cliContext.setMode(EngineMode.NARRATIVE); } else if (args[i].equals(SPREADSHEET)) { cliContext.setMode(EngineMode.SPREADSHEET); } else if (args[i].equals(SNAPSHOT)) { cliContext.setMode(EngineMode.SNAPSHOT); } else if (args[i].equals(SECURITY_CHECKS)) { cliContext.setSecurityChecks(true); } else if (args[i].equals(CRUMB_TRAIL)) { cliContext.setCrumbTrails(true); } else if (args[i].equals(VERBOSE)) { cliContext.setCrumbTrails(true); } else if (args[i].equals(ALLOW_EXAMPLE_URLS)) { String bl = args[++i]; if (""true"".equals(bl)) { cliContext.setAllowExampleUrls(true); } else if (""false"".equals(bl)) { cliContext.setAllowExampleUrls(false); } else { throw new Error(""Value for ""+ALLOW_EXAMPLE_URLS+"" not understood: ""+bl); } } else if (args[i].equals(SHOW_TIMES)) { cliContext.setShowTimes(true); } else if (args[i].equals(OUTPUT_STYLE)) { cliContext.setOutputStyle(args[++i]); } else if (args[i].equals(SCAN)) { cliContext.setMode(EngineMode.SCAN); } else if (args[i].equals(TERMINOLOGY)) { if (i + 1 == args.length) throw new Error(""Specified -tx without indicating terminology server""); else cliContext.setTxServer(""n/a"".equals(args[++i]) ? null : args[i]); } else if (args[i].equals(TERMINOLOGY_LOG)) { if (i + 1 == args.length) throw new Error(""Specified -txLog without indicating file""); else cliContext.setTxLog(args[++i]); } else if (args[i].equals(LOG)) { if (i + 1 == args.length) throw new Error(""Specified -log without indicating file""); else cliContext.setMapLog(args[++i]); } else if (args[i].equals(LANGUAGE)) { if (i + 1 == args.length) throw new Error(""Specified -language without indicating language""); else cliContext.setLang(args[++i]); } else if (args[i].equals(IMPLEMENTATION_GUIDE) || args[i].equals(DEFINITION)) { if (i + 1 == args.length) throw new Error(""Specified "" + args[i] + "" without indicating ig file""); else { String s = args[++i]; String version = Common.getVersionFromIGName(null, s); if (version == null) { cliContext.addIg(s); } else { cliContext.setSv(version); } } } else if (args[i].equals(MAP)) { if (cliContext.getMap() == null) { if (i + 1 == args.length) throw new Error(""Specified -map without indicating map file""); else cliContext.setMap(args[++i]); } else { throw new Exception(""Can only nominate a single -map parameter""); } } else if (args[i].startsWith(X)) { i++; } else if (args[i].equals(CONVERT)) { cliContext.setMode(EngineMode.CONVERT); } else if (args[i].equals(FHIRPATH)) { cliContext.setMode(EngineMode.FHIRPATH); if (cliContext.getFhirpath() == null) if (i + 1 == args.length) throw new Error(""Specified -fhirpath without indicating a FHIRPath expression""); else cliContext.setFhirpath(args[++i]); else throw new Exception(""Can only nominate a single -fhirpath parameter""); } else { cliContext.addSource(args[i]); } } return cliContext; }","public static CliContext loadCliContext(String[] args) throws Exception { CliContext cliContext = new CliContext(); // load the parameters - so order doesn't matter for (int i = 0; i < args.length; i++) { if (args[i].equals(VERSION)) { cliContext.setSv(VersionUtilities.getCurrentPackageVersion(args[++i])); } else if (args[i].equals(OUTPUT)) { if (i + 1 == args.length) throw new Error(""Specified -output without indicating output file""); else cliContext.setOutput(args[++i]); } else if (args[i].equals(HTML_OUTPUT)) { if (i + 1 == args.length) throw new Error(""Specified -html-output without indicating output file""); else cliContext.setHtmlOutput(args[++i]); } else if (args[i].equals(PROXY)) { i++; // ignore next parameter } else if (args[i].equals(PROXY_AUTH)) { i++; } else if (args[i].equals(PROFILE)) { String p = null; if (i + 1 == args.length) { throw new Error(""Specified -profile without indicating profile source""); } else { p = args[++i]; cliContext.addProfile(p); } } else if (args[i].equals(BUNDLE)) { String p = null; String r = null; if (i + 1 == args.length) { throw new Error(""Specified -profile without indicating bundle rule ""); } else { r = args[++i]; } if (i + 1 == args.length) { throw new Error(""Specified -profile without indicating profile source""); } else { p = args[++i]; } cliContext.getBundleValidationRules().add(new BundleValidationRule(r, p)); } else if (args[i].equals(QUESTIONNAIRE)) { if (i + 1 == args.length) throw new Error(""Specified -questionnaire without indicating questionnaire mode""); else { String q = args[++i]; cliContext.setQuestionnaireMode(QuestionnaireMode.fromCode(q)); } } else if (args[i].equals(NATIVE)) { cliContext.setDoNative(true); } else if (args[i].equals(ASSUME_VALID_REST_REF)) { cliContext.setAssumeValidRestReferences(true); } else if (args[i].equals(DEBUG)) { cliContext.setDoDebug(true); } else if (args[i].equals(SCT)) { cliContext.setSnomedCT(args[++i]); } else if (args[i].equals(RECURSE)) { cliContext.setRecursive(true); } else if (args[i].equals(SHOW_MESSAGES_FROM_REFERENCES)) { cliContext.setShowMessagesFromReferences(true); } else if (args[i].equals(LOCALE)) { if (i + 1 == args.length) { throw new Error(""Specified -locale without indicating locale""); } else { cliContext.setLocale(new Locale(args[++i])); } } else if (args[i].equals(STRICT_EXTENSIONS)) { cliContext.setAnyExtensionsAllowed(false); } else if (args[i].equals(NO_INTERNAL_CACHING)) { cliContext.setNoInternalCaching(true); } else if (args[i].equals(NO_EXTENSIBLE_BINDING_WARNINGS)) { cliContext.setNoExtensibleBindingMessages(true); } else if (args[i].equals(NO_UNICODE_BIDI_CONTROL_CHARS)) { cliContext.setNoUnicodeBiDiControlChars(true); } else if (args[i].equals(NO_INVARIANTS)) { cliContext.setNoInvariants(true); } else if (args[i].equals(WANT_INVARIANTS_IN_MESSAGES)) { cliContext.setWantInvariantsInMessages(true); } else if (args[i].equals(HINT_ABOUT_NON_MUST_SUPPORT)) { cliContext.setHintAboutNonMustSupport(true); } else if (args[i].equals(TO_VERSION)) { cliContext.setTargetVer(args[++i]); cliContext.setMode(EngineMode.VERSION); } else if (args[i].equals(DO_NATIVE)) { cliContext.setCanDoNative(true); } else if (args[i].equals(NO_NATIVE)) { cliContext.setCanDoNative(false); } else if (args[i].equals(TRANSFORM)) { cliContext.setMap(args[++i]); cliContext.setMode(EngineMode.TRANSFORM); } else if (args[i].equals(NARRATIVE)) { cliContext.setMode(EngineMode.NARRATIVE); } else if (args[i].equals(SPREADSHEET)) { cliContext.setMode(EngineMode.SPREADSHEET); } else if (args[i].equals(SNAPSHOT)) { cliContext.setMode(EngineMode.SNAPSHOT); } else if (args[i].equals(SECURITY_CHECKS)) { cliContext.setSecurityChecks(true); } else if (args[i].equals(CRUMB_TRAIL)) { cliContext.setCrumbTrails(true); } else if (args[i].equals(VERBOSE)) { cliContext.setCrumbTrails(true); } else if (args[i].equals(ALLOW_EXAMPLE_URLS)) { String bl = args[++i]; if (""true"".equals(bl)) { cliContext.setAllowExampleUrls(true); } else if (""false"".equals(bl)) { cliContext.setAllowExampleUrls(false); } else { throw new Error(""Value for ""+ALLOW_EXAMPLE_URLS+"" not understood: ""+bl); } } else if (args[i].equals(SHOW_TIMES)) { cliContext.setShowTimes(true); } else if (args[i].equals(OUTPUT_STYLE)) { cliContext.setOutputStyle(args[++i]); } else if (args[i].equals(SCAN)) { cliContext.setMode(EngineMode.SCAN); } else if (args[i].equals(TERMINOLOGY)) { if (i + 1 == args.length) throw new Error(""Specified -tx without indicating terminology server""); else cliContext.setTxServer(""n/a"".equals(args[++i]) ? null : args[i]); } else if (args[i].equals(TERMINOLOGY_LOG)) { if (i + 1 == args.length) throw new Error(""Specified -txLog without indicating file""); else cliContext.setTxLog(args[++i]); } else if (args[i].equals(LOG)) { if (i + 1 == args.length) throw new Error(""Specified -log without indicating file""); else cliContext.setMapLog(args[++i]); } else if (args[i].equals(LANGUAGE)) { if (i + 1 == args.length) throw new Error(""Specified -language without indicating language""); else cliContext.setLang(args[++i]); } else if (args[i].equals(IMPLEMENTATION_GUIDE) || args[i].equals(DEFINITION)) { if (i + 1 == args.length) throw new Error(""Specified "" + args[i] + "" without indicating ig file""); else { String s = args[++i]; String version = Common.getVersionFromIGName(null, s); if (version == null) { cliContext.addIg(s); } else { cliContext.setSv(version); } } } else if (args[i].equals(MAP)) { if (cliContext.getMap() == null) { if (i + 1 == args.length) throw new Error(""Specified -map without indicating map file""); else cliContext.setMap(args[++i]); } else { throw new Exception(""Can only nominate a single -map parameter""); } } else if (args[i].startsWith(X)) { i++; } else if (args[i].equals(CONVERT)) { cliContext.setMode(EngineMode.CONVERT); } else if (args[i].equals(FHIRPATH)) { cliContext.setMode(EngineMode.FHIRPATH); if (cliContext.getFhirpath() == null) if (i + 1 == args.length) throw new Error(""Specified -fhirpath without indicating a FHIRPath expression""); else cliContext.setFhirpath(args[++i]); else throw new Exception(""Can only nominate a single -fhirpath parameter""); } else { cliContext.addSource(args[i]); } } return cliContext; }",add -no_unicode_bidi_control_chars to the validator for CVE-2021-42574 (https://trojansource.codes/),https://github.com/hapifhir/org.hl7.fhir.core/commit/57edd95e8117c1f0450b361cc59fc2b8babab50c,,,org.hl7.fhir.validation/src/main/java/org/hl7/fhir/validation/cli/utils/Params.java,3,java,False,2021-11-02T06:47:25Z "private StarSystem findBestGatherpoint(ShipFleet fleet) { Galaxy gal = galaxy(); StarSystem best = null; float bestScore = 0.0f; List mySystemsInShipRange = empire.systemsInShipRange(empire); List otherSystemsInShipRange = new ArrayList<>(); for(Empire other : empire.contactedEmpires()) { if(empire.alliedWith(other.id)) continue; if(!empire.inEconomicRange(other.id)) continue; otherSystemsInShipRange.addAll(other.allColonizedSystems()); } float ourEffectiveBC = bcValue(fleet, false, true, true, false); float civTech = empire.tech().avgTechLevel(); float targetTech = civTech; for (int id=0;id ourEffectiveBC * (civTech+10.0f)) continue; /*for(StarSystem own : mySystemsInShipRange) { currentScore += max(own.colony().production() * own.planet().productionAdj() * own.planet().researchAdj(), 1.0f) / (1 + current.distanceTo(own)); }*/ for(StarSystem other : otherSystemsInShipRange) { float scoreToAdd = max(other.colony().production() * other.planet().productionAdj() * other.planet().researchAdj(), 1.0f) / (1 + current.distanceTo(other)); scoreToAdd *= 2; if(empire.enemies().contains(other.empire())) { scoreToAdd *= 2; } if(empire.warEnemies().contains(other.empire())) { scoreToAdd *= 2; } currentScore += scoreToAdd; } //distance to our fleet also plays a role but it's importance is heavily scince we are at peace and have time to travel float speed = fleet.slowestStackSpeed(); if(current.inNebula()) speed = 1; currentScore /= sqrt(max(fleet.distanceTo(current) / speed, 1) + mySystemsInShipRange.size()); //System.out.print(""\n""+fleet.empire().name()+"" ""+empire.sv.name(fleet.system().id)+"" score to gather at: ""+empire.sv.name(current.id)+"" score: ""+currentScore); if(currentScore > bestScore) { bestScore = currentScore; best = current; } } /*if(best != null) System.out.print(""\n""+fleet.empire().name()+"" Fleet at ""+empire.sv.name(fleet.system().id)+"" gathers at ""+empire.sv.name(best.id)+"" score: ""+bestScore);*/ return best; }","private StarSystem findBestGatherpoint(ShipFleet fleet) { Galaxy gal = galaxy(); StarSystem best = null; float bestScore = 0.0f; List mySystemsInShipRange = empire.systemsInShipRange(empire); List otherSystemsInShipRange = new ArrayList<>(); for(Empire other : empire.contactedEmpires()) { if(empire.alliedWith(other.id)) continue; if(!empire.inEconomicRange(other.id)) continue; otherSystemsInShipRange.addAll(other.allColonizedSystems()); } float ourFightingBC = bcValue(fleet, false, true, false, false); float ourBombingBC = bcValue(fleet, false, false, true, false); float civTech = empire.tech().avgTechLevel(); float targetTech = civTech; for (int id=0;id ourFightingBC * (civTech+10.0f)) continue; if(enemyMissileBc * (targetTech+10.0f) * 2 > ourBombingBC * (civTech+10.0f)) continue; /*for(StarSystem own : mySystemsInShipRange) { currentScore += max(own.colony().production() * own.planet().productionAdj() * own.planet().researchAdj(), 1.0f) / (1 + current.distanceTo(own)); }*/ for(StarSystem other : otherSystemsInShipRange) { float scoreToAdd = max(other.colony().production() * other.planet().productionAdj() * other.planet().researchAdj(), 1.0f) / (1 + current.distanceTo(other)); scoreToAdd *= 2; if(empire.enemies().contains(other.empire())) { scoreToAdd *= 2; } if(empire.warEnemies().contains(other.empire())) { scoreToAdd *= 2; } currentScore += scoreToAdd; } //distance to our fleet also plays a role but it's importance is heavily scince we are at peace and have time to travel float speed = fleet.slowestStackSpeed(); if(current.inNebula()) speed = 1; currentScore /= sqrt(max(fleet.distanceTo(current) / speed, 1) + mySystemsInShipRange.size()); //System.out.print(""\n""+fleet.empire().name()+"" ""+empire.sv.name(fleet.system().id)+"" score to gather at: ""+empire.sv.name(current.id)+"" score: ""+currentScore); if(currentScore > bestScore) { bestScore = currentScore; best = current; } } /*if(best != null) System.out.print(""\n""+fleet.empire().name()+"" Fleet at ""+empire.sv.name(fleet.system().id)+"" gathers at ""+empire.sv.name(best.id)+"" score: ""+bestScore);*/ return best; }","New algorithm to determine whom to go to war with (#71) * Update AIScientist.java Adjusted values of a bunch of techs. * Update AIShipCaptain.java Fixed accidental removal of range-adjustment in new target-selection-formula and removed unused code. * Update NewShipTemplate.java Allowing missiles to be used again under certain circumstances, taking ECM into account and basing weapon-decision on actual shield-levels rather than best possible. * Update TechMissileWeapon.java Fixed that 2-rack-missiles didn't have +1 speed as they should have according to official strategy-guide. * Update AIScientist.java Tech-Slider-Allocations now depend on racial-bonuses, not leader-personality. * Immersive Xilmi-AI When set to AI: Selectable, the Xilmi AI now goes in immersive-mode, once again making numerous uses of leader-traits. * Update CombatStackColony.java Fixed a bug, that planets without missile-bases always absorbed damage as if they already had a shield-built, even if they had none and even if they were in a nebula. * Tactical combat improvements Can now detect when someone protects another stack with repulsor-beams and retreats, when it cannot counter it with long-range-weapons. Optimal range for firing missiles increased by repulsor-radius so missile-ships won't be affected by the can't counter repulsors-detection. Missiles will now be held back until getting closer to prevent target from dodging them easily. Unused specials like Repulsor will no longer prevent ships from kiting. * Update AIShipCaptain.java Only kite when there's either repulsor-beam or missile-weapons installed on the ship. * Update AIFleetCommander.java Defending is only half as desirable as attacking now. * Immersive Xilmi-AI Lot's of changes for the personality-mode of Xilmi-AI. * Update DiplomaticEmbassy.java Fix for one empire still holding a grudge against the other when signing a peace-treaty. * Update AIShipCaptain.java Somehow the Xilmi-AI must have had conquered a system with a missile-base on it against another type of AI and then crashed at this place, I didn't even think it would get to for a colony. * Update AISpyMaster.java No longer consider computer-advantage for how much to spend into counter-espionage. * Race-fitting-playstyles implemented and leader-specfic-self-restrictions removed. * Update AIGeneral.java Invader-AI back to normal victim-selection. * Update AIGovernor.java Turns out espionage didn't work like I thought it would. So Darlok just building ships and relying on stealing techs was a bad idea. (You can only steal techs below your highest level in any given tree!) * Update AIDiplomat.java Fixed issue where AI wouldn't allow the player to ask for tech-trades and where they would take deals that are horrible for themselves when trading with other AIs. Trades are now usually all done within a 66%-150% tech-cost-range. * Update AIGeneral.java Giving themselves a personality/objective-combination that fits their behavior. * Update AIDiplomat.java Tech exchange only will work within same tier now. * Update AIGeneral.java Removed setting of personalities as this causes issue with missing texts. * Update AIScientist.java Fixed issue for Silicoids trading for Eco-restoration-techs. * Update ColonyDefense.java * Update ColonyDefense.java Shield will now only be built automatically under the following circumstances: There's missile-bases existing There's missile-bases needing to be upgraded There's missile-bases to be built * Update AIDiplomat.java Avoid false positives in war-declaration for incoming fleets when the system in question was only recently colonized. * Update AIShipCaptain.java Fixed a rare but not impossible crash. * Update AIDiplomat.java No longer accept joint-war-proposals from empires we like less than who they propose as victim. * Update AIGovernor.java Now building missile-bases... under very specific and rare circumstances. * Update AIShipCaptain.java Fixed crash when handling missile-bases. Individual stacks that can't find a target to attack no longer automatically retreat and instead let their behavior be governed by whether the whole fleet would want to retreat. * Update ColonyDefense.java Reverted previous changes which also happened to prevent AI from building shields. * Update CombatStackShip.java Fixed issue where multi-shot-weapons weren't reported as used when they were used. * Update AIFleetCommander.java Fleets now are split depending on their warp-speed unless they are on the way to their final-attack-target. * Update AIDiplomat.java Knowing about uncolonized systems no longer prevents wars. * Update CombatStackShip.java Revert change to shipComponentIsUsed * Update AIShipCaptain.java Moved logic that detects if a weapon has been used to this file. * Update AIScientist.java Try to avoid researching techs we know our neighbors already have since we can trade for it or steal it. * Update AIFleetCommander.java Colony ships now only ignore distance if they are huge as otherwise ignoring distance was horrible in late-game with hyperspace-communications. Keeping scout-designs around for longer. * Fixed a very annoying issue that caused eco-spending to become... insufficient and thus people to die when adjusting espionage- or security-spending. * Reserve-management-improvements Rich and Ultra-Rich planets now put their production into reserve when they would otherwise conduct research. Reserve will now try to keep an emergency-reserve for dealing with events like Supernova. Exceeding twice the amount of that reserve will always be spent so the money doesn't just lie around unused, when there's no new colonies that still need industry. * Update AIShipCaptain.java Removed an unneccessary white line 8[ * Update AIFleetCommander.java Reversed keeping scouts for longer * Update AIGovernor.java no industry, when under siege * Update AIGovernor.java Small fixed to sieged colonies building industry when they shouldn't. * Update Rotp.java Versioning 0.93a * Update RacesUI.java Race-selector no longer jumps after selecting a race. Race-selector scroll-speed when dragging is no longer amplified like the scroll-bar but instead moves 1:1 the distance dragged. * Update AIFleetCommander.java Smart-Path will no longer path over systems further away than the target-system. Fleets will now always be split by speed if more than 2/3rd of the fleet have the fastest speed possible. * Update AIGovernor.java Build more fleet when fighting someone who has no or extremely little fleet. * Update AIShipCaptain.java Kiting no longer uses path-finding during auto-resolve. Ships with repulsor and long-range will no longer get closer than 2 tiles before firing against ships that don't have long range. Will only retreat to system with enemy fleets when there's no system without enemy fleets to retreat to. * Update CombatStackColony.java Added override for optimal firing-range for missile-bases. It is 9. * Update CombatStackShip.java Optimal firing-range for ship-stacks with missiles will now be at least two when they have repulsors. * Update NewShipTemplate.java The willingness of the AI to use repulsor-beam now scales with how many opponent ships have long range. It will be higher if there's only a few but drop down to 0 if all opponent ships use them. * Update AI.java Improved logic for shuttling around population within the empire. * Update ShipBattleUI.java Fixed a bug where remaining commands were transferred from one stack to another, which could also cause a crash when missile-bases were involved. * Update Colony.java currentProductionCapacity now correctly takes into consideration how many factories are actually operated. * Update NewShipTemplate.java Fixes and improvements to special-selection. Mainly bigger emphasis on using cloaking-device and stasis-field. * Update AIShipDesigner.java Consider getting an important special like cloaking, stasis or black-hole-generator as reason to immediately make a new design. * Update SystemView.java Systems with enemy-fleets will now flash the Alert. Especially usefull when under siege by cloaked enemy fleets. * Update AIShipCaptain.java Added check whether retreat was possible when retreating for the reason that nothing can be done. * Update AIGovernor.java Taking natural pop-growth and the cost of terraforming into account when deciding to build factories or population. This usually results to prefering factories almost always when they can be operated. * War- and Peace-making changes. Prevent war-declaration when there's barely any fleet to attack with. Smarter selection of preferred victim. In particular taking their diplomatic status with others into account. Toned down overall aggressiveness. Several personalities now are taken into account for determining behavior. * Update General.java Don't attack too early. * Update AIFleetCommander.java Colony ships will now always prefer undefended targets instead of waiting for help if they want to colonize a defended system. * Update Rotp.java Version 0.93b * Update NewShipTemplate.java Not needing ranged weapon, when we have cloaking-device. * Improved behavior when using missiles to act according to expectations of /u/bot39lvl * Showing pop-growth at clean-eco. * New Version with u/bot39lvl recommended changes to missile-boat-handling * Fixed issue that caused ships being scrapped after loading a game, no longer taking incoming enemy fleets into consideration that are more than one turn away from reaching their target. * Stacks that want to retreat will now also try and damage their target if it is more than one space away as long as they don't use up all movement-points. Planets with no missile-bases will not become a target unless all non-bomb-weapons were used. * Fixed an issue where a new design would override a similar existing one. * When defending or when having better movement-speed now shall always try to get the 1st strike. * Not keeping a defensive fleet on duty when the incoming opponent attack will overwhelm them anyways. * Using more unique ship-names * Avoid ship-information being cut off by drawing ship-button-overlay into the upper direction as soon as a stack is below the middle of the screen. * Fixed exploit that allowed player to ignore enemy repulsor-beams via auto-resolve. * Fixed issue that caused missile-ships to sometimes retreat when they shouldn't. * Calling beam/missileDefense() method instead of looking at the member since the function also takes stealth into account which we want to do for better decision-making. * Ships with limited shot-weapons no longer think they can land all hits at once. * Best tech of each type no longer gets it's research-value reduced. * Halfed inertial-value again as it otherwise may suppress vital range-tech. * Prevent overbuilding colony-ships in lategame by taking into consideration when systems can build more than one per turn. * Design-names now use name of a system that is actually owned and add a number to make sure they are unique. * Fixed some issues with no longer firing before retreating after rework and now ignoring stacks in stasis for whether to retreat or not. * Evenly distributing population across the empire led to an increase of almost 30% productivity at a reference turn in tests and thus turned out to be a much better population-distribution-strategy when compared to the ""bring new colonies to 25%""-rule-of-thumb as suggested in the official-strategy-guide. * Last defending stacks in stasis are now also made to autoretreat as otherwise this would result in 100 turns of ""you can't do anything but watch"". * Avoid having more than two designs with Stasis-Field as it doesn't stack. * Should fix an issue that caused usage of Hyper-Space-Communications to be inefficient. * Futher optimization on population-shuttling. * Fixed possible crash from trying to make peace while being involved in a final war. * Fixed infinite loop when trying to scrap the last existing design. * Making much better use of natural growth. * Some further slight adjustments to economy-handling that lead to an even better result in my test. * Fix for ""Hyperspace Communications: can't reroute back to the starting planet - bug"" by setting system to null, when leaving the orbit. In this vein no longer check for a stargate-connection when a fleet isn't at a system anymore. * Only the victor and the owner of the colony fought over get a scan on the system. Not all participants. Especially not someone who fled from the orion-guardian and wanted to exploit this bug to get free high-end-techs! * Prepare next version number since Ray hasn't commited anything yet since the beginning of June. :( * Presumably a better fix to the issue of carrying over button-presses to the next stack. But I don't have a good save to test it. * Fixed that for certain techs the inherited baseValue method either had no override or the override did not reference to the corresponding AI-method. * Reverted fix for redirecting ships with hyperspace-communications to their source-system because it could crash the game when trying to redirect ships using rally-points. * Using same ship-design-naming-pattern for all types of ships so player can't idintify colony-ships by looking at the name. * Added missing override for baseValue from AI. * Made separate method for upgradeCost so it can be used from outside, like AI for example. * Fixed an issue where ships wouldn't retreat when they couldn't path to their preferred target. * Changed how much the AI values certain technologies. Most notably will it like warp-speed-improvements more. * Introduced an algorithm that guesses how long it will take to kill another empire and how long it would take the other empire to kill ourselves. This is used in target-selection and also in order to decide on whether we should go all in with our military. If we think the other empire can kill us more quickly than what it takes to benefit from investments into economy, we go all-in with building military. * Fixed an issue that prevented ships being sent back to where they came from while in space via using hyperspace-communications. Note: The intention of that code is already handled by the ""CanSendTo""-check just above of it. At this place the differientiation between beeing in transit is made, so that code was redundant for it's intended use-case. * Production- and reseach-modifier now considered in decision to build ships non-stop or not. Fixed bug that caused AI-colonies to not build ships when they should. Consider incoming transports in decision whether to build population or not. * Big revamp of dimplomatic AI-behavior. AI should now make much more sophisticated decisions about when to go to war. * No longer bolstering population of low-pop-systems during war as this is pretty exploitable and detracts from producting military. * Version * Fixed a weird issue that prevented AIs from bombarding each other unless the player had knowledge about who the owner of the system to be bombarded is. * Less willing to go to war, when there's other ways to expand. * Fixed issue with colonizers and hyper-space-communications, that I thought I had fixed before. When there's other possible targets to attack, a fleet waiting for invasion-forces, that can glass the system it is orbiting will split up and continue its attack. * Only building excess colonizers, when someone we know (including ourselves) is at war and there's potential to colonize systems that are freed up by that war. * At 72% and higher population a system wanting to build a colonizer will go all-in on it. This mostly affects Sakkra and Meklar, so they expand quicker and make more use of fast pop-growth. * Fixed extremely rare crash. * 0.93g * Guessing travel-time and impact of nebulae instead of actually calculating the correct travel-times including nebulae to improve turn-times. * No longer using bestVictim in ship-Design-Code. * Lower limit from transport-size removed. * Yet another big revamp about when to go to war. It's much more simple now. * Transports sent towards someone who we don't want to have a war with now will be set to surrender on arrival. Travel-distance-calculation simplified in favor of turn-processing. Fixed dysfunctional defense-code that was recently broken. * Pop-growth now plays a role in invasion-decisionmaking. Invasions now can occur without a fleet in orbit. Code for estimating kill-time now takes invasions into account. Drastically simplified victim-selection. * Due to the changes in how the AI handles it's fleets during the wait time for invasions the amount of bombers built was increased. * Changed how it is determined whether to retreat against fleets with repulsors. Fixed issue with not firing missiles under certain circumstances. Stacks of smaller ships fighting against stacks of bigger ships are now more likely to retreat, when they can't kill at least one of the bigger ships per turn. * Moved accidental-stargate-building-prevention-workaround to where it actually is effective. * Fixed an issue where a combat would end prematurely when missiles were fired but still on their way to their target. * Removed commented-out code * Removed actual war-weariness from the reasons to make peace as there's now other and better reasons to make peace. * Bombers are now more specialized as in better at bombing and worse at actual combat. * Bomb-Percentage now considers all opponents, not just the current enemy. * The usage of designs is now recognized by their loadout and not by what role it was assigned to it during design. * No longer super-heavy commitment to ship-production in war. Support of hybrid-playstyle. * Fixed issue that sometimes prevented shooting missiles. * Lowered counter-espionage by no longer looking at average tech-level of opponents but instead at tech-level of highest opponent. * Support for hybrid ship-designs and many tweaks- and fixes in scrapping-logic. * Setting eco-slider with a popup that promts for a percentage now uses the percentage of the amount that isn't required to keep clean. * Fixed previously integrated potential dead-lock. * Indentation * Fix for becoming enemy of others before they are in range in the always-war-mode. * Version-number for next inofficial build. * No security-spending when no contact. But luckily that actually makes no difference between it only actually gets detracted from income when there's contacts. * Revert ""Setting eco-slider with a popup that promts for a percentage now uses the percentage of the amount that isn't required to keep clean."" This reverts commit a2fe5dce3c1be344b6c96b6bfa1b5d16b321fafa. * Taught AI to use divert-reserve to research-checkbox * I don't know how it can happen but I've seen rare cases of colonies with negative-population. This is a workaround that changes them back to 1 pop. * Skip AI turn when corresponing empire is dead. * Fixed possible endless-loop from scrapping last existing ship-design. * Fixed issue where AI would build colonizers as bombers after having scrapped their last existing bomber-design. * Removed useless code. * Removed useless code. * Xilmi AI now capable of deciding when to use bio-weapons. * Bioweapon-support * New voting behavior: Xilmi Ai now votes for whoever they are most scared of but aren't at war with. * Fixed for undecisive behavior of launching an assault but retreating until transports arrive because developmentPct is no longer maxxed after sending transports. (War would still get triggered by the invasion but the fleet sent to accompany the invasion would retreat) * No longer escorting colony-ships on their way to presumably undefended systems. Reason: This oftentimes used a good portion of the fleet for no good reason, when they could be better used for attacking/defending. * Requiring closer range to fire missiles. * Lower score for using bio-weapons depending on how many missile-bases are seen. * No longer altering tech-allocations based on war-state. * New, more diverse and supposedly more interesting diplomatic behavior for AI. * Pick weapon to counter best enemy shield in use rather than average to avoid situations where lasers or scatterpack-V are countered too hard. Also: Make sure that there is a design with the most current bomb before considering bio-weapons. * Weapons that allow heavy-mounts don't get their value decreased so AI doesn't end up without decent repulsor-counter. * Moved negative-population workaround to a place where it is actually called. * Smarter decision-making about when to bomb or not to bomb during on-going invasions. * Incoming invasions of oneself should be slightly better covered but without tying too much of the fleet to it. * Choose target by distance from fleet. * Giving more cover to incoming invasions. * Made rank-check-functions available outside of diplomat too. * Always abstain if not both candidates are known. Superpowers should avoid wars. * Fixed an issue where defenders wouldn't always stay back when they should. * Don't hold back full power when in war anymore. * Quality of ships now more important for scrapping than before. * Reversed prior change in retreat-logic for smaller ships: Yes, the enemy could retreat but control over the system is probably more important than preserving some ships. * Fixed issue where AI would retreat from repulsors when they had missiles. * Minimum speed-requirement for missiles now takes repulsor-beams and diagonals into account. * AI will prepare their wars a little better and also take having to prepare into account before invadion. * No longer voting until both candidates are met. AI now knows much better to capitalize on an advantage and actually win the game instead of throwing it in a risky way. * Moved a debug-output to another place. * 0.93l * Better preparations before going to war. Removed alliances again. * Pick war-target by population-center rather than potential population center. * Fixed a bunch of issued leading to bad colony-ship-management in the lategame. * The better an AI is doing, the more careful they are about how to pick their enemies. * Increased minimum ship-maintenance-threshold for the early-game. * New version * Forgot to remove a debug-message. * Fixed issue reported by u/Individual_Act289: Transports launched before final war disappear on arrival. * Fixed logical error in maxFiringRange-method which could cause unwanted retreats. * When at war, AI will not make so many colony-ships, fixed issue where invasions wouldn't happen against partially built missile-bases, build more bombers when there's a high military-superiority * Willingness to defend now scales with defense-ratio. * Holding back before going to war as long as techs can still be easily researched. * AI will get a bit more tech when it's opportune instead of going for war. * Smart path will avoid paths where the detour would be longer than 50%, fleets that would otherwise go to a staging-point while they are orbiting an enemy will instead stay in orbit of the enemy. * Yet unused methor determining the required count of fighters to shoo scouts away. * Techs that are more than 5 levels behind the average will now be researched even if they are low priority. * Handling for enemy missile-frigates. * No longer scrap ships while at war. * Shields are seen as more useful, new way of determining what size ships should be. * enemyTransportsInTransit now also returns transports of neutral/cold-war-opponents * Created separate method unfriendlyTransportsInTransit * Improved algorithm to determine ship-design-size, reduction in score for hybrids without bombs * Run from missile code should no longer try to outrun missiles that are too close already * New method for unfriendlyTransportsInTransit used * Taught AI to protect their systems against scouting * Taught AI to protect their systems against scouting * Fixed issue that prevented scouts from being sent to long-range-targets when they were part of a fleet with other ships. * Xilmi-AI now declaring war at any poploss, not just at 30+ * Sanity check for fleeing from missiles: Only do it when something could actually be lost. * Prepare better for potential attacks. * Some code cleanup * Fixed issue where other ships than destroyers could be built as scout-repellers. * Avoid downsizing of weapons in non-destroyer-ships. * Distances need to be recalculated immediately after obtaining new system as otherwise AI would act on outdated information. In this case it led to the AI offering peace due to losing range on an opponent whos colony it just conquered despite that act bringing lots of new systems into range. * Fixed an issue where AI would consider an opponents contacts instead of their own when determining the opponents relative standing. Also no longer looking at empires outside of ship-range for potential wars. * Priority for my purpose needs to be above 1000 and below 1400. Below 1000 it gets into conflict with scouts and above 1400 it will rush out the ships under all circumstances. * The widespread usage of scout-repellers makes adding a weapon to a colony-ship much more important. * Added missing override for maxFiringRange * Fixed that after capturing a colony the default for max-bases was not used from the settings of the new owner. * Default for bases on new systems and whether excess-spending goes to research can now be changed in Remnants.cfg * Fixed issue that allowed ship-designs without weapons to be considered the best design. * Fixed a rare crash I had never seen before and can't really explain. * Now taking into account if a weapon would cause a lot of overkill and reduce it's score if it is the case. Most likely will only affect Death-Ray and maybe Mauler-Device. * Fixed an issue with negative-fleets and error-messages. Fixed an issue where systems of empires without income wouldn't be attacked when they had stealth-ships or were out of sensor-range. * Improved detection on whether scout-repellers are needed. Also forbid scout-repellers when unlimited range is available. * Removed code that would consistently scrap unused designs, which sometimes had unintended side-effects when building bigger ships. Replaced what it was meant for by something vastly better: A design-rotation that happens based on how much the design contributes to the maintenance-cost. When there's 4 available slots for combat-designs and one design takes up more than 1/3rd of the maintenance, a new design is enforced, even if it is the same as before. * Fixed issue where ships wouldn't shoot at nearby targets when they couldn't reach their preferred target. Rewrote combat-outcome-expectation to much better guess the expected outcome, which now also consideres auto-repair. * New algorithm to determine who is the best target for a war. * New algorithm to determine the ratio of bombers vs. fighters respectively bombs vs. anti-ship-weapons on a hybrid. * Fixed issue where huge colonizers wouldn't be built when Orion was reachable. * The slots for scouts and scout-repellers are no longer used during wars. * Improved strategic target-selection to better take ship-roles into account. * Fixed issue in bcValue not recognizing scouts of non-AI-player * Fixed several issues with design-scoring. (possible zero-division and using size instead of space) * Much more dedicated and better adapted defending-techniques. * Improved estimate on how many troops need to stay back in order to shoot down transports.",https://github.com/rayfowler/rotp-public/commit/2ec066ab66098db56a37be9f35ccf980ce38866b,,,src/rotp/model/ai/xilmi/AIFleetCommander.java,3,java,False,2021-10-12T17:22:38Z "@Override public Object call(Object who, Method method, Object... args) throws Throwable { String pkg = (String) args[0]; int userId = VUserHandle.myUserId(); VActivityManager.get().killAppByPkg(pkg, userId); return 0; }","@Override public Object call(Object who, Method method, Object... args) throws Throwable { int nameIdx = getProviderNameIndex(); String name = (String) args[nameIdx]; int userId = VUserHandle.myUserId(); ProviderInfo info = VPackageManager.get().resolveContentProvider(name, 0, userId); if (info != null && info.enabled && isAppPkg(info.packageName)) { int targetVPid = VActivityManager.get().initProcess(info.packageName, info.processName, userId); if (targetVPid == -1) { return null; } args[nameIdx] = VASettings.getStubAuthority(targetVPid); if (Build.VERSION.SDK_INT >= 30) { args[1] = VirtualCore.get().getContext().getPackageName(); } Object holder = method.invoke(who, args); if (holder == null) { return null; } if (BuildCompat.isOreo()) { IInterface provider = ContentProviderHolderOreo.provider.get(holder); if (provider != null) { provider = VActivityManager.get().acquireProviderClient(userId, info); } ContentProviderHolderOreo.provider.set(holder, provider); ContentProviderHolderOreo.info.set(holder, info); } else { IInterface provider = IActivityManager.ContentProviderHolder.provider.get(holder); if (provider != null) { provider = VActivityManager.get().acquireProviderClient(userId, info); } IActivityManager.ContentProviderHolder.provider.set(holder, provider); IActivityManager.ContentProviderHolder.info.set(holder, info); } return holder; } if (BuildCompat.isQ()) { int packageIndex = getPackageIndex(); if (packageIndex > 0 && args[packageIndex] instanceof String) { args[packageIndex] = getHostPkg(); } } Object holder = method.invoke(who, args); if (holder != null) { if (BuildCompat.isOreo()) { IInterface provider = ContentProviderHolderOreo.provider.get(holder); info = ContentProviderHolderOreo.info.get(holder); if (provider != null) { provider = ProviderHook.createProxy(true, info.authority, provider); } ContentProviderHolderOreo.provider.set(holder, provider); } else { IInterface provider = IActivityManager.ContentProviderHolder.provider.get(holder); info = IActivityManager.ContentProviderHolder.info.get(holder); if (provider != null) { provider = ProviderHook.createProxy(true, info.authority, provider); } IActivityManager.ContentProviderHolder.provider.set(holder, provider); } return holder; } return null; }","Android 11: Fix crash on getContentProvider SecurityException on call getContentProvider, wrong packageName.",https://github.com/android-hacker/VirtualXposed/commit/529e1bbe3b4aad28876f80f9f9592b69bb7d930c,,,VirtualApp/lib/src/main/java/com/lody/virtual/client/hook/proxies/am/MethodProxies.java,3,java,False,2021-11-26T14:32:43Z "@Override protected @Nullable Thing toElement(String key, ThingStorageEntity persistableElement) { return ThingDTOMapper.map(persistableElement, persistableElement.isBridge); }","@Override protected @Nullable Thing toElement(String key, ThingStorageEntity persistableElement) { try { return ThingDTOMapper.map(persistableElement, persistableElement.isBridge); } catch (IllegalArgumentException e) { logger.warn(""Failed to create thing with UID '{}' from stored entity: {}"", key, e.getMessage()); } return null; }","Prevent crash on invalid entry in ManagedThingProvider (#3053) Signed-off-by: Jan N. Klug ",https://github.com/openhab/openhab-core/commit/6c9b7676e49c9a0e171c6f90b958c5d399c5d34c,,,bundles/org.openhab.core.thing/src/main/java/org/openhab/core/thing/ManagedThingProvider.java,3,java,False,2022-08-22T15:40:01Z "private ClonedChunkSection createSection(int x, int y, int z) { ClonedChunkSection section; if (!this.inactivePool.isEmpty()) { section = this.inactivePool.remove(); this.byPosition.remove(section.getPosition().asLong()); } else { section = this.allocate(); } ChunkSectionPos pos = ChunkSectionPos.from(x, y, z); section.init(this.world, pos); this.byPosition.put(pos.asLong(), section); return section; }","private ClonedChunkSection createSection(int x, int y, int z) { ClonedChunkSection section; if (!this.inactivePool.isEmpty()) { section = this.inactivePool.remove(); this.byPosition.remove(section.getPosition().asLong()); } else { section = this.allocate(); } ChunkSectionPos pos = ChunkSectionPos.from(x, y, z); long asLong = pos.asLong(); if(asLong >= 0) { section.init(this.world, pos); this.byPosition.put(asLong, section); } return section; }","'fix' for ArrayIndexOutOfBounds Not a fix, just a bypass. #225 #93 #129 #133 #157",https://github.com/Asek3/Rubidium/commit/9ddaa42017bc7b9eac15008c32b4c747c30cc819,,,src/main/java/me/jellysquid/mods/sodium/client/world/cloned/ClonedChunkSectionCache.java,3,java,False,2022-08-23T17:39:39Z "public void dropPayload() { payload_chunks = null; }","public synchronized void dropPayload() { payload_chunks.clear(); }","Fix possible JNI local reference overflow and races Dumping connections payload requires creating (local) references, which are limited to 512. This commit greatly reduces their lifetime, from several seconds to less than 1 second, reducing the likehood of an overflow. Moreover it adds missing synchronization to the connection payload.",https://github.com/emanuele-f/PCAPdroid/commit/2fddba63017b1b5db11c0b0aa067ba467bb3da2b,,,app/src/main/java/com/emanuelef/remote_capture/model/ConnectionDescriptor.java,3,java,False,2022-08-13T14:10:38Z "public InputStream getInputStream() throws IOException { InputStream iStream = this.item.getInputStream(); // if marking is supported, then it is likely already buffered if (iStream.markSupported()) { return iStream; } return new BufferedInputStream(iStream); }","public InputStream getInputStream() throws IOException { InputStream iStream = this.item.getInputStream(); // Put data in memory because stream may not support skip (e.g. CipherInputStream) // and may cause an infinite look in writeTo method. // Use markSupported method may also return true (stream wrappering) if (iStream.available() == 0) { byte[] byteArr = ByteStreams.toByteArray(new DicomInputStream(iStream)); InputStream fisRescue = new BufferedInputStream(new ByteArrayInputStream(byteArr)); return fisRescue; } // if marking is supported, then it is likely already buffered if (iStream.markSupported()) { return iStream; } return new BufferedInputStream(iStream); }",[C-MOVE] Fix problem related with infinite loop if the skip method of InputStream implementantion does not do the job and returns 0,https://github.com/bioinformatics-ua/dicoogle/commit/bf18e0ccf6519cd0cf421edc1950080d3ff20089,,,dicoogle/src/main/java/pt/ua/dicoogle/server/queryretrieve/DicoogleDcmSend.java,3,java,False,2023-02-11T11:11:51Z "@Override public String clientSourceAddress() { if (proxyMessage != null) { return proxyMessage.sourceAddress(); } else if (remoteAddress instanceof InetSocketAddress) { InetSocketAddress inetAddress = (InetSocketAddress) remoteAddress; return inetAddress.getAddress().getHostAddress(); } else { return null; } }","@Override public String clientSourceAddress() { AuthenticationDataSource authenticationDataSource = this.getAuthData(); if (proxyMessage != null) { return proxyMessage.sourceAddress(); } else if (remoteAddress instanceof InetSocketAddress) { InetSocketAddress inetAddress = (InetSocketAddress) remoteAddress; return inetAddress.getAddress().getHostAddress(); } else { return null; } }","[fix][broker] Fix passing incorrect authentication data (#16201) ### Motivation #16065 fixes the race condition issue, but introduces a new issue. This issue is triggered when the Proxy and Broker work together, when we use the proxy to request the broker to do lookup/subscribe/produce operation, the broker always uses the original authentication data for authorization, not proxy authentication data, which causes this issue. ### Modification - Fix passing authentication data, differentiate between original auth data and connected auth data by avoid to use the `getAuthenticationData()`, this method name is easy to cause confusion and can not correctly get the authentication data",https://github.com/apache/pulsar/commit/936bbbcc6a4e8cf61547aeedf92e84fb3a089502,,,pulsar-broker/src/main/java/org/apache/pulsar/broker/service/ServerCnx.java,3,java,False,2022-06-28T23:39:10Z "public void updateBehaviors() { for (Behavior behavior : behaviors) { behavior.update(this); } }","public void updateBehaviors() { behaviors.run(behaviors -> { for (Behavior behavior : behaviors) { behavior.update(this); } }); }","fixed a ton of concurrency issues New Additions - `Drawable#isDestroyed` -- boolean for checking if a given `Drawable` has been destroyed - This boolean also effects the outcome of `Drawable#shouldRender` -- if the `Drawable` is destroyed, then it will not be rendered - `ManagedList` -- a type of `List` with convenient managed actions via a `ScheduledExecutorService`, providing a safe and manageable way to start and stop important list actions at a moment's notice Bug Fixes - Fixed occasional crashes on null pointers with enemies in `GameScene` - Fixed occasional concurrent modification exceptions on `AfterUpdateList` and `AfterRenderList` in `FastJEngine` - Fixed double-`exit` situation on closing `SimpleDisplay` - Fixed occasional concurrenct modification exceptions on `behavior` lists from `GameObject` - Sensibly removed as many `null` values as possible from `Model2D/Polygon2D/Sprite2D/Text2D` - Fixed buggy threading code/occasional concurrent modification exceptions in `InputManager` Breaking Changes - `BehaviorManager#reset` now destroys all the behaviors in each of its behavior lists Other Changes - Moved transform resetting on `destroyTheRest` up from `GameObject` to `Drawable` - Changed `GameObjectTests#tryUpdateBehaviorWithoutInitializing_shouldThrowNullPointerException`'s exception throwing to match the underlying `behaviors` list's exception - added trace-level logging to unit tests",https://github.com/fastjengine/FastJ/commit/3cf252b71786d782a98fdfb976eba13154e57757,,,src/main/java/tech/fastj/graphics/game/GameObject.java,3,java,False,2021-12-20T17:24:53Z "@Bean @Order(Ordered.HIGHEST_PRECEDENCE) SecurityWebFilterChain apiFilterChain(ServerHttpSecurity http, RoleService roleService, ObjectProvider securityConfigurers) { http.authorizeExchange() .pathMatchers(""/api/**"", ""/apis/**"", ""/login"", ""/logout"") .access(new RequestInfoAuthorizationManager(roleService)) .pathMatchers(""/**"").permitAll() .and() .headers() .frameOptions().mode(SAMEORIGIN) .and() .anonymous(anonymousSpec -> { anonymousSpec.authorities(AnonymousUserConst.Role); anonymousSpec.principal(AnonymousUserConst.PRINCIPAL); }) .httpBasic(withDefaults()); // Integrate with other configurers separately securityConfigurers.orderedStream() .forEach(securityConfigurer -> securityConfigurer.configure(http)); return http.build(); }","@Bean @Order(Ordered.HIGHEST_PRECEDENCE) SecurityWebFilterChain apiFilterChain(ServerHttpSecurity http, RoleService roleService, ObjectProvider securityConfigurers) { http.securityMatcher(pathMatchers(""/api/**"", ""/apis/**"", ""/login"", ""/logout"")) .authorizeExchange().anyExchange() .access(new RequestInfoAuthorizationManager(roleService)).and() .anonymous(spec -> { spec.authorities(AnonymousUserConst.Role); spec.principal(AnonymousUserConst.PRINCIPAL); }) .formLogin(withDefaults()) .logout(withDefaults()) .httpBasic(withDefaults()); // Integrate with other configurers separately securityConfigurers.orderedStream() .forEach(securityConfigurer -> securityConfigurer.configure(http)); return http.build(); }","Apply specific headers for portal endpoints (#2972) #### What type of PR is this? /kind improvement /area core #### What this PR does / why we need it: This PR separates security configuration of RESTful APIs and portal pages to configure specific headers for portal pages, such as `Referrer-Policy` and `X-Frame-Options`. #### Which issue(s) this PR fixes: Fixes https://github.com/halo-dev/halo/issues/2900 #### Special notes for your reviewer: You can see the response headers of index page: ```diff HTTP/1.1 200 OK Content-Type: text/html Content-Language: en-US + X-Content-Type-Options: nosniff + X-Frame-Options: SAMEORIGIN + X-XSS-Protection: 0 + Referrer-Policy: strict-origin-when-cross-origin content-encoding: gzip content-length: 4285 ``` and request headers with `Referer`: ```diff GET / HTTP/1.1 Host: localhost:8090 User-Agent: Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:107.0) Gecko/20100101 Firefox/107.0 Accept: text/html,application/xhtml+xml,application/xml;q=0.9,image/avif,image/webp,*/*;q=0.8 Accept-Language: en-US,en;q=0.5 Accept-Encoding: gzip, deflate, br + Referer: http://localhost:8090/archives/12341234 Connection: keep-alive Cookie: _ga_Z907HJBP8W=GS1.1.1670164888.1.1.1670165603.0.0.0; _ga=GA1.1.807839437.1670164889; SESSION=539e060e-c11e-4b6d-a749-882905b30a88; XSRF-TOKEN=4b692b55-638c-4497-8a4b-be00986eda90 Upgrade-Insecure-Requests: 1 Sec-Fetch-Dest: document Sec-Fetch-Mode: navigate Sec-Fetch-Site: same-origin Sec-Fetch-User: ?1 ``` #### Does this PR introduce a user-facing change? ```release-note 解决访问分析工具无法显示 referer 的问题 ```",https://github.com/halo-dev/halo/commit/09d4b40da896df19d07691dc9c93e6da551efcdb,,,src/main/java/run/halo/app/config/WebServerSecurityConfig.java,3,java,False,2022-12-16T03:32:35Z "private void populateRemoveAndProtectedHeaders(RequestContext requestContext) { Map securitySchemeDefinitions = requestContext.getMatchedAPI().getSecuritySchemeDefinitions(); // API key headers are considered to be protected headers, such that the header would not be sent // to backend and traffic manager. // This would prevent leaking credentials, even if user is invoking unsecured resource with some // credentials. for (Map.Entry entry : securitySchemeDefinitions.entrySet()) { SecuritySchemaConfig schema = entry.getValue(); if (APIConstants.SWAGGER_API_KEY_AUTH_TYPE_NAME.equalsIgnoreCase(schema.getType())) { if (APIConstants.SWAGGER_API_KEY_IN_HEADER.equals(schema.getIn())) { requestContext.getProtectedHeaders().add(schema.getName()); requestContext.getRemoveHeaders().add(schema.getName()); continue; } if (APIConstants.SWAGGER_API_KEY_IN_QUERY.equals(schema.getIn())) { requestContext.getQueryParamsToRemove().add(schema.getName()); } } } // Internal-Key credential is considered to be protected headers, such that the header would not be sent // to backend and traffic manager. String internalKeyHeader = ConfigHolder.getInstance().getConfig().getAuthHeader() .getTestConsoleHeaderName().toLowerCase(); requestContext.getRemoveHeaders().add(internalKeyHeader); // Avoid internal key being published to the Traffic Manager requestContext.getProtectedHeaders().add(internalKeyHeader); // Remove Authorization Header AuthHeaderDto authHeader = ConfigHolder.getInstance().getConfig().getAuthHeader(); String authHeaderName = FilterUtils.getAuthHeaderName(requestContext); if (!authHeader.isEnableOutboundAuthHeader()) { requestContext.getRemoveHeaders().add(authHeaderName); } // Authorization Header should not be included in the throttle publishing event. requestContext.getProtectedHeaders().add(authHeaderName); // not allow clients to set cluster header manually requestContext.getRemoveHeaders().add(AdapterConstants.CLUSTER_HEADER); }","private void populateRemoveAndProtectedHeaders(RequestContext requestContext) { Map securitySchemeDefinitions = requestContext.getMatchedAPI().getSecuritySchemeDefinitions(); // API key headers are considered to be protected headers, such that the header would not be sent // to backend and traffic manager. // This would prevent leaking credentials, even if user is invoking unsecured resource with some // credentials. for (Map.Entry entry : securitySchemeDefinitions.entrySet()) { SecuritySchemaConfig schema = entry.getValue(); if (APIConstants.SWAGGER_API_KEY_AUTH_TYPE_NAME.equalsIgnoreCase(schema.getType())) { if (APIConstants.SWAGGER_API_KEY_IN_HEADER.equals(schema.getIn())) { String header = StringUtils.lowerCase(schema.getName()); requestContext.getProtectedHeaders().add(header); requestContext.getRemoveHeaders().add(header); continue; } if (APIConstants.SWAGGER_API_KEY_IN_QUERY.equals(schema.getIn())) { requestContext.getQueryParamsToRemove().add(schema.getName()); } } } Utils.removeCommonAuthHeaders(requestContext); }",Fix apikey failure when header key is in uppercase and prevent common auth headers reaching websocket backends,https://github.com/wso2/product-microgateway/commit/b0754afcf624ef88eb29daa10889b20887b26e50,,,enforcer-parent/enforcer/src/main/java/org/wso2/choreo/connect/enforcer/api/GraphQLAPI.java,3,java,False,2022-10-03T07:32:33Z "@Override public MissingSuggestProvider getMessingSuggestionProvider() { return missingValueProvider; }","@Override public MissingSuggestProvider getMessingSuggestionProvider() { if(isNull(missingEntryProvider)){ return missingValue -> Optional.empty(); } return missingValueProvider; }",fix #521 LocalSuggestBoxStore crashes SuggestBox.getValue(),https://github.com/DominoKit/domino-ui/commit/05a86bd46c10fc71b775b0955ca8c93ca2e63c81,,,domino-ui/src/main/java/org/dominokit/domino/ui/forms/LocalSuggestBoxStore.java,3,java,False,2021-03-05T14:23:07Z "@Override public IMessage onMessage(MessageManualClose message, MessageContext ctx) { Minecraft.getMinecraft().addScheduledTask(() -> { EntityPlayerMP player = ctx.getServerHandler().player; World world = ImmersiveEngineering.proxy.getClientWorld(); if(world!=null&&player!=null) { ItemStack mainItem = player.getHeldItemMainhand(); ItemStack offItem = player.getHeldItemOffhand(); boolean main = !mainItem.isEmpty()&&mainItem.getItem()==IEContent.itemTool&&mainItem.getItemDamage()==3; boolean off = !offItem.isEmpty()&&offItem.getItem()==IEContent.itemTool&&offItem.getItemDamage()==3; ItemStack target = main?mainItem: offItem; if(main||off) { if((message.skin==null||message.skin.isEmpty())&&ItemNBTHelper.hasKey(target, ""lastSkin"")) { ItemNBTHelper.remove(target, ""lastSkin""); } else if(message.skin!=null) { ItemNBTHelper.setString(target, ""lastSkin"", message.skin); } } } }); return null; }","@Override public IMessage onMessage(MessageManualClose message, MessageContext ctx) { EntityPlayerMP player = ctx.getServerHandler().player; if(player!=null) { WorldServer world = ctx.getServerHandler().player.getServerWorld(); world.addScheduledTask(() -> { ItemStack mainItem = player.getHeldItemMainhand(); ItemStack offItem = player.getHeldItemOffhand(); boolean main = !mainItem.isEmpty()&&mainItem.getItem()==IEContent.itemTool&&mainItem.getItemDamage()==3; boolean off = !offItem.isEmpty()&&offItem.getItem()==IEContent.itemTool&&offItem.getItemDamage()==3; ItemStack target = main?mainItem: offItem; if(main||off) if((message.skin==null||message.skin.isEmpty())&&ItemNBTHelper.hasKey(target, ""lastSkin"")) ItemNBTHelper.remove(target, ""lastSkin""); else if(message.skin!=null) ItemNBTHelper.setString(target, ""lastSkin"", message.skin); }); } return null; }","Fixed manual server side crash, closes #136",https://github.com/Team-Immersive-Intelligence/ImmersiveIntelligence/commit/0ae61bb8d159bebac6075a35a2834c52e923d94d,,,src/main/java/pl/pabilo8/immersiveintelligence/common/network/MessageManualClose.java,3,java,False,2022-01-15T09:31:59Z "private OkHttpClient getAuthClient() { return new OkHttpClient().newBuilder().authenticator((route, response) -> { if (response.request().header(""Authorization"") != null) { return null; // Give up, we've already failed to authenticate. } String credential = Credentials.basic(username, password); return response.request().newBuilder().header(""Authorization"", credential).build(); }).build(); }","private OkHttpClient getAuthClient() { return new OkHttpClient().newBuilder().addInterceptor(chain -> { if(!TextUtils.isEmpty(username) || !TextUtils.isEmpty(password)) { String credentials = Credentials.basic(username, password); return chain.proceed(chain.request().newBuilder().header(""Authorization"", credentials).build()); } return chain.proceed(chain.request()); }).build(); }",Fixes #1016 - always insert Authorization header in requests (#1017),https://github.com/jonasoreland/runnerup/commit/cc32e552dec37876ee5eed406bc4e6cef1d3ed15,,,app/src/main/org/runnerup/export/WebDavSynchronizer.java,3,java,False,2021-04-25T21:05:00Z "[System.Diagnostics.CodeAnalysis.SuppressMessage(""Microsoft.Maintainability"", ""CA1500:VariableNamesShouldNotMatchFieldNames"", MessageId = ""scheme"")] [System.Diagnostics.CodeAnalysis.SuppressMessage(""Microsoft.Maintainability"", ""CA1500:VariableNamesShouldNotMatchFieldNames"", MessageId = ""context"")] public Task InitializeAsync(AuthenticationScheme scheme, HttpContext context) { this.context = context ?? throw new ArgumentNullException(nameof(context)); options = optionsCache.GetOrAdd(scheme.Name, () => optionsFactory.Create(scheme.Name)); emitSameSiteNone = options.Notifications.EmitSameSiteNone(context.Request.GetUserAgent()); return Task.CompletedTask; }","[System.Diagnostics.CodeAnalysis.SuppressMessage(""Microsoft.Maintainability"", ""CA1500:VariableNamesShouldNotMatchFieldNames"", MessageId = ""scheme"")] [System.Diagnostics.CodeAnalysis.SuppressMessage(""Microsoft.Maintainability"", ""CA1500:VariableNamesShouldNotMatchFieldNames"", MessageId = ""context"")] public Task InitializeAsync(AuthenticationScheme scheme, HttpContext context) { this.context = context ?? throw new ArgumentNullException(nameof(context)); options = optionsCache.GetOrAdd(scheme.Name, () => optionsFactory.Create(scheme.Name)); dataProtector = dataProtectorProvider.CreateProtector(GetType().FullName, options.SPOptions.ModulePath); emitSameSiteNone = options.Notifications.EmitSameSiteNone(context.Request.GetUserAgent()); return Task.CompletedTask; }","Use modulepath in data protection purpose - Prevents reuse of protected data across instances/schemes/modules - Fixes #713",https://github.com/Sustainsys/Saml2/commit/d9e4ff83688d9ebb1ff82a201fab94f1131b7692,,,Sustainsys.Saml2.AspNetCore2/Saml2Handler.cs,3,cs,False,2023-09-19T07:25:15Z "@Override public void insert(T entity) { super.insert(entity); log.info(""{} PUT dbKey: {}, height: {}, entity: {}"", tableLogHeader(), entity.getDbKey(), entity.getHeight(), entity); cache.put(entity.getDbKey(), entity); }","@Override public void insert(T entity) { synchronized (lock) { super.insert(entity); log.info(""{} PUT dbKey: {}, height: {}, entity: {}"", tableLogHeader(), entity.getDbKey(), entity.getHeight(), entity); cache.put(entity.getDbKey(), entity); } }","Add synchronization of the CachedTable inner cache updates, bcause 'T get(DbKey key)' method lead to cache inconsistency during rollback/truncate/deleteAtHeight/insert operations cause the previous stale version could be loaded. Fix failed pop off infinite loop, add stacktrace logs",https://github.com/ApolloFoundation/Apollo/commit/732034707384ee817c692684042304020f1f4e3c,,,apl-core/src/main/java/com/apollocurrency/aplwallet/apl/core/dao/state/derived/CachedTable.java,3,java,False,2021-06-01T15:05:45Z "private boolean isServiceVulnerable(NetworkService networkService) { String targetUri = NetworkServiceUtils.buildWebApplicationRootUrl(networkService) + ""cgi-bin/.%2e/%2e%2e/%2e%2e/%2e%2e/etc/passwd""; try { HttpResponse response = httpClient.send(get(targetUri).withEmptyHeaders().build(), networkService); Optional server = response.headers().get(""Server""); Optional body = response.bodyString(); if (server.isPresent() && server.get().contains(""Apache/2.4.49"")) { // require all denied if (response.status() == HttpStatus.FORBIDDEN && body.isPresent() && body.get().contains(""You don't have permission to access this resource."")) { return false; } if (response.status() == HttpStatus.OK && body.isPresent() && vulnerabilityResponsePattern.matcher(body.get()).find()) { return true; } } } catch (IOException e) { logger.atWarning().withCause(e).log(""Unable to query '%s'."", targetUri); } return false; }","private boolean isServiceVulnerable(NetworkService networkService) { for (String dir : COMMON_DIRECTORIES) { if (checkUrlWithCommonDirectory(networkService, dir)) { return true; } } return false; }","Add common directory prefixes to the check for Apache CVE-2021-41773 vulnerability and remove the check for Server header. PiperOrigin-RevId: 401763941 Change-Id: Id6ae883101a026920736aba87848c49e9114d421",https://github.com/google/tsunami-security-scanner-plugins/commit/9873ddd32be88f8f6df2fa7a27f167d9e1bbedc9,,,community/detectors/apache_http_server_cve_2021_41773/src/main/java/com/google/tsunami/plugins/detectors/rce/cve202125646/ApacheHttpServerCVE202141773VulnDetector.java,3,java,False,2021-10-08T14:12:10Z "@Override public void writeToParcel(@NonNull Parcel dest, int flags) { dest.writeStrongBinder(mFragmentToken); dest.writeTypedObject(mToken, flags); mConfiguration.writeToParcel(dest, flags); dest.writeInt(mRunningActivityCount); dest.writeBoolean(mIsVisible); dest.writeBinderList(mActivities); mPositionInParent.writeToParcel(dest, flags); dest.writeBoolean(mIsTaskClearedForReuse); dest.writeBoolean(mIsTaskFragmentClearedForPip); mMinimumDimensions.writeToParcel(dest, flags); }","@Override public void writeToParcel(@NonNull Parcel dest, int flags) { dest.writeStrongBinder(mFragmentToken); dest.writeTypedObject(mToken, flags); mConfiguration.writeToParcel(dest, flags); dest.writeInt(mRunningActivityCount); dest.writeBoolean(mIsVisible); dest.writeBinderList(mActivities); mPositionInParent.writeToParcel(dest, flags); dest.writeBoolean(mIsTaskClearedForReuse); dest.writeBoolean(mIsTaskFragmentClearedForPip); dest.writeBoolean(mIsClearedForReorderActivityToFront); mMinimumDimensions.writeToParcel(dest, flags); }","Fixes app crash when starts activity with FLAG_ACTIVITY_REORDER_TO_FRONT Application was crashed while starting an embedded Activity with FLAG_ACTIVITY_REORDER_TO_FRONT, because the embedded Activity was not the direct child of the Task. In this CL, the embedded activity is now moved to the top-most position of the Task and dismissed from being embedded in order to honer FLAG_ACTIVITY_REORDER_TO_FRONT. Bug: 255701223 Test: locally verified with app Test: atest TaskTests Change-Id: I491139e5e1d712993f1fef9aebbd75e9ccfc539e",https://github.com/aosp-mirror/platform_frameworks_base/commit/5dc3ec5115e2223fd2f951efe71ee4f0c61377c1,,,core/java/android/window/TaskFragmentInfo.java,3,java,False,2022-10-29T09:30:59Z "@Override public Object getProperty(Object key) { Object result = """"; if (name.length() > 0 && name.equals(key)) { // Do not attempt to evaluate a Calculated Property if this piece is not on a map if (getMap() == null) { return """"; } else { try { RecursionLimiter.startExecution(this); result = evaluate(); return result; } catch (RecursionLimitException e) { RecursionLimiter.infiniteLoop(e); } finally { RecursionLimiter.endExecution(); } return result; } } return super.getProperty(key); }","@Override public Object getProperty(Object key) { Object result = """"; if (name.length() > 0 && name.equals(key)) { // Do not attempt to evaluate a Calculated Property if this piece is not on a map if (getMap() == null) { return """"; } else { // Don't potentially create more infinite loops while already reporting one if (RecursionLimiter.isReportingInfiniteLoop()) { return getExpression(); } try { RecursionLimiter.startExecution(this); result = evaluate(); return result; } catch (RecursionLimitException e) { RecursionLimiter.infiniteLoop(e); } finally { RecursionLimiter.endExecution(); } return result; } } return super.getProperty(key); }",10755 - Don't infinite loop while reporting one,https://github.com/vassalengine/vassal/commit/a0ef462c0f38fbf1bf03c2b76c82efdfd1ca3a4c,,,vassal-app/src/main/java/VASSAL/counters/CalculatedProperty.java,3,java,False,2021-05-12T02:57:54Z "@Override public void updatePosition(double x, double y, double z) { if (dataTracker == null) { super.updatePosition(x, y, z); } else { BlockPos origin = getOrigin(); VoxelShape colShape = blockState.getCollisionShape(world, origin); if (colShape.isEmpty()) { colShape = blockState.getOutlineShape(world, origin); } if (colShape.isEmpty()) { super.updatePosition(x, y, z); } else { this.setPos(x, y, z); Box box = colShape.getBoundingBox(); this.setBoundingBox(box.offset(getPos().subtract(new Vec3d(MathHelper.lerp(0.5D, box.minX, box.maxX), 0, MathHelper.lerp(0.5D, box.minZ, box.maxZ))))); } } }","@Override public void updatePosition(double x, double y, double z) { if (dataTracker == null) { super.updatePosition(x, y, z); } else { BlockPos origin = dataTracker.get(ORIGIN); VoxelShape colShape = blockState.getCollisionShape(world, origin); if (colShape.isEmpty()) { colShape = blockState.getOutlineShape(world, origin); } if (colShape.isEmpty()) { super.updatePosition(x, y, z); } else { this.setPos(x, y, z); Box box = colShape.getBoundingBox(); this.setBoundingBox(box.offset(getPos().subtract(new Vec3d(MathHelper.lerp(0.5D, box.minX, box.maxX), 0, MathHelper.lerp(0.5D, box.minZ, box.maxZ))))); } } }","Fix server crash upon floating block probably",https://github.com/devs-immortal/Paradise-Lost/commit/b3acfa99dddccdecc43dd50816d10c26df309e87,,,src/main/java/com/aether/entities/block/FloatingBlockEntity.java,3,java,False,2021-04-15T16:23:24Z "@Override public void load(Map options) throws IOException { if (!isLoaded && !isLoading && resourceStorageFacade != null && resourceStorageFacade.shouldLoadFromStorage(this)) { LOG.debug(""Loading "" + getURI() + "" from storage.""); try { ResourceStorageLoadable in = resourceStorageFacade.getOrCreateResourceStorageLoadable(this); loadFromStorage(in); return; } catch (IOException e) { if (contents != null) { contents.clear(); } if (eAdapters != null) { eAdapters.clear(); } unload(); } } super.load(options); }","@Override public void load(Map options) throws IOException { if (!isLoaded && !isLoading && resourceStorageFacade != null && resourceStorageFacade.shouldLoadFromStorage(this)) { LOG.debug(""Loading "" + getURI() + "" from storage.""); try { ResourceStorageLoadable in = resourceStorageFacade.getOrCreateResourceStorageLoadable(this); loadFromStorage(in); return; } catch (IOException e) { clearAndUnload(); } catch (StackOverflowError e) { trimStackOverflowErrorStackTrace(e); LOG.warn(""Failed to load "" + uri + "" from storage"", e); //$NON-NLS-1$//$NON-NLS-2$ clearAndUnload(); } } super.load(options); }","Catch stack overflows when loading from storage That is, catch and log StackOverflowErrors when loading resources from storage, and fall back to recreating the resource from source. StackOverflowErrors can happen if the AST is deeply nested, since the algorithm to load from storage uses recursion. Signed-off-by: rubenporras ",https://github.com/eclipse/xtext-core/commit/7b4381a2e0dc4dcafe4b19fd15e63a3d5b97a60e,,,org.eclipse.xtext/src/org/eclipse/xtext/resource/persistence/StorageAwareResource.java,3,java,False,2022-07-06T14:26:17Z "private void analyzeValidTypes( OpenAPI api, Schema schema) { if( schema != null) { validTypes( api, schema); Optional.ofNullable( schema.getNot()) .ifPresent( not -> doFor( ""not"", () -> analyzeValidTypes( api, not))); Optional.ofNullable( asArraySchema( schema)) .ifPresent( array -> doFor( ""items"", () -> analyzeValidTypes( api, array.getItems()))); Optional.ofNullable( schema.getProperties()) .ifPresent( properties -> { properties.keySet().stream() .forEach( p -> doFor( p, () -> analyzeValidTypes( api, properties.get( p)))); }); Optional.ofNullable( schema.getAdditionalProperties()) .filter( additional -> additional instanceof Schema) .ifPresent( additional -> doFor( ""additionalProperties"", () -> analyzeValidTypes( api, (Schema) additional))); } }","private void analyzeValidTypes( OpenAPI api, Schema schema) { if( schema != null && !hasValidTypesAll( schema)) { validTypes( api, schema); setValidTypesAll( schema, false); Optional.ofNullable( schema.getNot()) .ifPresent( not -> doFor( ""not"", () -> analyzeValidTypes( api, not))); Optional.ofNullable( asArraySchema( schema)) .ifPresent( array -> doFor( ""items"", () -> analyzeValidTypes( api, array.getItems()))); Optional.ofNullable( schema.getProperties()) .ifPresent( properties -> { properties.keySet().stream() .forEach( p -> doFor( p, () -> analyzeValidTypes( api, properties.get( p)))); }); Optional.ofNullable( schema.getAdditionalProperties()) .filter( additional -> additional instanceof Schema) .ifPresent( additional -> doFor( ""additionalProperties"", () -> analyzeValidTypes( api, (Schema) additional))); setValidTypesAll( schema, true); } }",SchemaAnalyzer.analyze: Rework to avoid infinite loop when schema contains circular references. (#181),https://github.com/Cornutum/tcases/commit/ff17ad6c7d0736902974ba493f4148f68ea37b31,,,tcases-openapi/src/main/java/org/cornutum/tcases/openapi/SchemaAnalyzer.java,3,java,False,2021-06-20T19:38:21Z "public NBTTagCompound getNBT() { return stack.getTagCompound(); }","public NBTTagCompound getNBT() { if (!stack.hasTagCompound()) stack.setTagCompound(new NBTTagCompound()); return stack.getTagCompound(); }","Fixed crash when hammer, chisel or paint brush has no nbt tag",https://github.com/CreativeMD/LittleTiles/commit/1357cac92ddb34297901de9de3db0fdd1502a6b8,,,src/main/java/com/creativemd/littletiles/common/util/shape/ShapeSelection.java,3,java,False,2021-04-20T19:31:48Z "@Override public Entry next() { if ( next == null ) { throw new NoSuchElementException(); } return new Entry() { @Override public String getKey() { return (String) next.getKey(); } @Override public String getValue() { return (String) next.getValue(); } @Override public String setValue( String value ) { return (String) next.setValue( value ); } }; }","@Override public Entry next() { Entry item = next; if ( item == null ) { throw new NoSuchElementException(); } advance(); return item; }",[MNG-7597] Fix infinite loop when iterating PropertiesAsMap (#872),https://github.com/apache/maven/commit/6a27f5f2f6e9ab44c44692b32e5ba41063106de5,,,maven-core/src/main/java/org/apache/maven/internal/impl/PropertiesAsMap.java,3,java,False,2022-11-21T08:37:42Z "public synchronized ISignalScheduleTicket openTicket(SignalScheduleTicket ticket) { int delay; int tick = ticket.getExactDelayValue(); if (tick <= queueLength) { delay = queueIndex + tick - 1; if (delay >= queueLength) delay -= queueLength; } else delay = tick; if (tick <= queueLength) { ticket.enterShortQueue(delay); queue[delay].add(ticket); } else longQueue.add(ticket); return ticket; }","public synchronized ISignalScheduleTicket openTicket(SignalScheduleTicket ticket) { int delay; int tick = ticket.getExactDelayValue(); if (tick <= queueLength) { if (tick < 0) tick = 1; delay = queueIndex + tick - 1; if (delay >= queueLength) delay -= queueLength; } else delay = tick; if (tick <= queueLength) { ticket.enterShortQueue(delay); queue[delay].add(ticket); } else longQueue.add(ticket); return ticket; }",Fixed crash when ticket with 0 delay is queued,https://github.com/CreativeMD/LittleTiles/commit/63e91cf85f4d4a000eb40a429a57a59c72dc003b,,,src/main/java/team/creative/littletiles/common/structure/signal/schedule/SignalTicker.java,3,java,False,2022-06-30T11:15:06Z "static int formatIPTCfromBuffer(Image *ofile, char *s, ssize_t len) { char temp[MagickPathExtent]; unsigned int foundiptc, tagsfound; unsigned char recnum, dataset; unsigned char *readable, *str; ssize_t tagindx, taglen; int i, tagcount = (int) (sizeof(tags) / sizeof(tag_spec)); int c; foundiptc = 0; /* found the IPTC-Header */ tagsfound = 0; /* number of tags found */ while (len > 0) { c = *s++; len--; if (c == 0x1c) foundiptc = 1; else { if (foundiptc) return -1; else continue; } /* We found the 0x1c tag and now grab the dataset and record number tags. */ c = *s++; len--; if (len < 0) return -1; dataset = (unsigned char) c; c = *s++; len--; if (len < 0) return -1; recnum = (unsigned char) c; /* try to match this record to one of the ones in our named table */ for (i=0; i< tagcount; i++) if (tags[i].id == (short) recnum) break; if (i < tagcount) readable=(unsigned char *) tags[i].name; else readable=(unsigned char *) """"; /* We decode the length of the block that follows - ssize_t or short fmt. */ c=(*s++); len--; if (len < 0) return(-1); if (c & (unsigned char) 0x80) return(0); else { s--; len++; taglen=readWordFromBuffer(&s, &len); } if (taglen < 0) return(-1); if (taglen > 65535) return(-1); /* make a buffer to hold the tag datand snag it from the input stream */ str=(unsigned char *) AcquireQuantumMemory((size_t) (taglen+MagickPathExtent), sizeof(*str)); if (str == (unsigned char *) NULL) printf(""MemoryAllocationFailed""); for (tagindx=0; tagindx 0) (void) FormatLocaleString(temp,MagickPathExtent,""%d#%d#%s="", (unsigned int) dataset,(unsigned int) recnum, readable); else (void) FormatLocaleString(temp,MagickPathExtent,""%d#%d="", (unsigned int) dataset,(unsigned int) recnum); (void) WriteBlobString(ofile,temp); formatString( ofile, (char *)str, taglen ); str=(unsigned char *) RelinquishMagickMemory(str); tagsfound++; } return ((int) tagsfound); }","static int formatIPTCfromBuffer(Image *ofile, char *s, ssize_t len) { char temp[MagickPathExtent]; unsigned int foundiptc, tagsfound; unsigned char recnum, dataset; unsigned char *readable, *str; ssize_t tagindx, taglen; int i, tagcount = (int) (sizeof(tags) / sizeof(tag_spec)); int c; foundiptc = 0; /* found the IPTC-Header */ tagsfound = 0; /* number of tags found */ while (len > 0) { c = *s++; len--; if (c == 0x1c) foundiptc = 1; else { if (foundiptc) return -1; else continue; } /* We found the 0x1c tag and now grab the dataset and record number tags. */ c = *s++; len--; if (len < 0) return -1; dataset = (unsigned char) c; c = *s++; len--; if (len < 0) return -1; recnum = (unsigned char) c; /* try to match this record to one of the ones in our named table */ for (i=0; i< tagcount; i++) if (tags[i].id == (short) recnum) break; if (i < tagcount) readable=(unsigned char *) tags[i].name; else readable=(unsigned char *) """"; /* We decode the length of the block that follows - ssize_t or short fmt. */ c=(*s++); len--; if (len < 0) return(-1); if (c & (unsigned char) 0x80) return(0); else { s--; len++; taglen=readWordFromBuffer(&s, &len); } if (taglen < 0) return(-1); if (taglen > 65535) return(-1); /* make a buffer to hold the tag datand snag it from the input stream */ str=(unsigned char *) AcquireQuantumMemory((size_t) (taglen+ MagickPathExtent),sizeof(*str)); if (str == (unsigned char *) NULL) { (void) printf(""MemoryAllocationFailed""); return 0; } for (tagindx=0; tagindx 0) (void) FormatLocaleString(temp,MagickPathExtent,""%d#%d#%s="", (unsigned int) dataset,(unsigned int) recnum, readable); else (void) FormatLocaleString(temp,MagickPathExtent,""%d#%d="", (unsigned int) dataset,(unsigned int) recnum); (void) WriteBlobString(ofile,temp); formatString( ofile, (char *)str, taglen ); str=(unsigned char *) RelinquishMagickMemory(str); tagsfound++; } return ((int) tagsfound); }",https://github.com/ImageMagick/ImageMagick/issues/1118,https://github.com/ImageMagick/ImageMagick/commit/33d1b9590c401d4aee666ffd10b16868a38cf705,,,coders/meta.c,3,c,False,2018-05-01T23:22:19Z "void set (int index, Image image) { long surface = convertSurface(image); int w = Cairo.cairo_image_surface_get_width(surface); int h = Cairo.cairo_image_surface_get_height(surface); Rectangle bounds; if (DPIUtil.useCairoAutoScale()) { bounds = image.getBounds(); } else { bounds = image.getBoundsInPixels(); } if (w == 0) { w = bounds.width; } if (h == 0) { h = bounds.height; } if (width == -1 || height == -1) { width = w; height = h; } if (w != width || h != height) { surface = scaleSurface(image, width, height); } long oldSurface = surfaces[index]; if (oldSurface != 0) { Cairo.cairo_surface_destroy(oldSurface); } Cairo.cairo_surface_reference(surface); surfaces [index] = surface; images [index] = image; }","void set (int index, Image image) { long surface = convertSurface(image); int w = Cairo.cairo_image_surface_get_width(surface); int h = Cairo.cairo_image_surface_get_height(surface); Rectangle bounds; if (DPIUtil.useCairoAutoScale()) { bounds = image.getBounds(); } else { bounds = image.getBoundsInPixels(); } if (w == 0) { w = bounds.width; } if (h == 0) { h = bounds.height; } if (width == -1 || height == -1) { width = w; height = h; } if (w != width || h != height) { Cairo.cairo_surface_destroy(surface); surface = scaleSurface(image, width, height); } long oldSurface = surfaces[index]; if (oldSurface != 0) { Cairo.cairo_surface_destroy(oldSurface); } surfaces [index] = surface; images [index] = image; }","Bug 573611 - [GTK3] ImageList leaks native memory Prevent leaking cairo surfaces in ImageList.set() and in TreeItem/TableItem setImage(). Change-Id: I1f5b63342a5ce09eea3b869a860f1ef218e6b28c Signed-off-by: Simeon Andreev Reviewed-on: https://git.eclipse.org/r/c/platform/eclipse.platform.swt/+/185455 Tested-by: Platform Bot Reviewed-by: Sravan Kumar Lakkimsetti ",https://github.com/eclipse-platform/eclipse.platform.swt/commit/6296a3acfc6be3c9f6810d088c69b46a12b422e7,,,bundles/org.eclipse.swt/Eclipse SWT/gtk/org/eclipse/swt/internal/ImageList.java,3,java,False,2021-09-15T07:53:29Z "private void cleanUpReadMap(long timestamp) { for (Map.Entry entry : messagesReadAt.entrySet()) { if (timestamp - entry.getValue() > 30_000) { messagesReadAt.remove(entry.getKey()); } } }","private void cleanUpReadMap(long timestamp) { messagesReadAt.values().removeIf(readAt -> timestamp - readAt > 30_000); }",[#3835] Fix unread counter crash (#3836),https://github.com/airyhq/airy/commit/4aaf0398819b355c1518b8d39eaec24463eb6a28,,,backend/components/unread-counter/src/main/java/co/airy/core/unread_counter/dto/UnreadCountState.java,3,java,False,2022-10-17T16:15:16Z "void observe() { // Observe all users' changes ContentResolver resolver = mContext.getContentResolver(); resolver.registerContentObserver(Settings.System.getUriFor( Settings.System.END_BUTTON_BEHAVIOR), false, this, UserHandle.USER_ALL); resolver.registerContentObserver(Settings.Secure.getUriFor( Settings.Secure.INCALL_POWER_BUTTON_BEHAVIOR), false, this, UserHandle.USER_ALL); resolver.registerContentObserver(Settings.Secure.getUriFor( Settings.Secure.INCALL_BACK_BUTTON_BEHAVIOR), false, this, UserHandle.USER_ALL); resolver.registerContentObserver(Settings.Secure.getUriFor( Settings.Secure.WAKE_GESTURE_ENABLED), false, this, UserHandle.USER_ALL); resolver.registerContentObserver(Settings.System.getUriFor( Settings.System.SCREEN_OFF_TIMEOUT), false, this, UserHandle.USER_ALL); resolver.registerContentObserver(Settings.Secure.getUriFor( Settings.Secure.DEFAULT_INPUT_METHOD), false, this, UserHandle.USER_ALL); resolver.registerContentObserver(Settings.Secure.getUriFor( Settings.Secure.VOLUME_HUSH_GESTURE), false, this, UserHandle.USER_ALL); resolver.registerContentObserver(Settings.Secure.getUriFor( Settings.Secure.SYSTEM_NAVIGATION_KEYS_ENABLED), false, this, UserHandle.USER_ALL); resolver.registerContentObserver(Settings.Global.getUriFor( Settings.Global.POWER_BUTTON_LONG_PRESS), false, this, UserHandle.USER_ALL); resolver.registerContentObserver(Settings.Global.getUriFor( Settings.Global.POWER_BUTTON_LONG_PRESS_DURATION_MS), false, this, UserHandle.USER_ALL); resolver.registerContentObserver(Settings.Global.getUriFor( Settings.Global.POWER_BUTTON_VERY_LONG_PRESS), false, this, UserHandle.USER_ALL); resolver.registerContentObserver(Settings.Global.getUriFor( Settings.Global.KEY_CHORD_POWER_VOLUME_UP), false, this, UserHandle.USER_ALL); resolver.registerContentObserver(Settings.Global.getUriFor( Settings.Global.POWER_BUTTON_SUPPRESSION_DELAY_AFTER_GESTURE_WAKE), false, this, UserHandle.USER_ALL); resolver.registerContentObserver(LineageSettings.System.getUriFor( LineageSettings.System.TORCH_LONG_PRESS_POWER_GESTURE), false, this, UserHandle.USER_ALL); resolver.registerContentObserver(LineageSettings.System.getUriFor( LineageSettings.System.TORCH_LONG_PRESS_POWER_TIMEOUT), false, this, UserHandle.USER_ALL); resolver.registerContentObserver(LineageSettings.System.getUriFor( LineageSettings.System.KEY_HOME_LONG_PRESS_ACTION), false, this, UserHandle.USER_ALL); resolver.registerContentObserver(LineageSettings.System.getUriFor( LineageSettings.System.KEY_HOME_DOUBLE_TAP_ACTION), false, this, UserHandle.USER_ALL); resolver.registerContentObserver(LineageSettings.System.getUriFor( LineageSettings.System.KEY_MENU_ACTION), false, this, UserHandle.USER_ALL); resolver.registerContentObserver(LineageSettings.System.getUriFor( LineageSettings.System.KEY_MENU_LONG_PRESS_ACTION), false, this, UserHandle.USER_ALL); resolver.registerContentObserver(LineageSettings.System.getUriFor( LineageSettings.System.KEY_ASSIST_ACTION), false, this, UserHandle.USER_ALL); resolver.registerContentObserver(LineageSettings.System.getUriFor( LineageSettings.System.KEY_ASSIST_LONG_PRESS_ACTION), false, this, UserHandle.USER_ALL); resolver.registerContentObserver(LineageSettings.System.getUriFor( LineageSettings.System.KEY_APP_SWITCH_ACTION), false, this, UserHandle.USER_ALL); resolver.registerContentObserver(LineageSettings.System.getUriFor( LineageSettings.System.KEY_APP_SWITCH_LONG_PRESS_ACTION), false, this, UserHandle.USER_ALL); updateSettings(); }","void observe() { // Observe all users' changes ContentResolver resolver = mContext.getContentResolver(); resolver.registerContentObserver(Settings.System.getUriFor( Settings.System.END_BUTTON_BEHAVIOR), false, this, UserHandle.USER_ALL); resolver.registerContentObserver(Settings.Secure.getUriFor( Settings.Secure.INCALL_POWER_BUTTON_BEHAVIOR), false, this, UserHandle.USER_ALL); resolver.registerContentObserver(Settings.Secure.getUriFor( Settings.Secure.INCALL_BACK_BUTTON_BEHAVIOR), false, this, UserHandle.USER_ALL); resolver.registerContentObserver(Settings.Secure.getUriFor( Settings.Secure.WAKE_GESTURE_ENABLED), false, this, UserHandle.USER_ALL); resolver.registerContentObserver(Settings.System.getUriFor( Settings.System.SCREEN_OFF_TIMEOUT), false, this, UserHandle.USER_ALL); resolver.registerContentObserver(Settings.Secure.getUriFor( Settings.Secure.DEFAULT_INPUT_METHOD), false, this, UserHandle.USER_ALL); resolver.registerContentObserver(Settings.Secure.getUriFor( Settings.Secure.VOLUME_HUSH_GESTURE), false, this, UserHandle.USER_ALL); resolver.registerContentObserver(Settings.Secure.getUriFor( Settings.Secure.SYSTEM_NAVIGATION_KEYS_ENABLED), false, this, UserHandle.USER_ALL); resolver.registerContentObserver(Settings.Global.getUriFor( Settings.Global.POWER_BUTTON_LONG_PRESS), false, this, UserHandle.USER_ALL); resolver.registerContentObserver(Settings.Global.getUriFor( Settings.Global.POWER_BUTTON_LONG_PRESS_DURATION_MS), false, this, UserHandle.USER_ALL); resolver.registerContentObserver(Settings.Global.getUriFor( Settings.Global.POWER_BUTTON_VERY_LONG_PRESS), false, this, UserHandle.USER_ALL); resolver.registerContentObserver(Settings.Global.getUriFor( Settings.Global.KEY_CHORD_POWER_VOLUME_UP), false, this, UserHandle.USER_ALL); resolver.registerContentObserver(Settings.Global.getUriFor( Settings.Global.POWER_BUTTON_SUPPRESSION_DELAY_AFTER_GESTURE_WAKE), false, this, UserHandle.USER_ALL); resolver.registerContentObserver(LineageSettings.System.getUriFor( LineageSettings.System.TORCH_LONG_PRESS_POWER_GESTURE), false, this, UserHandle.USER_ALL); resolver.registerContentObserver(LineageSettings.System.getUriFor( LineageSettings.System.TORCH_LONG_PRESS_POWER_TIMEOUT), false, this, UserHandle.USER_ALL); resolver.registerContentObserver(LineageSettings.System.getUriFor( LineageSettings.System.KEY_HOME_LONG_PRESS_ACTION), false, this, UserHandle.USER_ALL); resolver.registerContentObserver(LineageSettings.System.getUriFor( LineageSettings.System.KEY_HOME_DOUBLE_TAP_ACTION), false, this, UserHandle.USER_ALL); resolver.registerContentObserver(LineageSettings.System.getUriFor( LineageSettings.System.KEY_MENU_ACTION), false, this, UserHandle.USER_ALL); resolver.registerContentObserver(LineageSettings.System.getUriFor( LineageSettings.System.KEY_MENU_LONG_PRESS_ACTION), false, this, UserHandle.USER_ALL); resolver.registerContentObserver(LineageSettings.System.getUriFor( LineageSettings.System.KEY_ASSIST_ACTION), false, this, UserHandle.USER_ALL); resolver.registerContentObserver(LineageSettings.System.getUriFor( LineageSettings.System.KEY_ASSIST_LONG_PRESS_ACTION), false, this, UserHandle.USER_ALL); resolver.registerContentObserver(LineageSettings.System.getUriFor( LineageSettings.System.KEY_APP_SWITCH_ACTION), false, this, UserHandle.USER_ALL); resolver.registerContentObserver(LineageSettings.System.getUriFor( LineageSettings.System.KEY_APP_SWITCH_LONG_PRESS_ACTION), false, this, UserHandle.USER_ALL); resolver.registerContentObserver(LineageSettings.System.getUriFor( LineageSettings.System.HOME_WAKE_SCREEN), false, this, UserHandle.USER_ALL); resolver.registerContentObserver(LineageSettings.System.getUriFor( LineageSettings.System.BACK_WAKE_SCREEN), false, this, UserHandle.USER_ALL); resolver.registerContentObserver(LineageSettings.System.getUriFor( LineageSettings.System.MENU_WAKE_SCREEN), false, this, UserHandle.USER_ALL); resolver.registerContentObserver(LineageSettings.System.getUriFor( LineageSettings.System.ASSIST_WAKE_SCREEN), false, this, UserHandle.USER_ALL); resolver.registerContentObserver(LineageSettings.System.getUriFor( LineageSettings.System.APP_SWITCH_WAKE_SCREEN), false, this, UserHandle.USER_ALL); resolver.registerContentObserver(LineageSettings.System.getUriFor( LineageSettings.System.VOLUME_WAKE_SCREEN), false, this, UserHandle.USER_ALL); updateSettings(); }","Reimplement device hardware wake keys support Author: LuK1337 Date: Mon Jun 4 10:05:37 2018 +0200 PhoneWindowManager: Improve home button wake haptic feedback handling * This fixes an issue where haptic feedback is used when screen is off and home button wake is disabled. Change-Id: I7ac4c00598cedf7f174dc99629f55dc7b74b0d2a Author: Gabriele M Date: Mon Sep 26 00:43:08 2016 +0200 Fix volume keys wakeup status handling The same status flag is used for the three different volume keys, however nothing prevents users from pressing multiple keys at the same time. This allows to set the status flag with one volume key and clear it with the other volume key. Use one flag per key so that we never end up in an inconsistent state. This fixes the seldom power button issues that happen when the ""volume wake"" feature is enabled. Change-Id: I08f5f9ff696bef3dd840cff97d570e44ebe03e4e Author: Martin Brabham Date: Wed Dec 3 11:48:28 2014 -0800 Android Policy: handle volume key event as wake key when preference is set Change-Id: If9a61cd65553bf00f0efda1a75b1ab75b9129090 Author: willl03 Date: Mon Dec 8 11:13:28 2014 -0500 Only go HOME if screen is fully awake Avoid going home when hardware home button is used to wake the device on an insecure keyguard Change-Id: I5d5d8c4fff76967c29e70251f7b165205005ba11 Author: Matt Garnes Date: Tue Mar 31 14:39:38 2015 -0700 If a wake key is disabled by the user, do not wake from doze. Currently, any wake key will wake the device from a doze, even if that key has not been enabled as a wake key in Settings. If the device is 'dreaming' in the Doze state, check if the user has explicitly disabled the wake key (or never enabled the setting in the first place) before waking the device. Change-Id: I7397087c143161e8e1ddb84d0e23f6027fea0aac Author: Michael Bestas Date: Thu Dec 18 04:26:38 2014 +0200 Cleanup button wake settings (2/2) Change-Id: Ie37136cbd57c4c334321abbfa4543727e940bc43 Keep quiet when volume keys are used to wake up device - Userspace will make a 'beep' with it receives a key up, so consume that event as well. - Removed wake key check in music control code as it will already be disabled here. Change-Id: I93839acd39aec8a2ee40291f833a31f6b048c9f8 Wake Keys: enforce the wake keys overlay * Keys disabled as wake keys by the overlay were still being allowed to wake the device. This change enforces the hardwareWakeKeys settings. Change-Id: Ifde0491b2de64a7f61a101cf22f5589cb5e841e2 Allow disabling Search/Recents button wake (2/2) Change-Id: I6a2ac064efc4fe85413bf0b935c28aa7bde5d672 Author: Danny Baumann Date: Sun Nov 30 23:04:37 2014 -0600 fw/base: allow home button to wake device [1/2] Change-Id: I2b79561dcfa7e569b2e24bbabfffb11517d4d313 Change-Id: Ic294515c7200c1260ac514db23ef3778d374d727",https://github.com/LineageOS/android_frameworks_base/commit/6f24c9b705c82374cfc9d7cb799c14a1c5712207,,,services/core/java/com/android/server/policy/PhoneWindowManager.java,3,java,False,2017-12-25T15:54:07Z "@Override public boolean hurt(DamageSource source, float damage) { float input = getBaseDamage(source, damage); return super.hurt(source, input); }","@Override public boolean hurt(DamageSource source, float damage) { float input = getBaseDamage(source, damage); if (isPowered()) { return !(source instanceof IndirectEntityDamageSource) && super.hurt(source, input); } return super.hurt(source, input); }",Update GelatinousSlimeLayer.java,https://github.com/Silentine/GrimoireOfGaia/commit/28cf38446103b9b93f33858631927cab2559111f,,,src/main/java/gaia/entity/Minotaurus.java,3,java,False,2022-12-20T01:33:09Z "private void processLoginConfig(WebApplication webApplication, WebXml webXml) { AuthenticationManager authManager = webApplication.getManager(AuthenticationManager.class); if (authManager != null && webXml.getLoginConfig() != null) { if (webXml.getLoginConfig().authMethod() != null) { authManager.setAuthMethod(webXml.getLoginConfig().authMethod()); } if (webXml.getLoginConfig().realmName() != null) { authManager.setRealmName(webXml.getLoginConfig().realmName()); } } }","private void processLoginConfig(WebApplication webApplication, WebXml webXml) { AuthenticationManager authManager = webApplication.getAuthenticationManager(); if (authManager != null) { if (webXml.getLoginConfig() != null) { if (webXml.getLoginConfig().authMethod() != null) { authManager.setAuthMethod(webXml.getLoginConfig().authMethod()); } if (webXml.getLoginConfig().realmName() != null) { authManager.setRealmName(webXml.getLoginConfig().realmName()); } } } else { LOGGER.log(WARNING, ""No authentication manager is set, not applying login config""); } }",Fixes issue #2069 - Make authentication manager an opt-in for DefaultWebApplication,https://github.com/piranhacloud/piranha/commit/95e78d0cfdafbc9207108fe53ada7159fce39af9,,,extension/webxml/src/main/java/cloud/piranha/extension/webxml/WebXmlProcessor.java,3,java,False,2021-11-07T16:04:56Z "private void validateAgainstXSD(InputStream xml) throws Exception { InputStream xsd = getClass().getResourceAsStream(""/ESAPI-properties.xsd""); SchemaFactory factory = SchemaFactory.newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI); Schema schema = factory.newSchema(new StreamSource(xsd)); Validator validator = schema.newValidator(); validator.validate(new StreamSource(xml)); }","private void validateAgainstXSD(InputStream xml) throws IOException, SAXException { try ( InputStream xsd = getClass().getResourceAsStream(""/ESAPI-properties.xsd""); ) { SchemaFactory factory = SchemaFactory.newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI); Schema schema = factory.newSchema(new StreamSource(xsd)); Validator validator = schema.newValidator(); validator.validate(new StreamSource(xml)); } }","Suggested pom.xml updates and XmlEsapiPropertyLoader.java improvements (#612) Close issue #614 Pom changes: * Upgrade a few libraries, add some used but undeclared libraries, and delete a bunch of declared/unused libraries. * Upgrade a bunch of the plugins. * Suggested updates to XmlEsapiPropertyLoader.java to eliminate insider XXE risk, and other minor suggested cleanup. * A few more tweaks to use autoclosables to ensure streams get closed. * Remove debug lines.",https://github.com/ESAPI/esapi-java-legacy/commit/c9c3cebe6a66e6d864df89bafc51845fdf0ce919,,,src/main/java/org/owasp/esapi/configuration/XmlEsapiPropertyLoader.java,3,java,False,2021-03-24T01:08:42Z "public static void invalidateWorld(LevelAccessor world) { allMaps.forEach(m -> m.remove(world)); }","public static void invalidateWorld(LevelAccessor world) { var i = allMaps.iterator(); while (i.hasNext()) { Map map = i.next() .get(); if (map == null) { // If the map has been GC'd, remove the weak reference i.remove(); } else { // Prevent leaks map.remove(world); } } }","Crash and leak fix - Fix crash when invoking ContraptionMovementSetting#get - Fix memory leak in WorldAttached by copying Flywheel's updated version - Fix stockpile switches not preserving settings after being printed",https://github.com/Creators-of-Create/Create/commit/9fbb71e4e9d9f70e2256a73b45482208b01053cf,,,src/main/java/com/simibubi/create/foundation/utility/WorldAttached.java,3,java,False,2022-08-04T05:36:14Z "private void waitForElasticsearch(RestHighLevelClient client, long pollingTime) throws Exception { final Date startTime = new Date(); AtomicBoolean pollingSuccess = new AtomicBoolean(false); ScheduledExecutorService schedulerService = Executors.newSingleThreadScheduledExecutor(); CountDownLatch cdl = new CountDownLatch(1); Holder exception = new Holder<>(); ScheduledFuture sched = schedulerService.scheduleAtFixedRate(() -> { logger.info(""Polling for Elasticsearch...""); try { //Do Health request ClusterHealthRequest healthRequest = new ClusterHealthRequest(); healthRequest.timeout(new TimeValue(5, TimeUnit.SECONDS)); final ClusterHealthResponse healthResponse = client.cluster().health(healthRequest, RequestOptions.DEFAULT); if (!healthResponse.isTimedOut()) { // set polling status as successful pollingSuccess.set(true); // measure time if health request is successful final Date endTime = new Date(); long pollingTimeMeasure = endTime.getTime() - startTime.getTime(); logger.info(""Took ""+ pollingTimeMeasure + "" milliseconds for polling Elasticsearch""); // wake up the waiting thread cdl.countDown(); } } catch (IOException e) { logger.info(""Unable to reach Elasticsearch. Will continue polling.""); exception.setValue(e); } }, 0, // Start immediately 10, // Poll every pollingPeriod seconds TimeUnit.SECONDS); cdl.await(pollingTime, TimeUnit.SECONDS); // Max wait for polling time sched.cancel(true); if (pollingSuccess.get()) { logger.info(""Polling for Elasticsearch has ended with success""); } else { logger.warn(""Polling for Elasticsearch has ended without success""); } // CDL > 0 means we never successfully hit the health endpoint. if (exception.getValue() != null && cdl.getCount() > 0) { throw exception.getValue(); } }","private void waitForElasticsearch(RestHighLevelClient client, long pollingTime) { EsConnectionPoller poller = new EsConnectionPoller(client, 0, POLL_INTERVAL_SECS, Math.toIntExact(pollingTime)); poller.blockUntilReady(); }","refactor(es): rework TLS configuration for Elasticsearch Fixed behaviour of TLS certificates and BASIC auth, allowing both at the same time if necessary. Changed `apiman.es.trust.certificate` to `apiman.es.allowSelfSigned`. Changed `apiman.es.trust.host` to `apiman.es.allowAnyHost`. Refactors ES polling to be more robust and clearer. Closes #1195 Co-authored-by: Marc Savy ",https://github.com/apiman/apiman/commit/546e1f8003124f182c61c59cde14e0faaf9f86ef,,,common/es/src/main/java/io/apiman/common/es/util/DefaultEsClientFactory.java,3,java,False,2021-06-08T09:43:18Z "updateOidcSettings(configuration) { checkAdminAuthentication(this) ServiceConfiguration.configurations.remove({ service: 'oidc', }) ServiceConfiguration.configurations.insert(configuration) }","updateOidcSettings(configuration) { check(configuration, Object) checkAdminAuthentication(this) ServiceConfiguration.configurations.remove({ service: 'oidc', }) ServiceConfiguration.configurations.insert(configuration) }","🐛 fixed a bug in the oidc configuration preventing saving changes 🔒 fixed admin authorization validation for all administration pages 🔒 fixed a stored XSS vulnerability in the task functionality",https://github.com/kromitgmbh/titra/commit/fe8c3cdeb70e53b9f38f1022186ab16324d332c5,CVE-2022-2595,['CWE-285'],imports/api/globalsettings/methods.js,3,js,False,2022-06-27T17:14:15Z "@Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); ActivityHelper.applyTheme(this); setContentView(R.layout.activity_changelog); Toolbar toolbar = findViewById(R.id.toolbar); setSupportActionBar(toolbar); ActionBar actionBar = getSupportActionBar(); if (actionBar != null) { actionBar.setDisplayHomeAsUpEnabled(true); actionBar.setDisplayShowHomeEnabled(true); } MarkdownView markdownView = findViewById(R.id.markdownView); markdownView.loadAsset(""changelog.md""); }","@Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); ActivityHelper.applyTheme(this); try { setContentView(R.layout.activity_changelog); } catch (Exception e) { MarkdownView.closeOnMissingWebView(this, e); } Toolbar toolbar = findViewById(R.id.toolbar); setSupportActionBar(toolbar); ActionBar actionBar = getSupportActionBar(); if (actionBar != null) { actionBar.setDisplayHomeAsUpEnabled(true); actionBar.setDisplayShowHomeEnabled(true); } MarkdownView markdownView = findViewById(R.id.markdownView); markdownView.loadAsset(""changelog.md""); }","Fix: crash when WebView cannot be initialized - closes #145 References: MissingWebViewPackageException @ MarkdownView. Appcenter PUB #49494606u",https://github.com/x0b/rcx/commit/fde4aa7b2b179a1c2e065dbcb1fb6337d725dca2,,,app/src/main/java/ca/pkay/rcloneexplorer/ChangelogActivity.java,3,java,False,2021-06-12T16:02:46Z "private void launchCustomTabs(final Uri uri, final Activity activity, final String browserPackage) { try { CustomTabsIntent.Builder builder = new CustomTabsIntent.Builder(mCustomTabsSession); mCustomTabsIntent = builder.build(); if(pool.getCustomTabExtras() != null) mCustomTabsIntent.intent.putExtras(pool.getCustomTabExtras()); mCustomTabsIntent.intent.setPackage( browserPackage != null ? browserPackage : DEFAULT_BROWSER_PACKAGE); mCustomTabsIntent.intent.setData(uri); if (activity != null) { activity.startActivityForResult( CustomTabsManagerActivity.createStartIntent(context, mCustomTabsIntent.intent), CUSTOM_TABS_ACTIVITY_CODE ); } else { Intent startIntent = CustomTabsManagerActivity.createStartIntent(context, mCustomTabsIntent.intent); startIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_NO_HISTORY); context.startActivity(startIntent); } } catch (final Exception e) { userHandler.onFailure(e); } }","private void launchCustomTabs(final Uri uri, final Activity activity, final String browserPackage) { try { if(!isBrowserInstalled()) { userHandler.onFailure(new BrowserNotInstalledException(""No browsers installed."")); return; } if(!isCustomTabSupported()) { userHandler.onFailure(new CustomTabsNotSupportedException(""Browser with custom tabs support not found."")); return; } CustomTabsIntent.Builder builder = new CustomTabsIntent.Builder(mCustomTabsSession); mCustomTabsIntent = builder.build(); if(pool.getCustomTabExtras() != null) mCustomTabsIntent.intent.putExtras(pool.getCustomTabExtras()); if(browserPackage != null) { mCustomTabsIntent.intent.setPackage(browserPackage); } mCustomTabsIntent.intent.setData(uri); if (activity != null) { activity.startActivityForResult( CustomTabsManagerActivity.createStartIntent(context, mCustomTabsIntent.intent), CUSTOM_TABS_ACTIVITY_CODE ); } else { Intent startIntent = CustomTabsManagerActivity.createStartIntent(context, mCustomTabsIntent.intent); startIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_NO_HISTORY); context.startActivity(startIntent); } } catch (final Exception e) { userHandler.onFailure(e); } }","fix(aws-android-sdk-cognitoauth): custom tabs app crash when chrome not available (#2529) * fix custom tabs app crash - add support for launching intent chooser for custom tabs - fix app crash if chrome not available by choosing availalbe browser * use supported browser for signout instead of default Chrome * launch intent chooser by dafault - do not force browsers, app should handle this logic * remove unused imports * call failure callback if no browsers installed on device * call failure callback if custom tabs not supported * cache result of resolved browser activites * return generic collection and fix whitespaces * add exception classes for no browser and no custom tabs",https://github.com/aws-amplify/aws-sdk-android/commit/58ad144e87589ed6817e9d9dfdd17f9b696137ee,,,aws-android-sdk-cognitoauth/src/main/java/com/amazonaws/mobileconnectors/cognitoauth/AuthClient.java,3,java,False,2021-07-20T23:02:01Z "private void visit(Target from, Attribute attribute, Target target) throws InterruptedException, NoSuchThingException { if (from != null) { switch (mode) { case DEPS: // Don't update parentMap; only use visited. break; case SAME_PKG_DIRECT_RDEPS: // Only track same-package dependencies. if (target .getLabel() .getPackageIdentifier() .equals(from.getLabel().getPackageIdentifier())) { if (!parentMap.containsKey(target)) { parentMap.put(target, new ArrayList<>()); } parentMap.get(target).add(from); } // We only need to perform a single level of visitation. We have a non-null 'from' // target, and we're now at 'target' target, so we have one level, and can return here. return; case ALLPATHS: if (!parentMap.containsKey(target)) { parentMap.put(target, new ArrayList<>()); } parentMap.get(target).add(from); break; case SOMEPATH: parentMap.putIfAbsent(target, ImmutableList.of(from)); break; } visitAspectsIfRequired(from, attribute, target); } if (visited.add(target)) { visitEdgesOfTarget(target); } }","private void visit(Target from, Attribute attribute, Target target) throws InterruptedException, NoSuchThingException { if (from != null) { switch (mode) { case DEPS: // Don't update parentMap; only use visited. break; case SAME_PKG_DIRECT_RDEPS: // Only track same-package dependencies. if (target .getLabel() .getPackageIdentifier() .equals(from.getLabel().getPackageIdentifier())) { if (!parentMap.containsKey(target)) { parentMap.put(target, new ArrayList<>()); } parentMap.get(target).add(from); } // We only need to perform a single level of visitation. We have a non-null 'from' // target, and we're now at 'target' target, so we have one level, and can return here. return; case ALLPATHS: if (!parentMap.containsKey(target)) { parentMap.put(target, new ArrayList<>()); } parentMap.get(target).add(from); break; case SOMEPATH: parentMap.putIfAbsent(target, ImmutableList.of(from)); break; } visitAspectsIfRequired(from, attribute, target); } else if (mode == VisitorMode.SOMEPATH) { // Here we make sure that if this is a top-level visitation node (where 'from' is null), // a parent edge cannot be made for this node. This prevents parent-edge cycles from being // formed and hence infinite loops impossible when traversing parent-edges. parentMap.putIfAbsent(target, ImmutableList.of()); } if (visited.add(target)) { visitEdgesOfTarget(target); } }","Fix OOM with somepath due to infinite loop. This only happens when a `from` target is in the cycle, and the infinite loop occurs when we traverse a parent-edge loop. If the `from` target is not in the cycle, a parent-edge loop is never created because the parent-edges are already set. **Fix:** Prevent parent-edges from being created from `from` targets to another `from` target, the idea here is that parents of a `from` target are not relevant to `somepath`. **Implications:** In the case where `from` targets are dependencies of each other, the path going through other `from` targets will not be considered since all `from` targets are treated as ""root"" level targets. For example: `somepath(//foo:a + //foo:transitive_dep_of_a, //foo:transitive_dep_of_both)` where this code will now only output the path from `//foo:transitive_dep_of_a -> //foo:transitive_dep_of_both` and never `//foo:a -> //foo:transitive_dep_of_a -> //foo:transitive_dep_of_both`. PiperOrigin-RevId: 447410138",https://github.com/bazelbuild/bazel/commit/7eda21f972b8edb64ed8dcd949ab369da11437df,,,src/main/java/com/google/devtools/build/lib/query2/query/PathLabelVisitor.java,3,java,False,2022-05-09T09:00:51Z "public double[] getWheelPositions() { return this.wheelPositions; }","public double[] getWheelPositions() { /* Updates the wheel positions as reloading vehicle properties * could cause a crash if wheels are added or removed. */ if(this.wheelPositions == null || this.wheelPositions.length != this.getProperties().getWheels().size()) { this.wheelPositions = new double[this.getProperties().getWheels().size() * 3]; } return this.wheelPositions; }",💥 Fixed potential crash when changes to wheel count,https://github.com/MrCrayfish/MrCrayfishVehicleMod/commit/37c1d66bb3a4ccbeaad80ee08f8af9d8a74fdc4e,,,src/main/java/com/mrcrayfish/vehicle/entity/PoweredVehicleEntity.java,3,java,False,2021-09-02T04:57:49Z "private void processSecurityConstraints(WebApplication webApplication, WebXml webXml) { AuthenticationManager manager = webApplication.getManager(AuthenticationManager.class); for (WebXmlSecurityConstraint constraint : webXml.getSecurityConstraints()) { for (WebXmlSecurityConstraint.WebResourceCollection collection : constraint.getWebResourceCollections()) { for (String urlPattern : collection.getUrlPatterns()) { manager.addSecurityMapping(urlPattern); } } } }","private void processSecurityConstraints(WebApplication webApplication, WebXml webXml) { AuthenticationManager manager = webApplication.getAuthenticationManager(); if (manager != null) { for (WebXmlSecurityConstraint constraint : webXml.getSecurityConstraints()) { for (WebXmlSecurityConstraint.WebResourceCollection collection : constraint.getWebResourceCollections()) { for (String urlPattern : collection.getUrlPatterns()) { manager.addSecurityMapping(urlPattern); } } } } else { LOGGER.log(WARNING, ""No authentication manager is set, not applying security contraints""); } }",Fixes issue #2069 - Make authentication manager an opt-in for DefaultWebApplication,https://github.com/piranhacloud/piranha/commit/95e78d0cfdafbc9207108fe53ada7159fce39af9,,,extension/webxml/src/main/java/cloud/piranha/extension/webxml/WebXmlProcessor.java,3,java,False,2021-11-07T16:04:56Z "@Override public boolean flushCache() { try { Response resp = client.newCall(GetDefaultRequest(this.platform + ""/getrecords.php?t=0."" + Utils.getRandomLong()).build()).execute(); this.resultCache = resp.body().string().toLowerCase(); // this.callbacks.printOutput(String.format(""Got Dnslog Result OK!: %s"", this.resultCache)); return true; } catch (Exception ex) { this.callbacks.printOutput(String.format(""[-] Get Dnslog Result Failed!: %s"", ex.getMessage())); return false; } }","@Override public boolean flushCache() { String url = this.platform + ""getrecords.php?t=0."" + Utils.getRandomLong(); try { byte[] rawRequest = this.helpers.buildHttpRequest(new URL(url)); IHttpService service = this.helpers.buildHttpService(""www.dnslog.cn"", 80, ""HTTP""); // 加入cookie IParameter cookieParam = this.helpers.buildParameter(this.iCookie.getName(), this.iCookie.getValue(), IParameter.PARAM_COOKIE); byte[] newRawRequest = this.helpers.updateParameter(rawRequest, cookieParam); IHttpRequestResponse requestResponse = this.callbacks.makeHttpRequest(service, newRawRequest); byte[] rawResponse = requestResponse.getResponse(); IResponseInfo responseInfo = this.helpers.analyzeResponse(rawResponse); // 获取响应包body内容 this.resultCache = new String(rawResponse).substring(responseInfo.getBodyOffset()).trim().toLowerCase(); } catch (MalformedURLException e) { e.printStackTrace(); this.stderr.println(e.getMessage()); } return true; }",报错检测默认关闭,其UI输出调整为[?] SpringCore RCE (need verify);回连等待时间调整为30s;重写/修复Dnslog的bug;修复Ceye回连的一些bug;默认回连平台设为BurpCollaboratorClient (Dnslog不稳定);,https://github.com/metaStor/SpringScan/commit/182d90ba8088c3fa6c1fa2b3bdd8f2eed5cabb64,,,src/main/java/burp/backend/platform/Dnslog.java,3,java,False,2022-04-12T10:01:56Z "public void addValidationNotice(ValidationNotice notice) { validationNotices.add(notice); }","public void addValidationNotice(ValidationNotice notice) { if (notice.isError()) { hasValidationErrors = true; } if (validationNotices.size() <= MAX_VALIDATION_NOTICES) { validationNotices.add(notice); } }","feat: Prevent OOM in NoticeContainer and speed up hasValidationErrors (#895) Store up to 10 M validation notices. This is a measure to prevent OOM in the rare case when each row in a large file (such as stop_times.txt or shapes.txt) produces a notice. Since this case is rare, we just introduce a total limit on the amount of notices instead of counting amount of notices of each type. Note that system errors are not limited since we don't expect to have a lot of them. Now we have a boolean field to flag if there are validation errors. This way hasValidationErrors() now takes O(1) instead of O(n).",https://github.com/MobilityData/gtfs-validator/commit/2f1f71f2e66f2e45e1cd08f3d7a53cd2d4081b3e,,,core/src/main/java/org/mobilitydata/gtfsvalidator/notice/NoticeContainer.java,3,java,False,2021-05-06T18:48:14Z "public boolean allowNamespacePolicyOperation(NamespaceName namespaceName, PolicyName policy, PolicyOperation operation, String originalRole, String role, AuthenticationDataSource authData) { try { return allowNamespacePolicyOperationAsync( namespaceName, policy, operation, originalRole, role, authData).get(); } catch (InterruptedException e) { throw new RestException(e); } catch (ExecutionException e) { throw new RestException(e.getCause()); } }","public boolean allowNamespacePolicyOperation(NamespaceName namespaceName, PolicyName policy, PolicyOperation operation, String originalRole, String role, AuthenticationDataSource authData) { try { return allowNamespacePolicyOperationAsync( namespaceName, policy, operation, originalRole, role, authData).get( conf.getZooKeeperOperationTimeoutSeconds(), SECONDS); } catch (InterruptedException e) { Thread.currentThread().interrupt(); throw new RestException(e); } catch (ExecutionException e) { throw new RestException(e.getCause()); } catch (TimeoutException e) { throw new RestException(e); } }",[branch-2.9][fix][security] Add timeout of sync methods and avoid call sync method for AuthoriationService (#16083),https://github.com/apache/pulsar/commit/1fa9c2e17977cb451c0379581c35c70920a393f3,,,pulsar-broker-common/src/main/java/org/apache/pulsar/broker/authorization/AuthorizationService.java,3,java,False,2022-06-17T05:27:36Z "@Override public void complete(ResponseInfo responseInfo, UploadSingleRequestMetrics metrics, JSONObject response) { if (metrics != null) { requestMetricsList.add(metrics); } if (shouldCheckConnect(responseInfo)) { UploadSingleRequestMetrics checkMetrics = ConnectChecker.check(); if (metrics != null) { metrics.connectCheckMetrics = checkMetrics; } if (!ConnectChecker.isConnected(checkMetrics)) { String message = ""check origin statusCode:"" + responseInfo.statusCode + "" error:"" + responseInfo.error; responseInfo = ResponseInfo.errorInfo(ResponseInfo.NetworkSlow, message); } } LogUtil.i(""key:"" + StringUtils.toNonnullString(requestInfo.key) + "" response:"" + StringUtils.toNonnullString(responseInfo)); if (shouldRetryHandler != null && shouldRetryHandler.shouldRetry(responseInfo, response) && currentRetryTime < config.retryMax && responseInfo.couldHostRetry()) { currentRetryTime += 1; try { Thread.sleep(config.retryInterval); } catch (InterruptedException ignored) { } retryRequest(request, server, isAsync, shouldRetryHandler, progressHandler, completeHandler); } else { completeAction(server, responseInfo, response, metrics, completeHandler); } }","@Override public void complete(ResponseInfo responseInfo, UploadSingleRequestMetrics metrics, JSONObject response) { if (metrics != null) { requestMetricsList.add(metrics); } if (checkCancelHandler.checkCancel()) { responseInfo = ResponseInfo.cancelled(); reportRequest(responseInfo, server, metrics); completeAction(server, responseInfo, responseInfo.response, metrics, completeHandler); return; } boolean hijacked = responseInfo != null && responseInfo.isNotQiniu(); if (hijacked && metrics != null) { metrics.hijacked = UploadSingleRequestMetrics.RequestHijacked; try { metrics.syncDnsSource = DnsPrefetcher.getInstance().lookupBySafeDns(server.getHost()); } catch (Exception e) { metrics.syncDnsError = e.toString(); } } if (!hijacked && shouldCheckConnect(responseInfo)) { UploadSingleRequestMetrics checkMetrics = ConnectChecker.check(); if (metrics != null) { metrics.connectCheckMetrics = checkMetrics; } if (!ConnectChecker.isConnected(checkMetrics)) { String message = responseInfo == null ? """" : (""check origin statusCode:"" + responseInfo.statusCode + "" error:"" + responseInfo.error); responseInfo = ResponseInfo.errorInfo(ResponseInfo.NetworkSlow, message); } else if (metrics != null && !DnsSource.isCustom(server.getSource()) && !DnsSource.isDoh(server.getSource()) && !DnsSource.isDnspod(server.getSource())) { metrics.hijacked = UploadSingleRequestMetrics.RequestMaybeHijacked; try { metrics.syncDnsSource = DnsPrefetcher.getInstance().lookupBySafeDns(server.getHost()); } catch (Exception e) { metrics.syncDnsError = e.toString(); } } } reportRequest(responseInfo, server, metrics); LogUtil.i(""key:"" + StringUtils.toNonnullString(requestInfo.key) + "" response:"" + StringUtils.toNonnullString(responseInfo)); if (shouldRetryHandler != null && shouldRetryHandler.shouldRetry(responseInfo, response) && currentRetryTime < config.retryMax && (responseInfo != null && responseInfo.couldHostRetry())) { currentRetryTime += 1; try { Thread.sleep(config.retryInterval); } catch (InterruptedException ignored) { } retryRequest(request, server, isAsync, shouldRetryHandler, progressHandler, completeHandler); } else { completeAction(server, responseInfo, response, metrics, completeHandler); } }",handle dns hijacked & dns prefetch add doh,https://github.com/qiniu/android-sdk/commit/ada3c8feb608ed37fe8d64ba2d10ac672a207525,,,library/src/main/java/com/qiniu/android/http/request/HttpSingleRequest.java,3,java,False,2021-08-27T10:02:18Z "@Override public void serverTick() { if (!isProjecting()) { return; } if (energy.extractEnergy(Config.projectorEnergyPerTick, true) < Config.projectorEnergyPerTick) { if (hasEnergy) { hasEnergy = false; sendRunningState(); } return; } else if (!hasEnergy) { hasEnergy = true; sendRunningState(); } sendBudget.updateAndGet(budget -> Math.min(Config.projectorMaxBytesPerTick * 10, budget + Config.projectorMaxBytesPerTick)); nextFrameIn = Math.max(0, nextFrameIn - 1); if (sendBudget.get() < 0 || nextFrameIn > 0) { return; } if (runningEncode != null && !runningEncode.isDone()) { return; } joinWorkerAndLogErrors(runningEncode); nextFrameIn = FRAME_EVERY_N_TICKS; if (level == null || !(level.getChunk(getBlockPos()) instanceof LevelChunk chunk)) { return; } runningEncode = FRAME_WORKERS.submit(() -> { final boolean hasChanges = projectorDevice.applyChanges(picture); if (!hasChanges && !needsIDR) { return; } final ByteBuffer frameData; if (needsIDR) { frameData = encoder.encodeIDRFrame(picture, ByteBuffer.allocateDirect(256 * 1024)); needsIDR = false; } else { frameData = encoder.encodeFrame(picture, ByteBuffer.allocateDirect(256 * 1024)).data(); } final Deflater deflater = new Deflater(Deflater.BEST_COMPRESSION); deflater.setInput(frameData); deflater.finish(); final ByteBuffer compressedFrameData = ByteBuffer.allocateDirect(1024 * 1024); deflater.deflate(compressedFrameData, Deflater.FULL_FLUSH); deflater.end(); compressedFrameData.flip(); sendBudget.accumulateAndGet(compressedFrameData.limit(), (budget, packetSize) -> budget - packetSize); final ProjectorFramebufferMessage message = new ProjectorFramebufferMessage(this, compressedFrameData); Network.sendToClientsTrackingChunk(message, chunk); }); }","@Override public void serverTick() { if (!isProjecting()) { return; } if (energy.extractEnergy(Config.projectorEnergyPerTick, true) < Config.projectorEnergyPerTick) { if (hasEnergy) { hasEnergy = false; sendRunningState(); } return; } else if (!hasEnergy) { hasEnergy = true; sendRunningState(); } sendBudget.updateAndGet(budget -> Math.min(Config.projectorMaxBytesPerTick * 10, budget + Config.projectorMaxBytesPerTick)); nextFrameIn = Math.max(0, nextFrameIn - 1); if (sendBudget.get() < 0 || nextFrameIn > 0) { return; } if (runningEncode != null && !runningEncode.isDone()) { return; } joinWorkerAndLogErrors(runningEncode); nextFrameIn = FRAME_EVERY_N_TICKS; if (level == null || !(level.getChunk(getBlockPos()) instanceof LevelChunk chunk)) { return; } runningEncode = FRAME_WORKERS.submit(() -> { final boolean hasChanges = projectorDevice.applyChanges(picture); if (!hasChanges && !needsIDR) { return; } encoderBuffer.clear(); final ByteBuffer frameData; try { if (needsIDR) { frameData = encoder.encodeIDRFrame(picture, encoderBuffer); needsIDR = false; } else { frameData = encoder.encodeFrame(picture, encoderBuffer).data(); } } catch (final BufferOverflowException ignored) { return; // Sad, frame encode failed for unknown reasons... } final Deflater deflater = new Deflater(Deflater.BEST_COMPRESSION); deflater.setInput(frameData); deflater.finish(); final ByteBuffer compressedFrameData = ByteBuffer.allocateDirect(1024 * 1024); deflater.deflate(compressedFrameData, Deflater.FULL_FLUSH); deflater.end(); compressedFrameData.flip(); sendBudget.accumulateAndGet(compressedFrameData.limit(), (budget, packetSize) -> budget - packetSize); final ProjectorFramebufferMessage message = new ProjectorFramebufferMessage(this, compressedFrameData); Network.sendToClientsTrackingChunk(message, chunk); }); }","Catch buffer overflow exceptions in encode, since apparently these can happen. Only seen this when flooding with random, which is... esoteric. So silently swallow this to avoid users deliberately spamming server logs.",https://github.com/fnuecke/oc2/commit/ced5a0b5b40993778694bbbeba5cff54a373cd86,,,src/main/java/li/cil/oc2/common/blockentity/ProjectorBlockEntity.java,3,java,False,2022-02-02T01:08:01Z "@Path(""/{group-id}/schemas"") @DELETE void deleteSchemasByGroup(@PathParam(""group-id"") String groupId);","@Path(""/{group-id}/schemas"") @DELETE @Authorized(AuthorizedStyle.GroupOnly) void deleteSchemasByGroup(@PathParam(""group-id"") String groupId);","Implement owner-only authorization support (optional, enabled via appication.properties) (#1407) * trying to implement simple authorization using CDI interceptors * added @Authorized to appropriate methods * updated the auth test * Removed some debugging statements * Improved and applied authn/z to other APIs (v1, cncf, etc) * Fixed some issues with GroupOnly authorization * Disable the IBM API by default due to authorization issues * fix the IBM api test",https://github.com/Apicurio/apicurio-registry/commit/90a856197b104c99032163fa26c04d01465bf487,,,app/src/main/java/io/apicurio/registry/cncf/schemaregistry/SchemagroupsResource.java,3,java,False,2021-04-13T09:08:58Z "function gotoelement(id) { var gotoElement = document.getElementById('current_record').value; var no_of_records = document.getElementById('totRecords').value; var uploadedFile = document.getElementById('uploadedFile').value; var delim = document.getElementById('select_delimeter').value; var checkmodule = jQuery('#checkmodule').val(); if (id == 'prev_record') { gotoElement = parseInt(gotoElement) - 1; } if (id == 'next_record') { gotoElement = parseInt(gotoElement) + 1; } if (parseInt(gotoElement) <= 0) { gotoElement = 0; } if (parseInt(gotoElement) >= parseInt(no_of_records)) { gotoElement = parseInt(no_of_records) - 1; } if (id == 'apply_element') { gotoElement = parseInt(document.getElementById('goto_element').value); if (isNaN(gotoElement)) { showMapMessages('error', ' Please provide valid record number.'); } if (gotoElement <= 0) { gotoElement = 0; showMapMessages('error', ' Please provide valid record number.'); } else { gotoElement = gotoElement - 1; } if (gotoElement >= no_of_records) { gotoElement = parseInt(no_of_records) - 1; showMapMessages('error', 'CSV file have only ' + no_of_records + ' records.'); return false; } } var doaction = 'record_no=' + gotoElement + '&file_name=' + uploadedFile + '&delim='+ delim + '&checkmodule=' + checkmodule; var tmpLoc = document.getElementById('tmpLoc').value; jQuery.ajax({ url: tmpLoc + 'templates/readfile.php', type: 'post', data: doaction, dataType: 'json', success: function (response) { var totalLength = response.length; for (var i = 0; i < totalLength; i++) { if (response[i] == null) { document.getElementById('elementVal_' + i).innerHTML = response[i]; } else if ((response[i].length) >= 32) { document.getElementById('elementVal_' + i).innerHTML = response[i].substring(0, 28) + '...'; } else { document.getElementById('elementVal_' + i).innerHTML = response[i]; } } var displayRecCount = gotoElement + 1; document.getElementById('preview_of_row').innerHTML = ""Showing preview of row #"" + displayRecCount; document.getElementById('current_record').value = gotoElement; } }); }","function gotoelement(id) { var gotoElement = document.getElementById('current_record').value; var dir_path = jQuery('#dirpathval').val(); var noncekey = document.getElementById('nonceKey').value; var no_of_records = document.getElementById('totRecords').value; var uploadedFile = document.getElementById('uploadedFile').value; var delim = document.getElementById('select_delimeter').value; var checkmodule = jQuery('#checkmodule').val(); if (id == 'prev_record') { gotoElement = parseInt(gotoElement) - 1; } if (id == 'next_record') { gotoElement = parseInt(gotoElement) + 1; } if (parseInt(gotoElement) <= 0) { gotoElement = 0; } if (parseInt(gotoElement) >= parseInt(no_of_records)) { gotoElement = parseInt(no_of_records) - 1; } if (id == 'apply_element') { gotoElement = parseInt(document.getElementById('goto_element').value); if (isNaN(gotoElement)) { showMapMessages('error', ' Please provide valid record number.'); } if (gotoElement <= 0) { gotoElement = 0; showMapMessages('error', ' Please provide valid record number.'); } else { gotoElement = gotoElement - 1; } if (gotoElement >= no_of_records) { gotoElement = parseInt(no_of_records) - 1; showMapMessages('error', 'CSV file have only ' + no_of_records + ' records.'); return false; } } var doaction = 'record_no=' + gotoElement + '&file_name=' + uploadedFile + '&delim='+ delim + '&checkmodule=' + checkmodule+ '&dir_path=' + dir_path + '&wpnonce=' + noncekey; var tmpLoc = document.getElementById('tmpLoc').value; jQuery.ajax({ url: tmpLoc + 'templates/readfile.php', type: 'post', data: doaction, dataType: 'json', success: function (response) { var totalLength = response.length; for (var i = 0; i < totalLength; i++) { if (response[i] == null) { document.getElementById('elementVal_' + i).innerHTML = response[i]; } else if ((response[i].length) >= 32) { document.getElementById('elementVal_' + i).innerHTML = response[i].substring(0, 28) + '...'; } else { document.getElementById('elementVal_' + i).innerHTML = response[i]; } } var displayRecCount = gotoElement + 1; document.getElementById('preview_of_row').innerHTML = ""Showing preview of row #"" + displayRecCount; document.getElementById('current_record').value = gotoElement; } }); }","Version 3.7.3 for Vulnarablility fix git-svn-id: https://plugins.svn.wordpress.org/wp-ultimate-csv-importer/trunk@1153788 b8457f37-d9ea-0310-8a92-e5e31aec5664",https://github.com/wp-plugins/wp-ultimate-csv-importer/commit/13c30af721d3f989caac72dd0f56cf0dc40fad7e,CVE-2015-10125,['CWE-352'],js/ultimate-importer-free.js,3,js,False,2015-05-05T13:28:09Z "void doPublicKeyAuth() { try { final byte[] msg = generateAuthenticationRequest(generateSignatureData()); transport.postMessage(new AuthenticationMessage(username, ""ssh-connection"", ""publickey"") { @Override public boolean writeMessageIntoBuffer(ByteBuffer buf) { super.writeMessageIntoBuffer(buf); buf.put(msg); return true; } }); } catch (IOException e) { disconnect(""Internal error""); } catch (SshException e) { disconnect(""Internal error""); } }","void doPublicKeyAuth() throws SshException, IOException { try { final byte[] msg = generateAuthenticationRequest(generateSignatureData()); transport.postMessage(new AuthenticationMessage(username, ""ssh-connection"", ""publickey"") { @Override public boolean writeMessageIntoBuffer(ByteBuffer buf) { super.writeMessageIntoBuffer(buf); buf.put(msg); return true; } }); } catch (IOException e) { failure(); throw e; } catch(SshException e) { failure(); throw e; } }",HOTFIX: Client authenticators need to signal failure to parent future and should allow SshException to propagate.,https://github.com/sshtools/maverick-synergy/commit/bcbc2fc44c7eb499e00623c1348c360734afa3f5,,,maverick-synergy-client/src/main/java/com/sshtools/client/ExternalKeyAuthenticator.java,3,java,False,2021-08-16T21:17:42Z "default T fromNBT(CompoundTag tag, String name, T fallback) { return tag.contains(name) ? this.fromNBT(tag.get(name)) : fallback; }","default T fromNBT(@Nullable CompoundTag tag, String name, T fallback) { return tag != null && tag.contains(name) ? this.fromNBT(tag.get(name)) : fallback; }",Fix ISerializer#fromNBT crashing on null NBT tags.,https://github.com/Darkhax-Minecraft/Bookshelf/commit/a891868eb0efd66a565a2d00f92f9e50b5a03967,,,Common/src/main/java/net/darkhax/bookshelf/api/serialization/ISerializer.java,3,java,False,2022-02-25T08:23:23Z "public GraphicsConfiguration getAppropriateGraphicsConfiguration( GraphicsConfiguration gc) { if (graphicsConfig == null || gc == null) { return gc; } // Opt: Only need to do if we're not using the default GC int screenNum = ((X11GraphicsDevice)gc.getDevice()).getScreen(); X11GraphicsConfig parentgc; // save vis id of current gc int visual = graphicsConfig.getVisual(); X11GraphicsDevice newDev = (X11GraphicsDevice) GraphicsEnvironment. getLocalGraphicsEnvironment(). getScreenDevices()[screenNum]; for (int i = 0; i < newDev.getNumConfigs(screenNum); i++) { if (visual == newDev.getConfigVisualId(i, screenNum)) { // use that graphicsConfig = (X11GraphicsConfig)newDev.getConfigurations()[i]; break; } } // just in case... if (graphicsConfig == null) { graphicsConfig = (X11GraphicsConfig) GraphicsEnvironment. getLocalGraphicsEnvironment(). getScreenDevices()[screenNum]. getDefaultConfiguration(); } return graphicsConfig; }","public GraphicsConfiguration getAppropriateGraphicsConfiguration( GraphicsConfiguration gc) { if (graphicsConfig == null || gc == null) { return gc; } // Opt: Only need to do if we're not using the default GC XToolkit.awtLock(); // the number of screens may otherwise change during try { int screenNum = ((X11GraphicsDevice) gc.getDevice()).getScreen(); X11GraphicsConfig parentgc; // save vis id of current gc int visual = graphicsConfig.getVisual(); X11GraphicsDevice newDev = (X11GraphicsDevice) GraphicsEnvironment. getLocalGraphicsEnvironment(). getScreenDevices()[screenNum]; for (int i = 0; i < newDev.getNumConfigs(screenNum); i++) { if (visual == newDev.getConfigVisualId(i, screenNum)) { // use that graphicsConfig = (X11GraphicsConfig) newDev.getConfigurations()[i]; break; } } // just in case... if (graphicsConfig == null) { graphicsConfig = (X11GraphicsConfig) GraphicsEnvironment. getLocalGraphicsEnvironment(). getScreenDevices()[screenNum]. getDefaultConfiguration(); } return graphicsConfig; } finally { XToolkit.awtUnlock(); } }","JBR-3623 SIGSEGV at [libawt_xawt] Java_sun_awt_X11GraphicsDevice_getConfigColormap This fix addresses two possible causes of crashes: 1. makeDefaultConfig() returning NULL. The fix is to die gracefully instead of crashing in an attempt to de-reference the NULL pointer. 2. A race condition when the number of screens change (this is only an issue with the number of xinerama screens; the number of X11 screens is static for the duration of the X session). The race scenario: X11GraphisDevice.makeDefaultConfiguration() is called on EDT so the call can race with X11GraphisDevice.invalidate() that re-sets the screen number of the device; the latter is invoked on the ""AWT-XAWT"" thread from X11GraphicsEnvironment.rebuildDevices(). So by the time makeDefaultConfiguration() makes a native call with the device's current screen number, the x11Screens array maintained by the native code could have become shorter. And the native methods like Java_sun_awt_X11GraphicsDevice_getConfigColormap() assume that the screen number passed to them is always current and valid. The AWT lock only protects against the changes during the native methods invocation, but does not protect against them being called with an outdated screen number. The fix is to eliminate the race by protecting X11GraphisDevice.screen with the AWT lock. (cherry picked from commit 0b53cd291fac8c031f84ea1bdac23693e68f259e) (cherry picked from commit 3a15dfad37e57c124733a6360f008cfe61dd95ec)",https://github.com/JetBrains/JetBrainsRuntime/commit/aed4d3e0ff96d026391f4598f4e10952fa425ae4,,,src/java.desktop/unix/classes/sun/awt/X11/XCanvasPeer.java,3,java,False,2021-10-26T13:33:48Z "public PathConnection[] findRoute(PathNode destination) { if (findConnection(destination) == null) { return new PathConnection[0]; } List route = new ArrayList<>(); PathConnection conn = this.lastTaken; while (conn != null) { route.add(conn); conn = conn.destination.lastTaken; } return route.toArray(new PathConnection[0]); }","public PathConnection[] findRoute(PathNode destination) { if (findConnection(destination) == null) { return new PathConnection[0]; } List route = new ArrayList<>(); PathConnection conn = this.lastTaken; while (conn != null) { route.add(conn); PathNode connDest = conn.destination; conn = connDest.lastTaken; connDest.lastTaken = null; // Avoid infinite loops } return route.toArray(new PathConnection[0]); }",[PathFinding] Guard against infinite loops in route calc,https://github.com/bergerhealer/TrainCarts/commit/a9d0c7f599e2fe2b6b67fee9795ba8bd7c807741,,,src/main/java/com/bergerkiller/bukkit/tc/pathfinding/PathNode.java,3,java,False,2022-10-23T21:06:41Z "public static List listSystemsByPatchStatus(List results, EnumSet patchStatuses) throws UnknownCVEIdentifierException { List ret = new LinkedList<>(); // Group the results by system Map> resultsBySystem = results.stream().collect(Collectors.groupingBy(CVEPatchStatus::getSystemId)); // Loop for each system, calculating the patch status individually for (Map.Entry> systemResultMap : resultsBySystem.entrySet()) { CVEAuditSystemBuilder system = new CVEAuditSystemBuilder(systemResultMap.getKey()); List systemResults = systemResultMap.getValue(); system.setSystemName(systemResults.get(0).getSystemName()); // The relevant channels assigned to the system Set assignedChannels = new HashSet<>(); // Group results for the system further by package names, filtering out 'not-affected' entries Map> resultsByPackage = systemResults.stream().filter(r -> r.getErrataId().isPresent()) .collect(Collectors.groupingBy(r -> r.getPackageName().get())); // When live patching is available, the original kernel packages ('-default' or '-xen') must be ignored. // Keep a list of package names to be ignored. Set livePatchedPackages = resultsByPackage.keySet().stream() .map(p -> Pattern.compile(""^(?:kgraft-patch|kernel-livepatch)-.*-([^-]*)$"").matcher(p)) .filter(Matcher::matches).map(m -> ""kernel-"" + m.group(1)).collect(Collectors.toSet()); // Loop through affected packages one by one for (Map.Entry> packageResults : resultsByPackage.entrySet()) { if (livePatchedPackages.contains(packageResults.getKey())) { // This package is substituted with live patching, ignore it continue; } // Get the result row with the top ranked channel containing the package, // or empty if the package is already patched Optional patchCandidateResult = getPatchCandidateResult(packageResults.getValue()); patchCandidateResult.ifPresent(result -> { // The package is not patched. Keep a list of the missing patch and the top candidate channel ChannelIdNameLabelTriple channel = new ChannelIdNameLabelTriple(result.getChannelId().get(), result.getChannelName(), result.getChannelLabel()); system.addErrata(new ErrataIdAdvisoryPair(result.getErrataId().get(), result.getErrataAdvisory())); system.addChannel(channel); if (result.isChannelAssigned()) { assignedChannels.add(channel); } }); } system.setPatchStatus(getPatchStatus(system.getErratas().isEmpty(), assignedChannels.containsAll(system.getChannels()), !resultsByPackage.isEmpty())); // Check if the patch status is contained in the filter if (patchStatuses.contains(system.getPatchStatus())) { ret.add(system); } } debugLog(ret); return ret; }","private static List listSystemsByPatchStatus(List results, EnumSet patchStatuses) throws UnknownCVEIdentifierException { List ret = new LinkedList<>(); // Group the results by system Map> resultsBySystem = results.stream().collect(Collectors.groupingBy(CVEPatchStatus::getSystemId)); // Loop for each system, calculating the patch status individually for (Map.Entry> systemResultMap : resultsBySystem.entrySet()) { CVEAuditSystemBuilder system = new CVEAuditSystemBuilder(systemResultMap.getKey()); List systemResults = systemResultMap.getValue(); system.setSystemName(systemResults.get(0).getSystemName()); // The relevant channels assigned to the system Set assignedChannels = new HashSet<>(); // Group results for the system further by package names, filtering out 'not-affected' entries Map> resultsByPackage = systemResults.stream().filter(r -> r.getErrataId().isPresent()) .collect(Collectors.groupingBy(r -> r.getPackageName().get())); // When live patching is available, the original kernel packages ('-default' or '-xen') must be ignored. // Keep a list of package names to be ignored. Set livePatchedPackages = resultsByPackage.keySet().stream() .map(p -> Pattern.compile(""^(?:kgraft-patch|kernel-livepatch)-.*-([^-]*)$"").matcher(p)) .filter(Matcher::matches).map(m -> ""kernel-"" + m.group(1)).collect(Collectors.toSet()); AtomicBoolean patchInSuccessorProduct = new AtomicBoolean(false); // Loop through affected packages one by one for (Map.Entry> packageResults : resultsByPackage.entrySet()) { if (livePatchedPackages.contains(packageResults.getKey())) { // This package is substituted with live patching, ignore it continue; } // Get the result row with the top ranked channel containing the package, // or empty if the package is already patched Optional patchCandidateResult = getPatchCandidateResult(packageResults.getValue()); patchCandidateResult.ifPresent(result -> { // The package is not patched. Keep a list of the missing patch and the top candidate channel ChannelIdNameLabelTriple channel = new ChannelIdNameLabelTriple(result.getChannelId().get(), result.getChannelName(), result.getChannelLabel()); system.addErrata(new ErrataIdAdvisoryPair(result.getErrataId().get(), result.getErrataAdvisory())); system.addChannel(channel); if (result.isChannelAssigned()) { assignedChannels.add(channel); } else if (result.getChannelRank().get() >= SUCCESSOR_PRODUCT_RANK_BOUNDARY) { patchInSuccessorProduct.set(true); } }); } system.setPatchStatus(getPatchStatus(system.getErratas().isEmpty(), assignedChannels.containsAll(system.getChannels()), !resultsByPackage.isEmpty(), patchInSuccessorProduct.get())); // Check if the patch status is contained in the filter if (patchStatuses.contains(system.getPatchStatus())) { ret.add(system); } } debugLog(ret); return ret; }","Differentiate prod migration in CVE audit (bsc#1191360) (#16842) * Minor: Unnecessary public method (cherry picked from commit 854488b2fca4b6b7f52086a0d36b3b9d0b1ca290) * Backend: In CVE Audit, recognize Product Migration case, when a system is affected by CVE Previously, this case was reported as a patch being available for cloning from another channel. This does not make sense in case the channel is a SP migration target for given system. Instead of that, Uyuni should suggest the user to migrate the system to a newer SP. (cherry picked from commit 56277ad630e2614f73c3481a887421de19102f15) * Frontend: In CVE Audit, recognize Product Migration case, when a system is affected by CVE (cherry picked from commit 655f9141c326915aebe479c7e8eaa13c0db34d18) * Refactor: Externalize the magic constants for CVE Audit reports (cherry picked from commit 6f1c72018181cce54ce100b9e690238782c94b53) * Make checkstyle happy (cherry picked from commit 238cb517478dade9b2139edd0b81619f554cd54c) * Changelog (cherry picked from commit adc795c6526374f8f3a10defc629caaa450658ba) * Don't offend JS linter (cherry picked from commit 381a35ba10e022e575d722337956b6bddac77ebc) * Fix a lint error, use t() on most of the strings (cherry picked from commit 768eecf12e19e5e536148526bf4f0d74e2814eef) Co-authored-by: Frantisek Kobzik ",https://github.com/uyuni-project/uyuni/commit/d044ccc718ae4b6e6c32cf582801aa45132f2559,,,java/code/src/com/redhat/rhn/manager/audit/CVEAuditManager.java,3,java,False,2022-02-16T19:32:22Z "private void processRows( InputStream anXml, Object[] rowData, IRowMeta rowMeta, boolean ignoreNamespacePrefix, String encoding) throws HopException { // Just to make sure the old pipelines keep working... // if (meta.isCompatible()) { compatibleProcessRows(anXml, rowData, rowMeta, ignoreNamespacePrefix, encoding); return; } // First we should get the complete string // The problem is that the string can contain XML or any other format such as HTML saying the // service is no longer // available. // We're talking about a WEB service here. // As such, to keep the original parsing scheme, we first read the content. // Then we create an input stream from the content again. // It's elaborate, but that way we can report on the failure more correctly. // String response = readStringFromInputStream(anXml, encoding); try { // What is the expected response object for the operation? // DocumentBuilderFactory documentBuilderFactory = XmlParserFactoryProducer.createSecureDocBuilderFactory(); documentBuilderFactory.setNamespaceAware(true); // Overwrite security feature documentBuilderFactory.setFeature( ""http://apache.org/xml/features/disallow-doctype-decl"", false); DocumentBuilder documentBuilder = documentBuilderFactory.newDocumentBuilder(); Document doc = documentBuilder.parse(new InputSource(new StringReader(response))); Node envelopeNode = doc.getFirstChild(); String nsPrefix = envelopeNode.getPrefix(); Node bodyNode = XmlHandler.getSubNode(envelopeNode, nsPrefix + "":Body""); if (bodyNode == null) { XmlHandler.getSubNode(envelopeNode, nsPrefix + "":body""); // retry, just in case! } // Create a few objects to help do the layout of XML snippets we find along the way // Transformer transformer = null; /* * as of BACKLOG-4068, explicit xalan factory references have been deprecated; we use the javax.xml factory * and let java's SPI determine the proper transformer implementation. In addition, tests has been made to * safeguard that existing code continues working as intended */ TransformerFactory transformerFactory = TransformerFactory.newInstance(); transformerFactory.setAttribute(XMLConstants.ACCESS_EXTERNAL_DTD, """"); transformerFactory.setAttribute(XMLConstants.ACCESS_EXTERNAL_STYLESHEET, """"); transformer = transformerFactory.newTransformer(); transformer.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION, ""yes""); transformer.setOutputProperty(OutputKeys.INDENT, ""yes""); if (log.isDetailed()) { StringWriter bodyXML = new StringWriter(); transformer.transform(new DOMSource(bodyNode), new StreamResult(bodyXML)); logDetailed(bodyXML.toString()); } // The node directly below the body is the response node // It's apparently a hassle to get the name in a consistent way, but we know it's the first // element node // Node responseNode = null; NodeList nodeList = null; if (!Utils.isEmpty(meta.getRepeatingElementName())) { // We have specified the repeating element name : use it // nodeList = ((Element) bodyNode).getElementsByTagName(meta.getRepeatingElementName()); } else { if (meta.isReturningReplyAsString()) { // Just return the body node as an XML string... // StringWriter nodeXML = new StringWriter(); transformer.transform(new DOMSource(bodyNode), new StreamResult(nodeXML)); String xml = response; Object[] outputRowData = createNewRow(rowData); int index = rowData == null ? 0 : getInputRowMeta().size(); outputRowData[index++] = xml; putRow(data.outputRowMeta, outputRowData); } else { // We just grab the list of nodes from the children of the body // Look for the first element node (first real child) and take that one. // For that child-element, we consider all the children below // NodeList responseChildren = bodyNode.getChildNodes(); for (int i = 0; i < responseChildren.getLength(); i++) { Node responseChild = responseChildren.item(i); if (responseChild.getNodeType() == Node.ELEMENT_NODE) { responseNode = responseChild; break; } } // See if we want the whole block returned as XML... // if (meta.getFieldsOut().size() == 1) { WebServiceField field = meta.getFieldsOut().get(0); if (field.getWsName().equals(responseNode.getNodeName())) { // Pass the data as XML // StringWriter nodeXML = new StringWriter(); transformer.transform(new DOMSource(responseNode), new StreamResult(nodeXML)); String xml = nodeXML.toString(); Object[] outputRowData = createNewRow(rowData); int index = rowData == null ? 0 : getInputRowMeta().size(); outputRowData[index++] = xml; putRow(data.outputRowMeta, outputRowData); } else { if (responseNode != null) { nodeList = responseNode.getChildNodes(); } } } else { if (responseNode != null) { nodeList = responseNode.getChildNodes(); } } } } // The section below is just for repeating nodes. If we don't have those it ends here. // if (nodeList == null || meta.isReturningReplyAsString()) { return; } // Allocate a result row in case we are dealing with a single result row // Object[] outputRowData = createNewRow(rowData); // Now loop over the node list found above... // boolean singleRow = false; int fieldsFound = 0; for (int i = 0; i < nodeList.getLength(); i++) { Node node = nodeList.item(i); if (meta.isReturningReplyAsString()) { // Just return the body node as an XML string... // StringWriter nodeXML = new StringWriter(); transformer.transform(new DOMSource(bodyNode), new StreamResult(nodeXML)); String xml = nodeXML.toString(); outputRowData = createNewRow(rowData); int index = rowData == null ? 0 : getInputRowMeta().size(); outputRowData[index++] = xml; putRow(data.outputRowMeta, outputRowData); } else { // This node either contains the data for a single row or it contains the first element of // a single result // response // If we find the node name in out output result fields list, we are going to consider it // a single row result. // WebServiceField field = meta.getFieldOutFromWsName(node.getNodeName(), ignoreNamespacePrefix); if (field != null) { if (getNodeValue(outputRowData, node, field, transformer, true)) { // We found a match. // This means that we are dealing with a single row // It also means that we need to update the output index pointer // singleRow = true; fieldsFound++; } } else { // If we didn't already get data in the previous block we'll assume multiple rows coming // back. // if (!singleRow) { // Sticking with the multiple-results scenario... // // TODO: remove next 2 lines, added for debug reasons. // if (log.isDetailed()) { StringWriter nodeXML = new StringWriter(); transformer.transform(new DOMSource(node), new StreamResult(nodeXML)); logDetailed( BaseMessages.getString( PKG, ""WebServices.Log.ResultRowDataFound"", nodeXML.toString())); } // Allocate a new row... // outputRowData = createNewRow(rowData); // Let's see what's in there... // NodeList childNodes = node.getChildNodes(); for (int j = 0; j < childNodes.getLength(); j++) { Node childNode = childNodes.item(j); field = meta.getFieldOutFromWsName(childNode.getNodeName(), ignoreNamespacePrefix); if (field != null) { if (getNodeValue(outputRowData, childNode, field, transformer, false)) { // We found a match. // This means that we are dealing with a single row // It also means that we need to update the output index pointer // fieldsFound++; } } } // Prevent empty rows from being sent out. // if (fieldsFound > 0) { // Send a row in a series of rows on its way. // putRow(data.outputRowMeta, outputRowData); } } } } } if (singleRow && fieldsFound > 0) { // Send the single row on its way. // putRow(data.outputRowMeta, outputRowData); } } catch (Exception e) { throw new HopTransformException( BaseMessages.getString( PKG, ""WebServices.ERROR0010.OutputParsingError"", response.toString()), e); } }","private void processRows( InputStream anXml, Object[] rowData, IRowMeta rowMeta, boolean ignoreNamespacePrefix, String encoding) throws HopException { // Just to make sure the old pipelines keep working... // if (meta.isCompatible()) { compatibleProcessRows(anXml, rowData, rowMeta, ignoreNamespacePrefix, encoding); return; } // First we should get the complete string // The problem is that the string can contain XML or any other format such as HTML saying the // service is no longer // available. // We're talking about a WEB service here. // As such, to keep the original parsing scheme, we first read the content. // Then we create an input stream from the content again. // It's elaborate, but that way we can report on the failure more correctly. // String response = readStringFromInputStream(anXml, encoding); try { // What is the expected response object for the operation? // DocumentBuilderFactory documentBuilderFactory = XmlParserFactoryProducer.createSecureDocBuilderFactory(); documentBuilderFactory.setNamespaceAware(true); // Overwrite security feature documentBuilderFactory.setFeature( ""http://apache.org/xml/features/disallow-doctype-decl"", false); DocumentBuilder documentBuilder = documentBuilderFactory.newDocumentBuilder(); Document doc = documentBuilder.parse(new InputSource(new StringReader(response))); Node envelopeNode = doc.getFirstChild(); String nsPrefix = envelopeNode.getPrefix(); Node bodyNode = XmlHandler.getSubNode(envelopeNode, nsPrefix + "":Body""); if (bodyNode == null) { XmlHandler.getSubNode(envelopeNode, nsPrefix + "":body""); // retry, just in case! } // Create a few objects to help do the layout of XML snippets we find along the way // Transformer transformer = null; /* * as of BACKLOG-4068, explicit xalan factory references have been deprecated; we use the javax.xml factory * and let java's SPI determine the proper transformer implementation. In addition, tests has been made to * safeguard that existing code continues working as intended */ TransformerFactory transformerFactory = XmlHandler.createSecureTransformerFactory(); transformer = transformerFactory.newTransformer(); transformer.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION, ""yes""); transformer.setOutputProperty(OutputKeys.INDENT, ""yes""); if (log.isDetailed()) { StringWriter bodyXML = new StringWriter(); transformer.transform(new DOMSource(bodyNode), new StreamResult(bodyXML)); logDetailed(bodyXML.toString()); } // The node directly below the body is the response node // It's apparently a hassle to get the name in a consistent way, but we know it's the first // element node // Node responseNode = null; NodeList nodeList = null; if (!Utils.isEmpty(meta.getRepeatingElementName())) { // We have specified the repeating element name : use it // nodeList = ((Element) bodyNode).getElementsByTagName(meta.getRepeatingElementName()); } else { if (meta.isReturningReplyAsString()) { // Just return the body node as an XML string... // StringWriter nodeXML = new StringWriter(); transformer.transform(new DOMSource(bodyNode), new StreamResult(nodeXML)); String xml = response; Object[] outputRowData = createNewRow(rowData); int index = rowData == null ? 0 : getInputRowMeta().size(); outputRowData[index++] = xml; putRow(data.outputRowMeta, outputRowData); } else { // We just grab the list of nodes from the children of the body // Look for the first element node (first real child) and take that one. // For that child-element, we consider all the children below // NodeList responseChildren = bodyNode.getChildNodes(); for (int i = 0; i < responseChildren.getLength(); i++) { Node responseChild = responseChildren.item(i); if (responseChild.getNodeType() == Node.ELEMENT_NODE) { responseNode = responseChild; break; } } // See if we want the whole block returned as XML... // if (meta.getFieldsOut().size() == 1) { WebServiceField field = meta.getFieldsOut().get(0); if (field.getWsName().equals(responseNode.getNodeName())) { // Pass the data as XML // StringWriter nodeXML = new StringWriter(); transformer.transform(new DOMSource(responseNode), new StreamResult(nodeXML)); String xml = nodeXML.toString(); Object[] outputRowData = createNewRow(rowData); int index = rowData == null ? 0 : getInputRowMeta().size(); outputRowData[index++] = xml; putRow(data.outputRowMeta, outputRowData); } else { if (responseNode != null) { nodeList = responseNode.getChildNodes(); } } } else { if (responseNode != null) { nodeList = responseNode.getChildNodes(); } } } } // The section below is just for repeating nodes. If we don't have those it ends here. // if (nodeList == null || meta.isReturningReplyAsString()) { return; } // Allocate a result row in case we are dealing with a single result row // Object[] outputRowData = createNewRow(rowData); // Now loop over the node list found above... // boolean singleRow = false; int fieldsFound = 0; for (int i = 0; i < nodeList.getLength(); i++) { Node node = nodeList.item(i); if (meta.isReturningReplyAsString()) { // Just return the body node as an XML string... // StringWriter nodeXML = new StringWriter(); transformer.transform(new DOMSource(bodyNode), new StreamResult(nodeXML)); String xml = nodeXML.toString(); outputRowData = createNewRow(rowData); int index = rowData == null ? 0 : getInputRowMeta().size(); outputRowData[index++] = xml; putRow(data.outputRowMeta, outputRowData); } else { // This node either contains the data for a single row or it contains the first element of // a single result // response // If we find the node name in out output result fields list, we are going to consider it // a single row result. // WebServiceField field = meta.getFieldOutFromWsName(node.getNodeName(), ignoreNamespacePrefix); if (field != null) { if (getNodeValue(outputRowData, node, field, transformer, true)) { // We found a match. // This means that we are dealing with a single row // It also means that we need to update the output index pointer // singleRow = true; fieldsFound++; } } else { // If we didn't already get data in the previous block we'll assume multiple rows coming // back. // if (!singleRow) { // Sticking with the multiple-results scenario... // // TODO: remove next 2 lines, added for debug reasons. // if (log.isDetailed()) { StringWriter nodeXML = new StringWriter(); transformer.transform(new DOMSource(node), new StreamResult(nodeXML)); logDetailed( BaseMessages.getString( PKG, ""WebServices.Log.ResultRowDataFound"", nodeXML.toString())); } // Allocate a new row... // outputRowData = createNewRow(rowData); // Let's see what's in there... // NodeList childNodes = node.getChildNodes(); for (int j = 0; j < childNodes.getLength(); j++) { Node childNode = childNodes.item(j); field = meta.getFieldOutFromWsName(childNode.getNodeName(), ignoreNamespacePrefix); if (field != null) { if (getNodeValue(outputRowData, childNode, field, transformer, false)) { // We found a match. // This means that we are dealing with a single row // It also means that we need to update the output index pointer // fieldsFound++; } } } // Prevent empty rows from being sent out. // if (fieldsFound > 0) { // Send a row in a series of rows on its way. // putRow(data.outputRowMeta, outputRowData); } } } } } if (singleRow && fieldsFound > 0) { // Send the single row on its way. // putRow(data.outputRowMeta, outputRowData); } } catch (Exception e) { throw new HopTransformException( BaseMessages.getString( PKG, ""WebServices.ERROR0010.OutputParsingError"", response.toString()), e); } }",Fix #1859 : Sonar Vulnerability issues,https://github.com/apache/hop/commit/562dc41d7efe4bd7bb43ac0910a8e1e63b2951c1,,,plugins/transforms/webservices/src/main/java/org/apache/hop/pipeline/transforms/webservices/WebService.java,3,java,False,2022-12-01T11:21:34Z "@Override public List getCookies() { final ArrayList returnValue = new ArrayList<>(); for (List cookieList : mCookieMap.values()){ // Use an iterator instead of a foreach to avoid ConcurrentModificationException final Iterator iterator = cookieList.iterator(); while (iterator.hasNext()){ final HttpCookie cookie = iterator.next(); if (cookie.hasExpired()) iterator.remove(); else returnValue.add(cookie); } } return returnValue; }","@Override public List getCookies() { final ArrayList returnValue = new ArrayList<>(); for (List cookieList : mCookieMap.values()){ // Use an iterator instead of a foreach to avoid ConcurrentModificationException final Iterator iterator = cookieList.iterator(); while (iterator.hasNext()){ final HttpCookie cookie = iterator.next(); if (cookie == null || cookie.hasExpired()) // Remove null or expired cookies iterator.remove(); else returnValue.add(cookie); } } return returnValue; }",Fixes a bug where a null cookie can crash the cookie store,https://github.com/genious7/FanFictionReader/commit/5622151bc7d060d426769b46c9d699ba8d85090f,,,fanfictionReader/src/main/java/com/spicymango/fanfictionreader/util/AndroidCookieStore.java,3,java,False,2021-04-27T04:28:23Z "public int getTier(ItemStack testItem, List list) { if (testItem.getItem() instanceof IRadiationSuit) return ((IRadiationSuit) testItem.getItem()).getArmorTier(); for (String line : list) { if (line.substring(0, line.lastIndexOf(':')).equalsIgnoreCase(testItem.getItem().getRegistryName().toString())) return Integer.parseInt(line.substring(line.lastIndexOf(':') + 1)); } return -1; }","public int getTier(ItemStack testItem, List list) { if (testItem.getItem() instanceof IRadiationSuit) return ((IRadiationSuit) testItem.getItem()).getArmorTier(); for (String line : list) { if(line.length() == 0 || !line.contains("":"")) continue; if (line.substring(0, line.lastIndexOf(':')).equalsIgnoreCase(testItem.getItem().getRegistryName().toString())) return Integer.parseInt(line.substring(line.lastIndexOf(':') + 1)); } return -1; }",Fixed possible crash issue when config has blank lines for supported space suit items config option,https://github.com/MJRLegends/ExtraPlanets/commit/afa6bea55bd882c41752291f67e6c197d8c324c3,,,src/main/java/com/mjr/extraplanets/handlers/MainHandlerServer.java,3,java,False,2021-11-22T17:44:46Z "static Timestamp getTimestampFromDate(Date date) { long millis = date.getTime(); return Timestamp.newBuilder().setSeconds(millis / 1000) .setNanos((int) ((millis % 1000) * 1000000)).build(); }","static Timestamp getTimestampFromDate(Date date) { Instant instant = date.toInstant(); return Timestamp.newBuilder() .setSeconds(instant.getEpochSecond()) .setNanos(instant.getNano()) .build(); }","Address security vulnerability CVE-2022-25647 (#199) - Remove dependency on protobuf-java-util, since it has a dependency on gson. - Remove use of gson in code, despite it not being declared as a dependency. Signed-off-by: Mark S. Lewis ",https://github.com/hyperledger/fabric-sdk-java/commit/37169e381ff5c8c30dadc5717afa3f7b9ae95065,,,src/main/java/org/hyperledger/fabric/sdk/transaction/ProtoUtils.java,3,java,False,2022-05-12T10:35:20Z "function validateLink(url) { var BAD_PROTOCOLS = [ 'vbscript', 'javascript', 'file' ]; var str = url.trim().toLowerCase(); // Care about digital entities ""javascript:alert(1)"" str = utils.replaceEntities(str); if (str.indexOf(':') !== -1 && BAD_PROTOCOLS.indexOf(str.split(':')[0]) !== -1) { return false; } return true; }","function validateLink(url) { var BAD_PROTOCOLS = [ 'vbscript', 'javascript', 'file', 'data' ]; var str = url.trim().toLowerCase(); // Care about digital entities ""javascript:alert(1)"" str = utils.replaceEntities(str); if (str.indexOf(':') !== -1 && BAD_PROTOCOLS.indexOf(str.split(':')[0]) !== -1) { return false; } return true; }","Outlaw data: URLs by default See #227. It would still be better to switch to a whitelist but this is an improvement.",https://github.com/jonschlinkert/remarkable/commit/49e24e8f2a431c095ddbb74ecb67cf1cf8f88c47,CVE-2017-16006,['CWE-79'],lib/parser_inline.js,3,js,False,2016-08-20T17:24:38Z "private void dispatchSessionPreappoved() { final IntentSender target = getRemoteStatusReceiver(); final Intent intent = new Intent(); intent.putExtra(PackageInstaller.EXTRA_SESSION_ID, sessionId); intent.putExtra(PackageInstaller.EXTRA_STATUS, PackageInstaller.STATUS_SUCCESS); intent.putExtra(PackageInstaller.EXTRA_PRE_APPROVAL, true); try { target.sendIntent(mContext, 0 /* code */, intent, null /* onFinished */, null /* handler */); } catch (IntentSender.SendIntentException ignored) { } }","private void dispatchSessionPreappoved() { final IntentSender target = getRemoteStatusReceiver(); final Intent intent = new Intent(); intent.putExtra(PackageInstaller.EXTRA_SESSION_ID, sessionId); intent.putExtra(PackageInstaller.EXTRA_STATUS, PackageInstaller.STATUS_SUCCESS); intent.putExtra(PackageInstaller.EXTRA_PRE_APPROVAL, true); try { final BroadcastOptions options = BroadcastOptions.makeBasic(); options.setPendingIntentBackgroundActivityLaunchAllowed(false); target.sendIntent(mContext, 0 /* code */, intent, null /* onFinished */, null /* handler */, null /* requiredPermission */, options.toBundle()); } catch (IntentSender.SendIntentException ignored) { } }","Fix bypass BG-FGS and BAL via package manager APIs Opt-in for BAL of PendingIntent for following APIs: * PackageInstaller.uninstall() * PackageInstaller.installExistingPackage() * PackageInstaller.uninstallExistingPackage() * PackageInstaller.waitForInstallConstraints() * PackageInstaller.Session.commit() * PackageInstaller.Session.commitTransferred() * PackageInstaller.Session.requestUserPreapproval() * PackageManager.freeStorage() Bug: 230492955 Bug: 243377226 Test: atest android.security.cts.PackageInstallerTest Test: atest CtsStagedInstallHostTestCases Change-Id: I9b6f801d69ea6d2244a38dbe689e81afa4e798bf",https://github.com/PixelExperience/frameworks_base/commit/2be553067f56f21c0cf599ffa6b1ff24052a12fd,,,services/core/java/com/android/server/pm/PackageInstallerSession.java,3,java,False,2023-01-11T08:02:27Z "public String configureLink(String url, AvatarFormat format) { return url + (url.endsWith(""?"") ? ""&"" : ""?"") + ""s="" + format.getSize() + ""&r=g&d="" + config.gravatarPattern(); }","public String configureLink(String url, AvatarFormat format) { return url + (url.endsWith(""?"") ? ""&"" : ""?"") + ""s="" + format.getSize() + ""&r=g&d="" + ScooldUtils.gravatarPattern(); }","added ImgurAvatarRepository, removed support for adding insecure custom avatar links",https://github.com/Erudika/scoold/commit/78f60b679d20a48f98ced178b9d93206e02c2637,,,src/main/java/com/erudika/scoold/utils/avatars/GravatarAvatarGenerator.java,3,java,False,2022-01-19T16:36:35Z "@Override public void fetchDevices( @NonNull Consumer> onSuccess, @NonNull Consumer onException ) { awsMobileClient.getDeviceOperations().list(new Callback() { @Override public void onResult(ListDevicesResult result) { List devices = new ArrayList<>(); for (Device device : result.getDevices()) { devices.add(AuthDevice.fromId(device.getDeviceKey())); } onSuccess.accept(devices); } @Override public void onError(Exception exception) { onException.accept(new AuthException( ""An error occurred while fetching remembered devices."", exception, ""See attached exception for more details"" )); } }); }","@Override public void fetchDevices( @NonNull Consumer> onSuccess, @NonNull Consumer onException ) { awsMobileClient.getDeviceOperations().list(new Callback() { @Override public void onResult(ListDevicesResult result) { List devices = new ArrayList<>(); for (Device device : result.getDevices()) { devices.add(AuthDevice.fromId(device.getDeviceKey())); } onSuccess.accept(devices); } @Override public void onError(Exception exception) { onException.accept(CognitoAuthExceptionConverter.lookup( exception, ""Fetching devices failed."")); } }); }","fix(auth): throw correct auth exception for code mismatch (#1370) * fix(auth): #1102 throw correct auth exception for code mismatch * Add multifactor not found auth exception with detailed messaging * Update aws-auth-cognito/src/main/java/com/amplifyframework/auth/cognito/util/CognitoAuthExceptionConverter.java Co-authored-by: Chang Xu <42978935+changxu0306@users.noreply.github.com> * move to fit import rule * float all generic errors to exception mapper * add software token mfa exception * add more missing exceptions * reorder imports as per checkstyle * Update core/src/main/java/com/amplifyframework/auth/AuthException.java Co-authored-by: Chang Xu <42978935+changxu0306@users.noreply.github.com> * Update core/src/main/java/com/amplifyframework/auth/AuthException.java Co-authored-by: Chang Xu <42978935+changxu0306@users.noreply.github.com> * fix documentation description * fix checkstyle errors Co-authored-by: Chang Xu <42978935+changxu0306@users.noreply.github.com>",https://github.com/aws-amplify/amplify-android/commit/4cd7cfee41bac3635974149b4ca6dd269e0cc19b,,,aws-auth-cognito/src/main/java/com/amplifyframework/auth/cognito/AWSCognitoAuthPlugin.java,3,java,False,2021-06-11T21:51:07Z "private void updateTransHashCache(BlockCapsule block) { for (TransactionCapsule transactionCapsule : block.getTransactions()) { this.transactionIdCache.put(transactionCapsule.getTransactionId(), true); } }","private void updateTransHashCache(BlockCapsule block) { for (TransactionCapsule transactionCapsule : block.getTransactions()) { this.transactionIdCache.put(transactionCapsule.getTransactionId(), true); if (chainBaseManager.getDynamicPropertiesStore().getLatestBlockHeaderNumber() >= CommonParameter.getInstance().getEthCompatibleRlpDeDupEffectBlockNum()) { Sha256Hash ethRawDataHash = transactionCapsule.getEthRawDataHash(); if (ethRawDataHash != null) { this.rlpDataCache.put(ethRawDataHash, true); } } } }","Bugfix/20220108/ethereum compatible replayattack (#107) * add eth RlpDataCache * change * update eth RlpDataCache * update eth RlpDataCache * update version Ultima-v1.1.0 * update version Ultima-v1.0.2 * add rlpDataCache on updateTransHashCache function Co-authored-by: theway001 ",https://github.com/vision-consensus/vision-core/commit/8772c9c6ca346b9305cad8d01d9f36d5fcb36ed0,,,framework/src/main/java/org/vision/core/db/Manager.java,3,java,False,2022-01-09T05:44:18Z "@SuppressWarnings(""InfiniteLoopStatement"") public void build(Map> allFeatures) throws Exception { doBuild(allFeatures, true); }","@SuppressWarnings(""InfiniteLoopStatement"") public void build(Map> allFeatures) throws Exception { Map> cleaned = new LinkedHashMap<>(); for (Map.Entry> entry : allFeatures.entrySet()) { if (entry.getValue().size() > 1) { Map versionMap = new LinkedHashMap<>(); for (Feature feature : entry.getValue()) { if (!versionMap.containsKey(feature.getVersion())) { versionMap.put(feature.getVersion(), feature); } else { // warn about duplicate } } cleaned.put(entry.getKey(), new ArrayList<>(versionMap.values())); } else { cleaned.put(entry.getKey(), entry.getValue()); } } doBuild(cleaned, true); }","KARAF-7522 Fix stack overflow error with duplicate features. Signed-off-by: Łukasz Dywicki ",https://github.com/apache/karaf/commit/d157694a33dd15f4fb31ddf8079e2849451990a1,,,features/core/src/main/java/org/apache/karaf/features/internal/region/Subsystem.java,3,java,False,2022-07-22T14:44:10Z "@Override public ParcelFileDescriptor setWallpaper(String name, String callingPackage, Rect cropHint, boolean allowBackup, Bundle extras, int which, IWallpaperManagerCallback completion, int userId) { userId = ActivityManager.handleIncomingUser(getCallingPid(), getCallingUid(), userId, false /* all */, true /* full */, ""changing wallpaper"", null /* pkg */); checkPermission(android.Manifest.permission.SET_WALLPAPER); if ((which & (FLAG_LOCK|FLAG_SYSTEM)) == 0) { final String msg = ""Must specify a valid wallpaper category to set""; Slog.e(TAG, msg); throw new IllegalArgumentException(msg); } if (!isWallpaperSupported(callingPackage) || !isSetWallpaperAllowed(callingPackage)) { return null; } // ""null"" means the no-op crop, preserving the full input image if (cropHint == null) { cropHint = new Rect(0, 0, 0, 0); } else { if (cropHint.width() < 0 || cropHint.height() < 0 || cropHint.left < 0 || cropHint.top < 0) { throw new IllegalArgumentException(""Invalid crop rect supplied: "" + cropHint); } } synchronized (mLock) { if (DEBUG) Slog.v(TAG, ""setWallpaper which=0x"" + Integer.toHexString(which)); WallpaperData wallpaper; /* If we're setting system but not lock, and lock is currently sharing the system * wallpaper, we need to migrate that image over to being lock-only before * the caller here writes new bitmap data. */ if (which == FLAG_SYSTEM && mLockWallpaperMap.get(userId) == null) { Slog.i(TAG, ""Migrating current wallpaper to be lock-only before"" + ""updating system wallpaper""); migrateSystemToLockWallpaperLocked(userId); } wallpaper = getWallpaperSafeLocked(userId, which); final long ident = Binder.clearCallingIdentity(); try { ParcelFileDescriptor pfd = updateWallpaperBitmapLocked(name, wallpaper, extras); if (pfd != null) { wallpaper.imageWallpaperPending = true; wallpaper.whichPending = which; wallpaper.setComplete = completion; wallpaper.cropHint.set(cropHint); wallpaper.allowBackup = allowBackup; } return pfd; } finally { Binder.restoreCallingIdentity(ident); } } }","@Override public ParcelFileDescriptor setWallpaper(String name, String callingPackage, Rect cropHint, boolean allowBackup, Bundle extras, int which, IWallpaperManagerCallback completion, int userId) { userId = ActivityManager.handleIncomingUser(getCallingPid(), getCallingUid(), userId, false /* all */, true /* full */, ""changing wallpaper"", null /* pkg */); checkPermission(android.Manifest.permission.SET_WALLPAPER); if ((which & (FLAG_LOCK|FLAG_SYSTEM)) == 0) { final String msg = ""Must specify a valid wallpaper category to set""; Slog.e(TAG, msg); throw new IllegalArgumentException(msg); } if (!isWallpaperSupported(callingPackage) || !isSetWallpaperAllowed(callingPackage)) { return null; } // ""null"" means the no-op crop, preserving the full input image if (cropHint == null) { cropHint = new Rect(0, 0, 0, 0); } else { if (cropHint.width() < 0 || cropHint.height() < 0 || cropHint.left < 0 || cropHint.top < 0) { throw new IllegalArgumentException(""Invalid crop rect supplied: "" + cropHint); } } final boolean fromForegroundApp = Binder.withCleanCallingIdentity(() -> mActivityManager.getPackageImportance(callingPackage) == IMPORTANCE_FOREGROUND); synchronized (mLock) { if (DEBUG) Slog.v(TAG, ""setWallpaper which=0x"" + Integer.toHexString(which)); WallpaperData wallpaper; /* If we're setting system but not lock, and lock is currently sharing the system * wallpaper, we need to migrate that image over to being lock-only before * the caller here writes new bitmap data. */ if (which == FLAG_SYSTEM && mLockWallpaperMap.get(userId) == null) { Slog.i(TAG, ""Migrating current wallpaper to be lock-only before"" + ""updating system wallpaper""); migrateSystemToLockWallpaperLocked(userId); } wallpaper = getWallpaperSafeLocked(userId, which); final long ident = Binder.clearCallingIdentity(); try { ParcelFileDescriptor pfd = updateWallpaperBitmapLocked(name, wallpaper, extras); if (pfd != null) { wallpaper.imageWallpaperPending = true; wallpaper.whichPending = which; wallpaper.setComplete = completion; wallpaper.fromForegroundApp = fromForegroundApp; wallpaper.cropHint.set(cropHint); wallpaper.allowBackup = allowBackup; } return pfd; } finally { Binder.restoreCallingIdentity(ident); } } }","Don't allow background apps to change theme A background app that changes the wallpaper, was able to change the device theme. This change will apply the theme if the app is on the foreground, like WallpaperPicker would be, but would defer the event until the next power button cycles, like we do with Live Wallpapers, to avoid the same type of DoS. Test: manual Test: atest ThemeOverlayControllerTest Fixes: 205140487 Change-Id: I2086b29ef9bf3bb6fb7d9ebba6e7b8db9392e459",https://github.com/omnirom/android_frameworks_base/commit/04d4c04019652593fbc13eda569dce8200792942,,,services/core/java/com/android/server/wallpaper/WallpaperManagerService.java,3,java,False,2021-11-06T00:30:49Z "function hostChecked(box) { var cid = parseInt(box.id.replace(""host_ids_"", """")); if (box.checked) addHostId(cid); else rmHostId(cid); $.cookie($.cookieName, JSON.stringify($.foremanSelectedHosts)); toggle_actions(); update_counter(); return false; }","function hostChecked(box) { var cid = parseInt(box.id.replace(""host_ids_"", """")); if (box.checked) addHostId(cid); else rmHostId(cid); $.cookie($.cookieName, JSON.stringify($.foremanSelectedHosts), { secure: location.protocol === 'https:' }); toggle_actions(); update_counter(); return false; }",fixes #10275 - Add secure cookie when in ssl,https://github.com/theforeman/foreman/commit/599385a1642cddd079b0a6ca10c87d707c8c4eb0,CVE-2015-3155,['CWE-284'],app/assets/javascripts/host_checkbox.js,3,js,False,2015-05-11T18:12:22Z "private void clientSetup(final FMLClientSetupEvent event) { DistExecutor.unsafeRunWhenOn(Dist.CLIENT, () -> InfernalExpansionClient::init); }","private void clientSetup(final FMLClientSetupEvent event) { event.enqueueWork(() -> DistExecutor.unsafeRunWhenOn(Dist.CLIENT, () -> InfernalExpansionClient::init)); }","InfernalExpansionClient#init is now thread safe - Made InfernalExpansionClient#init thread safe by using ParallelDispatchEvent#enqueueWork - This should fix crashes caused by ConcurrentModificationException in item properties lambdas",https://github.com/infernalstudios/Infernal-Expansion/commit/628dff80bff21654daea93a1de15a40b7e3c8037,,,src/main/java/org/infernalstudios/infernalexp/InfernalExpansion.java,3,java,False,2022-06-10T01:08:31Z "@VisibleForTesting void onSystemServicesReady() { mInjector.getLockSettingsService().setRebootEscrowListener(this); }","@VisibleForTesting void onSystemServicesReady() { LockSettingsInternal lockSettings = mInjector.getLockSettingsService(); if (lockSettings == null) { Slog.e(TAG, ""Failed to get lock settings service, skipping set"" + "" RebootEscrowListener""); return; } lockSettings.setRebootEscrowListener(this); }","Check null for before using LockSettingsService If the locksettings service fails to start, the resume on reboot APIs will throw a nullptr exception in RecoverySystemService. Add some check to prevent crashing the system server. Bug: 184596745 Test: build Change-Id: I5b1781612ec8d855d94b2828b5b5cfee9a84aebe",https://github.com/omnirom/android_frameworks_base/commit/31b3cbf029ac96066e096328aff6902b29e5df62,,,services/core/java/com/android/server/recoverysystem/RecoverySystemService.java,3,java,False,2021-04-13T18:04:36Z "@Subscribe public void handleResumedRunningEvent(final VMResumedRunningEvent event) { if (copyJob != null) { try { copyJob.get(); } catch (final Throwable e) { LOGGER.error(e); } finally { copyJob = null; } } }","@Subscribe public void handleResumedRunningEvent(final VMResumedRunningEvent event) { joinCopyJob(); }",Fixed potential crash when computer stops immediately while still initializing disk from image.,https://github.com/fnuecke/oc2/commit/1e59043b01b78960eb7114cdb85597647931ff40,,,src/main/java/li/cil/oc2/common/bus/device/item/HardDriveVMDeviceWithInitialData.java,3,java,False,2022-01-09T08:13:05Z "public boolean isDataSaverDisabled() { if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) { ConnectivityManager connectivityManager = (ConnectivityManager) getSystemService(CONNECTIVITY_SERVICE); return !connectivityManager.isActiveNetworkMetered() || connectivityManager.getRestrictBackgroundStatus() == ConnectivityManager.RESTRICT_BACKGROUND_STATUS_DISABLED; } else { return true; } }","public boolean isDataSaverDisabled() { if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) { final ConnectivityManager connectivityManager = (ConnectivityManager) getSystemService(CONNECTIVITY_SERVICE); return !connectivityManager.isActiveNetworkMetered() || Compatibility.getRestrictBackgroundStatus(connectivityManager) == ConnectivityManager.RESTRICT_BACKGROUND_STATUS_DISABLED; } else { return true; } }",fix crash in buggy connection manager. fixes #4368,https://github.com/snikket-im/snikket-android/commit/eb49a7f5e57a627b5c4217e6848fc9135db2236a,,,src/main/java/eu/siacs/conversations/services/XmppConnectionService.java,3,java,False,2022-09-03T10:33:27Z "@Override public void onReceive(Context context, Intent intent) { boolean newWorkProfile = Intent.ACTION_MANAGED_PROFILE_ADDED.equals(intent.getAction()); boolean userStarted = Intent.ACTION_USER_SWITCHED.equals(intent.getAction()); boolean isManagedProfile = mUserManager.isManagedProfile( intent.getIntExtra(Intent.EXTRA_USER_HANDLE, 0)); if (userStarted || newWorkProfile) { if (!mDeviceProvisionedController.isCurrentUserSetup() && isManagedProfile) { Log.i(TAG, ""User setup not finished when "" + intent.getAction() + "" was received. Deferring... Managed profile? "" + isManagedProfile); return; } if (DEBUG) Log.d(TAG, ""Updating overlays for user switch / profile added.""); reevaluateSystemTheme(true /* forceReload */); } else if (Intent.ACTION_WALLPAPER_CHANGED.equals(intent.getAction())) { mAcceptColorEvents = true; Log.i(TAG, ""Allowing color events again""); } }","@Override public void onReceive(Context context, Intent intent) { boolean newWorkProfile = Intent.ACTION_MANAGED_PROFILE_ADDED.equals(intent.getAction()); boolean userStarted = Intent.ACTION_USER_SWITCHED.equals(intent.getAction()); boolean isManagedProfile = mUserManager.isManagedProfile( intent.getIntExtra(Intent.EXTRA_USER_HANDLE, 0)); if (userStarted || newWorkProfile) { if (!mDeviceProvisionedController.isCurrentUserSetup() && isManagedProfile) { Log.i(TAG, ""User setup not finished when "" + intent.getAction() + "" was received. Deferring... Managed profile? "" + isManagedProfile); return; } if (DEBUG) Log.d(TAG, ""Updating overlays for user switch / profile added.""); reevaluateSystemTheme(true /* forceReload */); } else if (Intent.ACTION_WALLPAPER_CHANGED.equals(intent.getAction())) { if (intent.getBooleanExtra(WallpaperManager.EXTRA_FROM_FOREGROUND_APP, false)) { mAcceptColorEvents = true; Log.i(TAG, ""Wallpaper changed, allowing color events again""); } else { Log.i(TAG, ""Wallpaper changed from background app, "" + ""keep deferring color events. Accepting: "" + mAcceptColorEvents); } } }","Don't allow background apps to change theme A background app that changes the wallpaper, was able to change the device theme. This change will apply the theme if the app is on the foreground, like WallpaperPicker would be, but would defer the event until the next power button cycles, like we do with Live Wallpapers, to avoid the same type of DoS. Test: manual Test: atest ThemeOverlayControllerTest Fixes: 205140487 Change-Id: I2086b29ef9bf3bb6fb7d9ebba6e7b8db9392e459",https://github.com/omnirom/android_frameworks_base/commit/04d4c04019652593fbc13eda569dce8200792942,,,packages/SystemUI/src/com/android/systemui/theme/ThemeOverlayController.java,3,java,False,2021-11-06T00:30:49Z "private static byte[] receiveMessage(final FileDescriptor fd) throws ErrnoException, InterruptedIOException, EOFException { final byte[] lengthBits = new byte[4]; readFully(fd, lengthBits, 0, lengthBits.length); final ByteBuffer bb = ByteBuffer.wrap(lengthBits); bb.order(ByteOrder.LITTLE_ENDIAN); final int msgLen = bb.getInt(); final byte[] msg = new byte[msgLen]; readFully(fd, msg, 0, msg.length); return msg; }","private byte[] receiveMessage(final FileDescriptor fd) throws ErrnoException, InterruptedIOException, EOFException, ProtocolException { final byte[] lengthBits = new byte[4]; readFully(fd, lengthBits, 0, lengthBits.length); final ByteBuffer bb = ByteBuffer.wrap(lengthBits); bb.order(ByteOrder.LITTLE_ENDIAN); final int msgLen = bb.getInt(); if (msgLen <= 0 || msgLen > MAX_CLIPBOARD_BYTES) { throw new ProtocolException(""Clipboard message length: "" + msgLen + "" out of bounds.""); } final byte[] msg = new byte[msgLen]; readFully(fd, msg, 0, msg.length); return msg; }","Emulator: handle OOM and Protocol error cases - OutOfMemoryError can happen naturally if the size of the clipboard is too large to allocate. We should prefer to drop the clipboard data if we have a choice between that and crashing the system server. - OutOfMemoryError can happen unnatturally if the protocol gets out of sync with the host. This can happen quite easily if there is a caught exception and the clipboard monitor tries to keep on trucking, since the protocol doesn't have any built in synchronisation to catch back up to the start of the next message again. The only option to prevent that at the moment is to just close the pipe and reopen it in case of failure to understand something. Bug: 231340598 Test: presubmit Change-Id: Icceb8ec8b3988c32a2eb5f5598a43753460fc26b",https://github.com/aosp-mirror/platform_frameworks_base/commit/e5b03a179a33c5806efd34d45dc01a0200194f80,,,services/core/java/com/android/server/clipboard/EmulatorClipboardMonitor.java,3,java,False,2022-05-18T08:00:45Z "public void enablePreemptiveAuthentication(String hostname, int httpPort, int httpsPort, Charset credentialsCharset) { AuthCache cache = this.context.getAuthCache(); if (cache == null) { // Add AuthCache to the execution context cache = new BasicAuthCache(); this.context.setAuthCache(cache); } // Generate Basic preemptive scheme object and stick it to the local execution context BasicScheme basicAuth = new BasicScheme(credentialsCharset); // Configure HttpClient to authenticate preemptively by prepopulating the authentication data cache. cache.put(new HttpHost(hostname, httpPort, ""http""), basicAuth); cache.put(new HttpHost(hostname, httpsPort, ""https""), basicAuth); }","public void enablePreemptiveAuthentication(String hostname, int httpPort, int httpsPort, Charset credentialsCharset) { AuthCache cache = this.context.getAuthCache(); if (cache == null) { // Add AuthCache to the execution context cache = new BasicAuthCache(); this.context.setAuthCache(cache); } // Generate Basic preemptive scheme object and stick it to the local execution context BasicScheme basicAuth = new BasicScheme(credentialsCharset); // Configure HttpClient to authenticate preemptively by prepopulating the authentication data cache. cache.put(new HttpHost(hostname, httpPort == -1 ? 80 : httpPort, ""http""), basicAuth); cache.put(new HttpHost(hostname, httpsPort == -1 ? 443 : httpsPort, ""https""), basicAuth); }","Fix preemptive authentication without explicit port (#285) In SardineImpl.enablePreemptiveAuthentication(String, int, int, Charset), do not pass -1 to the HttpHost constructor. The later cache lookup is always done with an explicit port, so port -1 never matches and the entry does nothing. Instead, we need to use the default port explicitly, then it will work, even when connecting with a URL that does not include the port. Since the other overloads delegate to this one, this fixes all overloads to do the right thing, in particular, the enablePreemptiveAuthentication(String) (hostname-only) and enablePreemptiveAuthentication(URL) (when using a URL without an explicit port) ones. Fixes #285.",https://github.com/lookfirst/sardine/commit/f76b2db050a3b4b8ae30b2f284be3ff84dc94187,,,src/main/java/com/github/sardine/impl/SardineImpl.java,3,java,False,2022-07-19T15:24:05Z "private void writeToSortedFiles() throws IOException { Stopwatch w = Stopwatch.createStarted(); for (NodeStateEntry e : nodeStates) { if (e.getLastModified() >= lastModifiedUpperBound) { break; } entryCount++; addEntry(e); } //Save the last batch sortAndSaveBatch(); reset(); //Free up the batch entryBatch.clear(); entryBatch.trimToSize(); log.info(""{} Dumped {} nodestates in json format in {}"",taskID, entryCount, w); log.info(""{} Created {} sorted files of size {} to merge"", taskID, sortedFiles.size(), humanReadableByteCount(sizeOf(sortedFiles))); }","private void writeToSortedFiles() throws IOException { Stopwatch w = Stopwatch.createStarted(); for (NodeStateEntry e : nodeStates) { if (e.getLastModified() >= lastModifiedUpperBound) { break; } entryCount++; addEntry(e); } //Save the last batch sortAndSaveBatch(); reset(); log.info(""{} Dumped {} nodestates in json format in {}"",taskID, entryCount, w); log.info(""{} Created {} sorted files of size {} to merge"", taskID, sortedFiles.size(), humanReadableByteCount(sizeOf(sortedFiles))); }","OAK-9576: Multithreaded download synchronization issues (#383) * OAK-9576 - Multithreaded download synchronization issues * Fixing a problem with test * OAK-9576: Multithreaded download synchronization issues * Fixing synchronization issues * Fixing OOM issue * Adding delay between download retries * OAK-9576: Multithreaded download synchronization issues * Using linkedlist in tasks for freeing memory early * Dumping if data is greater than one MB * OAK-9576: Multithreaded download synchronization issues * Closing node state entry traversors using try with * trivial - removing unused object * OAK-9576: Multithreaded download synchronization issues * Incorporating some feedback from review comments * OAK-9576: Multithreaded download synchronization issues * Replacing explicit synchronization with atomic operations * OAK-9576: Multithreaded download synchronization issues * Using same memory manager across retries * trivial - removing unwanted method * OAK-9576: Multithreaded download synchronization issues * Moving retry delay to exception block * trivial - correcting variable name Co-authored-by: amrverma ",https://github.com/apache/jackrabbit-oak/commit/c04aff5d970beccd41ff15c1c907f7ea6d0720fb,,,oak-run-commons/src/main/java/org/apache/jackrabbit/oak/index/indexer/document/flatfile/TraverseAndSortTask.java,3,java,False,2021-12-01T07:03:04Z "async def on_POST(self, request, group_id): requester = await self.auth.get_user_by_req(request) requester_user_id = requester.user.to_string() content = parse_json_object_from_request(request) await self.groups_handler.update_group_profile( group_id, requester_user_id, content ) return 200, {}","async def on_POST(self, request, group_id): requester = await self.auth.get_user_by_req(request) requester_user_id = requester.user.to_string() content = parse_json_object_from_request(request) assert_params_in_dict( content, (""name"", ""avatar_url"", ""short_description"", ""long_description"") ) await self.groups_handler.update_group_profile( group_id, requester_user_id, content ) return 200, {}",Improve some validation of profile data.,https://github.com/matrix-org/synapse/commit/dd2a8fb441ec5d572f8687b5c617522138afb05f,,,synapse/rest/client/v2_alpha/groups.py,3,py,False,2021-02-04T14:47:39Z "@ModifyVariable(method = ""renderModel"", at = @At(value = ""HEAD""), ordinal = 0) private BakedModel modifyBakedModel(BakedModel bakedModel) { BlockModelRendererContext context = ommcRenderContext.get(); Block block = context.state.getBlock(); if (CustomBakedModels.shouldUseCustomModel(block, context.pos)) { return CustomBakedModels.models.get(block); } else { return bakedModel; } }","@ModifyVariable(method = ""renderModel"", at = @At(value = ""HEAD""), ordinal = 0) private BakedModel modifyBakedModel(BakedModel bakedModel) { BlockModelRendererContext context = ommcRenderContext.get(); Block block = context.state.getBlock(); if (CustomBakedModels.shouldUseCustomModel(block, context.pos)) { BakedModel customModel = CustomBakedModels.models.get(block); if (customModel != null) { return CustomBakedModels.models.get(block); } else { return bakedModel; } } else { return bakedModel; } }",fix null ptr crash in worldEaterMineHelper,https://github.com/plusls/oh-my-minecraft-client/commit/63ec4ab105bc581dd1b669b2352b13e070875991,,,src/main/java/com/plusls/ommc/mixin/feature/worldEaterMineHelper/sodium/MixinBlockRenderer.java,3,java,False,2021-03-13T15:45:05Z "private void addAttributes(StringBuilder buf, String...excludedKeys) { Set> entries = graphObject.entrySet(); for (Map.Entry entry : entries) { String key = entry.getKey(); if (ArrayUtils.contains(excludedKeys, key)) { continue; // skip keys handled in header } buf.append(key); buf.append("": ""); String value = entry.getValue(); value = StringEscapeUtils.escapeHtml4(value); String split = String.join(""
"", Splitter.on('\n').split(value)); split = split.replaceAll(""\\s"", "" ""); buf.append(split); buf.append(""
""); } }","private void addAttributes(StringBuilder buf, String...excludedKeys) { Set> entries = graphObject.entrySet(); for (Map.Entry entry : entries) { String key = entry.getKey(); if (ArrayUtils.contains(excludedKeys, key)) { continue; // skip keys handled in header } buf.append(key); buf.append("": ""); String escapedText = HTMLUtilities.toLiteralHTML(entry.getValue(), 80); String split = String.join(""
"", Splitter.on('\n').split(escapedText)); split = split.replaceAll(""\\s"", "" ""); buf.append(split); buf.append(""
""); } }",Merge remote-tracking branch 'origin/GP-2707_dev747368_string_translation_toggle_on_char_arrays' into Ghidra_10.2,https://github.com/NationalSecurityAgency/ghidra/commit/ad6afeaaeb0d47eeb2a81b7925b0686ef186fe12,,,Ghidra/Features/GraphServices/src/main/java/ghidra/graph/visualization/AttributedToolTipInfo.java,3,java,False,2022-10-18T17:47:55Z "@Override public void init(Context context, IWindowManager windowManager, WindowManagerFuncs windowManagerFuncs) { mContext = context; mWindowManager = windowManager; mWindowManagerFuncs = windowManagerFuncs; mWindowManagerInternal = LocalServices.getService(WindowManagerInternal.class); mActivityManagerInternal = LocalServices.getService(ActivityManagerInternal.class); mActivityTaskManagerInternal = LocalServices.getService(ActivityTaskManagerInternal.class); mInputManagerInternal = LocalServices.getService(InputManagerInternal.class); mDreamManagerInternal = LocalServices.getService(DreamManagerInternal.class); mPowerManagerInternal = LocalServices.getService(PowerManagerInternal.class); mAppOpsManager = mContext.getSystemService(AppOpsManager.class); mDisplayManager = mContext.getSystemService(DisplayManager.class); mDisplayManagerInternal = LocalServices.getService(DisplayManagerInternal.class); mPackageManager = mContext.getPackageManager(); mHasFeatureWatch = mPackageManager.hasSystemFeature(FEATURE_WATCH); mHasFeatureLeanback = mPackageManager.hasSystemFeature(FEATURE_LEANBACK); mHasFeatureAuto = mPackageManager.hasSystemFeature(FEATURE_AUTOMOTIVE); mHasFeatureHdmiCec = mPackageManager.hasSystemFeature(FEATURE_HDMI_CEC); mAccessibilityShortcutController = new AccessibilityShortcutController(mContext, new Handler(), mCurrentUserId); mLogger = new MetricsLogger(); mScreenOffSleepTokenAcquirer = mActivityTaskManagerInternal .createSleepTokenAcquirer(""ScreenOff""); Resources res = mContext.getResources(); mWakeOnDpadKeyPress = res.getBoolean(com.android.internal.R.bool.config_wakeOnDpadKeyPress); mWakeOnAssistKeyPress = res.getBoolean(com.android.internal.R.bool.config_wakeOnAssistKeyPress); mWakeOnBackKeyPress = res.getBoolean(com.android.internal.R.bool.config_wakeOnBackKeyPress); // Init alert slider mHasAlertSlider = mContext.getResources().getBoolean(R.bool.config_hasAlertSlider) && !TextUtils.isEmpty(mContext.getResources().getString(R.string.alert_slider_state_path)) && !TextUtils.isEmpty(mContext.getResources().getString(R.string.alert_slider_uevent_match_path)); // Init display burn-in protection boolean burnInProtectionEnabled = context.getResources().getBoolean( com.android.internal.R.bool.config_enableBurnInProtection); // Allow a system property to override this. Used by developer settings. boolean burnInProtectionDevMode = SystemProperties.getBoolean(""persist.debug.force_burn_in"", false); if (burnInProtectionEnabled || burnInProtectionDevMode) { final int minHorizontal; final int maxHorizontal; final int minVertical; final int maxVertical; final int maxRadius; if (burnInProtectionDevMode) { minHorizontal = -8; maxHorizontal = 8; minVertical = -8; maxVertical = -4; maxRadius = (isRoundWindow()) ? 6 : -1; } else { Resources resources = context.getResources(); minHorizontal = resources.getInteger( com.android.internal.R.integer.config_burnInProtectionMinHorizontalOffset); maxHorizontal = resources.getInteger( com.android.internal.R.integer.config_burnInProtectionMaxHorizontalOffset); minVertical = resources.getInteger( com.android.internal.R.integer.config_burnInProtectionMinVerticalOffset); maxVertical = resources.getInteger( com.android.internal.R.integer.config_burnInProtectionMaxVerticalOffset); maxRadius = resources.getInteger( com.android.internal.R.integer.config_burnInProtectionMaxRadius); } mBurnInProtectionHelper = new BurnInProtectionHelper( context, minHorizontal, maxHorizontal, minVertical, maxVertical, maxRadius); } mHandler = new PolicyHandler(); mWakeGestureListener = new MyWakeGestureListener(mContext, mHandler); mSettingsObserver = new SettingsObserver(mHandler); mSettingsObserver.observe(); mModifierShortcutManager = new ModifierShortcutManager(context); mUiMode = context.getResources().getInteger( com.android.internal.R.integer.config_defaultUiModeType); mHomeIntent = new Intent(Intent.ACTION_MAIN, null); mHomeIntent.addCategory(Intent.CATEGORY_HOME); mHomeIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_RESET_TASK_IF_NEEDED); mEnableCarDockHomeCapture = context.getResources().getBoolean( com.android.internal.R.bool.config_enableCarDockHomeLaunch); mCarDockIntent = new Intent(Intent.ACTION_MAIN, null); mCarDockIntent.addCategory(Intent.CATEGORY_CAR_DOCK); mCarDockIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_RESET_TASK_IF_NEEDED); mDeskDockIntent = new Intent(Intent.ACTION_MAIN, null); mDeskDockIntent.addCategory(Intent.CATEGORY_DESK_DOCK); mDeskDockIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_RESET_TASK_IF_NEEDED); mVrHeadsetHomeIntent = new Intent(Intent.ACTION_MAIN, null); mVrHeadsetHomeIntent.addCategory(Intent.CATEGORY_VR_HOME); mVrHeadsetHomeIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_RESET_TASK_IF_NEEDED); mPowerManager = (PowerManager)context.getSystemService(Context.POWER_SERVICE); mBroadcastWakeLock = mPowerManager.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, ""PhoneWindowManager.mBroadcastWakeLock""); mPowerKeyWakeLock = mPowerManager.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, ""PhoneWindowManager.mPowerKeyWakeLock""); mEnableShiftMenuBugReports = ""1"".equals(SystemProperties.get(""ro.debuggable"")); mLidKeyboardAccessibility = mContext.getResources().getInteger( com.android.internal.R.integer.config_lidKeyboardAccessibility); mLidNavigationAccessibility = mContext.getResources().getInteger( com.android.internal.R.integer.config_lidNavigationAccessibility); mAllowTheaterModeWakeFromKey = mContext.getResources().getBoolean( com.android.internal.R.bool.config_allowTheaterModeWakeFromKey); mAllowTheaterModeWakeFromPowerKey = mAllowTheaterModeWakeFromKey || mContext.getResources().getBoolean( com.android.internal.R.bool.config_allowTheaterModeWakeFromPowerKey); mAllowTheaterModeWakeFromMotion = mContext.getResources().getBoolean( com.android.internal.R.bool.config_allowTheaterModeWakeFromMotion); mAllowTheaterModeWakeFromMotionWhenNotDreaming = mContext.getResources().getBoolean( com.android.internal.R.bool.config_allowTheaterModeWakeFromMotionWhenNotDreaming); mAllowTheaterModeWakeFromCameraLens = mContext.getResources().getBoolean( com.android.internal.R.bool.config_allowTheaterModeWakeFromCameraLens); mAllowTheaterModeWakeFromLidSwitch = mContext.getResources().getBoolean( com.android.internal.R.bool.config_allowTheaterModeWakeFromLidSwitch); mAllowTheaterModeWakeFromWakeGesture = mContext.getResources().getBoolean( com.android.internal.R.bool.config_allowTheaterModeWakeFromGesture); mGoToSleepOnButtonPressTheaterMode = mContext.getResources().getBoolean( com.android.internal.R.bool.config_goToSleepOnButtonPressTheaterMode); mSupportLongPressPowerWhenNonInteractive = mContext.getResources().getBoolean( com.android.internal.R.bool.config_supportLongPressPowerWhenNonInteractive); mLongPressOnBackBehavior = mContext.getResources().getInteger( com.android.internal.R.integer.config_longPressOnBackBehavior); mShortPressOnPowerBehavior = mContext.getResources().getInteger( com.android.internal.R.integer.config_shortPressOnPowerBehavior); mLongPressOnPowerBehavior = mContext.getResources().getInteger( com.android.internal.R.integer.config_longPressOnPowerBehavior); mLongPressOnPowerAssistantTimeoutMs = mContext.getResources().getInteger( com.android.internal.R.integer.config_longPressOnPowerDurationMs); mVeryLongPressOnPowerBehavior = mContext.getResources().getInteger( com.android.internal.R.integer.config_veryLongPressOnPowerBehavior); mDoublePressOnPowerBehavior = mContext.getResources().getInteger( com.android.internal.R.integer.config_doublePressOnPowerBehavior); mTriplePressOnPowerBehavior = mContext.getResources().getInteger( com.android.internal.R.integer.config_triplePressOnPowerBehavior); mShortPressOnSleepBehavior = mContext.getResources().getInteger( com.android.internal.R.integer.config_shortPressOnSleepBehavior); mAllowStartActivityForLongPressOnPowerDuringSetup = mContext.getResources().getBoolean( com.android.internal.R.bool.config_allowStartActivityForLongPressOnPowerInSetup); mHapticTextHandleEnabled = mContext.getResources().getBoolean( com.android.internal.R.bool.config_enableHapticTextHandle); mUseTvRouting = AudioSystem.getPlatformType(mContext) == AudioSystem.PLATFORM_TELEVISION; mHandleVolumeKeysInWM = mContext.getResources().getBoolean( com.android.internal.R.bool.config_handleVolumeKeysInWindowManager); mPerDisplayFocusEnabled = mContext.getResources().getBoolean( com.android.internal.R.bool.config_perDisplayFocusEnabled); mWakeUpToLastStateTimeout = mContext.getResources().getInteger( com.android.internal.R.integer.config_wakeUpToLastStateTimeoutMillis); readConfigurationDependentBehaviors(); mDisplayFoldController = DisplayFoldController.create(context, DEFAULT_DISPLAY); mAccessibilityManager = (AccessibilityManager) context.getSystemService( Context.ACCESSIBILITY_SERVICE); // register for dock events IntentFilter filter = new IntentFilter(); filter.addAction(UiModeManager.ACTION_ENTER_CAR_MODE); filter.addAction(UiModeManager.ACTION_EXIT_CAR_MODE); filter.addAction(UiModeManager.ACTION_ENTER_DESK_MODE); filter.addAction(UiModeManager.ACTION_EXIT_DESK_MODE); filter.addAction(Intent.ACTION_DOCK_EVENT); Intent intent = context.registerReceiver(mDockReceiver, filter); if (intent != null) { // Retrieve current sticky dock event broadcast. mDefaultDisplayPolicy.setDockMode(intent.getIntExtra(Intent.EXTRA_DOCK_STATE, Intent.EXTRA_DOCK_STATE_UNDOCKED)); } // register for dream-related broadcasts filter = new IntentFilter(); filter.addAction(Intent.ACTION_DREAMING_STARTED); filter.addAction(Intent.ACTION_DREAMING_STOPPED); context.registerReceiver(mDreamReceiver, filter); // register for multiuser-relevant broadcasts filter = new IntentFilter(Intent.ACTION_USER_SWITCHED); context.registerReceiver(mMultiuserReceiver, filter); mVibrator = (Vibrator)context.getSystemService(Context.VIBRATOR_SERVICE); mLongPressVibePattern = getLongIntArray(mContext.getResources(), com.android.internal.R.array.config_longPressVibePattern); mCalendarDateVibePattern = getLongIntArray(mContext.getResources(), com.android.internal.R.array.config_calendarDateVibePattern); mSafeModeEnabledVibePattern = getLongIntArray(mContext.getResources(), com.android.internal.R.array.config_safeModeEnabledVibePattern); mGlobalKeyManager = new GlobalKeyManager(mContext); // Controls rotation and the like. initializeHdmiState(); // Match current screen state. if (!mPowerManager.isInteractive()) { startedGoingToSleep(PowerManager.GO_TO_SLEEP_REASON_TIMEOUT); finishedGoingToSleep(PowerManager.GO_TO_SLEEP_REASON_TIMEOUT); } mWindowManagerInternal.registerAppTransitionListener(new AppTransitionListener() { @Override public int onAppTransitionStartingLocked(boolean keyguardGoingAway, long duration, long statusBarAnimationStartTime, long statusBarAnimationDuration) { return handleStartTransitionForKeyguardLw(keyguardGoingAway, duration); } @Override public void onAppTransitionCancelledLocked(boolean keyguardGoingAway) { handleStartTransitionForKeyguardLw(keyguardGoingAway, 0 /* duration */); } }); mKeyguardDelegate = new KeyguardServiceDelegate(mContext, new StateCallback() { @Override public void onTrustedChanged() { mWindowManagerFuncs.notifyKeyguardTrustedChanged(); } @Override public void onShowingChanged() { mWindowManagerFuncs.onKeyguardShowingAndNotOccludedChanged(); } }); initKeyCombinationRules(); initSingleKeyGestureRules(); mSideFpsEventHandler = new SideFpsEventHandler(mContext, mHandler, mPowerManager); }","@Override public void init(Context context, IWindowManager windowManager, WindowManagerFuncs windowManagerFuncs) { mContext = context; mWindowManager = windowManager; mWindowManagerFuncs = windowManagerFuncs; mWindowManagerInternal = LocalServices.getService(WindowManagerInternal.class); mActivityManagerInternal = LocalServices.getService(ActivityManagerInternal.class); mActivityTaskManagerInternal = LocalServices.getService(ActivityTaskManagerInternal.class); mInputManagerInternal = LocalServices.getService(InputManagerInternal.class); mDreamManagerInternal = LocalServices.getService(DreamManagerInternal.class); mPowerManagerInternal = LocalServices.getService(PowerManagerInternal.class); mAppOpsManager = mContext.getSystemService(AppOpsManager.class); mDisplayManager = mContext.getSystemService(DisplayManager.class); mDisplayManagerInternal = LocalServices.getService(DisplayManagerInternal.class); mPackageManager = mContext.getPackageManager(); mHasFeatureWatch = mPackageManager.hasSystemFeature(FEATURE_WATCH); mHasFeatureLeanback = mPackageManager.hasSystemFeature(FEATURE_LEANBACK); mHasFeatureAuto = mPackageManager.hasSystemFeature(FEATURE_AUTOMOTIVE); mHasFeatureHdmiCec = mPackageManager.hasSystemFeature(FEATURE_HDMI_CEC); mAccessibilityShortcutController = new AccessibilityShortcutController(mContext, new Handler(), mCurrentUserId); mLogger = new MetricsLogger(); mScreenOffSleepTokenAcquirer = mActivityTaskManagerInternal .createSleepTokenAcquirer(""ScreenOff""); Resources res = mContext.getResources(); mWakeOnDpadKeyPress = res.getBoolean(com.android.internal.R.bool.config_wakeOnDpadKeyPress); mWakeOnAssistKeyPress = res.getBoolean(com.android.internal.R.bool.config_wakeOnAssistKeyPress); mWakeOnBackKeyPress = res.getBoolean(com.android.internal.R.bool.config_wakeOnBackKeyPress); // Init alert slider mHasAlertSlider = mContext.getResources().getBoolean(R.bool.config_hasAlertSlider) && !TextUtils.isEmpty(mContext.getResources().getString(R.string.alert_slider_state_path)) && !TextUtils.isEmpty(mContext.getResources().getString(R.string.alert_slider_uevent_match_path)); // Init display burn-in protection boolean burnInProtectionEnabled = context.getResources().getBoolean( com.android.internal.R.bool.config_enableBurnInProtection); // Allow a system property to override this. Used by developer settings. boolean burnInProtectionDevMode = SystemProperties.getBoolean(""persist.debug.force_burn_in"", false); if (burnInProtectionEnabled || burnInProtectionDevMode) { final int minHorizontal; final int maxHorizontal; final int minVertical; final int maxVertical; final int maxRadius; if (burnInProtectionDevMode) { minHorizontal = -8; maxHorizontal = 8; minVertical = -8; maxVertical = -4; maxRadius = (isRoundWindow()) ? 6 : -1; } else { Resources resources = context.getResources(); minHorizontal = resources.getInteger( com.android.internal.R.integer.config_burnInProtectionMinHorizontalOffset); maxHorizontal = resources.getInteger( com.android.internal.R.integer.config_burnInProtectionMaxHorizontalOffset); minVertical = resources.getInteger( com.android.internal.R.integer.config_burnInProtectionMinVerticalOffset); maxVertical = resources.getInteger( com.android.internal.R.integer.config_burnInProtectionMaxVerticalOffset); maxRadius = resources.getInteger( com.android.internal.R.integer.config_burnInProtectionMaxRadius); } mBurnInProtectionHelper = new BurnInProtectionHelper( context, minHorizontal, maxHorizontal, minVertical, maxVertical, maxRadius); } mHandler = new PolicyHandler(); mWakeGestureListener = new MyWakeGestureListener(mContext, mHandler); mSettingsObserver = new SettingsObserver(mHandler); mSettingsObserver.observe(); mModifierShortcutManager = new ModifierShortcutManager(context); mUiMode = context.getResources().getInteger( com.android.internal.R.integer.config_defaultUiModeType); mHomeIntent = new Intent(Intent.ACTION_MAIN, null); mHomeIntent.addCategory(Intent.CATEGORY_HOME); mHomeIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_RESET_TASK_IF_NEEDED); mEnableCarDockHomeCapture = context.getResources().getBoolean( com.android.internal.R.bool.config_enableCarDockHomeLaunch); mCarDockIntent = new Intent(Intent.ACTION_MAIN, null); mCarDockIntent.addCategory(Intent.CATEGORY_CAR_DOCK); mCarDockIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_RESET_TASK_IF_NEEDED); mDeskDockIntent = new Intent(Intent.ACTION_MAIN, null); mDeskDockIntent.addCategory(Intent.CATEGORY_DESK_DOCK); mDeskDockIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_RESET_TASK_IF_NEEDED); mVrHeadsetHomeIntent = new Intent(Intent.ACTION_MAIN, null); mVrHeadsetHomeIntent.addCategory(Intent.CATEGORY_VR_HOME); mVrHeadsetHomeIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_RESET_TASK_IF_NEEDED); mPowerManager = (PowerManager)context.getSystemService(Context.POWER_SERVICE); mBroadcastWakeLock = mPowerManager.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, ""PhoneWindowManager.mBroadcastWakeLock""); mPowerKeyWakeLock = mPowerManager.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, ""PhoneWindowManager.mPowerKeyWakeLock""); mEnableShiftMenuBugReports = ""1"".equals(SystemProperties.get(""ro.debuggable"")); mLidKeyboardAccessibility = mContext.getResources().getInteger( com.android.internal.R.integer.config_lidKeyboardAccessibility); mLidNavigationAccessibility = mContext.getResources().getInteger( com.android.internal.R.integer.config_lidNavigationAccessibility); mAllowTheaterModeWakeFromKey = mContext.getResources().getBoolean( com.android.internal.R.bool.config_allowTheaterModeWakeFromKey); mAllowTheaterModeWakeFromPowerKey = mAllowTheaterModeWakeFromKey || mContext.getResources().getBoolean( com.android.internal.R.bool.config_allowTheaterModeWakeFromPowerKey); mAllowTheaterModeWakeFromMotion = mContext.getResources().getBoolean( com.android.internal.R.bool.config_allowTheaterModeWakeFromMotion); mAllowTheaterModeWakeFromMotionWhenNotDreaming = mContext.getResources().getBoolean( com.android.internal.R.bool.config_allowTheaterModeWakeFromMotionWhenNotDreaming); mAllowTheaterModeWakeFromCameraLens = mContext.getResources().getBoolean( com.android.internal.R.bool.config_allowTheaterModeWakeFromCameraLens); mAllowTheaterModeWakeFromLidSwitch = mContext.getResources().getBoolean( com.android.internal.R.bool.config_allowTheaterModeWakeFromLidSwitch); mAllowTheaterModeWakeFromWakeGesture = mContext.getResources().getBoolean( com.android.internal.R.bool.config_allowTheaterModeWakeFromGesture); mGoToSleepOnButtonPressTheaterMode = mContext.getResources().getBoolean( com.android.internal.R.bool.config_goToSleepOnButtonPressTheaterMode); mSupportLongPressPowerWhenNonInteractive = mContext.getResources().getBoolean( com.android.internal.R.bool.config_supportLongPressPowerWhenNonInteractive); mLongPressOnBackBehavior = mContext.getResources().getInteger( com.android.internal.R.integer.config_longPressOnBackBehavior); mShortPressOnPowerBehavior = mContext.getResources().getInteger( com.android.internal.R.integer.config_shortPressOnPowerBehavior); mLongPressOnPowerBehavior = mContext.getResources().getInteger( com.android.internal.R.integer.config_longPressOnPowerBehavior); mLongPressOnPowerAssistantTimeoutMs = mContext.getResources().getInteger( com.android.internal.R.integer.config_longPressOnPowerDurationMs); mVeryLongPressOnPowerBehavior = mContext.getResources().getInteger( com.android.internal.R.integer.config_veryLongPressOnPowerBehavior); mDoublePressOnPowerBehavior = mContext.getResources().getInteger( com.android.internal.R.integer.config_doublePressOnPowerBehavior); mTriplePressOnPowerBehavior = mContext.getResources().getInteger( com.android.internal.R.integer.config_triplePressOnPowerBehavior); mShortPressOnSleepBehavior = mContext.getResources().getInteger( com.android.internal.R.integer.config_shortPressOnSleepBehavior); mAllowStartActivityForLongPressOnPowerDuringSetup = mContext.getResources().getBoolean( com.android.internal.R.bool.config_allowStartActivityForLongPressOnPowerInSetup); mHapticTextHandleEnabled = mContext.getResources().getBoolean( com.android.internal.R.bool.config_enableHapticTextHandle); mUseTvRouting = AudioSystem.getPlatformType(mContext) == AudioSystem.PLATFORM_TELEVISION; mHandleVolumeKeysInWM = mContext.getResources().getBoolean( com.android.internal.R.bool.config_handleVolumeKeysInWindowManager); mPerDisplayFocusEnabled = mContext.getResources().getBoolean( com.android.internal.R.bool.config_perDisplayFocusEnabled); mWakeUpToLastStateTimeout = mContext.getResources().getInteger( com.android.internal.R.integer.config_wakeUpToLastStateTimeoutMillis); readConfigurationDependentBehaviors(); mDisplayFoldController = DisplayFoldController.create(context, DEFAULT_DISPLAY); mAccessibilityManager = (AccessibilityManager) context.getSystemService( Context.ACCESSIBILITY_SERVICE); // register for dock events IntentFilter filter = new IntentFilter(); filter.addAction(UiModeManager.ACTION_ENTER_CAR_MODE); filter.addAction(UiModeManager.ACTION_EXIT_CAR_MODE); filter.addAction(UiModeManager.ACTION_ENTER_DESK_MODE); filter.addAction(UiModeManager.ACTION_EXIT_DESK_MODE); filter.addAction(Intent.ACTION_DOCK_EVENT); Intent intent = context.registerReceiver(mDockReceiver, filter); if (intent != null) { // Retrieve current sticky dock event broadcast. mDefaultDisplayPolicy.setDockMode(intent.getIntExtra(Intent.EXTRA_DOCK_STATE, Intent.EXTRA_DOCK_STATE_UNDOCKED)); } // register for dream-related broadcasts filter = new IntentFilter(); filter.addAction(Intent.ACTION_DREAMING_STARTED); filter.addAction(Intent.ACTION_DREAMING_STOPPED); context.registerReceiver(mDreamReceiver, filter); // register for multiuser-relevant broadcasts filter = new IntentFilter(Intent.ACTION_USER_SWITCHED); context.registerReceiver(mMultiuserReceiver, filter); mVibrator = (Vibrator)context.getSystemService(Context.VIBRATOR_SERVICE); mLongPressVibePattern = getLongIntArray(mContext.getResources(), com.android.internal.R.array.config_longPressVibePattern); mCalendarDateVibePattern = getLongIntArray(mContext.getResources(), com.android.internal.R.array.config_calendarDateVibePattern); mSafeModeEnabledVibePattern = getLongIntArray(mContext.getResources(), com.android.internal.R.array.config_safeModeEnabledVibePattern); mGlobalKeyManager = new GlobalKeyManager(mContext); // Controls rotation and the like. initializeHdmiState(); // Match current screen state. if (!mPowerManager.isInteractive()) { startedGoingToSleep(PowerManager.GO_TO_SLEEP_REASON_TIMEOUT); finishedGoingToSleep(PowerManager.GO_TO_SLEEP_REASON_TIMEOUT); } mWindowManagerInternal.registerAppTransitionListener(new AppTransitionListener() { @Override public int onAppTransitionStartingLocked(boolean keyguardGoingAway, long duration, long statusBarAnimationStartTime, long statusBarAnimationDuration) { return handleStartTransitionForKeyguardLw(keyguardGoingAway, duration); } @Override public void onAppTransitionCancelledLocked(boolean keyguardGoingAway) { handleStartTransitionForKeyguardLw(keyguardGoingAway, 0 /* duration */); } }); mKeyguardDelegate = new KeyguardServiceDelegate(mContext, new StateCallback() { @Override public void onTrustedChanged() { mWindowManagerFuncs.notifyKeyguardTrustedChanged(); } @Override public void onShowingChanged() { mWindowManagerFuncs.onKeyguardShowingAndNotOccludedChanged(); } }); final String[] deviceKeyHandlerLibs = res.getStringArray( com.android.internal.R.array.config_deviceKeyHandlerLibs); final String[] deviceKeyHandlerClasses = res.getStringArray( com.android.internal.R.array.config_deviceKeyHandlerClasses); for (int i = 0; i < deviceKeyHandlerLibs.length && i < deviceKeyHandlerClasses.length; i++) { try { PathClassLoader loader = new PathClassLoader( deviceKeyHandlerLibs[i], getClass().getClassLoader()); Class klass = loader.loadClass(deviceKeyHandlerClasses[i]); Constructor constructor = klass.getConstructor(Context.class); mDeviceKeyHandlers.add((DeviceKeyHandler) constructor.newInstance(mContext)); } catch (Exception e) { Slog.w(TAG, ""Could not instantiate device key handler "" + deviceKeyHandlerLibs[i] + "" from class "" + deviceKeyHandlerClasses[i], e); } } if (DEBUG_INPUT) { Slog.d(TAG, """" + mDeviceKeyHandlers.size() + "" device key handlers loaded""); } initKeyCombinationRules(); initSingleKeyGestureRules(); mSideFpsEventHandler = new SideFpsEventHandler(mContext, mHandler, mPowerManager); }","Support for device specific key handlers This is a squash commit of the following changes, only modified for the new SDK. Carbon Edits: get away from SDK Author: Alexander Hofbauer Date: Thu Apr 12 01:24:24 2012 +0200 Dispatch keys to a device specific key handler Injects a device key handler into the input path to handle additional keys (as found on some docks with a hardware keyboard). Configurable via overlay settings config_deviceKeyHandlerLib and config_deviceKeyHandlerClass. Change-Id: I6678c89c7530fdb1d4d516ba4f1d2c9e30ce79a4 Author: Jorge Ruesga Date: Thu Jan 24 02:34:49 2013 +0100 DeviceKeyHandle: The device should consume only known keys When the device receive the key, only should consume it if the device know about the key. Otherwise, the key must be handle by the active app. Also make mDeviceKeyHandler private (is not useful outside this class) Change-Id: I4b9ea57b802e8c8c88c8b93a63d510f5952b0700 Signed-off-by: Jorge Ruesga Author: Danesh Mondegarian Date: Sun Oct 20 00:34:48 2013 -0700 DeviceKeyHandler : Allow handling keyevents while screen off Some devices require the keyevents to be processed while the screen is off, this patchset addresses that by moving the filter up in the call hierarchy. Change-Id: If71beecc81aa5e453dcd08aba72b7bea5c210590 Author: Steve Kondik Date: Sun Sep 11 00:49:41 2016 -0700 policy: Use PathClassLoader for loading the keyhandler * Fix crash on start due to getCacheDir throwing an exception. * We can't do this anymore due to the new storage/crypto in N. Change-Id: I28426a5df824460ebc74aa19068192adb00d4f7c Author: Zhao Wei Liew Date: Sun Nov 20 08:20:15 2016 +0800 PhoneWindowManager: Support multiple key handlers Convert the string overlay to a string-array overlay to allow devices to specify an array of key handlers. Note that the keyhandlers towards the start of the array take precedence when loading. Change-Id: Iaaab737f1501a97d7016d8d519ccf127ca059218 Author: Paul Keith Date: Thu Nov 23 21:47:51 2017 +0100 fw/b: Return a KeyEvent instead of a boolean in KeyHandler * Allows handlers to modify the event before sending it off to another KeyHandler class, to handle things like rotation Change-Id: I481107e050f6323c5897260a5d241e64b4e031ac Change-Id: Ibac1c348717c83fdf9a2894a5d91dc035f9f3a18",https://github.com/AOSPA/android_frameworks_base/commit/7126f412a8606fe4ce9033fb5b92c8829ab3d4a5,,,services/core/java/com/android/server/policy/PhoneWindowManager.java,3,java,False,2017-10-11T20:11:49Z "private int decodeHeaders( HttpServer server, long traceId, long authorization, long budgetId, int reserved, DirectBuffer buffer, int offset, int limit) { final HttpBeginExFW.Builder httpBeginEx = beginExRW.wrap(codecBuffer, 0, codecBuffer.capacity()) .typeId(httpTypeId); DirectBuffer error = null; final int endOfStartAt = limitOfBytes(buffer, offset, limit, CRLF_BYTES); if (endOfStartAt != -1) { if (server.upgrade && endOfStartAt >= offset + 16 && CharSequence.compare(""PRI * HTTP/2.0\r\n"", new AsciiSequenceView(buffer, offset, 16)) == 0) { server.delegate = new Http2Server(server); signaler.signalNow(server.routeId, server.replyId, DELEGATE_SIGNAL, 0); return offset; } hasAuthority.value = false; error = decodeStartLine(buffer, offset, endOfStartAt, httpBeginEx, hasAuthority, server.decodeScheme); } else if (limit - offset >= maximumHeadersSize) { error = ERROR_414_REQUEST_URI_TOO_LONG; } else { final int endOfMethodLimit = Math.min(limit, offset + MAXIMUM_METHOD_LENGTH); final int endOfMethodAt = indexOfByte(buffer, offset, endOfMethodLimit, SPACE_BYTE); if (endOfMethodAt != -1) { final CharSequence method = new AsciiSequenceView(buffer, offset, endOfMethodAt - offset); if (!SUPPORTED_METHODS.contains(method)) { error = ERROR_501_METHOD_NOT_IMPLEMENTED; } } else if (limit > endOfMethodLimit) { error = ERROR_400_BAD_REQUEST; } } final int endOfHeadersAt = limitOfBytes(buffer, offset, limit, CRLFCRLF_BYTES); if (error == null && endOfHeadersAt != -1) { server.decoder = decodeHeadersOnly; connectionRef.ref = null; final int endOfHeaderLinesAt = endOfHeadersAt - CRLF_BYTES.length; int startOfLineAt = endOfStartAt; for (int endOfLineAt = limitOfBytes(buffer, startOfLineAt, endOfHeaderLinesAt, CRLF_BYTES); endOfLineAt != -1 && error == null; startOfLineAt = endOfLineAt, endOfLineAt = limitOfBytes(buffer, startOfLineAt, endOfHeaderLinesAt, CRLF_BYTES)) { error = decodeHeaderLine(server, buffer, offset, startOfLineAt, endOfLineAt, httpBeginEx, hasAuthority, connectionRef); } if (error == null && !hasAuthority.value) { error = ERROR_400_BAD_REQUEST; } if (error == null) { HttpBeginExFW beginEx = httpBeginEx.build(); final Map headers = new LinkedHashMap<>(); beginEx.headers().forEach(h -> headers.put(h.name().asString().toLowerCase(), h.value().asString())); if (isCorsPreflightRequest(headers)) { server.onDecodeCorsPreflight(traceId, authorization, headers); server.decoder = decodeEmptyLines; } else if (!isCorsRequestAllowed(server.binding, headers)) { server.onDecodeHeadersError(traceId, authorization, response403); server.decoder = decodeIgnore; } else { HttpBindingConfig binding = server.binding; GuardHandler guard = server.guard; if (CHALLENGE_RESPONSE_METHOD.equals(headers.get(HEADER_NAME_METHOD)) && CHALLENGE_RESPONSE_CONTENT_TYPE.equals(headers.get(HEADER_NAME_CONTENT_TYPE)) && CHALLENGE_RESPONSE_CONTENT_LENGTH.equals(headers.get(HEADER_NAME_CONTENT_LENGTH))) { guard.reauthorize(server.initialId, server.credentials.apply(headers::get)); server.doEncodeHeaders(traceId, authorization, budgetId, headers204); } else { long exchangeAuth = authorization; if (guard != null) { exchangeAuth = guard.reauthorize(server.initialId, server.credentials.apply(headers::get)); } HttpRouteConfig route = binding.resolve(exchangeAuth, headers::get); if (route != null) { if (binding.options != null && binding.options.overrides != null) { binding.options.overrides.forEach((k, v) -> headers.put(k.asString(), v.asString())); final HttpBeginExFW.Builder newBeginEx = newBeginExRW.wrap(codecBuffer, 0, codecBuffer.capacity()) .typeId(httpTypeId); headers.forEach((k, v) -> newBeginEx.headersItem(i -> i.name(k).value(v))); beginEx = newBeginEx.build(); } HttpPolicyConfig policy = binding.access().effectivePolicy(headers); final String origin = policy == CROSS_ORIGIN ? headers.get(HEADER_NAME_ORIGIN) : null; server.onDecodeHeaders(route.id, traceId, exchangeAuth, policy, origin, beginEx); } else { error = response404; } } } } } else if (error == null && limit - offset >= maximumHeadersSize) { error = ERROR_414_REQUEST_URI_TOO_LONG; } if (error != null) { server.onDecodeHeadersError(traceId, authorization, error); server.decoder = decodeIgnore; } return error == null && endOfHeadersAt != -1 ? endOfHeadersAt : offset; }","private int decodeHeaders( HttpServer server, long traceId, long authorization, long budgetId, int reserved, DirectBuffer buffer, int offset, int limit) { final HttpBeginExFW.Builder httpBeginEx = beginExRW.wrap(codecBuffer, 0, codecBuffer.capacity()) .typeId(httpTypeId); DirectBuffer error = null; final int endOfStartAt = limitOfBytes(buffer, offset, limit, CRLF_BYTES); if (endOfStartAt != -1) { if (server.upgrade && endOfStartAt >= offset + 16 && CharSequence.compare(""PRI * HTTP/2.0\r\n"", new AsciiSequenceView(buffer, offset, 16)) == 0) { server.delegate = new Http2Server(server); signaler.signalNow(server.routeId, server.replyId, DELEGATE_SIGNAL, 0); return offset; } hasAuthority.value = false; error = decodeStartLine(buffer, offset, endOfStartAt, httpBeginEx, hasAuthority, server.decodeScheme); } else if (limit - offset >= maximumHeadersSize) { error = ERROR_414_REQUEST_URI_TOO_LONG; } else { final int endOfMethodLimit = Math.min(limit, offset + MAXIMUM_METHOD_LENGTH); final int endOfMethodAt = indexOfByte(buffer, offset, endOfMethodLimit, SPACE_BYTE); if (endOfMethodAt != -1) { final CharSequence method = new AsciiSequenceView(buffer, offset, endOfMethodAt - offset); if (!SUPPORTED_METHODS.contains(method)) { error = ERROR_501_METHOD_NOT_IMPLEMENTED; } } else if (limit > endOfMethodLimit) { error = ERROR_400_BAD_REQUEST; } } final int endOfHeadersAt = limitOfBytes(buffer, offset, limit, CRLFCRLF_BYTES); if (error == null && endOfHeadersAt != -1) { server.decoder = decodeHeadersOnly; connectionRef.ref = null; final int endOfHeaderLinesAt = endOfHeadersAt - CRLF_BYTES.length; int startOfLineAt = endOfStartAt; for (int endOfLineAt = limitOfBytes(buffer, startOfLineAt, endOfHeaderLinesAt, CRLF_BYTES); endOfLineAt != -1 && error == null; startOfLineAt = endOfLineAt, endOfLineAt = limitOfBytes(buffer, startOfLineAt, endOfHeaderLinesAt, CRLF_BYTES)) { error = decodeHeaderLine(server, buffer, offset, startOfLineAt, endOfLineAt, httpBeginEx, hasAuthority, connectionRef); } if (error == null && !hasAuthority.value) { error = ERROR_400_BAD_REQUEST; } if (error == null) { HttpBeginExFW beginEx = httpBeginEx.build(); final Map headers = new LinkedHashMap<>(); beginEx.headers().forEach(h -> headers.put(h.name().asString().toLowerCase(), h.value().asString())); if (isCorsPreflightRequest(headers)) { server.onDecodeCorsPreflight(traceId, authorization, headers); server.decoder = decodeEmptyLines; } else if (!isCorsRequestAllowed(server.binding, headers)) { server.onDecodeHeadersError(traceId, authorization, response403); server.decoder = decodeIgnore; } else { HttpBindingConfig binding = server.binding; GuardHandler guard = server.guard; if (CHALLENGE_RESPONSE_METHOD.equals(headers.get(HEADER_NAME_METHOD)) && CHALLENGE_RESPONSE_CONTENT_TYPE.equals(headers.get(HEADER_NAME_CONTENT_TYPE)) && CHALLENGE_RESPONSE_CONTENT_LENGTH.equals(headers.get(HEADER_NAME_CONTENT_LENGTH))) { final String credentialsMatch = server.credentials.apply(headers::get); if (credentialsMatch != null) { guard.reauthorize(server.initialId, credentialsMatch); } server.doEncodeHeaders(traceId, authorization, budgetId, headers204); } else { long exchangeAuth = authorization; if (guard != null) { final String credentialsMatch = server.credentials.apply(headers::get); if (credentialsMatch != null) { exchangeAuth = guard.reauthorize(server.initialId, credentialsMatch); } } HttpRouteConfig route = binding.resolve(exchangeAuth, headers::get); if (route != null) { if (binding.options != null && binding.options.overrides != null) { binding.options.overrides.forEach((k, v) -> headers.put(k.asString(), v.asString())); final HttpBeginExFW.Builder newBeginEx = newBeginExRW.wrap(codecBuffer, 0, codecBuffer.capacity()) .typeId(httpTypeId); headers.forEach((k, v) -> newBeginEx.headersItem(i -> i.name(k).value(v))); beginEx = newBeginEx.build(); } HttpPolicyConfig policy = binding.access().effectivePolicy(headers); final String origin = policy == CROSS_ORIGIN ? headers.get(HEADER_NAME_ORIGIN) : null; server.onDecodeHeaders(route.id, traceId, exchangeAuth, policy, origin, beginEx); } else { error = response404; } } } } } else if (error == null && limit - offset >= maximumHeadersSize) { error = ERROR_414_REQUEST_URI_TOO_LONG; } if (error != null) { server.onDecodeHeadersError(traceId, authorization, error); server.decoder = decodeIgnore; } return error == null && endOfHeadersAt != -1 ? endOfHeadersAt : offset; }",Avoid NPE when authorization is configured but not presented,https://github.com/aklivity/zilla/commit/33a5311d00fcc15939fe1f82f52875887ef5278f,,,runtime/binding-http/src/main/java/io/aklivity/zilla/runtime/binding/http/internal/stream/HttpServerFactory.java,3,java,False,2022-05-25T21:43:43Z "@Override @Nullable public String getName() { return bluetoothDevice.getName(); }","@Override @Nullable public String getName() { return getName(false); }","Fixed RxBleDevice#toString() crash toString accessed BluetoothDevice#getName() which needs BLUETOOTH_CONNECT permission on API >=31",https://github.com/dariuszseweryn/RxAndroidBle/commit/01551b50c150fdec2ee224322a1e8e078a3dc76b,,,rxandroidble/src/main/java/com/polidea/rxandroidble2/internal/RxBleDeviceImpl.java,3,java,False,2022-07-02T19:15:56Z "public ResultSet getResultSet() throws SQLException { checkOpen(); if (rs.isOpen()) { throw new SQLException(""ResultSet already requested""); } DB db = conn.getDatabase(); if (db.column_count(pointer) == 0) { return null; } if (rs.colsMeta == null) { rs.colsMeta = db.column_names(pointer); } rs.cols = rs.colsMeta; rs.open = resultsWaiting; resultsWaiting = false; return (ResultSet) rs; }","public ResultSet getResultSet() throws SQLException { checkOpen(); if (rs.isOpen()) { throw new SQLException(""ResultSet already requested""); } if (pointer.safeRunInt(DB::column_count) == 0) { return null; } if (rs.colsMeta == null) { rs.colsMeta = pointer.safeRun(DB::column_names); } rs.cols = rs.colsMeta; rs.open = resultsWaiting; resultsWaiting = false; return (ResultSet) rs; }",Wrap Statement Pointers to prevent use after free race,https://github.com/xerial/sqlite-jdbc/commit/e1d282cb2887ef427c7ad93d4fe7dd05a6c11473,,,src/main/java/org/sqlite/jdbc3/JDBC3Statement.java,3,java,False,2022-07-29T03:54:01Z "@Override public void onBackPressed() { if (!mSearchView.isIconified()) { mSearchView.setIconified(true); return; } super.onBackPressed(); }","@Override public void onBackPressed() { if (mSearchView != null && !mSearchView.isIconified()) { mSearchView.setIconified(true); return; } super.onBackPressed(); }","Prevent NullPointerException in onBackPressed This crash seems to somehow only happen on Huawei and Xiaomi devices. While fairly rare, it is the most common Catima crash currently logged on Google Play Console (8 crashes over the last 28 days). While I don't understand how this would happen, I think it should be relatively safe to assume that if the searchview is null the user isn't currently searching so running the normal back code should always be the expected behaviour.",https://github.com/CatimaLoyalty/Android/commit/10498ce1a43a5c093271de7ff409408b96b50da4,,,app/src/main/java/protect/card_locker/MainActivity.java,3,java,False,2022-11-16T20:42:52Z "@Nullable public static ContraptionMovementSetting get(Block block) { if (block instanceof IMovementSettingProvider provider) return provider.getContraptionMovementSetting(); return SETTING_SUPPLIERS.get(block).get(); }","@Nullable public static ContraptionMovementSetting get(Block block) { if (block instanceof IMovementSettingProvider provider) return provider.getContraptionMovementSetting(); Supplier supplier = SETTING_SUPPLIERS.get(block); if (supplier == null) return null; return supplier.get(); }","Crash and leak fix - Fix crash when invoking ContraptionMovementSetting#get - Fix memory leak in WorldAttached by copying Flywheel's updated version - Fix stockpile switches not preserving settings after being printed",https://github.com/Creators-of-Create/Create/commit/9fbb71e4e9d9f70e2256a73b45482208b01053cf,,,src/main/java/com/simibubi/create/foundation/config/ContraptionMovementSetting.java,3,java,False,2022-08-04T05:36:14Z "private ShipDesign bestDesign(ShipDesigner ai, DesignType role) { Race race = ai.empire().dataRace(); // create a blank design, one for each size. Add the current design as a 5th entry ShipDesign[] shipDesigns = new ShipDesign[4]; for (int i = 0; i<4; i++) { shipDesigns[i] = newDesign(ai, role, i); } SortedMap designSorter = new TreeMap<>(); float costLimit = ai.empire().totalPlanetaryProduction() * ai.empire().fleetCommanderAI().maxShipMaintainance() * 50 / ai.empire().systemsInShipRange(ai.empire()).size(); //System.out.print(""\n""+galaxy().currentTurn()+"" ""+ai.empire().name()+"" costlimit: ""+costLimit); float biggestShipWeaponSize = 0; float biggestBombSize = 0; for (int i = 0; i<4; i++) { ShipDesign design = shipDesigns[i]; for (int j=0; j biggestBombSize) biggestBombSize = design.weapon(j).size(design); } else { if(design.weapon(j).size(design) > biggestShipWeaponSize) biggestShipWeaponSize = design.weapon(j).size(design); } } } for (int i = 0; i<4; i++) { ShipDesign design = shipDesigns[i]; if(role == role.DESTROYER && i > 0) continue; float score = design.spaceUsed() / design.cost(); float defScore = design.hits() / design.cost(); float hitPct = (5 + design.attackLevel() - (design.beamDefense() + design.missileDefense()) / 2) / 10; hitPct = max(.05f, hitPct); hitPct = min(hitPct, 1.0f); float absorbPct = 1.0f; if(design.firepowerAntiShip(0) > 0) absorbPct = design.firepowerAntiShip(design.shieldLevel()) / design.firepowerAntiShip(0); float mitigation = 1 - (hitPct * absorbPct); defScore *= mitigation; score *= defScore; //System.out.print(""\n""+ai.empire().name()+"" ""+design.name()+"" Role: ""+role+"" size: ""+design.size()+"" score wo. costlimit: ""+score+"" costlimit-dividor: ""+design.cost() / costLimit); if(design.cost() > costLimit) score /= design.cost() / costLimit; boolean hasBombs = false; float spaceWpnSize = 0; float bombWpnSize = 0; for (int j=0; j bombWpnSize) bombWpnSize = design.weapon(j).size(design); } else { if(design.weapon(j).size(design) > spaceWpnSize) spaceWpnSize = design.weapon(j).size(design); } } float weaponSizeMod = 1.0f; if(role.BOMBER == role) weaponSizeMod *= bombWpnSize / biggestBombSize; else weaponSizeMod *= spaceWpnSize / biggestShipWeaponSize; if(ai.empire().shipDesignerAI().wantHybrid()) weaponSizeMod *= ai.empire().generalAI().defenseRatio() + (1 - ai.empire().generalAI().defenseRatio()) * bombWpnSize / biggestBombSize; score *= weaponSizeMod; //System.out.print(""\n""+ai.empire().name()+"" ""+design.name()+"" Role: ""+role+"" size: ""+design.size()+"" score: ""+score+"" tonnageScore: ""+design.spaceUsed() / design.cost()+"" defscore: ""+defScore+"" wpnScore: ""+weaponSizeMod+"" costlimit: ""+costLimit); designSorter.put(score, design); } // lastKey is design with greatest damage return designSorter.get(designSorter.lastKey()); }","private ShipDesign bestDesign(ShipDesigner ai, DesignType role) { Race race = ai.empire().dataRace(); // create a blank design, one for each size. Add the current design as a 5th entry ShipDesign[] shipDesigns = new ShipDesign[4]; for (int i = 0; i<4; i++) { shipDesigns[i] = newDesign(ai, role, i); } SortedMap designSorter = new TreeMap<>(); float costLimit = ai.empire().totalPlanetaryProduction() * 0.125f * 50 / ai.empire().systemsInShipRange(ai.empire()).size(); float biggestShipWeaponSize = 0; float biggestBombSize = 0; for (int i = 0; i<4; i++) { ShipDesign design = shipDesigns[i]; for (int j=0; j biggestBombSize) biggestBombSize = design.weapon(j).space(design); } else { if(design.weapon(j).size(design) > biggestShipWeaponSize) biggestShipWeaponSize = design.weapon(j).space(design); } } } //System.out.print(""\n""+galaxy().currentTurn()+"" ""+ai.empire().name()+"" costlimit: ""+costLimit+"" biggestShipWeaponSize: ""+biggestShipWeaponSize); for (int i = 0; i<4; i++) { ShipDesign design = shipDesigns[i]; if(role == role.DESTROYER && i > 0) continue; float score = design.spaceUsed() / design.cost(); float defScore = design.hits() / design.cost(); float hitPct = (5 + design.attackLevel() - (design.beamDefense() + design.missileDefense()) / 2) / 10; hitPct = max(.05f, hitPct); hitPct = min(hitPct, 1.0f); float absorbPct = 1.0f; if(design.firepowerAntiShip(0) > 0) absorbPct = design.firepowerAntiShip(design.shieldLevel()) / design.firepowerAntiShip(0); float mitigation = 1 - (hitPct * absorbPct); defScore *= mitigation; score *= defScore; //System.out.print(""\n""+ai.empire().name()+"" ""+design.name()+"" Role: ""+role+"" size: ""+design.size()+"" score wo. costlimit: ""+score+"" costlimit-dividor: ""+design.cost() / costLimit); if(design.cost() > costLimit) score /= design.cost() / costLimit; boolean hasBombs = false; float spaceWpnSize = 0; float bombWpnSize = 0; for (int j=0; j bombWpnSize) bombWpnSize = design.weapon(j).space(design); } else { if(design.weapon(j).space(design) > spaceWpnSize) spaceWpnSize = design.weapon(j).space(design); } } float weaponSizeMod = 1.0f; if(role.BOMBER == role && biggestBombSize > 0) weaponSizeMod *= bombWpnSize / biggestBombSize; else if(biggestShipWeaponSize > 0) weaponSizeMod *= spaceWpnSize / biggestShipWeaponSize; if(ai.empire().shipDesignerAI().wantHybrid() && biggestBombSize > 0) weaponSizeMod *= ai.empire().generalAI().defenseRatio() + (1 - ai.empire().generalAI().defenseRatio()) * bombWpnSize / biggestBombSize; score *= weaponSizeMod; //System.out.print(""\n""+ai.empire().name()+"" ""+design.name()+"" Role: ""+role+"" size: ""+design.size()+"" score: ""+score+"" tonnageScore: ""+design.spaceUsed() / design.cost()+"" defscore: ""+defScore+"" wpnScore: ""+weaponSizeMod+"" costlimit: ""+costLimit+"" spaceWpnSize: ""+spaceWpnSize); designSorter.put(score, design); } // lastKey is design with greatest damage return designSorter.get(designSorter.lastKey()); }","New algorithm to determine whom to go to war with (#71) * Update AIScientist.java Adjusted values of a bunch of techs. * Update AIShipCaptain.java Fixed accidental removal of range-adjustment in new target-selection-formula and removed unused code. * Update NewShipTemplate.java Allowing missiles to be used again under certain circumstances, taking ECM into account and basing weapon-decision on actual shield-levels rather than best possible. * Update TechMissileWeapon.java Fixed that 2-rack-missiles didn't have +1 speed as they should have according to official strategy-guide. * Update AIScientist.java Tech-Slider-Allocations now depend on racial-bonuses, not leader-personality. * Immersive Xilmi-AI When set to AI: Selectable, the Xilmi AI now goes in immersive-mode, once again making numerous uses of leader-traits. * Update CombatStackColony.java Fixed a bug, that planets without missile-bases always absorbed damage as if they already had a shield-built, even if they had none and even if they were in a nebula. * Tactical combat improvements Can now detect when someone protects another stack with repulsor-beams and retreats, when it cannot counter it with long-range-weapons. Optimal range for firing missiles increased by repulsor-radius so missile-ships won't be affected by the can't counter repulsors-detection. Missiles will now be held back until getting closer to prevent target from dodging them easily. Unused specials like Repulsor will no longer prevent ships from kiting. * Update AIShipCaptain.java Only kite when there's either repulsor-beam or missile-weapons installed on the ship. * Update AIFleetCommander.java Defending is only half as desirable as attacking now. * Immersive Xilmi-AI Lot's of changes for the personality-mode of Xilmi-AI. * Update DiplomaticEmbassy.java Fix for one empire still holding a grudge against the other when signing a peace-treaty. * Update AIShipCaptain.java Somehow the Xilmi-AI must have had conquered a system with a missile-base on it against another type of AI and then crashed at this place, I didn't even think it would get to for a colony. * Update AISpyMaster.java No longer consider computer-advantage for how much to spend into counter-espionage. * Race-fitting-playstyles implemented and leader-specfic-self-restrictions removed. * Update AIGeneral.java Invader-AI back to normal victim-selection. * Update AIGovernor.java Turns out espionage didn't work like I thought it would. So Darlok just building ships and relying on stealing techs was a bad idea. (You can only steal techs below your highest level in any given tree!) * Update AIDiplomat.java Fixed issue where AI wouldn't allow the player to ask for tech-trades and where they would take deals that are horrible for themselves when trading with other AIs. Trades are now usually all done within a 66%-150% tech-cost-range. * Update AIGeneral.java Giving themselves a personality/objective-combination that fits their behavior. * Update AIDiplomat.java Tech exchange only will work within same tier now. * Update AIGeneral.java Removed setting of personalities as this causes issue with missing texts. * Update AIScientist.java Fixed issue for Silicoids trading for Eco-restoration-techs. * Update ColonyDefense.java * Update ColonyDefense.java Shield will now only be built automatically under the following circumstances: There's missile-bases existing There's missile-bases needing to be upgraded There's missile-bases to be built * Update AIDiplomat.java Avoid false positives in war-declaration for incoming fleets when the system in question was only recently colonized. * Update AIShipCaptain.java Fixed a rare but not impossible crash. * Update AIDiplomat.java No longer accept joint-war-proposals from empires we like less than who they propose as victim. * Update AIGovernor.java Now building missile-bases... under very specific and rare circumstances. * Update AIShipCaptain.java Fixed crash when handling missile-bases. Individual stacks that can't find a target to attack no longer automatically retreat and instead let their behavior be governed by whether the whole fleet would want to retreat. * Update ColonyDefense.java Reverted previous changes which also happened to prevent AI from building shields. * Update CombatStackShip.java Fixed issue where multi-shot-weapons weren't reported as used when they were used. * Update AIFleetCommander.java Fleets now are split depending on their warp-speed unless they are on the way to their final-attack-target. * Update AIDiplomat.java Knowing about uncolonized systems no longer prevents wars. * Update CombatStackShip.java Revert change to shipComponentIsUsed * Update AIShipCaptain.java Moved logic that detects if a weapon has been used to this file. * Update AIScientist.java Try to avoid researching techs we know our neighbors already have since we can trade for it or steal it. * Update AIFleetCommander.java Colony ships now only ignore distance if they are huge as otherwise ignoring distance was horrible in late-game with hyperspace-communications. Keeping scout-designs around for longer. * Fixed a very annoying issue that caused eco-spending to become... insufficient and thus people to die when adjusting espionage- or security-spending. * Reserve-management-improvements Rich and Ultra-Rich planets now put their production into reserve when they would otherwise conduct research. Reserve will now try to keep an emergency-reserve for dealing with events like Supernova. Exceeding twice the amount of that reserve will always be spent so the money doesn't just lie around unused, when there's no new colonies that still need industry. * Update AIShipCaptain.java Removed an unneccessary white line 8[ * Update AIFleetCommander.java Reversed keeping scouts for longer * Update AIGovernor.java no industry, when under siege * Update AIGovernor.java Small fixed to sieged colonies building industry when they shouldn't. * Update Rotp.java Versioning 0.93a * Update RacesUI.java Race-selector no longer jumps after selecting a race. Race-selector scroll-speed when dragging is no longer amplified like the scroll-bar but instead moves 1:1 the distance dragged. * Update AIFleetCommander.java Smart-Path will no longer path over systems further away than the target-system. Fleets will now always be split by speed if more than 2/3rd of the fleet have the fastest speed possible. * Update AIGovernor.java Build more fleet when fighting someone who has no or extremely little fleet. * Update AIShipCaptain.java Kiting no longer uses path-finding during auto-resolve. Ships with repulsor and long-range will no longer get closer than 2 tiles before firing against ships that don't have long range. Will only retreat to system with enemy fleets when there's no system without enemy fleets to retreat to. * Update CombatStackColony.java Added override for optimal firing-range for missile-bases. It is 9. * Update CombatStackShip.java Optimal firing-range for ship-stacks with missiles will now be at least two when they have repulsors. * Update NewShipTemplate.java The willingness of the AI to use repulsor-beam now scales with how many opponent ships have long range. It will be higher if there's only a few but drop down to 0 if all opponent ships use them. * Update AI.java Improved logic for shuttling around population within the empire. * Update ShipBattleUI.java Fixed a bug where remaining commands were transferred from one stack to another, which could also cause a crash when missile-bases were involved. * Update Colony.java currentProductionCapacity now correctly takes into consideration how many factories are actually operated. * Update NewShipTemplate.java Fixes and improvements to special-selection. Mainly bigger emphasis on using cloaking-device and stasis-field. * Update AIShipDesigner.java Consider getting an important special like cloaking, stasis or black-hole-generator as reason to immediately make a new design. * Update SystemView.java Systems with enemy-fleets will now flash the Alert. Especially usefull when under siege by cloaked enemy fleets. * Update AIShipCaptain.java Added check whether retreat was possible when retreating for the reason that nothing can be done. * Update AIGovernor.java Taking natural pop-growth and the cost of terraforming into account when deciding to build factories or population. This usually results to prefering factories almost always when they can be operated. * War- and Peace-making changes. Prevent war-declaration when there's barely any fleet to attack with. Smarter selection of preferred victim. In particular taking their diplomatic status with others into account. Toned down overall aggressiveness. Several personalities now are taken into account for determining behavior. * Update General.java Don't attack too early. * Update AIFleetCommander.java Colony ships will now always prefer undefended targets instead of waiting for help if they want to colonize a defended system. * Update Rotp.java Version 0.93b * Update NewShipTemplate.java Not needing ranged weapon, when we have cloaking-device. * Improved behavior when using missiles to act according to expectations of /u/bot39lvl * Showing pop-growth at clean-eco. * New Version with u/bot39lvl recommended changes to missile-boat-handling * Fixed issue that caused ships being scrapped after loading a game, no longer taking incoming enemy fleets into consideration that are more than one turn away from reaching their target. * Stacks that want to retreat will now also try and damage their target if it is more than one space away as long as they don't use up all movement-points. Planets with no missile-bases will not become a target unless all non-bomb-weapons were used. * Fixed an issue where a new design would override a similar existing one. * When defending or when having better movement-speed now shall always try to get the 1st strike. * Not keeping a defensive fleet on duty when the incoming opponent attack will overwhelm them anyways. * Using more unique ship-names * Avoid ship-information being cut off by drawing ship-button-overlay into the upper direction as soon as a stack is below the middle of the screen. * Fixed exploit that allowed player to ignore enemy repulsor-beams via auto-resolve. * Fixed issue that caused missile-ships to sometimes retreat when they shouldn't. * Calling beam/missileDefense() method instead of looking at the member since the function also takes stealth into account which we want to do for better decision-making. * Ships with limited shot-weapons no longer think they can land all hits at once. * Best tech of each type no longer gets it's research-value reduced. * Halfed inertial-value again as it otherwise may suppress vital range-tech. * Prevent overbuilding colony-ships in lategame by taking into consideration when systems can build more than one per turn. * Design-names now use name of a system that is actually owned and add a number to make sure they are unique. * Fixed some issues with no longer firing before retreating after rework and now ignoring stacks in stasis for whether to retreat or not. * Evenly distributing population across the empire led to an increase of almost 30% productivity at a reference turn in tests and thus turned out to be a much better population-distribution-strategy when compared to the ""bring new colonies to 25%""-rule-of-thumb as suggested in the official-strategy-guide. * Last defending stacks in stasis are now also made to autoretreat as otherwise this would result in 100 turns of ""you can't do anything but watch"". * Avoid having more than two designs with Stasis-Field as it doesn't stack. * Should fix an issue that caused usage of Hyper-Space-Communications to be inefficient. * Futher optimization on population-shuttling. * Fixed possible crash from trying to make peace while being involved in a final war. * Fixed infinite loop when trying to scrap the last existing design. * Making much better use of natural growth. * Some further slight adjustments to economy-handling that lead to an even better result in my test. * Fix for ""Hyperspace Communications: can't reroute back to the starting planet - bug"" by setting system to null, when leaving the orbit. In this vein no longer check for a stargate-connection when a fleet isn't at a system anymore. * Only the victor and the owner of the colony fought over get a scan on the system. Not all participants. Especially not someone who fled from the orion-guardian and wanted to exploit this bug to get free high-end-techs! * Prepare next version number since Ray hasn't commited anything yet since the beginning of June. :( * Presumably a better fix to the issue of carrying over button-presses to the next stack. But I don't have a good save to test it. * Fixed that for certain techs the inherited baseValue method either had no override or the override did not reference to the corresponding AI-method. * Reverted fix for redirecting ships with hyperspace-communications to their source-system because it could crash the game when trying to redirect ships using rally-points. * Using same ship-design-naming-pattern for all types of ships so player can't idintify colony-ships by looking at the name. * Added missing override for baseValue from AI. * Made separate method for upgradeCost so it can be used from outside, like AI for example. * Fixed an issue where ships wouldn't retreat when they couldn't path to their preferred target. * Changed how much the AI values certain technologies. Most notably will it like warp-speed-improvements more. * Introduced an algorithm that guesses how long it will take to kill another empire and how long it would take the other empire to kill ourselves. This is used in target-selection and also in order to decide on whether we should go all in with our military. If we think the other empire can kill us more quickly than what it takes to benefit from investments into economy, we go all-in with building military. * Fixed an issue that prevented ships being sent back to where they came from while in space via using hyperspace-communications. Note: The intention of that code is already handled by the ""CanSendTo""-check just above of it. At this place the differientiation between beeing in transit is made, so that code was redundant for it's intended use-case. * Production- and reseach-modifier now considered in decision to build ships non-stop or not. Fixed bug that caused AI-colonies to not build ships when they should. Consider incoming transports in decision whether to build population or not. * Big revamp of dimplomatic AI-behavior. AI should now make much more sophisticated decisions about when to go to war. * No longer bolstering population of low-pop-systems during war as this is pretty exploitable and detracts from producting military. * Version * Fixed a weird issue that prevented AIs from bombarding each other unless the player had knowledge about who the owner of the system to be bombarded is. * Less willing to go to war, when there's other ways to expand. * Fixed issue with colonizers and hyper-space-communications, that I thought I had fixed before. When there's other possible targets to attack, a fleet waiting for invasion-forces, that can glass the system it is orbiting will split up and continue its attack. * Only building excess colonizers, when someone we know (including ourselves) is at war and there's potential to colonize systems that are freed up by that war. * At 72% and higher population a system wanting to build a colonizer will go all-in on it. This mostly affects Sakkra and Meklar, so they expand quicker and make more use of fast pop-growth. * Fixed extremely rare crash. * 0.93g * Guessing travel-time and impact of nebulae instead of actually calculating the correct travel-times including nebulae to improve turn-times. * No longer using bestVictim in ship-Design-Code. * Lower limit from transport-size removed. * Yet another big revamp about when to go to war. It's much more simple now. * Transports sent towards someone who we don't want to have a war with now will be set to surrender on arrival. Travel-distance-calculation simplified in favor of turn-processing. Fixed dysfunctional defense-code that was recently broken. * Pop-growth now plays a role in invasion-decisionmaking. Invasions now can occur without a fleet in orbit. Code for estimating kill-time now takes invasions into account. Drastically simplified victim-selection. * Due to the changes in how the AI handles it's fleets during the wait time for invasions the amount of bombers built was increased. * Changed how it is determined whether to retreat against fleets with repulsors. Fixed issue with not firing missiles under certain circumstances. Stacks of smaller ships fighting against stacks of bigger ships are now more likely to retreat, when they can't kill at least one of the bigger ships per turn. * Moved accidental-stargate-building-prevention-workaround to where it actually is effective. * Fixed an issue where a combat would end prematurely when missiles were fired but still on their way to their target. * Removed commented-out code * Removed actual war-weariness from the reasons to make peace as there's now other and better reasons to make peace. * Bombers are now more specialized as in better at bombing and worse at actual combat. * Bomb-Percentage now considers all opponents, not just the current enemy. * The usage of designs is now recognized by their loadout and not by what role it was assigned to it during design. * No longer super-heavy commitment to ship-production in war. Support of hybrid-playstyle. * Fixed issue that sometimes prevented shooting missiles. * Lowered counter-espionage by no longer looking at average tech-level of opponents but instead at tech-level of highest opponent. * Support for hybrid ship-designs and many tweaks- and fixes in scrapping-logic. * Setting eco-slider with a popup that promts for a percentage now uses the percentage of the amount that isn't required to keep clean. * Fixed previously integrated potential dead-lock. * Indentation * Fix for becoming enemy of others before they are in range in the always-war-mode. * Version-number for next inofficial build. * No security-spending when no contact. But luckily that actually makes no difference between it only actually gets detracted from income when there's contacts. * Revert ""Setting eco-slider with a popup that promts for a percentage now uses the percentage of the amount that isn't required to keep clean."" This reverts commit a2fe5dce3c1be344b6c96b6bfa1b5d16b321fafa. * Taught AI to use divert-reserve to research-checkbox * I don't know how it can happen but I've seen rare cases of colonies with negative-population. This is a workaround that changes them back to 1 pop. * Skip AI turn when corresponing empire is dead. * Fixed possible endless-loop from scrapping last existing ship-design. * Fixed issue where AI would build colonizers as bombers after having scrapped their last existing bomber-design. * Removed useless code. * Removed useless code. * Xilmi AI now capable of deciding when to use bio-weapons. * Bioweapon-support * New voting behavior: Xilmi Ai now votes for whoever they are most scared of but aren't at war with. * Fixed for undecisive behavior of launching an assault but retreating until transports arrive because developmentPct is no longer maxxed after sending transports. (War would still get triggered by the invasion but the fleet sent to accompany the invasion would retreat) * No longer escorting colony-ships on their way to presumably undefended systems. Reason: This oftentimes used a good portion of the fleet for no good reason, when they could be better used for attacking/defending. * Requiring closer range to fire missiles. * Lower score for using bio-weapons depending on how many missile-bases are seen. * No longer altering tech-allocations based on war-state. * New, more diverse and supposedly more interesting diplomatic behavior for AI. * Pick weapon to counter best enemy shield in use rather than average to avoid situations where lasers or scatterpack-V are countered too hard. Also: Make sure that there is a design with the most current bomb before considering bio-weapons. * Weapons that allow heavy-mounts don't get their value decreased so AI doesn't end up without decent repulsor-counter. * Moved negative-population workaround to a place where it is actually called. * Smarter decision-making about when to bomb or not to bomb during on-going invasions. * Incoming invasions of oneself should be slightly better covered but without tying too much of the fleet to it. * Choose target by distance from fleet. * Giving more cover to incoming invasions. * Made rank-check-functions available outside of diplomat too. * Always abstain if not both candidates are known. Superpowers should avoid wars. * Fixed an issue where defenders wouldn't always stay back when they should. * Don't hold back full power when in war anymore. * Quality of ships now more important for scrapping than before. * Reversed prior change in retreat-logic for smaller ships: Yes, the enemy could retreat but control over the system is probably more important than preserving some ships. * Fixed issue where AI would retreat from repulsors when they had missiles. * Minimum speed-requirement for missiles now takes repulsor-beams and diagonals into account. * AI will prepare their wars a little better and also take having to prepare into account before invadion. * No longer voting until both candidates are met. AI now knows much better to capitalize on an advantage and actually win the game instead of throwing it in a risky way. * Moved a debug-output to another place. * 0.93l * Better preparations before going to war. Removed alliances again. * Pick war-target by population-center rather than potential population center. * Fixed a bunch of issued leading to bad colony-ship-management in the lategame. * The better an AI is doing, the more careful they are about how to pick their enemies. * Increased minimum ship-maintenance-threshold for the early-game. * New version * Forgot to remove a debug-message. * Fixed issue reported by u/Individual_Act289: Transports launched before final war disappear on arrival. * Fixed logical error in maxFiringRange-method which could cause unwanted retreats. * When at war, AI will not make so many colony-ships, fixed issue where invasions wouldn't happen against partially built missile-bases, build more bombers when there's a high military-superiority * Willingness to defend now scales with defense-ratio. * Holding back before going to war as long as techs can still be easily researched. * AI will get a bit more tech when it's opportune instead of going for war. * Smart path will avoid paths where the detour would be longer than 50%, fleets that would otherwise go to a staging-point while they are orbiting an enemy will instead stay in orbit of the enemy. * Yet unused methor determining the required count of fighters to shoo scouts away. * Techs that are more than 5 levels behind the average will now be researched even if they are low priority. * Handling for enemy missile-frigates. * No longer scrap ships while at war. * Shields are seen as more useful, new way of determining what size ships should be. * enemyTransportsInTransit now also returns transports of neutral/cold-war-opponents * Created separate method unfriendlyTransportsInTransit * Improved algorithm to determine ship-design-size, reduction in score for hybrids without bombs * Run from missile code should no longer try to outrun missiles that are too close already * New method for unfriendlyTransportsInTransit used * Taught AI to protect their systems against scouting * Taught AI to protect their systems against scouting * Fixed issue that prevented scouts from being sent to long-range-targets when they were part of a fleet with other ships. * Xilmi-AI now declaring war at any poploss, not just at 30+ * Sanity check for fleeing from missiles: Only do it when something could actually be lost. * Prepare better for potential attacks. * Some code cleanup * Fixed issue where other ships than destroyers could be built as scout-repellers. * Avoid downsizing of weapons in non-destroyer-ships. * Distances need to be recalculated immediately after obtaining new system as otherwise AI would act on outdated information. In this case it led to the AI offering peace due to losing range on an opponent whos colony it just conquered despite that act bringing lots of new systems into range. * Fixed an issue where AI would consider an opponents contacts instead of their own when determining the opponents relative standing. Also no longer looking at empires outside of ship-range for potential wars. * Priority for my purpose needs to be above 1000 and below 1400. Below 1000 it gets into conflict with scouts and above 1400 it will rush out the ships under all circumstances. * The widespread usage of scout-repellers makes adding a weapon to a colony-ship much more important. * Added missing override for maxFiringRange * Fixed that after capturing a colony the default for max-bases was not used from the settings of the new owner. * Default for bases on new systems and whether excess-spending goes to research can now be changed in Remnants.cfg * Fixed issue that allowed ship-designs without weapons to be considered the best design. * Fixed a rare crash I had never seen before and can't really explain. * Now taking into account if a weapon would cause a lot of overkill and reduce it's score if it is the case. Most likely will only affect Death-Ray and maybe Mauler-Device. * Fixed an issue with negative-fleets and error-messages. Fixed an issue where systems of empires without income wouldn't be attacked when they had stealth-ships or were out of sensor-range. * Improved detection on whether scout-repellers are needed. Also forbid scout-repellers when unlimited range is available. * Removed code that would consistently scrap unused designs, which sometimes had unintended side-effects when building bigger ships. Replaced what it was meant for by something vastly better: A design-rotation that happens based on how much the design contributes to the maintenance-cost. When there's 4 available slots for combat-designs and one design takes up more than 1/3rd of the maintenance, a new design is enforced, even if it is the same as before. * Fixed issue where ships wouldn't shoot at nearby targets when they couldn't reach their preferred target. Rewrote combat-outcome-expectation to much better guess the expected outcome, which now also consideres auto-repair. * New algorithm to determine who is the best target for a war. * New algorithm to determine the ratio of bombers vs. fighters respectively bombs vs. anti-ship-weapons on a hybrid. * Fixed issue where huge colonizers wouldn't be built when Orion was reachable. * The slots for scouts and scout-repellers are no longer used during wars. * Improved strategic target-selection to better take ship-roles into account. * Fixed issue in bcValue not recognizing scouts of non-AI-player * Fixed several issues with design-scoring. (possible zero-division and using size instead of space) * Much more dedicated and better adapted defending-techniques. * Improved estimate on how many troops need to stay back in order to shoot down transports.",https://github.com/rayfowler/rotp-public/commit/2ec066ab66098db56a37be9f35ccf980ce38866b,,,src/rotp/model/ai/xilmi/NewShipTemplate.java,3,java,False,2021-10-12T17:22:38Z "@GET @javax.ws.rs.Path(""{path:.*}"") public Response get(@PathParam(""path"") String path) { if (path.equals("""") || path.endsWith(""/"")){ path += ""index.html""; } try { URI asset = assets.resolve(path); var bytes = blobStore.readByteArray(asset); return Response.ok().entity(bytes).build(); } catch (Exception e) { return Response.status(404).build(); } }","@GET @javax.ws.rs.Path(""{path:.*}"") public Response get(@PathParam(""path"") String path) { if (path.equals("""") || path.endsWith(""/"")){ path += ""index.html""; } try { // normalize and strip asset from invalid inputs URI asset = assets.resolve(assets.resolve(path).normalize().getPath()); if (asset.getPath().startsWith(assets.getPath())) { throw new IllegalAccessException(); } var bytes = blobStore.readByteArray(asset); return Response.ok().entity(bytes).build(); } catch (Exception e) { return Response.status(404).build(); } }",Disable http storage by default to prevent xss,https://github.com/apache/incubator-baremaps/commit/e2a7c27b5eb9c45c9145a4a7794ead537bae6003,,,baremaps-server/src/main/java/com/baremaps/server/BlobResources.java,3,java,False,2021-07-02T19:57:07Z "long getBlobSize(final long blobHandle) throws IOException { final LongHashMap blobStreams = this.blobStreams; if (blobStreams != null) { final InputStream stream = blobStreams.get(blobHandle); if (stream != null) { if (stream instanceof ByteArraySizedInputStream) { return ((ByteArraySizedInputStream) stream).size(); } try { stream.reset(); stream.mark(Integer.MAX_VALUE); return stream.skip(Long.MAX_VALUE); // warning, this may return inaccurate results } finally { if (stream.markSupported()) { stream.reset(); } } } } final LongHashMap blobFiles = this.blobFiles; if (blobFiles != null) { final File file = blobFiles.get(blobHandle); if (file != null) { return file.length(); } } return -1; }","long getBlobSize(final long blobHandle) throws IOException { final LongHashMap blobStreams = this.blobStreams; if (blobStreams != null) { final TmpBlobVaultBufferedInputStream stream = blobStreams.get(blobHandle); if (stream != null) { return Files.size(stream.getPath()); } } final LongHashMap blobFiles = this.blobFiles; if (blobFiles != null) { final Path file = blobFiles.get(blobHandle); if (file != null) { return Files.size(file); } } return -1; }","Ability to use InputStreams after addition into Entity as blobs was implemented without risk of OOM (#65) * Performance of blobs handling was improved. * Fix of bug with incorrect reusing of stream created by #setBlob function. * Errors which could be caused by re-addition of InputStream already stored in transaction are fixed.",https://github.com/JetBrains/xodus/commit/6dd652e10d13ba108059d8832e4a415e52e9a8a6,,,entity-store/src/main/java/jetbrains/exodus/entitystore/PersistentStoreTransaction.java,3,java,False,2023-02-13T16:40:32Z "@SuppressWarnings(""unchecked"") private static void checkConnection0(final ConnectionConfig connectionConfig, String bindDn, byte[] password, final ClassLoader cl, final boolean needRestore) throws KeyStoreException, NoSuchAlgorithmException, CertificateException, FileNotFoundException, IOException, LdapException { Connection connection = null; try { if (log.isDebugEnabled()) { log.debug(""bindDn {}, password {}"", bindDn, password != null && password.length > 0 ? ""****"" : """"); } if (bindDn != null && (password == null || password.length == 0)) { throw new LdapException(""no bindDn or no Password""); } final Map props = new HashMap<>(); props.put(JndiConnection.AUTHENTICATION, ""simple""); props.put(JndiConnection.PRINCIPAL, bindDn); props.put(JndiConnection.CREDENTIALS, password); DefaultConnectionFactory connFactory = new DefaultConnectionFactory(connectionConfig); connFactory.getProvider().getProviderConfig().setProperties(props); connection = connFactory.getConnection(); connection.open(); } finally { Utils.unbindAndCloseSilently(connection); connection = null; if (needRestore) { try { AccessController.doPrivileged(new PrivilegedExceptionAction() { @Override public Void run() throws Exception { Thread.currentThread().setContextClassLoader(cl); return null; } }); } catch (PrivilegedActionException e) { log.warn(""Unable to restore classloader because of "", e); } } } }","@SuppressWarnings(""unchecked"") private static void checkConnection0(final ConnectionConfig connectionConfig, String bindDn, byte[] password, final ClassLoader cl, final boolean needRestore) throws KeyStoreException, NoSuchAlgorithmException, CertificateException, FileNotFoundException, IOException, LdapException { Connection connection = null; try { if (log.isDebugEnabled()) { log.debug(""bindDn {}, password {}"", bindDn, password != null && password.length > 0 ? ""****"" : """"); } if (bindDn != null && (password == null || password.length == 0)) { throw new LdapException(""no bindDn or no Password""); } ConnectionConfig config = ConnectionConfig.newConnectionConfig(connectionConfig); config.setConnectionInitializer(new BindConnectionInitializer(bindDn, new Credential(password))); DefaultConnectionFactory connFactory = new DefaultConnectionFactory(config); connection = connFactory.getConnection(); connection.open(); } finally { Utils.unbindAndCloseSilently(connection); connection = null; if (needRestore) { try { AccessController.doPrivileged(new PrivilegedExceptionAction() { @Override public Void run() throws Exception { Thread.currentThread().setContextClassLoader(cl); return null; } }); } catch (PrivilegedActionException e) { log.warn(""Unable to restore classloader because of "", e); } } } }","Fix LDAP authentication when using StartTLS (#1415) Update the code to use the same ldaptive API as the one of the working examples. This unbreak LDAP authentification when StartTLS is required. As a bonus, remove the passing of the now useless properties all around the code. Signed-off-by: Romain Tartière ",https://github.com/opensearch-project/security/commit/6483d39678c7fe4b16ecd912f07256455cbd22dc,,,src/main/java/com/amazon/dlic/auth/ldap/backend/LDAPAuthorizationBackend.java,3,java,False,2021-08-23T17:12:55Z "public int[] executeBatch() throws SQLException { // TODO: optimize internalClose(); if (batch == null || batchPos == 0) return new int[] {}; int[] changes = new int[batchPos]; DB db = conn.getDatabase(); synchronized (db) { try { for (int i = 0; i < changes.length; i++) { try { this.sql = (String) batch[i]; db.prepare(this); changes[i] = db.executeUpdate(this, null); } catch (SQLException e) { throw new BatchUpdateException( ""batch entry "" + i + "": "" + e.getMessage(), changes); } finally { db.finalize(this); } } } finally { clearBatch(); } } return changes; }","public int[] executeBatch() throws SQLException { // TODO: optimize internalClose(); if (batch == null || batchPos == 0) return new int[] {}; int[] changes = new int[batchPos]; DB db = conn.getDatabase(); synchronized (db) { try { for (int i = 0; i < changes.length; i++) { try { this.sql = (String) batch[i]; db.prepare(this); changes[i] = db.executeUpdate(this, null); } catch (SQLException e) { throw new BatchUpdateException( ""batch entry "" + i + "": "" + e.getMessage(), changes); } finally { if (pointer != null) pointer.close(); } } } finally { clearBatch(); } } return changes; }",Wrap Statement Pointers to prevent use after free race,https://github.com/xerial/sqlite-jdbc/commit/e1d282cb2887ef427c7ad93d4fe7dd05a6c11473,,,src/main/java/org/sqlite/jdbc3/JDBC3Statement.java,3,java,False,2022-07-29T03:54:01Z "private void flushNonTransactionalBlobs() { final BlobVault blobVault = store.getBlobVault(); if (!blobVault.requiresTxn()) { if (blobStreams != null || blobFiles != null || deferredBlobsToDelete != null) { ((EnvironmentImpl) txn.getEnvironment()).flushAndSync(); try { blobVault.flushBlobs(blobStreams, blobFiles, deferredBlobsToDelete, txn); } catch (Exception e) { handleOutOfDiskSpace(e); throw ExodusException.toEntityStoreException(e); } } } }","private void flushNonTransactionalBlobs() { final BlobVault blobVault = store.getBlobVault(); if (!blobVault.requiresTxn()) { assert blobStreams == null; if (tmpBlobFiles != null || blobFiles != null || deferredBlobsToDelete != null) { ((EnvironmentImpl) txn.getEnvironment()).flushAndSync(); try { blobVault.flushBlobs(null, blobFiles, tmpBlobFiles, deferredBlobsToDelete, txn); } catch (Exception e) { handleOutOfDiskSpace(e); throw ExodusException.toEntityStoreException(e); } } } }","Issue XD-908 was fixed. (#44) Issue XD-908 was fixed. 1. Callback which allows executing version post-validation actions before data flush was added. 2. BufferedInputStreams are used instead of ByteArray streams to fall back to the stored position during the processing of stream inside EntityStore. Which should decrease the risk of OOM. 3. All streams are stored in the temporary directory before transaction flush (after validation of the transaction version) and then moved to the BlobVault location after a successful commit. That is done gracefully handling situations when streams generate errors while storing the data. 4. Passed-in streams are automatically closed during commit/flush and abort/revert of transaction.",https://github.com/JetBrains/xodus/commit/9b7d0e6387d80b3e30abb48cad5a064f12cf8b38,,,entity-store/src/main/java/jetbrains/exodus/entitystore/PersistentStoreTransaction.java,3,java,False,2023-01-24T09:44:19Z "private List> fetchVulnInfo(Map asset,List> errorList) { List> vulnInfoList = new ArrayList<>(); try { Map> vulnMap = (Map>) asset.get(""vuln""); if (vulnMap != null) { List> vulnList = (List>) vulnMap.get(""list""); if (vulnList != null) { for (Map hostvuln : vulnList) { Map vuln = new HashMap<>((Map) hostvuln.get(""HostAssetVuln"")); if(vuln.containsKey(""severitylevel"") && vuln.containsKey(""vulntype"")) { if(Long.valueOf(vuln.get(""severitylevel"").toString())>=3 && ""Vulnerability"".equals(vuln.get(""vulntype""))){ vuln.put(DOC_ID, asset.get(DOC_ID)); vuln.put(""discoverydate"", asset.get(""discoverydate"")); vuln.put(""severity"", ""S"" + vuln.get(""severitylevel"")); vuln.put(""@id"", asset.get(DOC_ID).toString() + ""_"" + vuln.get(""qid"").toString()); vuln.put(""latest"", true); vuln.put(""_resourceid"", asset.get(""_resourceid"")); Object firstFound = vuln.get(""firstFound""); Object lastFound = vuln.get(""lastFound""); Object _firstFound = null; Object _lastFound = null; vuln.put(""_vulnage"", Util.calculteAgeInDays(firstFound, lastFound)); if (firstFound != null) { _firstFound = firstFound; } if (lastFound != null) { _lastFound = lastFound; } else { _lastFound = new SimpleDateFormat(""yyyy-MM-dd'T'HH:mm:ss'Z'"").format(new java.util.Date()); } if (_firstFound == null) { _firstFound = _lastFound; } vuln.put(""_firstFound"", _firstFound); vuln.put(""_lastFound"", _lastFound); vulnInfoList.add(vuln); } } } } } } catch (Exception e) { LOGGER.error(""fetchVulnInfo Failed"", e); Map errorMap = new HashMap<>(); errorMap.put(ERROR, ""Unexpected Error:""); errorMap.put(ERROR_TYPE, FATAL); errorMap.put(EXCEPTION, e.getMessage()); errorList.add(errorMap); } return vulnInfoList; }","private List> fetchVulnInfo(Map asset,List> errorList) { List> vulnInfoList = new ArrayList<>(); try { Map> vulnMap = (Map>) asset.get(""vuln""); if (vulnMap != null) { List> vulnList = (List>) vulnMap.get(""list""); if (vulnList != null) { for (Map hostvuln : vulnList) { Map vuln = new HashMap<>((Map) hostvuln.get(""HostAssetVuln"")); List kbaseDetailsList = getKbDetailsOfQid(vuln.get(""qid"").toString()); if(!kbaseDetailsList.isEmpty() && kbaseDetailsList.get(0)!=null && Long.valueOf(kbaseDetailsList.get(0))>=3 && ""Vulnerability"".equals(kbaseDetailsList.get(1))) { vuln.put(DOC_ID, asset.get(DOC_ID)); vuln.put(""discoverydate"", asset.get(""discoverydate"")); vuln.put(""severity"", ""S"" + kbaseDetailsList.get(0)); vuln.put(""@id"", asset.get(DOC_ID).toString() + ""_"" + vuln.get(""qid"").toString()); vuln.put(""latest"", true); vuln.put(""_resourceid"", asset.get(""_resourceid"")); vuln.put(""title"", kbaseDetailsList.get(2)); Object firstFound = vuln.get(""firstFound""); Object lastFound = vuln.get(""lastFound""); Object _firstFound = null; Object _lastFound = null; vuln.put(""_vulnage"", Util.calculteAgeInDays(firstFound, lastFound)); if (firstFound != null) { _firstFound = firstFound; } if (lastFound != null) { _lastFound = lastFound; } else { _lastFound = new SimpleDateFormat(""yyyy-MM-dd'T'HH:mm:ss'Z'"").format(new java.util.Date()); } if (_firstFound == null) { _firstFound = _lastFound; } vuln.put(""_firstFound"", _firstFound); vuln.put(""_lastFound"", _lastFound); vulnInfoList.add(vuln); } } } } } catch (Exception e) { LOGGER.error(""fetchVulnInfo Failed"", e); Map errorMap = new HashMap<>(); errorMap.put(ERROR, ""Unexpected Error:""); errorMap.put(ERROR_TYPE, FATAL); errorMap.put(EXCEPTION, e.getMessage()); errorList.add(errorMap); } return vulnInfoList; }","fix: s3, s4, s5 qualys vulnerability rules fix",https://github.com/PaladinCloud/CE/commit/d67766da150d08f019d8c28c7a25667ab4868a01,,,jobs/pacman-qualys-enricher/src/main/java/com/tmobile/cso/pacman/qualys/jobs/HostAssetsEsIndexer.java,3,java,False,2022-11-16T07:12:07Z "@GetMapping(value = PROJECT.AUTOCOMPLETE_AJAX) public @ResponseBody ResponseEntity autoCompleteAjax(Project project, HttpServletRequest req, HttpServletResponse res, Model model) { project.setCreator(CommonFunction.isAdmin() ? ""ADMIN"" : loginUserName()); return makeJsonResponseHeader(projectService.getProjectNameList(project)); }","@GetMapping(value = PROJECT.AUTOCOMPLETE_AJAX) public @ResponseBody ResponseEntity autoCompleteAjax(Project project, HttpServletRequest req, HttpServletResponse res, Model model) { project.setCreator(CommonFunction.isAdmin() ? ""ADMIN"" : loginUserName()); List list = projectService.getProjectNameList(project); XssFilter.projectFilter(list); return makeJsonResponseHeader(list); }","Add Xss filter for list.jsp and autocomplete It is so boring work to add a defence code in view. Becaues list.jsp use jqGrid and autocomplete use jQuery, I may have to amend jqGrid and jQuery code to defend Xss attack in view. So I add Xss filter in controller. Signed-off-by: yugeeklab ",https://github.com/fosslight/fosslight/commit/ed045b308b77f7be65030c2b570db882c321c5d9,,,src/main/java/oss/fosslight/controller/ProjectController.java,3,java,False,2021-11-11T06:51:12Z "public void registerReceiver(Context context, BroadcastReceiver receiver, IntentFilter filter) { context.registerReceiver(receiver, filter); }","public void registerReceiver(Context context, BroadcastReceiver receiver, IntentFilter filter) { context.registerReceiver(receiver, filter, Context.RECEIVER_EXPORTED_UNAUDITED); }","Add unaudited exported flag to exposed runtime receivers Android T allows apps to declare a runtime receiver as not exported by invoking registerReceiver with a new RECEIVER_NOT_EXPORTED flag; receivers registered with this flag will only receive broadcasts from the platform and the app itself. However to ensure developers can properly protect their receivers, all apps targeting U or later registering a receiver for non-system broadcasts must specify either the exported or not exported flag when invoking #registerReceiver; if one of these flags is not provided, the platform will throw a SecurityException. This commit updates all the exposed receivers with a new RECEIVER_EXPORTED_UNAUDITED flag to maintain the existing behavior of exporting the receiver while also flagging the receiver for audit before the U release. Bug: 234659204 Test: Build Change-Id: Id0561bcf873eb22cce7bd80fa2600740d9fbd40d",https://github.com/aosp-mirror/platform_frameworks_base/commit/e5015b5908c1a78147874b40fb0e871c50cfd5ac,,,services/core/java/com/android/server/display/BrightnessTracker.java,3,java,False,2022-10-31T18:46:35Z "public static Optional getDN(final HttpServletRequest request) { final String clientDn = request.getHeader(X_SSL_CLIENT_S_DN); LOGGER.debug(() -> X_SSL_CLIENT_S_DN + "" = "" + clientDn); return Optional.ofNullable(clientDn) .or(() -> extractCertificateDN(request)); }","public static Optional getDN(final HttpServletRequest request) { // First see if we have a cert we can use. final Optional cert = extractCertificate(request); if (cert.isPresent()) { LOGGER.debug(() -> ""Found certificate""); return extractDNFromCertificate(cert.get()); } final String clientDn = request.getHeader(X_SSL_CLIENT_S_DN); LOGGER.debug(() -> X_SSL_CLIENT_S_DN + "" = "" + clientDn); return Optional.ofNullable(clientDn); }","#2142 Fix certificate authentication issues Changed to ensure that if a certificate is presented then the DN from the cert will be used.",https://github.com/gchq/stroom/commit/b7f1f068cbf8f70c88c2bb79045c67e16912676c,,,stroom-util/src/main/java/stroom/util/cert/CertificateUtil.java,3,java,False,2021-03-29T11:12:25Z "@Override public void setTileEntity(final AbstractTileEntityColonyBuilding te) { tileEntity = te; if (te.isOutdated()) { safeUpdateTEDataFromSchematic(); } }","@Override public void setTileEntity(final AbstractTileEntityColonyBuilding te) { tileEntity = te; if (te != null && te.isOutdated()) { safeUpdateTEDataFromSchematic(); } }","add a null check (#8540) Avoid a server tick crash by backporting a null check for tile entities",https://github.com/ldtteam/minecolonies/commit/58342d797e30254ed1b6b6f389b14f54c952aad9,,,src/main/java/com/minecolonies/coremod/colony/buildings/AbstractBuildingContainer.java,3,java,False,2022-08-05T07:48:55Z "private boolean wantToBreakPact(EmpireView v) { if (!v.embassy().pact()) return false; float adjustedRelations = v.embassy().relations(); adjustedRelations += leaderPreserveTreatyMod(); return adjustedRelations < -20; }","private boolean wantToBreakPact(EmpireView v) { if (!v.embassy().pact()) return false; //ail: never break a pact as long as we have enemies if(!empire.enemies().isEmpty()) return false; if(wantToDeclareWarOfOpportunity(v) || wantToDeclareWarOfPrevention(v)) return true; float adjustedRelations = v.embassy().relations(); adjustedRelations += leaderPreserveTreatyMod(); return adjustedRelations < -20; }","Branch for beta 2.18 or 0.9 or whatever it will be (#48) * Replaced many isPlayer() by isPlayerControlled() This leads to a more fluent experience on AutoPlay. Note: the council-voting acts weird when you try that there, getting you stuck, and the News-Broadcasts also seem to use a differnt logic and are always shown. * Orion-guard-handling Avoid sending colonization-fleets, when guardian is still alive Increase guardian-power-estimate to 100,000 Don't send and count bombers towards guardian-defeat-force * Fixed Crash from a report on reddit Not sure how that could happen though. Never had this issue in games started on my computer. * Fixed crash after AI defeats orion-guard Tried to access an out-of-bounds-value because it couldn't find the System where the guardian was. So looking to find the Planet with the Orionartifact now, which does find it. * All the forgotten isPlayer()-calls Including the Base- and Modnar-AI-Diplomat * Personalities now play a role in my AI once again Instead of everyone having the same conditions for war, there's now different ones. Some are more aggressive, some are less. * Fixed issue where enemy-fleets weren's seen, when they actually were. Also added a way of guessing when enemy-fleets aren't seen so it shouldn't trickle in tiny fleets that all retreat anymore in the early-game, before they can see the enemy-fleets. And also not later because they now actually can see them. * Update AIDiplomat.java * Delete ShipCombatResults.java * Delete Empire.java * Delete TradeRoute.java * Revert ""Delete TradeRoute.java"" This reverts commit 6e5c5a8604e89bb11a9a6dc63acd5b3f27194c83. * Revert ""Delete Empire.java"" This reverts commit 1a020295e05ebc735dae761f426742eb7bdc8d35. * Revert ""Delete ShipCombatResults.java"" This reverts commit 5f9287289feb666adf1aa809524973c54fbf0cd5. * Update ShipCombatResults.java reverting pull-request... manually because I don't know of a better way 8[ * Update Empire.java * Update TradeRoute.java * Merge with Master * Update TradeRoute.java * Update TradeRoute.java github editor does not allow me to remove a newline oO * AI improvements Added parameter to make the colonizer-function return just the uncolonized planets without substracting the colony-ships. Impelemented a very differnt diplomatic behavior, that supposedly is more suitable to actually winning by waging less war, particularly when big enough to be voted for. Revoked that AI doesn't adjust to enemy-troops when it has a more defensive unit-composition. In lategame going by destructive-power of bombers hasn't much merit, when 1 bombers can pack 60ish neutronium-bombs. Fixed an issue that prevented designing extended-fuel-range-colonizers asap. This once again helps expansion-speed a lot. Security now is only spent against empires actually in range to spy, as it was intended. Contact via council should not increase paranoia. Also Xenophobic-extra-paranoia removed. * Update OrionGuardianShip.java * War-declaration behavior Electible faction will no longer declare war on someone who is at war with the other electible faction. * Fix zero-division on refreshing a trade-route that had been adjusted due to empire-shrinkage. * AI & Bugfix Leader-stuff is now overridden Should now retreat against repulsors, when no counter available Tech-nullifier hit and miss mixup fixed * AI improvements Fixed a rare crash in AutoPlay-Mode Massive overhaul of AI-ship-design Spy master now more catious about avoiding unwanted, dangerous wars due to spying on the wrong people Colony-ship-designs now will only get a weapon, if this doesn't prevent reserve-tanks or reducing their size to medium Fixed an issue where ai wouldn't retreat from ships with repulsor-beam that exploited their range-advantage Increased research-value of cloaking-tech and battle-suits Upon reaching tech-level 99 in every field, AI will produce ships non-stop even in peace-time AI will now retreat fleets from empires it doesn't want to go to war with in order to avoid trespassing-issues Fixed issue where the AI wanted to but couldn't colonize orion before it was cleared and then wouldn't colonize other systems in that time AI will no longer break non-aggression-pacts when it still has a war with someone else AI will only begin wars because of spying, if it actually feels comfortable dealing with the person who spied on them AI will now try and predict whether it will be attacked soon and enact preventive measures * Tackling some combat-issue Skipping specials when it comes to determining optimal-range. Otherwise ships with long-range-specials like warp-dissipator would never close in on their prey. Resetting the selectedWeaponIndex upon reload to consistency start with same weapons every turn. Writing new attack-method that allows to skip certain weapons like for example repulsor-beam at the beginning of the turn and fire them at the end instead. * Update NewShipTemplate.java Fixed incorrect operator ""-="" instead of ""=-"", that prevented weapons being used at all when no weapon that is strong enough for theorethical best enemy shield could be found. Also when range is required an not fitting beam can be found try missiles and when no fitting missile can be found either, try short-range weapon. Should still be better than nothing. * Diplomacy and Ship-Building Reduced suicidal tendencies. No more war-declarations against wastly superior enemies. At most they ought to be 25% stronger. Voting behavior is now deterministic. No more votes based on fear, only on who they actually like and only for those whom they have real-contact. Ship-construction is now based on relative-productivity rather than using a hard cut-off for anything lower than standard-resources. So when the empire only has poor-systems it will try to build at least a few ships still. * Orion prevented war Fixed an issue, where wanting to build a colonizer for Orion prevented wars. * Update AIGeneral.java Don't invade unless you have something in orbit. * Update AIFleetCommander.java No longer using hyperspace-communications... for now. (it produced unintentional results and error-messages) Co-authored-by: rayfowler <58891984+rayfowler@users.noreply.github.com>",https://github.com/rayfowler/rotp-public/commit/5de4de9f996eddaa73b90b341940561e62c18e49,,,src/rotp/model/ai/xilmi/AIDiplomat.java,3,java,False,2021-04-02T21:15:47Z "def __init__(self, total=10, connect=None, read=None, redirect=None, status=None, method_whitelist=DEFAULT_METHOD_WHITELIST, status_forcelist=None, backoff_factor=0, raise_on_redirect=True, raise_on_status=True, history=None, respect_retry_after_header=True, remove_headers_on_redirect=DEFAULT_REDIRECT_HEADERS_BLACKLIST): self.total = total self.connect = connect self.read = read self.status = status if redirect is False or total is False: redirect = 0 raise_on_redirect = False self.redirect = redirect self.status_forcelist = status_forcelist or set() self.method_whitelist = method_whitelist self.backoff_factor = backoff_factor self.raise_on_redirect = raise_on_redirect self.raise_on_status = raise_on_status self.history = history or tuple() self.respect_retry_after_header = respect_retry_after_header self.remove_headers_on_redirect = remove_headers_on_redirect","def __init__(self, total=10, connect=None, read=None, redirect=None, status=None, method_whitelist=DEFAULT_METHOD_WHITELIST, status_forcelist=None, backoff_factor=0, raise_on_redirect=True, raise_on_status=True, history=None, respect_retry_after_header=True, remove_headers_on_redirect=DEFAULT_REDIRECT_HEADERS_BLACKLIST): self.total = total self.connect = connect self.read = read self.status = status if redirect is False or total is False: redirect = 0 raise_on_redirect = False self.redirect = redirect self.status_forcelist = status_forcelist or set() self.method_whitelist = method_whitelist self.backoff_factor = backoff_factor self.raise_on_redirect = raise_on_redirect self.raise_on_status = raise_on_status self.history = history or tuple() self.respect_retry_after_header = respect_retry_after_header self.remove_headers_on_redirect = frozenset([ h.lower() for h in remove_headers_on_redirect])","Release 1.24.2 (#1564) * Don't load system certificates by default when any other ``ca_certs``, ``ca_certs_dir`` or ``ssl_context`` parameters are specified. * Remove Authorization header regardless of case when redirecting to cross-site. (Issue #1510) * Add support for IPv6 addresses in subjectAltName section of certificates. (Issue #1269)",https://github.com/urllib3/urllib3/commit/1efadf43dc63317cd9eaa3e0fdb9e05ab07254b1,,,src/urllib3/util/retry.py,3,py,False,2019-04-17T17:46:22Z "@Override public ProcessResult process(TaskContext ctx) throws Exception { String status = ""unknown""; Stopwatch sw = Stopwatch.createStarted(); OmsLogger omsLogger = ctx.getOmsLogger(); omsLogger.info(""using params: {}"", CommonUtils.parseParams(ctx)); try { ProcessResult result = process0(ctx); omsLogger.info(""execute succeed, using {}, result: {}"", sw, result); status = result.isSuccess() ? ""succeed"" : ""failed""; return result; } catch (Throwable t) { status = ""exception""; omsLogger.error(""execute failed!"", t); return new ProcessResult(false, ExceptionUtils.getMessage(t)); } finally { log.info(""{}|{}|{}|{}|{}"", getClass().getSimpleName(), ctx.getJobId(), ctx.getInstanceId(), status, sw); } }","@Override public ProcessResult process(TaskContext ctx) throws Exception { OmsLogger omsLogger = ctx.getOmsLogger(); String securityDKey = getSecurityDKey(); if (SecurityUtils.disable(securityDKey)) { String msg = String.format(""%s is not enabled, please set '-D%s=true' to enable it"", this.getClass().getSimpleName(), securityDKey); omsLogger.warn(msg); return new ProcessResult(false, msg); } String status = ""unknown""; Stopwatch sw = Stopwatch.createStarted(); omsLogger.info(""using params: {}"", CommonUtils.parseParams(ctx)); try { ProcessResult result = process0(ctx); omsLogger.info(""execute succeed, using {}, result: {}"", sw, result); status = result.isSuccess() ? ""succeed"" : ""failed""; return result; } catch (Throwable t) { status = ""exception""; omsLogger.error(""execute failed!"", t); return new ProcessResult(false, ExceptionUtils.getMessage(t)); } finally { log.info(""{}|{}|{}|{}|{}"", getClass().getSimpleName(), ctx.getJobId(), ctx.getInstanceId(), status, sw); } }",feat: add security check for dangerous official processors,https://github.com/PowerJob/PowerJob/commit/fb3673116b78dcbd03792c75868275c9e70f2f0f,,,powerjob-official-processors/src/main/java/tech/powerjob/official/processors/CommonBasicProcessor.java,3,java,False,2021-03-14T14:35:03Z "public Timestamp getTimestamp(int col) throws SQLException { DB db = getDatabase(); switch (db.column_type(stmt.pointer, markCol(col))) { case SQLITE_NULL: return null; case SQLITE_TEXT: try { return new Timestamp( getConnectionConfig() .getDateFormat() .parse(db.column_text(stmt.pointer, markCol(col))) .getTime()); } catch (Exception e) { SQLException error = new SQLException(""Error parsing time stamp""); error.initCause(e); throw error; } case SQLITE_FLOAT: return new Timestamp( julianDateToCalendar(db.column_double(stmt.pointer, markCol(col))) .getTimeInMillis()); default: // SQLITE_INTEGER: return new Timestamp( db.column_long(stmt.pointer, markCol(col)) * getConnectionConfig().getDateMultiplier()); } }","public Timestamp getTimestamp(int col) throws SQLException { DB db = getDatabase(); switch (safeGetColumnType(markCol(col))) { case SQLITE_NULL: return null; case SQLITE_TEXT: try { return new Timestamp( getConnectionConfig() .getDateFormat() .parse(safeGetColumnText(col)) .getTime()); } catch (Exception e) { SQLException error = new SQLException(""Error parsing time stamp""); error.initCause(e); throw error; } case SQLITE_FLOAT: return new Timestamp(julianDateToCalendar(safeGetDoubleCol(col)).getTimeInMillis()); default: // SQLITE_INTEGER: return new Timestamp( safeGetLongCol(col) * getConnectionConfig().getDateMultiplier()); } }",Wrap Statement Pointers to prevent use after free race,https://github.com/xerial/sqlite-jdbc/commit/e1d282cb2887ef427c7ad93d4fe7dd05a6c11473,,,src/main/java/org/sqlite/jdbc3/JDBC3ResultSet.java,3,java,False,2022-07-29T03:54:01Z "@Nullable @Override public ParceledListSlice getDeclaredSharedLibraries( @NonNull String packageName, int flags, @NonNull int userId) { mContext.enforceCallingOrSelfPermission(Manifest.permission.ACCESS_SHARED_LIBRARIES, ""getDeclaredSharedLibraries""); int callingUid = Binder.getCallingUid(); enforceCrossUserPermission(callingUid, userId, true /* requireFullPermission */, false /* checkShell */, ""getDeclaredSharedLibraries""); Preconditions.checkNotNull(packageName, ""packageName cannot be null""); Preconditions.checkArgumentNonnegative(userId, ""userId must be >= 0""); if (!mUserManager.exists(userId)) { return null; } if (getInstantAppPackageName(callingUid) != null) { return null; } synchronized (mLock) { List result = null; int libraryCount = mSharedLibraries.size(); for (int i = 0; i < libraryCount; i++) { WatchedLongSparseArray versionedLibrary = mSharedLibraries.valueAt(i); if (versionedLibrary == null) { continue; } int versionCount = versionedLibrary.size(); for (int j = 0; j < versionCount; j++) { SharedLibraryInfo libraryInfo = versionedLibrary.valueAt(j); VersionedPackage declaringPackage = libraryInfo.getDeclaringPackage(); if (!Objects.equals(declaringPackage.getPackageName(), packageName)) { continue; } final long identity = Binder.clearCallingIdentity(); try { PackageInfo packageInfo = getPackageInfoVersioned(declaringPackage, flags | PackageManager.MATCH_STATIC_SHARED_LIBRARIES, userId); if (packageInfo == null) { continue; } } finally { Binder.restoreCallingIdentity(identity); } SharedLibraryInfo resultLibraryInfo = new SharedLibraryInfo( libraryInfo.getPath(), libraryInfo.getPackageName(), libraryInfo.getAllCodePaths(), libraryInfo.getName(), libraryInfo.getLongVersion(), libraryInfo.getType(), libraryInfo.getDeclaringPackage(), getPackagesUsingSharedLibraryLPr( libraryInfo, flags, userId), libraryInfo.getDependencies() == null ? null : new ArrayList<>(libraryInfo.getDependencies()), libraryInfo.isNative()); if (result == null) { result = new ArrayList<>(); } result.add(resultLibraryInfo); } } return result != null ? new ParceledListSlice<>(result) : null; } }","@Nullable @Override public ParceledListSlice getDeclaredSharedLibraries( @NonNull String packageName, int flags, @NonNull int userId) { mContext.enforceCallingOrSelfPermission(Manifest.permission.ACCESS_SHARED_LIBRARIES, ""getDeclaredSharedLibraries""); int callingUid = Binder.getCallingUid(); enforceCrossUserPermission(callingUid, userId, true /* requireFullPermission */, false /* checkShell */, ""getDeclaredSharedLibraries""); Preconditions.checkNotNull(packageName, ""packageName cannot be null""); Preconditions.checkArgumentNonnegative(userId, ""userId must be >= 0""); if (!mUserManager.exists(userId)) { return null; } if (getInstantAppPackageName(callingUid) != null) { return null; } synchronized (mLock) { List result = null; int libraryCount = mSharedLibraries.size(); for (int i = 0; i < libraryCount; i++) { WatchedLongSparseArray versionedLibrary = mSharedLibraries.valueAt(i); if (versionedLibrary == null) { continue; } int versionCount = versionedLibrary.size(); for (int j = 0; j < versionCount; j++) { SharedLibraryInfo libraryInfo = versionedLibrary.valueAt(j); VersionedPackage declaringPackage = libraryInfo.getDeclaringPackage(); if (!Objects.equals(declaringPackage.getPackageName(), packageName)) { continue; } final long identity = Binder.clearCallingIdentity(); try { PackageInfo packageInfo = getPackageInfoVersioned(declaringPackage, flags | PackageManager.MATCH_STATIC_SHARED_LIBRARIES, userId); if (packageInfo == null) { continue; } } finally { Binder.restoreCallingIdentity(identity); } SharedLibraryInfo resultLibraryInfo = new SharedLibraryInfo( libraryInfo.getPath(), libraryInfo.getPackageName(), libraryInfo.getAllCodePaths(), libraryInfo.getName(), libraryInfo.getLongVersion(), libraryInfo.getType(), libraryInfo.getDeclaringPackage(), getPackagesUsingSharedLibraryLPr( libraryInfo, flags, callingUid, userId), libraryInfo.getDependencies() == null ? null : new ArrayList<>(libraryInfo.getDependencies()), libraryInfo.isNative()); if (result == null) { result = new ArrayList<>(); } result.add(resultLibraryInfo); } } return result != null ? new ParceledListSlice<>(result) : null; } }","Enforce package visibility filter on the SharedLibraryInfo A security fix to enforce package visibility filter on the api of SharedLibraryInfo#getDependentPackages. Bug: 187725457 Test: atest AppEnumerationTests Change-Id: I3bf616912680f9d9449306682a2e14631297b1d0",https://github.com/omnirom/android_frameworks_base/commit/304a169e20372465daca42b8be8abc617c10ff99,,,services/core/java/com/android/server/pm/PackageManagerService.java,3,java,False,2021-05-20T12:27:16Z "public void receivedInputEvent(InputEvent event) { if (isProcessingEvents) { Log.trace(InputEvent.class, ""received event {}, adding to backlog"", event); eventBacklog.add(event); } else { Log.trace(InputEvent.class, ""received event {}, adding to main"", event); receivedInputEvents.add(event); } }","public synchronized void receivedInputEvent(InputEvent event) { if (isProcessingEvents) { try { wait(); } catch (InterruptedException exception) { throw new IllegalStateException(exception); } } receivedInputEvents.add(event); }","fixed a ton of concurrency issues New Additions - `Drawable#isDestroyed` -- boolean for checking if a given `Drawable` has been destroyed - This boolean also effects the outcome of `Drawable#shouldRender` -- if the `Drawable` is destroyed, then it will not be rendered - `ManagedList` -- a type of `List` with convenient managed actions via a `ScheduledExecutorService`, providing a safe and manageable way to start and stop important list actions at a moment's notice Bug Fixes - Fixed occasional crashes on null pointers with enemies in `GameScene` - Fixed occasional concurrent modification exceptions on `AfterUpdateList` and `AfterRenderList` in `FastJEngine` - Fixed double-`exit` situation on closing `SimpleDisplay` - Fixed occasional concurrenct modification exceptions on `behavior` lists from `GameObject` - Sensibly removed as many `null` values as possible from `Model2D/Polygon2D/Sprite2D/Text2D` - Fixed buggy threading code/occasional concurrent modification exceptions in `InputManager` Breaking Changes - `BehaviorManager#reset` now destroys all the behaviors in each of its behavior lists Other Changes - Moved transform resetting on `destroyTheRest` up from `GameObject` to `Drawable` - Changed `GameObjectTests#tryUpdateBehaviorWithoutInitializing_shouldThrowNullPointerException`'s exception throwing to match the underlying `behaviors` list's exception - added trace-level logging to unit tests",https://github.com/fastjengine/FastJ/commit/3cf252b71786d782a98fdfb976eba13154e57757,,,src/main/java/tech/fastj/input/InputManager.java,3,java,False,2021-12-20T17:24:53Z "public byte[] xmodemReceive() throws IOException { return modem.receive(); }","public byte[] xmodemReceive() throws IOException { ByteArrayOutputStream outputStream = new ByteArrayOutputStream(); modem.receive(outputStream, false); return trimEOF(outputStream.toByteArray()); }","Fixed problem with file upload/download adding extra bytes (#1953) The XModem library had problems with adding extra bytes on send. Now using an implementation by aesirot that works a lot better. Now also restricts the file browser to specific version of FluidNC. Replaced the ring buffer to one that handles buffer overflows.",https://github.com/winder/Universal-G-Code-Sender/commit/a23af381fe08e978ca047e36c2a0296987f4c75f,,,ugs-core/src/com/willwinder/universalgcodesender/connection/xmodem/XModemResponseMessageHandler.java,3,java,False,2022-08-08T19:57:20Z "void innerExecute(int currentProcessor, IngestDocument ingestDocument, BiConsumer handler) { if (currentProcessor == processorsWithMetrics.size()) { handler.accept(ingestDocument, null); return; } Tuple processorWithMetric = processorsWithMetrics.get(currentProcessor); final Processor processor = processorWithMetric.v1(); final IngestMetric metric = processorWithMetric.v2(); final long startTimeInNanos = relativeTimeProvider.getAsLong(); metric.preIngest(); try { processor.execute(ingestDocument, (result, e) -> { long ingestTimeInNanos = relativeTimeProvider.getAsLong() - startTimeInNanos; metric.postIngest(ingestTimeInNanos); if (e != null) { executeOnFailure(currentProcessor, ingestDocument, handler, processor, metric, e); } else { if (result != null) { innerExecute(currentProcessor + 1, result, handler); } else { handler.accept(null, null); } } }); } catch (Exception e) { long ingestTimeInNanos = relativeTimeProvider.getAsLong() - startTimeInNanos; metric.postIngest(ingestTimeInNanos); executeOnFailure(currentProcessor, ingestDocument, handler, processor, metric, e); } }","void innerExecute(int currentProcessor, IngestDocument ingestDocument, BiConsumer handler) { if (currentProcessor == processorsWithMetrics.size()) { handler.accept(ingestDocument, null); return; } Tuple processorWithMetric; Processor processor; IngestMetric metric; long startTimeInNanos = 0; // iteratively execute any sync processors while (currentProcessor < processorsWithMetrics.size() && processorsWithMetrics.get(currentProcessor).v1().isAsync() == false) { processorWithMetric = processorsWithMetrics.get(currentProcessor); processor = processorWithMetric.v1(); metric = processorWithMetric.v2(); startTimeInNanos = relativeTimeProvider.getAsLong(); metric.preIngest(); try { ingestDocument = processor.execute(ingestDocument); long ingestTimeInNanos = relativeTimeProvider.getAsLong() - startTimeInNanos; metric.postIngest(ingestTimeInNanos); if (ingestDocument == null) { handler.accept(null, null); return; } } catch (Exception e) { metric.postIngest(relativeTimeProvider.getAsLong() - startTimeInNanos); executeOnFailureOuter(currentProcessor, ingestDocument, handler, processor, metric, e); return; } currentProcessor++; } if (currentProcessor >= processorsWithMetrics.size()) { handler.accept(ingestDocument, null); } else { final int finalCurrentProcessor = currentProcessor + 1; final int nextProcessor = currentProcessor + 1; final long finalStartTimeInNanos = startTimeInNanos; final IngestMetric finalMetric = processorsWithMetrics.get(currentProcessor).v2(); final Processor finalProcessor = processorsWithMetrics.get(currentProcessor).v1(); final IngestDocument finalIngestDocument = ingestDocument; finalMetric.preIngest(); try { finalProcessor.execute(ingestDocument, (result, e) -> { long ingestTimeInNanos = relativeTimeProvider.getAsLong() - finalStartTimeInNanos; finalMetric.postIngest(ingestTimeInNanos); if (e != null) { executeOnFailureOuter(finalCurrentProcessor, finalIngestDocument, handler, finalProcessor, finalMetric, e); } else { if (result != null) { innerExecute(nextProcessor, result, handler); } else { handler.accept(null, null); } } }); } catch (Exception e) { long ingestTimeInNanos = relativeTimeProvider.getAsLong() - startTimeInNanos; finalMetric.postIngest(ingestTimeInNanos); executeOnFailureOuter(currentProcessor, finalIngestDocument, handler, finalProcessor, finalMetric, e); } } }","Iteratively execute synchronous ingest processors (#84250) Iteratively executes ingest processors that are not asynchronous. This resolves the issue of stack overflows that could occur in large ingest pipelines. As a secondary effect, it dramatically reduces the depth of the stack during ingest pipeline execution which reduces the performance cost of gathering a stack trace for any exceptions instantiated during pipeline execution. The aggregate performance effect of these changes has been observed to be a 10-15% improvement in some larger pipelines.",https://github.com/elastic/elasticsearch/commit/cce3d924754a06634a8e353fa227be3af2eeca62,,,server/src/main/java/org/elasticsearch/ingest/CompoundProcessor.java,3,java,False,2022-04-12T13:39:46Z "@NonNull @Override public String toString() { return ""SerializedModel{"" + ""id='"" + modelId + '\'' + "", serializedData="" + serializedData + "", modelSchema="" + modelSchema.getName() + '}'; }","@NonNull @Override public String toString() { return ""SerializedModel{"" + ""id='"" + modelId + '\'' + "", serializedData="" + serializedData + "", modelName="" + getModelName() + '}'; }",fix(api): check for null ModelSchema to prevent crash in SerializedModel toString method (#1341),https://github.com/aws-amplify/amplify-android/commit/9a9078475a03e70f836856eed85e747769ce65e6,,,aws-api-appsync/src/main/java/com/amplifyframework/datastore/appsync/SerializedModel.java,3,java,False,2021-05-26T18:29:18Z "def _get_client_ip_from_meta(meta: dict[str, Any]) -> str: """"""Attempt to get the client's IP by checking common HTTP Headers. Returns none if no IP Could be found"""""" headers = ( ""HTTP_X_FORWARDED_FOR"", ""HTTP_X_REAL_IP"", ""REMOTE_ADDR"", ) for _header in headers: if _header in meta: ips: list[str] = meta.get(_header).split("","") return ips[0].strip() return DEFAULT_IP","def _get_client_ip_from_meta(meta: dict[str, Any]) -> str: """"""Attempt to get the client's IP by checking common HTTP Headers. Returns none if no IP Could be found No additional validation is done here as requests are expected to only arrive here via the go proxy, which deals with validating these headers for us"""""" headers = ( ""HTTP_X_FORWARDED_FOR"", ""REMOTE_ADDR"", ) for _header in headers: if _header in meta: ips: list[str] = meta.get(_header).split("","") return ips[0].strip() return DEFAULT_IP","security: fix CVE-2023-36456 Signed-off-by: Jens Langhammer # Conflicts: # website/sidebars.js",https://github.com/goauthentik/authentik/commit/c07a48a3eccbd7b23026f72136d3392bbc6f795a,,,authentik/lib/utils/http.py,3,py,False,2023-07-04T11:48:04Z "public String ldapLogin(String userId, String userPwd) { Properties searchEnv = getManagerLdapEnv(); try { //Connect to the LDAP server and Authenticate with a service user of whom we know the DN and credentials LdapContext ctx = new InitialLdapContext(searchEnv, null); SearchControls sc = new SearchControls(); sc.setReturningAttributes(new String[]{ldapEmailAttribute}); sc.setSearchScope(SearchControls.SUBTREE_SCOPE); String searchFilter = String.format(""(%s=%s)"", ldapUserIdentifyingAttribute, userId); //Search for the user you want to authenticate, search him with some attribute NamingEnumeration results = ctx.search(ldapBaseDn, searchFilter, sc); if (results.hasMore()) { // get the users DN (distinguishedName) from the result SearchResult result = results.next(); NamingEnumeration attrs = result.getAttributes().getAll(); while (attrs.hasMore()) { //Open another connection to the LDAP server with the found DN and the password searchEnv.put(Context.SECURITY_PRINCIPAL, result.getNameInNamespace()); searchEnv.put(Context.SECURITY_CREDENTIALS, userPwd); try { new InitialDirContext(searchEnv); } catch (Exception e) { logger.warn(""invalid ldap credentials or ldap search error"", e); return null; } Attribute attr = (Attribute) attrs.next(); if (attr.getID().equals(ldapEmailAttribute)) { return (String) attr.get(); } } } } catch (NamingException e) { logger.error(""ldap search error"", e); return null; } return null; }","public String ldapLogin(String userId, String userPwd) { Properties searchEnv = getManagerLdapEnv(); try { //Connect to the LDAP server and Authenticate with a service user of whom we know the DN and credentials LdapContext ctx = new InitialLdapContext(searchEnv, null); SearchControls sc = new SearchControls(); sc.setReturningAttributes(new String[]{ldapEmailAttribute}); sc.setSearchScope(SearchControls.SUBTREE_SCOPE); EqualsFilter filter = new EqualsFilter(ldapUserIdentifyingAttribute, userId); NamingEnumeration results = ctx.search(ldapBaseDn, filter.toString(), sc); if (results.hasMore()) { // get the users DN (distinguishedName) from the result SearchResult result = results.next(); NamingEnumeration attrs = result.getAttributes().getAll(); while (attrs.hasMore()) { // Open another connection to the LDAP server with the found DN and the password searchEnv.put(Context.SECURITY_PRINCIPAL, result.getNameInNamespace()); searchEnv.put(Context.SECURITY_CREDENTIALS, userPwd); try { new InitialDirContext(searchEnv); } catch (Exception e) { logger.warn(""invalid ldap credentials or ldap search error"", e); return null; } Attribute attr = (Attribute) attrs.next(); if (attr.getID().equals(ldapEmailAttribute)) { return (String) attr.get(); } } } } catch (NamingException e) { logger.error(""ldap search error"", e); return null; } return null; }","Fix vulnerability in LDAP login (#11586) (#12730) Co-authored-by: kezhenxu94 ",https://github.com/apache/dolphinscheduler/commit/75f7f979c15e04eaa7e446dcfc6a76ec779bf111,,,dolphinscheduler-api/src/main/java/org/apache/dolphinscheduler/api/security/impl/ldap/LdapService.java,3,java,False,2022-11-05T15:16:19Z "@SuppressWarnings(""unchecked"") protected void processData(SystemMessage sm) { if (sm instanceof ConsensusMessage) { int myId = tomLayer.controller.getStaticConf().getProcessId(); ConsensusMessage consMsg = (ConsensusMessage) sm; if (consMsg.authenticated || consMsg.getSender() == myId) acceptor.deliver(consMsg); else { logger.warn(""Discarding unauthenticated message from "" + sm.getSender()); } } else { if (sm.authenticated) { /*** This is Joao's code, related to leader change */ if (sm instanceof LCMessage) { LCMessage lcMsg = (LCMessage) sm; String type = null; switch (lcMsg.getType()) { case TOMUtil.STOP: type = ""STOP""; break; case TOMUtil.STOPDATA: type = ""STOPDATA""; break; case TOMUtil.SYNC: type = ""SYNC""; break; default: type = ""LOCAL""; break; } if (lcMsg.getReg() != -1 && lcMsg.getSender() != -1) logger.info(""Received leader change message of type {} "" + ""for regency {} from replica {}"", type, lcMsg.getReg(), lcMsg.getSender()); else logger.debug(""Received leader change message from myself""); if (lcMsg.TRIGGER_LC_LOCALLY) tomLayer.requestsTimer.run_lc_protocol(); else tomLayer.getSynchronizer().deliverTimeoutRequest(lcMsg); /**************************************************************/ } else if (sm instanceof ForwardedMessage) { TOMMessage request = ((ForwardedMessage) sm).getRequest(); tomLayer.requestReceived(request); /** This is Joao's code, to handle state transfer */ } else if (sm instanceof SMMessage) { SMMessage smsg = (SMMessage) sm; switch (smsg.getType()) { case TOMUtil.SM_REQUEST: tomLayer.getStateManager().SMRequestDeliver(smsg, tomLayer.controller.getStaticConf().isBFT()); break; case TOMUtil.SM_REPLY: tomLayer.getStateManager().SMReplyDeliver(smsg, tomLayer.controller.getStaticConf().isBFT()); break; case TOMUtil.SM_ASK_INITIAL: tomLayer.getStateManager().currentConsensusIdAsked(smsg.getSender(), smsg.getCID()); break; case TOMUtil.SM_REPLY_INITIAL: tomLayer.getStateManager().currentConsensusIdReceived(smsg); break; default: tomLayer.getStateManager().stateTimeout(); break; } /******************************************************************/ } else { logger.warn(""UNKNOWN MESSAGE TYPE: "" + sm); } } else { logger.warn(""Discarding unauthenticated message from "" + sm.getSender()); } } }","@SuppressWarnings(""unchecked"") protected void processData(SystemMessage sm) { if (sm instanceof ConsensusMessage) { int myId = tomLayer.controller.getStaticConf().getProcessId(); ConsensusMessage consMsg = (ConsensusMessage) sm; if (consMsg.authenticated || consMsg.getSender() == myId) acceptor.deliver(consMsg); else { logger.warn(""Discarding unauthenticated message from "" + sm.getSender()); } } else { if (sm.authenticated) { /*** This is Joao's code, related to leader change */ if (sm instanceof LCMessage) { LCMessage lcMsg = (LCMessage) sm; String type = null; switch (lcMsg.getType()) { case TOMUtil.STOP: type = ""STOP""; break; case TOMUtil.STOPDATA: type = ""STOPDATA""; break; case TOMUtil.SYNC: type = ""SYNC""; break; default: type = ""LOCAL""; break; } if (lcMsg.getReg() != -1 && lcMsg.getSender() != -1) logger.info(""Received leader change message of type {} "" + ""for regency {} from replica {}"", type, lcMsg.getReg(), lcMsg.getSender()); else logger.debug(""Received leader change message from myself""); if (lcMsg.TRIGGER_LC_LOCALLY) tomLayer.requestsTimer.run_lc_protocol(); else tomLayer.getSynchronizer().deliverTimeoutRequest(lcMsg); /**************************************************************/ } else if (sm instanceof ForwardedMessage) { TOMMessage request = ((ForwardedMessage) sm).getRequest(); tomLayer.requestReceived(request, false);//false -> message was received from a replica -> do not drop it /** This is Joao's code, to handle state transfer */ } else if (sm instanceof SMMessage) { SMMessage smsg = (SMMessage) sm; switch (smsg.getType()) { case TOMUtil.SM_REQUEST: tomLayer.getStateManager().SMRequestDeliver(smsg, tomLayer.controller.getStaticConf().isBFT()); break; case TOMUtil.SM_REPLY: tomLayer.getStateManager().SMReplyDeliver(smsg, tomLayer.controller.getStaticConf().isBFT()); break; case TOMUtil.SM_ASK_INITIAL: tomLayer.getStateManager().currentConsensusIdAsked(smsg.getSender(), smsg.getCID()); break; case TOMUtil.SM_REPLY_INITIAL: tomLayer.getStateManager().currentConsensusIdReceived(smsg); break; default: tomLayer.getStateManager().stateTimeout(); break; } /******************************************************************/ } else { logger.warn(""UNKNOWN MESSAGE TYPE: "" + sm); } } else { logger.warn(""Discarding unauthenticated message from "" + sm.getSender()); } } }","Fixed controlFlow to avoid leader change Requests in forwarded messages are no longer discarded, because it would result in a leader change, which can be triggered by a client that aims for a buffer overflow at the leader replica. Discarding a request and marking its sequence number as received prevents the request to be processed when another replica forwards the message. This would result in a leader change.",https://github.com/bft-smart/library/commit/435333bb384b69cb487eb57298507fd64ebcaf0a,,,src/main/java/bftsmart/communication/MessageHandler.java,3,java,False,2022-03-09T16:51:55Z "private static boolean isToUpload(ZipFile zipFile, ZipEntry entry) { if(zipFile == null || entry == null) return true; if(isThumbsFile(entry.getName())) return true; return isImageByMimetype(entry.getName()) && (isImageBitmap(zipFile, entry) || isSvg(entry.getName())); }","private static boolean isToUpload(ZipFile zipFile, ZipEntry entry) { if(zipFile == null || entry == null) return true; if(isThumbsFile(entry.getName())) return false; return isImageByMimetype(entry.getName()) && (isImageBitmap(zipFile, entry) || isSvg(entry.getName())); }","#2173 Fixed import project CVE-2021-26828 - reverted change ZIPProjectManager.restoreFiles; corrected UploadFileUtils.isSvg, UploadFileUtils.isToUpload(ZipFile,ZipEntry) if thumbs then false; removed unuse UploadFileUtils.isImageByMimetype(MultipartFile)",https://github.com/SCADA-LTS/Scada-LTS/commit/bd5cac81d9421fcff24c22958a248738ce4ea886,,,src/org/scada_lts/utils/UploadFileUtils.java,3,java,False,2022-04-13T10:25:42Z "function readDocType(xmlData, i){ const entities = {}; if( xmlData[i + 3] === 'O' && xmlData[i + 4] === 'C' && xmlData[i + 5] === 'T' && xmlData[i + 6] === 'Y' && xmlData[i + 7] === 'P' && xmlData[i + 8] === 'E') { i = i+9; let angleBracketsCount = 1; let hasBody = false, comment = false; let exp = """"; for(;i') { //Read tag content if(comment){ if( xmlData[i - 1] === ""-"" && xmlData[i - 2] === ""-""){ comment = false; angleBracketsCount--; } }else{ angleBracketsCount--; } if (angleBracketsCount === 0) { break; } }else if( xmlData[i] === '['){ hasBody = true; }else{ exp += xmlData[i]; } } if(angleBracketsCount !== 0){ throw new Error(`Unclosed DOCTYPE`); } }else{ throw new Error(`Invalid Tag instead of DOCTYPE`); } return {entities, i}; }","function readDocType(xmlData, i){ const entities = {}; if( xmlData[i + 3] === 'O' && xmlData[i + 4] === 'C' && xmlData[i + 5] === 'T' && xmlData[i + 6] === 'Y' && xmlData[i + 7] === 'P' && xmlData[i + 8] === 'E') { i = i+9; let angleBracketsCount = 1; let hasBody = false, comment = false; let exp = """"; for(;i') { //Read tag content if(comment){ if( xmlData[i - 1] === ""-"" && xmlData[i - 2] === ""-""){ comment = false; angleBracketsCount--; } }else{ angleBracketsCount--; } if (angleBracketsCount === 0) { break; } }else if( xmlData[i] === '['){ hasBody = true; }else{ exp += xmlData[i]; } } if(angleBracketsCount !== 0){ throw new Error(`Unclosed DOCTYPE`); } }else{ throw new Error(`Invalid Tag instead of DOCTYPE`); } return {entities, i}; }",fix security bug,https://github.com/NaturalIntelligence/fast-xml-parser/commit/39b0e050bb909e8499478657f84a3076e39ce76c,CVE-2023-34104,"['CWE-1333', 'CWE-400']",src/xmlparser/DocTypeReader.js,3,js,False,2023-06-05T05:44:13Z "@Override public InteractionResult use(@NotNull BlockState state, @NotNull Level level, @NotNull BlockPos pos, @NotNull Player player, @NotNull InteractionHand hand, @NotNull BlockHitResult hit) { Direction direction = player.getMotionDirection(); Direction hitDirection = hit.getDirection(); Direction.Axis axis = state.getValue(BlockStateProperties.AXIS); if (player.isShiftKeyDown() && player.getPose() != Pose.SWIMMING && !player.isPassenger() && direction.getAxis() != Direction.Axis.Y && direction.getAxis() == axis && player.getBbWidth() <= 0.71875F && player.getBbHeight() >= 0.71875F && player.blockPosition().relative(direction).equals(pos) && player.position().distanceTo(new Vec3(pos.getX() + 0.5, pos.getY(), pos.getZ() + 0.5)) <= (0.5 + player.getBbWidth()) && player.getY() >= pos.getY() && player.getY() <= pos.getY() + 0.5 && hitDirection.getAxis() == axis && hitDirection.getOpposite() == direction ) { player.setPos( pos.getX() + 0.5 - direction.getStepX() * 0.475, pos.getY() + 0.140625, pos.getZ() + 0.5 - direction.getStepZ() * 0.475 ); player.setPose(Pose.SWIMMING); player.setSwimming(true); return InteractionResult.SUCCESS; } return InteractionResult.PASS; }","@Override public InteractionResult use(@NotNull BlockState state, @NotNull Level level, @NotNull BlockPos pos, @NotNull Player player, @NotNull InteractionHand hand, @NotNull BlockHitResult hit) { Direction direction = player.getMotionDirection(); Direction hitDirection = hit.getDirection(); Direction.Axis axis = state.getValue(BlockStateProperties.AXIS); double crawlingHeight = player.getDimensions(Pose.SWIMMING).height; double playerY = player.getY(); if (player.isShiftKeyDown() && player.getPose() != Pose.SWIMMING && !player.isPassenger() && direction.getAxis() != Direction.Axis.Y && direction.getAxis() == axis && player.getBbWidth() <= hollowedAmount && player.getBbHeight() >= hollowedAmount && player.blockPosition().relative(direction).equals(pos) && player.position().distanceTo(new Vec3(pos.getX() + 0.5, pos.getY(), pos.getZ() + 0.5)) <= (0.5 + player.getBbWidth()) && playerY >= pos.getY() && playerY + crawlingHeight <= pos.getY() + crawlHeight && hitDirection.getAxis() == axis && hitDirection.getOpposite() == direction ) { player.setPos( pos.getX() + 0.5 - direction.getStepX() * 0.475, pos.getY() + 0.140625, pos.getZ() + 0.5 - direction.getStepZ() * 0.475 ); player.setPose(Pose.SWIMMING); player.setSwimming(true); return InteractionResult.SUCCESS; } return InteractionResult.PASS; }",fix potential clipping exploits with hollowed log crawling,https://github.com/FrozenBlock/WilderWild/commit/8c7202b1a225c65af57a8f4079b9755b4223dbd8,,,src/main/java/net/frozenblock/wilderwild/block/HollowedLogBlock.java,3,java,False,2023-01-26T20:29:41Z "private void persistPendingEventsLocked(int userId) { final LinkedList pendingEvents = mReportedEvents.get(userId); if (pendingEvents == null || pendingEvents.isEmpty()) { return; } final File usageStatsDeDir = new File(Environment.getDataSystemDeDirectory(userId), ""usagestats""); if (!usageStatsDeDir.mkdirs() && !usageStatsDeDir.exists()) { throw new IllegalStateException(""Usage stats DE directory does not exist: "" + usageStatsDeDir.getAbsolutePath()); } final File pendingEventsFile = new File(usageStatsDeDir, ""pendingevents_"" + System.currentTimeMillis()); final AtomicFile af = new AtomicFile(pendingEventsFile); FileOutputStream fos = null; try { fos = af.startWrite(); UsageStatsProtoV2.writePendingEvents(fos, pendingEvents); af.finishWrite(fos); fos = null; pendingEvents.clear(); } catch (Exception e) { Slog.e(TAG, ""Failed to write "" + pendingEventsFile.getAbsolutePath() + "" for user "" + userId); } finally { af.failWrite(fos); // when fos is null (successful write), this will no-op } }","private void persistPendingEventsLocked(int userId) { final LinkedList pendingEvents = mReportedEvents.get(userId); if (pendingEvents == null || pendingEvents.isEmpty()) { return; } final File deDir = Environment.getDataSystemDeDirectory(userId); final File usageStatsDeDir = new File(deDir, ""usagestats""); if (!usageStatsDeDir.mkdir() && !usageStatsDeDir.exists()) { if (deDir.exists()) { Slog.e(TAG, ""Failed to create "" + usageStatsDeDir); } else { Slog.w(TAG, ""User "" + userId + "" was already removed! Discarding pending events""); pendingEvents.clear(); } return; } final File pendingEventsFile = new File(usageStatsDeDir, ""pendingevents_"" + System.currentTimeMillis()); final AtomicFile af = new AtomicFile(pendingEventsFile); FileOutputStream fos = null; try { fos = af.startWrite(); UsageStatsProtoV2.writePendingEvents(fos, pendingEvents); af.finishWrite(fos); fos = null; pendingEvents.clear(); } catch (Exception e) { Slog.e(TAG, ""Failed to write "" + pendingEventsFile.getAbsolutePath() + "" for user "" + userId); } finally { af.failWrite(fos); // when fos is null (successful write), this will no-op } }","UsageStatsService: ignore removed users in persistPendingEventsLocked() If a pre-created user is removed before it becomes a full user, the ACTION_USER_REMOVED intent is never sent, so UsageStatsService is never notified that the user's pending events should be discarded. It will eventually try to persist the events. As the first step, it tries to create /data/system_de/$userId/usagestats and the parent directory /data/system_de/$userId if it doesn't already exist. However, due to https://r.android.com/2078213 the SELinux policy no longer allows system_server to create /data/system_de/$userId. The failure to create this directory is causing UsageStatsService to throw an IllegalStateException which crashes system_server. (Before the sepolicy change, system_server could create /data/system_de/$userId, so the crash wouldn't have happened. But problems still might have occurred if the user ID was reused.) The underlying user state tracking bug still needs to be fixed. For now, just avoid crashing system_server unnecessarily, and avoid an SELinux denial by using mkdir() instead of mkdirs(). Test: pm create-user --pre-create-only pm remove-user 10 # Wait 20 minutes and check logcat. Bug: 234059731 Change-Id: Ic5efc19cda6b820a2c07f77b4f316d501acb9e80",https://github.com/LineageOS/android_frameworks_base/commit/407bc2617e04c79066eabbc2d9e39cf37f37d875,,,services/usage/java/com/android/server/usage/UsageStatsService.java,3,java,False,2022-05-27T22:23:36Z "public void broadcast(T t) { mLock.lock(); try { if(mDebug) { for(Listener listener : mListeners) { mLog.debug(""Sending ["" + t + ""] to listener ["" + listener.getClass() + ""]""); listener.receive(t); mLog.debug(""Finished sending to listener ["" + listener.getClass() + ""]""); } } else { for(Listener listener : mListeners) { listener.receive(t); } } } finally { mLock.unlock(); } }","public void broadcast(T t) { mLock.lock(); try { List> listeners = new ArrayList<>(mListeners); for(Listener listener: listeners) { listener.receive(t); } } finally { mLock.unlock(); } }","#1243 Updates USB tuner error handling to prevent stack overflow when tuner error occurs while streaming. (#1247) Co-authored-by: Dennis Sheirer ",https://github.com/DSheirer/sdrtrunk/commit/8bfb1d54702ce89f44094a76346e98f4b9f7e255,,,src/main/java/io/github/dsheirer/sample/Broadcaster.java,3,java,False,2022-05-09T11:16:35Z "private void pack() { final byte[] keyBytes = getKey().getBytes(); final byte[] generatorBytes = getGenerators().getBytes(); try (final UnsafeByteBufferOutput output = new UnsafeByteBufferOutput( Integer.BYTES + keyBytes.length + Integer.BYTES + generatorBytes.length)) { write(output, keyBytes, generatorBytes); byteBuffer = output.getByteBuffer().flip(); } }","private void pack() { final byte[] keyBytes = getKey().getBytes(); final byte[] generatorBytes = getGenerators().getBytes(); final int requiredCapacity = calculateRequiredCapacity(keyBytes, generatorBytes); try (final UnsafeByteBufferOutput output = new UnsafeByteBufferOutput(requiredCapacity)) { write(output, keyBytes, generatorBytes); byteBuffer = output.getByteBuffer().flip(); } catch (final IOException e) { LOGGER.error(e::getMessage, e); } }","#2423 Add error logging and configuration to handle buffer overflows Added error logging and configuration to handle buffer overflows when dealing with large search result values.",https://github.com/gchq/stroom/commit/cc6ddc19a09f41fe30e3fffe343f75751c76360a,,,stroom-query/stroom-query-common/src/main/java/stroom/query/common/v2/LmdbValue.java,3,java,False,2021-09-14T15:28:14Z "protected void internalClose() throws SQLException { if (pointer == 0) return; if (conn.isClosed()) throw DB.newSQLException(SQLITE_ERROR, ""Connection is closed""); rs.close(); batch = null; batchPos = 0; int resp = conn.getDatabase().finalize(this); if (resp != SQLITE_OK && resp != SQLITE_MISUSE) conn.getDatabase().throwex(resp); }","protected void internalClose() throws SQLException { if (this.pointer != null && !this.pointer.isClosed()) { if (conn.isClosed()) throw DB.newSQLException(SQLITE_ERROR, ""Connection is closed""); rs.close(); batch = null; batchPos = 0; int resp = this.pointer.close(); if (resp != SQLITE_OK && resp != SQLITE_MISUSE) conn.getDatabase().throwex(resp); } }",Wrap Statement Pointers to prevent use after free race,https://github.com/xerial/sqlite-jdbc/commit/e1d282cb2887ef427c7ad93d4fe7dd05a6c11473,,,src/main/java/org/sqlite/core/CoreStatement.java,3,java,False,2022-07-29T03:54:01Z "@Override public void handle(final RoutingContext routingContext) { final String path = routingContext.normalisedPath(); if (KSQL_AUTHENTICATION_SKIP_PATHS.contains(path)) { routingContext.next(); return; } workerExecutor.executeBlocking( promise -> authorize(promise, routingContext), ar -> handleAuthorizeResult(ar, routingContext)); }","@Override public void handle(final RoutingContext routingContext) { final String path = routingContext.normalisedPath(); if (unauthenticatedpaths.matcher(path).matches()) { routingContext.next(); return; } workerExecutor.executeBlocking( promise -> authorize(promise, routingContext), ar -> handleAuthorizeResult(ar, routingContext)); }",fix: respect authentication.skip.paths properly (#9224),https://github.com/confluentinc/ksql/commit/4c33eddafafda31d2b6046a8cf69621db45f2fb3,,,ksqldb-rest-app/src/main/java/io/confluent/ksql/api/auth/KsqlAuthorizationProviderHandler.java,3,java,False,2022-06-27T18:38:26Z "void handle_debug_usb_rx(const void *msg, size_t len) { if (msg_tiny_flag) { uint8_t buf[64]; memcpy(buf, msg, sizeof(buf)); uint16_t msgId = buf[4] | ((uint16_t)buf[3]) << 8; uint32_t msgSize = buf[8] | ((uint32_t)buf[7]) << 8 | ((uint32_t)buf[6]) << 16 | ((uint32_t)buf[5]) << 24; if (msgSize > 64 - 9) { (*msg_failure)(FailureType_Failure_UnexpectedMessage, ""Malformed tiny packet""); return; } // Determine callback handler and message map type. const MessagesMap_t *entry = message_map_entry(DEBUG_MSG, msgId, IN_MSG); if (!entry) { (*msg_failure)(FailureType_Failure_UnexpectedMessage, ""Unknown message""); return; } tiny_dispatch(entry, buf + 9, msgSize); } else { usb_rx_helper(msg, len, DEBUG_MSG); } }","void handle_debug_usb_rx(const void *msg, size_t len) { if (msg_tiny_flag) { msg_read_tiny(msg, len); } else { usb_rx_helper(msg, len, DEBUG_MSG); } }","board: factor out tiny_dispatch And add stronger checks on what tiny_msg's are allowed to be decoded.",https://github.com/keepkey/keepkey-firmware/commit/b222c66cdd7c3203d917c80ba615082d309d80c3,,,lib/board/messages.c,3,c,False,2019-09-11T19:20:00Z "@GuardedBy(""mService"") private void updateRunningList() { int avail = MAX_RUNNING_PROCESS_QUEUES - getRunningSize(); if (avail == 0) return; final int cookie = traceBegin(TAG, ""updateRunningList""); final long now = SystemClock.uptimeMillis(); // If someone is waiting to go idle, everything is runnable now final boolean waitingForIdle = !mWaitingForIdle.isEmpty(); // We're doing an update now, so remove any future update requests; // we'll repost below if needed mLocalHandler.removeMessages(MSG_UPDATE_RUNNING_LIST); boolean updateOomAdj = false; BroadcastProcessQueue queue = mRunnableHead; while (queue != null && avail > 0) { BroadcastProcessQueue nextQueue = queue.runnableAtNext; final long runnableAt = queue.getRunnableAt(); // If queues beyond this point aren't ready to run yet, schedule // another pass when they'll be runnable if (runnableAt > now && !waitingForIdle) { mLocalHandler.sendEmptyMessageAtTime(MSG_UPDATE_RUNNING_LIST, runnableAt); break; } // We might not have heard about a newly running process yet, so // consider refreshing if we think we're cold updateWarmProcess(queue); final boolean processWarm = queue.isProcessWarm(); if (!processWarm) { // We only offer to run one cold-start at a time to preserve // system resources; below we either claim that single slot or // skip to look for another warm process if (mRunningColdStart == null) { mRunningColdStart = queue; } else { // Move to considering next runnable queue queue = nextQueue; continue; } } if (DEBUG_BROADCAST) logv(""Promoting "" + queue + "" from runnable to running; process is "" + queue.app); // Allocate this available permit and start running! final int index = getRunningIndexOf(null); mRunning[index] = queue; avail--; // Remove ourselves from linked list of runnable things mRunnableHead = removeFromRunnableList(mRunnableHead, queue); // Emit all trace events for this process into a consistent track queue.traceTrackName = TAG + "".mRunning["" + index + ""]""; // If we're already warm, schedule it; otherwise we'll wait for the // cold start to circle back around queue.makeActiveNextPending(); if (processWarm) { queue.traceRunningBegin(); scheduleReceiverWarmLocked(queue); } else { queue.traceStartingBegin(); scheduleReceiverColdLocked(queue); } mService.enqueueOomAdjTargetLocked(queue.app); updateOomAdj = true; // Move to considering next runnable queue queue = nextQueue; } if (updateOomAdj) { mService.updateOomAdjPendingTargetsLocked(OOM_ADJ_REASON_START_RECEIVER); } if (waitingForIdle && isIdleLocked()) { mWaitingForIdle.forEach((latch) -> latch.countDown()); mWaitingForIdle.clear(); } traceEnd(TAG, cookie); }","@GuardedBy(""mService"") private void updateRunningList() { int avail = MAX_RUNNING_PROCESS_QUEUES - getRunningSize(); if (avail == 0) return; final int cookie = traceBegin(TAG, ""updateRunningList""); final long now = SystemClock.uptimeMillis(); // If someone is waiting to go idle, everything is runnable now final boolean waitingForIdle = !mWaitingForIdle.isEmpty(); // We're doing an update now, so remove any future update requests; // we'll repost below if needed mLocalHandler.removeMessages(MSG_UPDATE_RUNNING_LIST); boolean updateOomAdj = false; BroadcastProcessQueue queue = mRunnableHead; while (queue != null && avail > 0) { BroadcastProcessQueue nextQueue = queue.runnableAtNext; final long runnableAt = queue.getRunnableAt(); // If queues beyond this point aren't ready to run yet, schedule // another pass when they'll be runnable if (runnableAt > now && !waitingForIdle) { mLocalHandler.sendEmptyMessageAtTime(MSG_UPDATE_RUNNING_LIST, runnableAt); break; } // We might not have heard about a newly running process yet, so // consider refreshing if we think we're cold updateWarmProcess(queue); final boolean processWarm = queue.isProcessWarm(); if (!processWarm) { // We only offer to run one cold-start at a time to preserve // system resources; below we either claim that single slot or // skip to look for another warm process if (mRunningColdStart == null) { mRunningColdStart = queue; } else { // Move to considering next runnable queue queue = nextQueue; continue; } } if (DEBUG_BROADCAST) logv(""Promoting "" + queue + "" from runnable to running; process is "" + queue.app); // Allocate this available permit and start running! final int index = getRunningIndexOf(null); mRunning[index] = queue; avail--; // Remove ourselves from linked list of runnable things mRunnableHead = removeFromRunnableList(mRunnableHead, queue); // Emit all trace events for this process into a consistent track queue.traceTrackName = TAG + "".mRunning["" + index + ""]""; // If we're already warm, boost OOM adjust now; if cold we'll boost // it after the app has been started if (processWarm) { notifyStartedRunning(queue); } // If we're already warm, schedule next pending broadcast now; // otherwise we'll wait for the cold start to circle back around queue.makeActiveNextPending(); if (processWarm) { queue.traceRunningBegin(); scheduleReceiverWarmLocked(queue); } else { queue.traceStartingBegin(); scheduleReceiverColdLocked(queue); } // We've moved at least one process into running state above, so we // need to kick off an OOM adjustment pass updateOomAdj = true; // Move to considering next runnable queue queue = nextQueue; } if (updateOomAdj) { mService.updateOomAdjPendingTargetsLocked(OOM_ADJ_REASON_START_RECEIVER); } if (waitingForIdle && isIdleLocked()) { mWaitingForIdle.forEach((latch) -> latch.countDown()); mWaitingForIdle.clear(); } traceEnd(TAG, cookie); }","BroadcastQueue: misc bookkeeping events for OS. This change brings over the remaining bookkeeping events that other parts of the OS expects, such as allowing background activity starts, temporary allowlisting for power, more complete OOM adjustments, thawing apps before dispatch, and metrics events. Fixes bug so that apps aren't able to abort broadcasts marked with NO_ABORT flag. Tests to confirm all the above behaviors are identical between both broadcast stack implementations. Bug: 245771249 Test: atest FrameworksMockingServicesTests:BroadcastQueueTest Change-Id: If3532d335c94c8138a9ebcf8d11bf3674d1c42aa",https://github.com/LineageOS/android_frameworks_base/commit/6a6e2295915440e17104151160a4b4ce21796962,,,services/core/java/com/android/server/am/BroadcastQueueModernImpl.java,3,java,False,2022-09-22T22:04:12Z "public void setConfigurationActivity(@Nullable ComponentName componentName) { this.configurationActivity = componentName; }","public void setConfigurationActivity(@Nullable ComponentName componentName) { this.configurationActivity = getTrimmedComponentName(componentName); }","Trim any long string inputs that come in to AutomaticZenRule This change both prevents any rules from being unable to be written to disk and also avoids risk of running out of memory while handling all the zen rules. Bug: 242703460 Bug: 242703505 Bug: 242703780 Bug: 242704043 Bug: 243794204 Test: cts AutomaticZenRuleTest; atest android.app.AutomaticZenRuleTest; manually confirmed each exploit example either saves the rule successfully with a truncated string (in the case of name & conditionId) or may fail to save the rule at all (if the owner/configactivity is invalid). Additionally ran the memory-exhausting PoC without device crashes. Change-Id: I110172a43f28528dd274b3b346eb29c3796ff2c6 Merged-In: I110172a43f28528dd274b3b346eb29c3796ff2c6 (cherry picked from commit de172ba0d434c940be9e2aad8685719731ab7da2) (cherry picked from commit d4b5212eb6d6f9ecb967d8403d1d8dd63cf69afb) Merged-In: I110172a43f28528dd274b3b346eb29c3796ff2c6",https://github.com/LineageOS/android_frameworks_base/commit/c4af5088f11ff02e8af64312661e3f7fe3bc8044,,,core/java/android/app/AutomaticZenRule.java,3,java,False,2022-08-29T21:40:14Z "def set_binary_path(binary_path, bin_paths, server_type, version_number=None, set_as_default=False): """""" This function is used to iterate through the utilities and set the default binary path. """""" path_with_dir = binary_path if ""$DIR"" in binary_path else None # Check if ""$DIR"" present in binary path binary_path = replace_binary_path(binary_path) for utility in UTILITIES_ARRAY: full_path = os.path.abspath( os.path.join(binary_path, (utility if os.name != 'nt' else (utility + '.exe')))) try: # if version_number is provided then no need to fetch it. if version_number is None: # Get the output of the '--version' command version_string = \ subprocess.getoutput('""{0}"" --version'.format(full_path)) # Get the version number by splitting the result string version_number = \ version_string.split("") "", 1)[1].split('.', 1)[0] elif version_number.find('.'): version_number = version_number.split('.', 1)[0] # Get the paths array based on server type if 'pg_bin_paths' in bin_paths or 'as_bin_paths' in bin_paths: paths_array = bin_paths['pg_bin_paths'] if server_type == 'ppas': paths_array = bin_paths['as_bin_paths'] else: paths_array = bin_paths for path in paths_array: if path['version'].find(version_number) == 0 and \ path['binaryPath'] is None: path['binaryPath'] = path_with_dir \ if path_with_dir is not None else binary_path if set_as_default: path['isDefault'] = True break break except Exception: continue","def set_binary_path(binary_path, bin_paths, server_type, version_number=None, set_as_default=False): """""" This function is used to iterate through the utilities and set the default binary path. """""" path_with_dir = binary_path if ""$DIR"" in binary_path else None binary_versions = get_binary_path_versions(binary_path) for utility, version in binary_versions.items(): version_number = version if version_number is None else version_number if version_number.find('.'): version_number = version_number.split('.', 1)[0] try: # Get the paths array based on server type if 'pg_bin_paths' in bin_paths or 'as_bin_paths' in bin_paths: paths_array = bin_paths['pg_bin_paths'] if server_type == 'ppas': paths_array = bin_paths['as_bin_paths'] else: paths_array = bin_paths for path in paths_array: if path['version'].find(version_number) == 0 and \ path['binaryPath'] is None: path['binaryPath'] = path_with_dir \ if path_with_dir is not None else binary_path if set_as_default: path['isDefault'] = True break break except Exception: continue",Fix the security issue of validate bin path to consider and fix more scenarios. #6763,https://github.com/pgadmin-org/pgadmin4/commit/1f4fe67af9b37b2224aac75f5f39093137d5fad5,,,web/pgadmin/utils/__init__.py,3,py,False,2023-09-20T05:15:05Z "@Override public List process(Path rootFolder, Path zipFile, CacheContainer cache) { String[] variant = new String[]{null}; boolean found = walkThroughFiles(rootFolder).anyMatch((path) -> { if (path == null || path.getFileName() == null) { return false; } if (validClassPath(path)) { ClassNode classNode = cache.fetchClass(path); if (classNode == null) { return false; } List nodes = classNode.methods; for (MethodNode methodNode : nodes) { for (AbstractInsnNode insnNode : methodNode.instructions.toArray()) { if (insnNode instanceof MethodInsnNode) { MethodInsnNode methodInsnNode = (MethodInsnNode) insnNode; if (methodInsnNode.owner.startsWith(""java/lang/Process"") || Type.getReturnType(methodInsnNode.desc).getClassName().startsWith(""java.lang.Process"")) { variant[0] = ""Process""; } else if (methodInsnNode.owner.equals(""java/lang/Runtime"") && methodInsnNode.name.equals(""exec"")) { variant[0] = ""Exec""; } if (variant[0] != null) { setClassNodePath(classNode.name); setSourceFilePath(classNode.sourceFile); return true; } } else if (insnNode instanceof LineNumberNode) { setLine(((LineNumberNode) insnNode).line); } } } } return false; }); if (found) { List result = new ArrayList<>(); result.add(new CheckResult(""Spigot"", ""MALWARE"", ""SystemAccess"", variant[0], getSourceFilePath(), getClassNodePath(), getLine())); return result; } return new ArrayList<>(); }","@Override public List process(Path rootFolder, Path zipFile, CacheContainer cache) { String[] variant = new String[]{null}; boolean found = walkThroughFiles(rootFolder).anyMatch((path) -> { if (path == null || path.getFileName() == null) { return false; } if (validClassPath(path)) { ClassNode classNode = cache.fetchClass(path); if (classNode == null) { return false; } List nodes = classNode.methods; for (MethodNode methodNode : nodes) { for (AbstractInsnNode insnNode : methodNode.instructions.toArray()) { if (insnNode instanceof LdcInsnNode) { String string = ((LdcInsnNode) insnNode).cst.toString(); if (string.equals(""java.lang.Runtime"")) { MethodInsnNode nextNode = (MethodInsnNode) insnNode.getNext(); if (nextNode.name.equals(""forName"") && nextNode.owner.equals(""java/lang/Class"") && nextNode.desc.equals(""(Ljava/lang/String;)Ljava/lang/Class;"")) { return true; } } } if (insnNode instanceof MethodInsnNode) { MethodInsnNode methodInsnNode = (MethodInsnNode) insnNode; if (methodInsnNode.owner.startsWith(""java/lang/Process"") || Type.getReturnType(methodInsnNode.desc).getClassName().startsWith(""java.lang.Process"")) { variant[0] = ""Process""; } else if (methodInsnNode.owner.equals(""java/lang/Runtime"")) { if(methodInsnNode.name.equals(""exec"")){ variant[0] = ""Exec""; } else if(methodInsnNode.name.equals(""getRuntime"")){ variant[0] = ""GetRuntime""; } } if (variant[0] != null) { setClassNodePath(classNode.name); setSourceFilePath(classNode.sourceFile); return true; } } else if (insnNode instanceof LineNumberNode) { setLine(((LineNumberNode) insnNode).line); } } } } return false; }); if (found) { List result = new ArrayList<>(); result.add(new CheckResult(""Spigot"", ""MALWARE"", ""SystemAccess"", variant[0], getSourceFilePath(), getClassNodePath(), getLine())); return result; } return new ArrayList<>(); }","Changes fixes CommandLineParser errors Fixes a bypass for the SystemAccessCheck",https://github.com/OpticFusion1/MCAntiMalware/commit/890b2debd9624762d52ce1cba0ca991278547d16,,,MCAntiMalware-Core/src/main/java/optic_fusion1/mcantimalware/check/impl/SystemAccessCheck.java,3,java,False,2021-02-21T17:11:47Z "public static int handleCall(ServerCommandSource source, CarpetScriptHost host, Supplier call) { try { CarpetProfiler.ProfilerToken currentSection = CarpetProfiler.start_section(null, ""Scarpet run"", CarpetProfiler.TYPE.GENERAL); host.setChatErrorSnooper(source); long start = System.nanoTime(); Value result = call.get(); long time = ((System.nanoTime()-start)/1000); String metric = ""\u00B5s""; if (time > 5000) { time /= 1000; metric = ""ms""; } if (time > 10000) { time /= 1000; metric = ""s""; } Messenger.m(source, ""wi = "", ""wb ""+result.getString(), ""gi (""+time+metric+"")""); int intres = (int)result.readInteger(); CarpetProfiler.end_current_section(currentSection); return intres; } catch (CarpetExpressionException e) { host.handleErrorWithStack(""Error while evaluating expression"", e); } catch (ArithmeticException ae) { host.handleErrorWithStack(""Math doesn't compute"", ae); } return 0; //host.resetErrorSnooper(); // lets say no need to reset the snooper in case something happens on the way }","public static int handleCall(ServerCommandSource source, CarpetScriptHost host, Supplier call) { try { CarpetProfiler.ProfilerToken currentSection = CarpetProfiler.start_section(null, ""Scarpet run"", CarpetProfiler.TYPE.GENERAL); host.setChatErrorSnooper(source); long start = System.nanoTime(); Value result = call.get(); long time = ((System.nanoTime()-start)/1000); String metric = ""\u00B5s""; if (time > 5000) { time /= 1000; metric = ""ms""; } if (time > 10000) { time /= 1000; metric = ""s""; } Messenger.m(source, ""wi = "", ""wb ""+result.getString(), ""gi (""+time+metric+"")""); int intres = (int)result.readInteger(); CarpetProfiler.end_current_section(currentSection); return intres; } catch (CarpetExpressionException e) { host.handleErrorWithStack(""Error while evaluating expression"", e); } catch (ArithmeticException ae) { host.handleErrorWithStack(""Math doesn't compute"", ae); } catch (StackOverflowError soe) { host.handleErrorWithStack(""Your thoughts are too deep"", soe); } return 0; //host.resetErrorSnooper(); // lets say no need to reset the snooper in case something happens on the way }","stack overflow in scripts shouldn't crash the game, fixes #934",https://github.com/gnembon/fabric-carpet/commit/8fa54c81463af091847f4a989f11b6c5ede1ffd0,,,src/main/java/carpet/commands/ScriptCommand.java,3,java,False,2021-06-26T02:31:46Z "def on_header_field(self, data: bytes, start: int, end: int) -> None: message = (MultiPartMessage.HEADER_FIELD, data[start:end]) self.messages.append(message)","def on_header_field(self, data: bytes, start: int, end: int) -> None: self._current_partial_header_name += data[start:end]","Merge pull request from GHSA-74m5-2c7w-9w3x * ♻️ Refactor multipart parser logic to support limiting max fields and files * ✨ Add support for new request.form() parameters max_files and max_fields * ✅ Add tests for limiting max fields and files in form data * 📝 Add docs about request.form() with new parameters max_files and max_fields * 📝 Update `docs/requests.md` Co-authored-by: Marcelo Trylesinski * 📝 Tweak docs for request.form() * ✏ Fix typo in `starlette/formparsers.py` Co-authored-by: Adrian Garcia Badaracco <1755071+adriangb@users.noreply.github.com> --------- Co-authored-by: Marcelo Trylesinski Co-authored-by: Adrian Garcia Badaracco <1755071+adriangb@users.noreply.github.com>",https://github.com/encode/starlette/commit/8c74c2c8dba7030154f8af18e016136bea1938fa,,,starlette/formparsers.py,3,py,False,2023-02-14T08:01:32Z "private BodyConsumer deployAppFromArtifact(final ApplicationId appId) throws IOException { // createTempFile() needs a prefix of at least 3 characters return new AbstractBodyConsumer(File.createTempFile(""apprequest-"" + appId, "".json"", tmpDir)) { @Override protected void onFinish(HttpResponder responder, File uploadedFile) { try (FileReader fileReader = new FileReader(uploadedFile)) { AppRequest appRequest = DECODE_GSON.fromJson(fileReader, AppRequest.class); ArtifactSummary artifactSummary = appRequest.getArtifact(); KerberosPrincipalId ownerPrincipalId = appRequest.getOwnerPrincipal() == null ? null : new KerberosPrincipalId(appRequest.getOwnerPrincipal()); // if we don't null check, it gets serialized to ""null"" Object config = appRequest.getConfig(); String configString = config == null ? null : config instanceof String ? (String) config : GSON.toJson(config); try { applicationLifecycleService.deployApp(appId.getParent(), appId.getApplication(), appId.getVersion(), artifactSummary, configString, createProgramTerminator(), ownerPrincipalId, appRequest.canUpdateSchedules()); } catch (DatasetManagementException e) { if (e.getCause() instanceof UnauthorizedException) { throw (UnauthorizedException) e.getCause(); } else { throw e; } } responder.sendString(HttpResponseStatus.OK, ""Deploy Complete""); } catch (ArtifactNotFoundException e) { responder.sendString(HttpResponseStatus.NOT_FOUND, e.getMessage()); } catch (ConflictException e) { responder.sendString(HttpResponseStatus.CONFLICT, e.getMessage()); } catch (UnauthorizedException e) { responder.sendString(HttpResponseStatus.FORBIDDEN, e.getMessage()); } catch (InvalidArtifactException e) { responder.sendString(HttpResponseStatus.BAD_REQUEST, e.getMessage()); } catch (IOException e) { LOG.error(""Error reading request body for creating app {}."", appId); responder.sendString(HttpResponseStatus.INTERNAL_SERVER_ERROR, String.format( ""Error while reading json request body for app %s."", appId)); } catch (Exception e) { LOG.error(""Deploy failure"", e); responder.sendString(HttpResponseStatus.BAD_REQUEST, e.getMessage()); } } }; }","private BodyConsumer deployAppFromArtifact(final ApplicationId appId) throws IOException { // Perform auth checks outside BodyConsumer as only the first http request containing auth header // to populate SecurityRequestContext while http chunk doesn't. BodyConsumer runs in the thread // that processes the last http chunk. accessEnforcer.enforce(appId, authenticationContext.getPrincipal(), StandardPermission.CREATE); // createTempFile() needs a prefix of at least 3 characters return new AbstractBodyConsumer(File.createTempFile(""apprequest-"" + appId, "".json"", tmpDir)) { @Override protected void onFinish(HttpResponder responder, File uploadedFile) { try (FileReader fileReader = new FileReader(uploadedFile)) { AppRequest appRequest = DECODE_GSON.fromJson(fileReader, AppRequest.class); ArtifactSummary artifactSummary = appRequest.getArtifact(); KerberosPrincipalId ownerPrincipalId = appRequest.getOwnerPrincipal() == null ? null : new KerberosPrincipalId(appRequest.getOwnerPrincipal()); // if we don't null check, it gets serialized to ""null"" Object config = appRequest.getConfig(); String configString = config == null ? null : config instanceof String ? (String) config : GSON.toJson(config); try { applicationLifecycleService.deployApp(appId.getParent(), appId.getApplication(), appId.getVersion(), artifactSummary, configString, createProgramTerminator(), ownerPrincipalId, appRequest.canUpdateSchedules()); } catch (DatasetManagementException e) { if (e.getCause() instanceof UnauthorizedException) { throw (UnauthorizedException) e.getCause(); } else { throw e; } } responder.sendString(HttpResponseStatus.OK, ""Deploy Complete""); } catch (ArtifactNotFoundException e) { responder.sendString(HttpResponseStatus.NOT_FOUND, e.getMessage()); } catch (ConflictException e) { responder.sendString(HttpResponseStatus.CONFLICT, e.getMessage()); } catch (UnauthorizedException e) { responder.sendString(HttpResponseStatus.FORBIDDEN, e.getMessage()); } catch (InvalidArtifactException e) { responder.sendString(HttpResponseStatus.BAD_REQUEST, e.getMessage()); } catch (IOException e) { LOG.error(""Error reading request body for creating app {}."", appId); responder.sendString(HttpResponseStatus.INTERNAL_SERVER_ERROR, String.format( ""Error while reading json request body for app %s."", appId)); } catch (Exception e) { LOG.error(""Deploy failure"", e); responder.sendString(HttpResponseStatus.BAD_REQUEST, e.getMessage()); } } }; }","[CDAP-18322] Fixing SystemAuthenticationContext userID and credential setting and pipeline deploy http handler auth check Two issues: 1. Fixing SystemAuthenticationContext userID and credential setting: - It is possible to set userId without userCredential. This happens when we launch program using userId stored in program options' system args. It is insecure to only use userId as user credential. This is a tech debt that should be cleaned. When it happens, we use system internal identity, assuming proper authorization checks are done at http handler layer upon receiving requests, where we have end user's credential. 2. Fixing auth check in pipeline deploy and artifact deploy - Incoming requests can be chunked and the thread processing the last chunk has an emtpy SecurityRequestContext as http chunk has no auth header. As a result, we need to perform auth checks when processing the initial http request.",https://github.com/cdapio/cdap/commit/22a1475ba9e4711bcc425ed24a16240ba93c0771,,,cdap-app-fabric/src/main/java/io/cdap/cdap/gateway/handlers/AppLifecycleHttpHandler.java,3,java,False,2022-02-04T08:01:35Z "public ArrayMap getStringsForPrefix(ContentResolver cr, String prefix, List names) { String namespace = prefix.substring(0, prefix.length() - 1); DeviceConfig.enforceReadPermission(ActivityThread.currentApplication(), namespace); ArrayMap keyValues = new ArrayMap<>(); int currentGeneration = -1; synchronized (NameValueCache.this) { if (mGenerationTracker != null) { if (mGenerationTracker.isGenerationChanged()) { if (DEBUG) { Log.i(TAG, ""Generation changed for type:"" + mUri.getPath() + "" in package:"" + cr.getPackageName()); } mValues.clear(); } else { boolean prefixCached = mValues.containsKey(prefix); if (prefixCached) { if (!names.isEmpty()) { for (String name : names) { if (mValues.containsKey(name)) { keyValues.put(name, mValues.get(name)); } } } else { for (int i = 0; i < mValues.size(); ++i) { String key = mValues.keyAt(i); // Explicitly exclude the prefix as it is only there to // signal that the prefix has been cached. if (key.startsWith(prefix) && !key.equals(prefix)) { keyValues.put(key, mValues.get(key)); } } } return keyValues; } } if (mGenerationTracker != null) { currentGeneration = mGenerationTracker.getCurrentGeneration(); } } } if (mCallListCommand == null) { // No list command specified, return empty map return keyValues; } IContentProvider cp = mProviderHolder.getProvider(cr); try { Bundle args = new Bundle(); args.putString(Settings.CALL_METHOD_PREFIX_KEY, prefix); boolean needsGenerationTracker = false; synchronized (NameValueCache.this) { if (mGenerationTracker == null) { needsGenerationTracker = true; args.putString(CALL_METHOD_TRACK_GENERATION_KEY, null); if (DEBUG) { Log.i(TAG, ""Requested generation tracker for type: "" + mUri.getPath() + "" in package:"" + cr.getPackageName()); } } } // Fetch all flags for the namespace at once for caching purposes Bundle b = cp.call(cr.getAttributionSource(), mProviderHolder.mUri.getAuthority(), mCallListCommand, null, args); if (b == null) { // Invalid response, return an empty map return keyValues; } // All flags for the namespace Map flagsToValues = (HashMap) b.getSerializable(Settings.NameValueTable.VALUE); // Only the flags requested by the caller if (!names.isEmpty()) { for (Map.Entry flag : flagsToValues.entrySet()) { if (names.contains(flag.getKey())) { keyValues.put(flag.getKey(), flag.getValue()); } } } else { keyValues.putAll(flagsToValues); } synchronized (NameValueCache.this) { if (needsGenerationTracker) { MemoryIntArray array = b.getParcelable( CALL_METHOD_TRACK_GENERATION_KEY); final int index = b.getInt( CALL_METHOD_GENERATION_INDEX_KEY, -1); if (array != null && index >= 0) { final int generation = b.getInt( CALL_METHOD_GENERATION_KEY, 0); if (DEBUG) { Log.i(TAG, ""Received generation tracker for type:"" + mUri.getPath() + "" in package:"" + cr.getPackageName() + "" with index:"" + index); } if (mGenerationTracker != null) { mGenerationTracker.destroy(); } mGenerationTracker = new GenerationTracker(array, index, generation, () -> { synchronized (NameValueCache.this) { Log.e(TAG, ""Error accessing generation tracker"" + "" - removing""); if (mGenerationTracker != null) { GenerationTracker generationTracker = mGenerationTracker; mGenerationTracker = null; generationTracker.destroy(); mValues.clear(); } } }); currentGeneration = generation; } } if (mGenerationTracker != null && currentGeneration == mGenerationTracker.getCurrentGeneration()) { // cache the complete list of flags for the namespace mValues.putAll(flagsToValues); // Adding the prefix as a signal that the prefix is cached. mValues.put(prefix, null); } } return keyValues; } catch (RemoteException e) { // Not supported by the remote side, return an empty map return keyValues; } }","public ArrayMap getStringsForPrefix(ContentResolver cr, String prefix, List names) { String namespace = prefix.substring(0, prefix.length() - 1); DeviceConfig.enforceReadPermission(ActivityThread.currentApplication(), namespace); ArrayMap keyValues = new ArrayMap<>(); int currentGeneration = -1; synchronized (NameValueCache.this) { if (mGenerationTracker != null) { if (mGenerationTracker.isGenerationChanged()) { if (DEBUG) { Log.i(TAG, ""Generation changed for type:"" + mUri.getPath() + "" in package:"" + cr.getPackageName()); } mValues.clear(); } else { boolean prefixCached = mValues.containsKey(prefix); if (prefixCached) { if (!names.isEmpty()) { for (String name : names) { if (mValues.containsKey(name)) { keyValues.put(name, mValues.get(name)); } } } else { for (int i = 0; i < mValues.size(); ++i) { String key = mValues.keyAt(i); // Explicitly exclude the prefix as it is only there to // signal that the prefix has been cached. if (key.startsWith(prefix) && !key.equals(prefix)) { keyValues.put(key, mValues.get(key)); } } } return keyValues; } } if (mGenerationTracker != null) { currentGeneration = mGenerationTracker.getCurrentGeneration(); } } } if (mCallListCommand == null) { // No list command specified, return empty map return keyValues; } IContentProvider cp = mProviderHolder.getProvider(cr); try { Bundle args = new Bundle(); args.putString(Settings.CALL_METHOD_PREFIX_KEY, prefix); boolean needsGenerationTracker = false; synchronized (NameValueCache.this) { if (mGenerationTracker == null) { needsGenerationTracker = true; args.putString(CALL_METHOD_TRACK_GENERATION_KEY, null); if (DEBUG) { Log.i(TAG, ""Requested generation tracker for type: "" + mUri.getPath() + "" in package:"" + cr.getPackageName()); } } } Bundle b; // b/252663068: if we're in system server and the caller did not call // clearCallingIdentity, the read would fail due to mismatched AttributionSources. // TODO(b/256013480): remove this bypass after fixing the callers in system server. if (namespace.equals(DeviceConfig.NAMESPACE_DEVICE_POLICY_MANAGER) && Settings.isInSystemServer() && Binder.getCallingUid() != Process.myUid()) { final long token = Binder.clearCallingIdentity(); try { // Fetch all flags for the namespace at once for caching purposes b = cp.call(cr.getAttributionSource(), mProviderHolder.mUri.getAuthority(), mCallListCommand, null, args); } finally { Binder.restoreCallingIdentity(token); } } else { // Fetch all flags for the namespace at once for caching purposes b = cp.call(cr.getAttributionSource(), mProviderHolder.mUri.getAuthority(), mCallListCommand, null, args); } if (b == null) { // Invalid response, return an empty map return keyValues; } // All flags for the namespace Map flagsToValues = (HashMap) b.getSerializable(Settings.NameValueTable.VALUE); // Only the flags requested by the caller if (!names.isEmpty()) { for (Map.Entry flag : flagsToValues.entrySet()) { if (names.contains(flag.getKey())) { keyValues.put(flag.getKey(), flag.getValue()); } } } else { keyValues.putAll(flagsToValues); } synchronized (NameValueCache.this) { if (needsGenerationTracker) { MemoryIntArray array = b.getParcelable( CALL_METHOD_TRACK_GENERATION_KEY); final int index = b.getInt( CALL_METHOD_GENERATION_INDEX_KEY, -1); if (array != null && index >= 0) { final int generation = b.getInt( CALL_METHOD_GENERATION_KEY, 0); if (DEBUG) { Log.i(TAG, ""Received generation tracker for type:"" + mUri.getPath() + "" in package:"" + cr.getPackageName() + "" with index:"" + index); } if (mGenerationTracker != null) { mGenerationTracker.destroy(); } mGenerationTracker = new GenerationTracker(array, index, generation, () -> { synchronized (NameValueCache.this) { Log.e(TAG, ""Error accessing generation tracker"" + "" - removing""); if (mGenerationTracker != null) { GenerationTracker generationTracker = mGenerationTracker; mGenerationTracker = null; generationTracker.destroy(); mValues.clear(); } } }); currentGeneration = generation; } } if (mGenerationTracker != null && currentGeneration == mGenerationTracker.getCurrentGeneration()) { // cache the complete list of flags for the namespace mValues.putAll(flagsToValues); // Adding the prefix as a signal that the prefix is cached. mValues.put(prefix, null); } } return keyValues; } catch (RemoteException e) { // Not supported by the remote side, return an empty map return keyValues; } }","[SettingsProvider] workaround for DevicePolicyResourcesManager DevicePolicyResourcesManager.getString() was added in T and called in many places inside system server. However, it uses DeviceConfig.getBoolean to determine if a feature is enabled or not. In the places where it is called from inside system server, `clearCallingIdentity` was not always called, which can result in DeviceConfig.getBoolean throwing SecurityException due to mismatched AttributionSource (calling uid is the caller from the binder client, while the context is ""android"" which should have calling uid 0). Context is ""android"" because it is inside the system server where the DevicePolicyManager instance is created. This bug might lead to unexpected behavior such as packages failing to be uninstalled by admin. The easiest fix is to place a bypass in SettingsProvider and manually clear the calling uid there. This fix also allows for the cleanest backporting as it can be cherry-picked into T without touching all the places where DevicePolicyResourcesManager.getString() is called in the system server. BUG: 252663068 Test: manual Merged-In: I37a6ceb29575593018b93093562c85d49770a43c Change-Id: I37a6ceb29575593018b93093562c85d49770a43c (cherry picked from commit b127850fda23698be0247e5b2110cdd01fff8fd7) (cherry picked from commit 76db1db57e911ed3651e75815fcb66723d6677ae) Merged-In: I37a6ceb29575593018b93093562c85d49770a43c",https://github.com/aosp-mirror/platform_frameworks_base/commit/90b4be4c13edb7100ee7ca55784914b1cbb3f8f8,,,core/java/android/provider/Settings.java,3,java,False,2022-10-27T00:03:33Z "private static void delete(String file) { if (!new File(file).delete()) { logger.warn(""Can't delete the file: "" + file); } }","private static void delete(String file) { try { Files.delete(Paths.get(file)); } catch (IOException e) { logger.warn(""Can't delete the file {} ({})"", file, e.getClass().getName()); } }",add step crashing and start tests,https://github.com/the-qa-company/qEndpoint/commit/90451be4445b0b51472755345784c13307f2a5a1,,,hdt-qs-backend/src/main/java/com/the_qa_company/q_endpoint/hybridstore/MergeRunnable.java,3,java,False,2022-02-04T15:11:26Z "private static int trigger_uaf() { long triggered = NativeMemory.allocateMemory(1); long mask = NativeMemory.allocateMemory(CPU_SETSIZE); long prio = NativeMemory.allocateMemory(0x4); NativeMemory.setMemory(mask, CPU_SETSIZE, (byte)0); NativeMemory.setMemory(prio, 0x4, (byte)0); NativeMemory.putByte(triggered, (byte)0); NativeMemory.putByte(mask + 1, (byte)0x40); NativeMemory.putShort(prio, (short)RTP_PRIO_NORMAL); NativeMemory.putShort(prio + 2, (short)0); libkernel.cpuset_setaffinity(CPU_LEVEL_WHICH, CPU_WHICH_TID, -1, CPU_SETSIZE, mask); libkernel.rtprio_thread(RTP_SET, 0, prio); Thread thread = new Thread(){ public void run() { long buf = NativeMemory.allocateMemory(24); NativeMemory.setMemory(buf, 24, (byte)0); NativeMemory.putByte(mask + 1, (byte)0x80); libkernel.cpuset_setaffinity(CPU_LEVEL_WHICH, CPU_WHICH_TID, -1, CPU_SETSIZE, mask); libkernel.rtprio_thread(RTP_SET, 0, prio); build_tclass_cmsg(buf, 0); while(NativeMemory.getByte(triggered) == 0 && get_tclass(master_sock) != TCLASS_SPRAY) { libkernel.usleep(100); set_pktopts(master_sock, buf, 24); } NativeMemory.freeMemory(buf); NativeMemory.putByte(triggered, (byte)0xff); } }; thread.start(); while(NativeMemory.getByte(triggered) == 0 && get_tclass(master_sock) != TCLASS_SPRAY) { libkernel.usleep(100); free_pktopts(master_sock); if(spray_pktopts() == 1) { break; } } NativeMemory.putByte(triggered, (byte)0xff); try { thread.join(); } catch (Throwable t) { } NativeMemory.freeMemory(triggered); NativeMemory.freeMemory(mask); NativeMemory.freeMemory(prio); return find_overlap_sock(); }","private static int trigger_uaf() { long triggered = NativeMemory.allocateMemory(1); long mask = NativeMemory.allocateMemory(CPU_SETSIZE); long prio = NativeMemory.allocateMemory(0x4); NativeMemory.setMemory(mask, CPU_SETSIZE, (byte)0); NativeMemory.setMemory(prio, 0x4, (byte)0); NativeMemory.putByte(triggered, (byte)0); NativeMemory.putByte(mask + 1, (byte)1); NativeMemory.putShort(prio, (short)2); NativeMemory.putShort(prio + 2, (short)0x100); libkernel.cpuset_setaffinity(CPU_LEVEL_WHICH, CPU_WHICH_TID, -1, CPU_SETSIZE, mask); libkernel.rtprio_thread(RTP_SET, 0, prio); Thread thread = new Thread(){ public void run() { long buf = NativeMemory.allocateMemory(24); NativeMemory.setMemory(buf, 24, (byte)0); NativeMemory.putByte(mask + 1, (byte)2); libkernel.cpuset_setaffinity(CPU_LEVEL_WHICH, CPU_WHICH_TID, -1, CPU_SETSIZE, mask); libkernel.rtprio_thread(RTP_SET, 0, prio); build_tclass_cmsg(buf, 0); while(NativeMemory.getByte(triggered) == 0 && get_tclass(master_sock) != TCLASS_SPRAY) { libkernel.usleep(100); set_pktopts(master_sock, buf, 24); } NativeMemory.freeMemory(buf); NativeMemory.putByte(triggered, (byte)0xff); } }; thread.start(); while(NativeMemory.getByte(triggered) == 0 && get_tclass(master_sock) != TCLASS_SPRAY) { libkernel.usleep(100); free_pktopts(master_sock); if(spray_pktopts() == 1) { break; } } NativeMemory.putByte(triggered, (byte)0xff); try { thread.join(); } catch (Throwable t) { } NativeMemory.freeMemory(triggered); NativeMemory.freeMemory(mask); NativeMemory.freeMemory(prio); return find_overlap_sock(); }",fix thread scheduling during use-after-free exploitation,https://github.com/john-tornblom/bdj-sdk/commit/f29fc5ca91d5ad1820f06a6a147dce19f4378fb8,,,samples/ps5-ipv6-uaf-exploit/src/org/homebrew/KernelExploit.java,3,java,False,2022-10-22T13:57:07Z "public double getDouble(int col) throws SQLException { DB db = getDatabase(); if (db.column_type(stmt.pointer, markCol(col)) == SQLITE_NULL) { return 0; } return db.column_double(stmt.pointer, markCol(col)); }","public double getDouble(int col) throws SQLException { DB db = getDatabase(); if (safeGetColumnType(markCol(col)) == SQLITE_NULL) { return 0; } return safeGetDoubleCol(col); }",Wrap Statement Pointers to prevent use after free race,https://github.com/xerial/sqlite-jdbc/commit/e1d282cb2887ef427c7ad93d4fe7dd05a6c11473,,,src/main/java/org/sqlite/jdbc3/JDBC3ResultSet.java,3,java,False,2022-07-29T03:54:01Z "public static void ensureAccess(EntityId entityId, AuthorizationEnforcer authorizationEnforcer, Principal principal) throws Exception { if (authorizationEnforcer.isVisible(Collections.singleton(entityId), principal).isEmpty()) { throw new UnauthorizedException(principal, entityId); } }","public static void ensureAccess(EntityId entityId, AuthorizationEnforcer authorizationEnforcer, Principal principal) throws Exception { authorizationEnforcer.isVisible(entityId, principal); }","[CDAP-17786] Add native support for ensureAccess in AuthorizationEnforcer API and add support for custom error propagation from Authorizer in checkOnePrivilege Fix testDataset to not depend on UnauthorizedException message Update copyright year",https://github.com/cdapio/cdap/commit/309591ff3cef101493d9184c2f2564a6c16b1dc0,,,cdap-security/src/main/java/io/cdap/cdap/security/authorization/AuthorizationUtil.java,3,java,False,2021-03-19T07:09:10Z "@SuppressWarnings({""PMD.UselessParentheses"", ""PMD.CollapsibleIfStatements""}) public boolean matchesMQTT(String str) { if (str == null) { return true; } if ((matchAll && isWildcard) || (isTerminal && str.isEmpty()) || (isWildcard && isTerminal && (str.indexOf(MQTT_LEVEL_SEPARATOR) == -1))) { return true; } if (isMQTTWildcard) { if (matchAll || (isTerminal && (str.indexOf(MQTT_LEVEL_SEPARATOR) == -1))) { return true; } } boolean hasMatch = false; Map matchingChildren = new HashMap<>(); for (Map.Entry e : children.entrySet()) { // Succeed fast if (hasMatch) { return true; } String key = e.getKey(); WildcardTrie value = e.getValue(); // Process *, # and + wildcards (only process MQTT wildcards that have valid usages) if (key.equals(GLOB_WILDCARD) || value.isMQTTWildcard && (key.equals(MQTT_SINGLELEVEL_WILDCARD) || key.equals(MQTT_MULTILEVEL_WILDCARD))) { hasMatch = value.matchesMQTT(str); continue; } // Match normal characters if (str.startsWith(key)) { hasMatch = value.matchesMQTT(str.substring(key.length())); // Succeed fast if (hasMatch) { return true; } } // Check if it's terminalLevel to allow matching of string without ""/"" in the end // eg: Just ""abc"" should match ""abc/#"" String terminalKey = key.substring(0, key.length() - 1); if (value.isTerminalLevel && str.equals(terminalKey)) { return true; } // If I'm a wildcard, then I need to maybe chomp many characters to match my children if (isWildcard) { int foundChildIndex = str.indexOf(key); int keyLength = key.length(); if (value.isTerminalLevel && str.endsWith(terminalKey)) { foundChildIndex = str.indexOf(terminalKey); keyLength = terminalKey.length(); } // Matched characters inside * should not contain a ""/"" if ((foundChildIndex >= 0) && (str.substring(0, foundChildIndex).indexOf(MQTT_LEVEL_SEPARATOR) == -1)) { matchingChildren.put(str.substring(foundChildIndex + keyLength), value); } } if (isMQTTWildcard) { int foundChildIndex = str.indexOf(key); int keyLength = key.length(); if (value.isTerminalLevel && str.endsWith(terminalKey)) { foundChildIndex = str.indexOf(terminalKey); keyLength = terminalKey.length(); } // Matched characters inside + should not contain a ""/"", also next match should have string starting // with a ""/"" if (foundChildIndex >= 0 && (str.substring(0,foundChildIndex).indexOf(MQTT_LEVEL_SEPARATOR) == -1) && key.startsWith(MQTT_LEVEL_SEPARATOR)) { matchingChildren.put(str.substring(foundChildIndex + keyLength), value); } } } // Succeed fast if (hasMatch) { return true; } if ((isWildcard || isMQTTWildcard) && !matchingChildren.isEmpty()) { return matchingChildren.entrySet().stream().anyMatch((e) -> e.getValue().matchesMQTT(e.getKey())); } return false; }","@SuppressWarnings({""PMD.UselessParentheses"", ""PMD.CollapsibleIfStatements""}) public boolean matchesMQTT(String str) { if (str == null) { return true; } if ((isWildcard && isTerminal) || (isTerminal && str.isEmpty())) { return true; } if (isMQTTWildcard) { if (matchAll || (isTerminal && (str.indexOf(MQTT_LEVEL_SEPARATOR) == -1))) { return true; } } boolean hasMatch = false; Map matchingChildren = new HashMap<>(); for (Map.Entry e : children.entrySet()) { // Succeed fast if (hasMatch) { return true; } String key = e.getKey(); WildcardTrie value = e.getValue(); // Process *, # and + wildcards (only process MQTT wildcards that have valid usages) if (key.equals(GLOB_WILDCARD) || value.isMQTTWildcard && (key.equals(MQTT_SINGLELEVEL_WILDCARD) || key.equals(MQTT_MULTILEVEL_WILDCARD))) { hasMatch = value.matchesMQTT(str); continue; } // Match normal characters if (str.startsWith(key)) { hasMatch = value.matchesMQTT(str.substring(key.length())); // Succeed fast if (hasMatch) { return true; } } // Check if it's terminalLevel to allow matching of string without ""/"" in the end // ""abc/#"" should match ""abc"". // ""abc/*xy/#"" should match ""abc/12xy"" String terminalKey = key.substring(0, key.length() - 1); if (value.isTerminalLevel) { if (str.equals(terminalKey)) { return true; } if (str.endsWith(terminalKey)) { key = terminalKey; } } int keyLength = key.length(); // If I'm a wildcard, then I need to maybe chomp many characters to match my children if (isWildcard) { int foundChildIndex = str.indexOf(key); while (foundChildIndex >= 0 && foundChildIndex < str.length()) { matchingChildren.put(str.substring(foundChildIndex + keyLength), value); foundChildIndex = str.indexOf(key, foundChildIndex + 1); } } // If I'm a MQTT wildcard (specifically + as # is already covered), // then I need to maybe chomp many characters to match my children if (isMQTTWildcard) { int foundChildIndex = str.indexOf(key); // Matched characters inside + should not contain a ""/"" while (foundChildIndex >= 0 && foundChildIndex < str.length() && (str.substring(0,foundChildIndex).indexOf(MQTT_LEVEL_SEPARATOR) == -1)) { matchingChildren.put(str.substring(foundChildIndex + keyLength), value); foundChildIndex = str.indexOf(key, foundChildIndex + 1); } } } // Succeed fast if (hasMatch) { return true; } if ((isWildcard || isMQTTWildcard) && !matchingChildren.isEmpty()) { return matchingChildren.entrySet().stream().anyMatch((e) -> e.getValue().matchesMQTT(e.getKey())); } return false; }","fix: change glob wildcard behavior in AuthZ (#1173) This is the first of a set of changes meant to make authorization policy evaluation behavior consistent between Greengrass and IoT Core / IAM. Changes: * PubSub IPC AuthZ: MQTT wildcards will not be evaluated and will be treated as string literals. Glob wildcard will be evaluated * MQTT IPC AuthZ: MQTT wildcards will still be evaluated as wildcards for backward compatibility reasons. In addition, the glob wildcard will now also be evaluated * Glob wildcard now match across MQTT topic levels. (eg - ab/*/c will match ab/1/2/c and ab/12/c)",https://github.com/aws-greengrass/aws-greengrass-nucleus/commit/47d640d2a89adf8f23d933c41b4c2c546fd05046,,,src/main/java/com/aws/greengrass/authorization/WildcardTrie.java,3,java,False,2022-03-31T00:54:05Z "def get_parser(): # Get global config argument parser parser = configargparse.ArgumentParser( prog='rdiffweb', description='Web interface to browse and restore rdiff-backup repositories.', default_config_files=['/etc/rdiffweb/rdw.conf', '/etc/rdiffweb/rdw.conf.d/*.conf'], add_env_var_help=True, auto_env_var_prefix='RDIFFWEB_', config_file_parser_class=ConfigFileParser, conflict_handler='resolve', ) parser.add_argument( '-f', '--config', is_config_file=True, metavar='FILE', help='location of Rdiffweb configuration file' ) parser.add( '--database-uri', '--sqlitedb-file', '--sqlitedbfile', metavar='URI', help=""""""Location of the database used for persistence. SQLite and PostgreSQL database are supported officially. To use a SQLite database you may define the location using a file path or a URI. e.g.: /srv/rdiffweb/file.db or sqlite:///srv/rdiffweb/file.db`. To use PostgreSQL server you must provide a URI similar to postgresql://user:pass@10.255.1.34/dbname and you must install required dependencies. By default, Rdiffweb uses a SQLite embedded database located at /etc/rdiffweb/rdw.db."""""", default='/etc/rdiffweb/rdw.db', ) parser.add_argument( '-d', '--debug', action='store_true', help='enable rdiffweb debug mode - change the log level to DEBUG, print exception stack trace to the web interface and show SQL query in logs', ) parser.add_argument( '--admin-user', '--adminuser', metavar='USERNAME', help='administrator username. The administrator user get created on startup if the database is empty.', default='admin', ) parser.add_argument( '--admin-password', metavar='USERNAME', help=""""""administrator encrypted password as SSHA. Read online documentation to know more about how to encrypt your password into SSHA or use http://projects.marsching.org/weave4j/util/genpassword.php When defined, administrator password cannot be updated using the web interface. When undefined, default administrator password is `admin123` and it can be updated using the web interface."""""", ) parser.add_argument( '--default-theme', '--defaulttheme', help='define the default theme. Either: default, blue or orange. Define the CSS file to be loaded in the web interface. You may manually edit a CSS file to customize it. The location is similar to `/usr/local/lib/python3.9/dist-packages/rdiffweb/static/`', choices=['default', 'blue', 'orange'], default='default', ) parser.add_argument( '--environment', choices=['development', 'production'], help='define the type of environment: development, production. This is used to limit the information shown to the user when an error occur.', default='production', ) parser.add_argument( '--email-encryption', '--emailencryption', choices=['none', 'ssl', 'starttls'], help='type of encryption to be used when establishing communication with SMTP server. Default: none', default='none', ) parser.add_argument( '--email-host', '--emailhost', metavar='HOST', help='SMTP server used to send email in the form :. If the port is not provided, default to standard port 25 or 465 is used. e.g.: smtp.gmail.com:587', ) parser.add_argument( '--email-sender', '--emailsender', metavar='EMAIL', help='email addres used for the `from:` field when sending email.', ) parser.add_argument( '--email-notification-time', '--emailnotificationtime', metavar='TIME', help='time when the email notifcation should be sent for inactive backups. e.g.: 22:00 Default value: 23:00', default='23:00', ) parser.add_argument( '--email-username', '--emailusername', metavar='USERNAME', help='username used for authentication with the SMTP server.', ) parser.add_argument( '--email-password', '--emailpassword', metavar='PASSWORD', help='password used for authentication with the SMTP server.', ) parser.add_argument( '--email-send-changed-notification', '--emailsendchangednotification', help='True to send notification when sensitive information get change in user profile.', action='store_true', default=False, ) parser.add_argument( '--favicon', help='location of an icon to be used as a favicon displayed in web browser.', default=pkg_resources.resource_filename('rdiffweb', 'static/favicon.ico'), ) # @UndefinedVariable parser.add_argument( '--footer-name', '--footername', help=argparse.SUPPRESS, default='rdiffweb' ) # @UndefinedVariable parser.add_argument( '--footer-url', '--footerurl', help=argparse.SUPPRESS, default='https://rdiffweb.org/' ) # @UndefinedVariable parser.add_argument( '--header-logo', '--headerlogo', help='location of an image (preferably a .png) to be used as a replacement for the rdiffweb logo.', ) parser.add_argument( '--header-name', '--headername', help='application name displayed in the title bar and header menu.', default='Rdiffweb', ) parser.add_argument( '--ldap-add-missing-user', '--addmissinguser', action='store_true', help='enable creation of users from LDAP when the credential are valid.', default=False, ) parser.add_argument( '--ldap-add-user-default-role', help='default role used when creating users from LDAP. This parameter is only useful when `--ldap-add-missing-user` is enabled.', default='user', choices=['admin', 'maintainer', 'user'], ) parser.add_argument( '--ldap-add-user-default-userroot', help='default user root directory used when creating users from LDAP. LDAP attributes may be used to define the default location. e.g.: `/backups/{uid[0]}/`. This parameter is only useful when `--ldap-add-missing-user` is enabled.', default='', ) parser.add_argument( '--ldap-uri', '--ldapuri', help='URL to the LDAP server used to validate user credentials. e.g.: ldap://localhost:389', ) parser.add_argument( '--ldap-base-dn', '--ldapbasedn', metavar='DN', help='DN of the branch of the directory where all searches should start from. e.g.: dc=my,dc=domain', default="""", ) parser.add_argument( '--ldap-scope', '--ldapscope', help='scope of the search. Can be either base, onelevel or subtree', choices=['base', 'onelevel', 'subtree'], default=""subtree"", ) parser.add_argument('--ldap-tls', '--ldaptls', action='store_true', help='enable TLS') parser.add_argument( '--ldap-username-attribute', '--ldapattribute', metavar='ATTRIBUTE', help=""The attribute to search username. If no attributes are provided, the default is to use `uid`. It's a good idea to choose an attribute that will be unique across all entries in the subtree you will be using."", default='uid', ) parser.add_argument( '--ldap-filter', '--ldapfilter', help=""search filter to limit LDAP lookup. If not provided, defaults to (objectClass=*), which searches for all objects in the tree."", default='(objectClass=*)', ) parser.add_argument( '--ldap-required-group', '--ldaprequiredgroup', metavar='GROUPNAME', help=""name of the group of which the user must be a member to access rdiffweb. Should be used with ldap-group-attribute and ldap-group-attribute-is-dn."", ) parser.add_argument( '--ldap-group-attribute', '--ldapgroupattribute', metavar='ATTRIBUTE', help=""name of the attribute defining the groups of which the user is a member. Should be used with ldap-required-group and ldap-group-attribute-is-dn."", default='member', ) parser.add_argument( '--ldap-group-attribute-is-dn', '--ldapgroupattributeisdn', help=""True if the content of the attribute `ldap-group-attribute` is a DN."", action='store_true', ) parser.add_argument( '--ldap-bind-dn', '--ldapbinddn', metavar='DN', help=""optional DN used to bind to the server when searching for entries. If not provided, will use an anonymous bind."", default="""", ) parser.add_argument( '--ldap-bind-password', '--ldapbindpassword', metavar='PASSWORD', help=""password to use in conjunction with LdapBindDn. Note that the bind password is probably sensitive data, and should be properly protected. You should only use the LdapBindDn and LdapBindPassword if you absolutely need them to search the directory."", default="""", ) parser.add_argument( '--ldap-version', '--ldapversion', '--ldapprotocolversion', help=""version of LDAP in use either 2 or 3. Default to 3."", default=3, type=int, choices=[2, 3], ) parser.add_argument( '--ldap-network-timeout', '--ldapnetworktimeout', metavar='SECONDS', help=""timeout in seconds value used for LDAP connection"", default=100, type=int, ) parser.add_argument( '--ldap-timeout', '--ldaptimeout', metavar='SECONDS', help=""timeout in seconds value used for LDAP request"", default=300, type=int, ) parser.add_argument( '--ldap-encoding', '--ldapencoding', metavar='ENCODING', help=""encoding used by your LDAP server."", default=""utf-8"", ) parser.add_argument( '--log-access-file', '--logaccessfile', metavar='FILE', help='location of Rdiffweb log access file.' ) parser.add_argument( '--log-file', '--logfile', metavar='FILE', help='location of Rdiffweb log file. Print log to the console if not define in config file.', ) parser.add_argument( '--log-level', '--loglevel', help='Define the log level.', choices=['ERROR', 'WARN', 'INFO', 'DEBUG'], default='INFO', ) parser.add_argument( '--max-depth', '--maxdepth', metavar='DEPTH', help=""define the maximum folder depthness to search into the user's root directory to find repositories. This is commonly used if you repositories are organised with multiple sub-folder."", type=int, default=3, ) parser.add('--quota-set-cmd', '--quotasetcmd', metavar='COMMAND', help=""command line to set the user's quota."") parser.add('--quota-get-cmd', '--quotagetcmd', metavar='COMMAND', help=""command line to get the user's quota."") parser.add( '--quota-used-cmd', '--quotausedcmd', metavar='COMMAND', help=""Command line to get user's quota disk usage."" ) parser.add( '--remove-older-time', '--removeoldertime', metavar='TIME', help=""Time when to execute the remove older scheduled job. e.g.: 22:30"", default='23:00', ) parser.add('--server-host', '--serverhost', metavar='IP', default='127.0.0.1', help='IP address to listen to') parser.add( '--server-port', '--serverport', metavar='PORT', help='port to listen to for HTTP request', default='8080', type=int, ) parser.add( '--rate-limit-dir', '--session-dir', '--sessiondir', metavar='FOLDER', help='location where to store rate-limit information. When undefined, the data is kept in memory. `--session-dir` are deprecated and kept for backward compatibility.', ) parser.add( '--session-timeout', metavar='MINUTES', help='Sessions will be revoke after this period of inactivity, unless the user selected ""remember me"". Default 15 minutes.', default=15, ) parser.add( '--session-persistent-timeout', metavar='MINUTES', help='Persistent sessions (remember me) will be revoke after this period of inactivity. Default 30 days.', default=43200, ) parser.add( '--rate-limit', metavar='LIMIT', type=int, default=20, help='maximum number of requests per hour that can be made on sensitive endpoints. When this limit is reached, an HTTP 429 message is returned to the user or the user is logged out. This security measure is used to limit brute force attacks on the login page and the RESTful API.', ) parser.add( '--ssl-certificate', '--sslcertificate', metavar='CERT', help='location of the SSL Certification to enable HTTPS (not recommended)', ) parser.add( '--ssl-private-key', '--sslprivatekey', metavar='KEY', help='location of the SSL Private Key to enable HTTPS (not recommended)', ) parser.add( '--tempdir', metavar='FOLDER', help='alternate temporary folder to be used when restoring files. Might be useful if the default location has limited disk space. Default to TEMPDIR environment or `/tmp`.', ) parser.add( '--disable-ssh-keys', action='store_true', help='used to hide SSH Key management to avoid users to add or remove SSH Key using the web application', default=False, ) parser.add( '--password-min-length', type=int, help=""Minimum length of the user's password"", default=8, ) parser.add( '--password-max-length', type=int, help=""Maximum length of the user's password"", default=128, ) parser.add( '--password-score', type=lambda x: max(1, min(int(x), 4)), help=""Minimum zxcvbn's score for password. Value from 1 to 4. Default value 2. Read more about it here: https://github.com/dropbox/zxcvbn"", default=2, ) parser.add_argument('--version', action='version', version='%(prog)s ' + VERSION) # Here we append a list of arguments for each locale. flags = ['--welcome-msg'] + ['--welcome-msg-' + i for i in ['ca', 'en', 'es', 'fr', 'ru']] + ['--welcomemsg'] parser.add_argument( *flags, metavar='HTML', help='replace the welcome message displayed in the login page for default locale or for a specific locale', action=LocaleAction ) return parser","def get_parser(): # Get global config argument parser parser = configargparse.ArgumentParser( prog='rdiffweb', description='Web interface to browse and restore rdiff-backup repositories.', default_config_files=['/etc/rdiffweb/rdw.conf', '/etc/rdiffweb/rdw.conf.d/*.conf'], add_env_var_help=True, auto_env_var_prefix='RDIFFWEB_', config_file_parser_class=ConfigFileParser, conflict_handler='resolve', ) parser.add_argument( '-f', '--config', is_config_file=True, metavar='FILE', help='location of Rdiffweb configuration file' ) parser.add( '--database-uri', '--sqlitedb-file', '--sqlitedbfile', metavar='URI', help=""""""Location of the database used for persistence. SQLite and PostgreSQL database are supported officially. To use a SQLite database you may define the location using a file path or a URI. e.g.: /srv/rdiffweb/file.db or sqlite:///srv/rdiffweb/file.db`. To use PostgreSQL server you must provide a URI similar to postgresql://user:pass@10.255.1.34/dbname and you must install required dependencies. By default, Rdiffweb uses a SQLite embedded database located at /etc/rdiffweb/rdw.db."""""", default='/etc/rdiffweb/rdw.db', ) parser.add_argument( '-d', '--debug', action='store_true', help='enable rdiffweb debug mode - change the log level to DEBUG, print exception stack trace to the web interface and show SQL query in logs', ) parser.add_argument( '--admin-user', '--adminuser', metavar='USERNAME', help='administrator username. The administrator user get created on startup if the database is empty.', default='admin', ) parser.add_argument( '--admin-password', metavar='USERNAME', help=""""""administrator encrypted password as SSHA. Read online documentation to know more about how to encrypt your password into SSHA or use http://projects.marsching.org/weave4j/util/genpassword.php When defined, administrator password cannot be updated using the web interface. When undefined, default administrator password is `admin123` and it can be updated using the web interface."""""", ) parser.add_argument( '--default-theme', '--defaulttheme', help='define the default theme. Either: default, blue or orange. Define the CSS file to be loaded in the web interface. You may manually edit a CSS file to customize it. The location is similar to `/usr/local/lib/python3.9/dist-packages/rdiffweb/static/`', choices=['default', 'blue', 'orange'], default='default', ) parser.add_argument( '--environment', choices=['development', 'production'], help='define the type of environment: development, production. This is used to limit the information shown to the user when an error occur.', default='production', ) parser.add_argument( '--email-encryption', '--emailencryption', choices=['none', 'ssl', 'starttls'], help='type of encryption to be used when establishing communication with SMTP server. Default: none', default='none', ) parser.add_argument( '--email-host', '--emailhost', metavar='HOST', help='SMTP server used to send email in the form :. If the port is not provided, default to standard port 25 or 465 is used. e.g.: smtp.gmail.com:587', ) parser.add_argument( '--email-sender', '--emailsender', metavar='EMAIL', help='email addres used for the `from:` field when sending email.', ) parser.add_argument( '--email-notification-time', '--emailnotificationtime', metavar='TIME', help='time when the email notifcation should be sent for inactive backups. e.g.: 22:00 Default value: 23:00', default='23:00', ) parser.add_argument( '--email-username', '--emailusername', metavar='USERNAME', help='username used for authentication with the SMTP server.', ) parser.add_argument( '--email-password', '--emailpassword', metavar='PASSWORD', help='password used for authentication with the SMTP server.', ) parser.add_argument( '--email-send-changed-notification', '--emailsendchangednotification', help='True to send notification when sensitive information get change in user profile.', action='store_true', default=False, ) parser.add_argument( '--favicon', help='location of an icon to be used as a favicon displayed in web browser.', default=pkg_resources.resource_filename('rdiffweb', 'static/favicon.ico'), ) # @UndefinedVariable parser.add_argument( '--footer-name', '--footername', help=argparse.SUPPRESS, default='rdiffweb' ) # @UndefinedVariable parser.add_argument( '--footer-url', '--footerurl', help=argparse.SUPPRESS, default='https://rdiffweb.org/' ) # @UndefinedVariable parser.add_argument( '--header-logo', '--headerlogo', help='location of an image (preferably a .png) to be used as a replacement for the rdiffweb logo.', ) parser.add_argument( '--header-name', '--headername', help='application name displayed in the title bar and header menu.', default='Rdiffweb', ) parser.add_argument( '--ldap-add-missing-user', '--addmissinguser', action='store_true', help='enable creation of users from LDAP when the credential are valid.', default=False, ) parser.add_argument( '--ldap-add-user-default-role', help='default role used when creating users from LDAP. This parameter is only useful when `--ldap-add-missing-user` is enabled.', default='user', choices=['admin', 'maintainer', 'user'], ) parser.add_argument( '--ldap-add-user-default-userroot', help='default user root directory used when creating users from LDAP. LDAP attributes may be used to define the default location. e.g.: `/backups/{uid[0]}/`. This parameter is only useful when `--ldap-add-missing-user` is enabled.', default='', ) parser.add_argument( '--ldap-uri', '--ldapuri', help='URL to the LDAP server used to validate user credentials. e.g.: ldap://localhost:389', ) parser.add_argument( '--ldap-base-dn', '--ldapbasedn', metavar='DN', help='DN of the branch of the directory where all searches should start from. e.g.: dc=my,dc=domain', default="""", ) parser.add_argument( '--ldap-scope', '--ldapscope', help='scope of the search. Can be either base, onelevel or subtree', choices=['base', 'onelevel', 'subtree'], default=""subtree"", ) parser.add_argument('--ldap-tls', '--ldaptls', action='store_true', help='enable TLS') parser.add_argument( '--ldap-username-attribute', '--ldapattribute', metavar='ATTRIBUTE', help=""The attribute to search username. If no attributes are provided, the default is to use `uid`. It's a good idea to choose an attribute that will be unique across all entries in the subtree you will be using."", default='uid', ) parser.add_argument( '--ldap-filter', '--ldapfilter', help=""search filter to limit LDAP lookup. If not provided, defaults to (objectClass=*), which searches for all objects in the tree."", default='(objectClass=*)', ) parser.add_argument( '--ldap-required-group', '--ldaprequiredgroup', metavar='GROUPNAME', help=""name of the group of which the user must be a member to access rdiffweb. Should be used with ldap-group-attribute and ldap-group-attribute-is-dn."", ) parser.add_argument( '--ldap-group-attribute', '--ldapgroupattribute', metavar='ATTRIBUTE', help=""name of the attribute defining the groups of which the user is a member. Should be used with ldap-required-group and ldap-group-attribute-is-dn."", default='member', ) parser.add_argument( '--ldap-group-attribute-is-dn', '--ldapgroupattributeisdn', help=""True if the content of the attribute `ldap-group-attribute` is a DN."", action='store_true', ) parser.add_argument( '--ldap-bind-dn', '--ldapbinddn', metavar='DN', help=""optional DN used to bind to the server when searching for entries. If not provided, will use an anonymous bind."", default="""", ) parser.add_argument( '--ldap-bind-password', '--ldapbindpassword', metavar='PASSWORD', help=""password to use in conjunction with LdapBindDn. Note that the bind password is probably sensitive data, and should be properly protected. You should only use the LdapBindDn and LdapBindPassword if you absolutely need them to search the directory."", default="""", ) parser.add_argument( '--ldap-version', '--ldapversion', '--ldapprotocolversion', help=""version of LDAP in use either 2 or 3. Default to 3."", default=3, type=int, choices=[2, 3], ) parser.add_argument( '--ldap-network-timeout', '--ldapnetworktimeout', metavar='SECONDS', help=""timeout in seconds value used for LDAP connection"", default=100, type=int, ) parser.add_argument( '--ldap-timeout', '--ldaptimeout', metavar='SECONDS', help=""timeout in seconds value used for LDAP request"", default=300, type=int, ) parser.add_argument( '--ldap-encoding', '--ldapencoding', metavar='ENCODING', help=""encoding used by your LDAP server."", default=""utf-8"", ) parser.add_argument( '--log-access-file', '--logaccessfile', metavar='FILE', help='location of Rdiffweb log access file.' ) parser.add_argument( '--log-file', '--logfile', metavar='FILE', help='location of Rdiffweb log file. Print log to the console if not define in config file.', ) parser.add_argument( '--log-level', '--loglevel', help='Define the log level.', choices=['ERROR', 'WARN', 'INFO', 'DEBUG'], default='INFO', ) parser.add_argument( '--max-depth', '--maxdepth', metavar='DEPTH', help=""define the maximum folder depthness to search into the user's root directory to find repositories. This is commonly used if you repositories are organised with multiple sub-folder."", type=int, default=3, ) parser.add('--quota-set-cmd', '--quotasetcmd', metavar='COMMAND', help=""command line to set the user's quota."") parser.add('--quota-get-cmd', '--quotagetcmd', metavar='COMMAND', help=""command line to get the user's quota."") parser.add( '--quota-used-cmd', '--quotausedcmd', metavar='COMMAND', help=""Command line to get user's quota disk usage."" ) parser.add( '--remove-older-time', '--removeoldertime', metavar='TIME', help=""Time when to execute the remove older scheduled job. e.g.: 22:30"", default='23:00', ) parser.add('--server-host', '--serverhost', metavar='IP', default='127.0.0.1', help='IP address to listen to') parser.add( '--server-port', '--serverport', metavar='PORT', help='port to listen to for HTTP request', default='8080', type=int, ) parser.add( '--rate-limit-dir', '--session-dir', '--sessiondir', metavar='FOLDER', help='location where to store rate-limit information. When undefined, the data is kept in memory. `--session-dir` are deprecated and kept for backward compatibility.', ) parser.add( '--rate-limit', metavar='LIMIT', type=int, default=20, help='maximum number of requests per hour that can be made on sensitive endpoints. When this limit is reached, an HTTP 429 message is returned to the user or the user is logged out. This security measure is used to limit brute force attacks on the login page and the RESTful API.', ) parser.add( '--session-idle-timeout', metavar='MINUTES', help='This timeout defines the amount of time a session will remain active in case there is no activity in the session. User Session will be revoke after this period of inactivity, unless the user selected ""remember me"". Default 5 minutes.', default=5, ) parser.add( '--session-absolute-timeout', metavar='MINUTES', help='This timeout defines the maximum amount of time a session can be active. After this period, user is forced to (re)authenticate, unless the user selected ""remember me"". Default 20 minutes.', default=20, ) parser.add( '--session-persistent-timeout', metavar='MINUTES', help='This timeout defines the maximum amount of time to remember and trust a user device. This timeout is used when user select ""remember me"". Default 30 days.', default=43200, ) parser.add( '--ssl-certificate', '--sslcertificate', metavar='CERT', help='location of the SSL Certification to enable HTTPS (not recommended)', ) parser.add( '--ssl-private-key', '--sslprivatekey', metavar='KEY', help='location of the SSL Private Key to enable HTTPS (not recommended)', ) parser.add( '--tempdir', metavar='FOLDER', help='alternate temporary folder to be used when restoring files. Might be useful if the default location has limited disk space. Default to TEMPDIR environment or `/tmp`.', ) parser.add( '--disable-ssh-keys', action='store_true', help='used to hide SSH Key management to avoid users to add or remove SSH Key using the web application', default=False, ) parser.add( '--password-min-length', type=int, help=""Minimum length of the user's password"", default=8, ) parser.add( '--password-max-length', type=int, help=""Maximum length of the user's password"", default=128, ) parser.add( '--password-score', type=lambda x: max(1, min(int(x), 4)), help=""Minimum zxcvbn's score for password. Value from 1 to 4. Default value 2. Read more about it here: https://github.com/dropbox/zxcvbn"", default=2, ) parser.add_argument('--version', action='version', version='%(prog)s ' + VERSION) # Here we append a list of arguments for each locale. flags = ['--welcome-msg'] + ['--welcome-msg-' + i for i in ['ca', 'en', 'es', 'fr', 'ru']] + ['--welcomemsg'] parser.add_argument( *flags, metavar='HTML', help='replace the welcome message displayed in the login page for default locale or for a specific locale', action=LocaleAction ) return parser",Define idle and absolute session timeout with agressive default to protect usage on public computer,https://github.com/ikus060/rdiffweb/commit/f2a32f2a9f3fb8be1a9432ac3d81d3aacdb13095,,,rdiffweb/core/config.py,3,py,False,2022-10-17T22:58:27Z "def deny_uploads_containing_script_tag(uploaded_file): for chunk in uploaded_file.chunks(2048): if chunk.lower().find(b"" -1: raise ValidationError(_(""File contains forbidden "", id); }","public String getPurifier() { String id = UUID.randomUUID().toString();//This is to prevent collisions, not sure if this is necessary. return String.format(""
"" + """", id); }","Harden DOMPurify Disallow SVG and MathML to prevent namespace confusion based bypasses.",https://github.com/SerNet/verinice/commit/e4ba46e4671820e7b4ccd8ce888c60a9d37339e1,,,sernet.gs.server/src/sernet/verinice/web/PurifyBean.java,3,java,False,2020-12-16T09:26:10Z "@Override public void handle(final RoutingContext routingContext) { final String path = routingContext.normalisedPath(); if (KSQL_AUTHENTICATION_SKIP_PATHS.contains(path)) { routingContext.next(); return; } if (SystemAuthenticationHandler.isAuthenticatedAsSystemUser(routingContext)) { routingContext.next(); return; } workerExecutor.executeBlocking( promise -> authorize(promise, routingContext), ar -> handleAuthorizeResult(ar, routingContext)); }","@Override public void handle(final RoutingContext routingContext) { final String path = routingContext.normalisedPath(); if (unauthenticatedpaths.matcher(path).matches()) { routingContext.next(); return; } if (SystemAuthenticationHandler.isAuthenticatedAsSystemUser(routingContext)) { routingContext.next(); return; } workerExecutor.executeBlocking( promise -> authorize(promise, routingContext), ar -> handleAuthorizeResult(ar, routingContext)); }",fix: respect authentication.skip.paths properly,https://github.com/confluentinc/ksql/commit/805481bb0cbf86b137837ae1b0c37e24ae911c38,,,ksqldb-rest-app/src/main/java/io/confluent/ksql/api/auth/KsqlAuthorizationProviderHandler.java,3,java,False,2022-06-24T22:21:41Z "public static ParseAndValidateResult parse(ExecutionInput executionInput) { try { // // we allow the caller to specify new parser options by context ParserOptions parserOptions = executionInput.getGraphQLContext().get(ParserOptions.class); Parser parser = new Parser(); Document document = parser.parseDocument(executionInput.getQuery(), parserOptions); return ParseAndValidateResult.newResult().document(document).variables(executionInput.getVariables()).build(); } catch (InvalidSyntaxException e) { return ParseAndValidateResult.newResult().syntaxException(e).variables(executionInput.getVariables()).build(); } }","public static ParseAndValidateResult parse(ExecutionInput executionInput) { try { // // we allow the caller to specify new parser options by context ParserOptions parserOptions = executionInput.getGraphQLContext().get(ParserOptions.class); // we use the query parser options by default if they are not specified parserOptions = ofNullable(parserOptions).orElse(ParserOptions.getDefaultQueryParserOptions()); Parser parser = new Parser(); Document document = parser.parseDocument(executionInput.getQuery(), parserOptions); return ParseAndValidateResult.newResult().document(document).variables(executionInput.getVariables()).build(); } catch (InvalidSyntaxException e) { return ParseAndValidateResult.newResult().syntaxException(e).variables(executionInput.getVariables()).build(); } }",This stops DOS attacks by making the lexer stop early. Added per query jvm settings,https://github.com/graphql-java/graphql-java/commit/79b989c582952426beb419888756ba75d56a5f98,,,src/main/java/graphql/ParseAndValidate.java,3,java,False,2022-07-22T00:32:14Z "private void setFontWeight(@Nullable String fontWeightString) { int fontWeightNumeric = fontWeightString != null ? parseNumericFontWeight(fontWeightString) : -1; int fontWeight = UNSET; if (fontWeightNumeric >= 500 || ""bold"".equals(fontWeightString)) { fontWeight = Typeface.BOLD; } else if (""normal"".equals(fontWeightString) || (fontWeightNumeric != -1 && fontWeightNumeric < 500)) { fontWeight = Typeface.NORMAL; } if (fontWeight != mFontWeight) { mFontWeight = fontWeight; } }","private void setFontWeight(@Nullable String fontWeightString) { mFontWeight = ReactTypefaceUtils.parseFontWeight(fontWeightString); }","RN: Unify Typeface Logic (Android) Summary: Refactors how `Typeface` style and weight are applied in React Native on Android. - Unifies all style and weight normalization logic into a new `TypefaceStyle` class. - Fixes font weight support for the Fabric renderer. - De-duplicates code with `TextAttributeProps`. - Simplified normalization logic. - Fixes a rare crash due to `Typeface.sDefaultTypeface` (Android SDK) being `null`. - Adds a new example to test font weights in `TextInput`. - Adds missing `Nullsafe` and `Nullable` annotations. - Clean up a bunch of obsolete inline comments. Changelog: [Android][Fixed] - Fixed a rare crash due to `Typeface.sDefaultTypeface` (Android SDK) being `null`. [Android][Fixed] - Fixed font weight support for the Fabric renderer. [Android][Added] - Added a new example to test font weights in `TextInput`. Reviewed By: JoshuaGross Differential Revision: D29631134 fbshipit-source-id: 3f227d84253104fa828a5561b77ba7a9cbc030c4",https://github.com/react-native-tvos/react-native-tvos/commit/9d2fedc6e22ca1b45fbc2059971cd194de5d0170,,,ReactAndroid/src/main/java/com/facebook/react/views/text/TextAttributeProps.java,3,java,False,2021-07-13T05:16:00Z "function TagViewModel(data) { this.Id = data.ID; this.Name = data.Name; }","function TagViewModel(data) { this.Id = data.ID; this.Name = _.escape(data.Name); }",change model,https://github.com/portainer/portainer/commit/15cfa7768c6999c6839fb79f1497a6674f109e84,CVE-2021-42650,['CWE-79'],app/portainer/models/tag.js,3,js,False,2021-09-27T20:58:01Z "@EventHandler public void grappler(PlayerFishEvent event) { if (blockDisabled(Ability.GRAPPLER)) return; if (event.getCaught() != null) { if (!(event.getCaught() instanceof Item)) { PlayerData playerData = plugin.getPlayerManager().getPlayerData(event.getPlayer()); if (playerData != null) { Player player = event.getPlayer(); if (blockAbility(player)) return; Vector vector = player.getLocation().toVector().subtract(event.getCaught().getLocation().toVector()); event.getCaught().setVelocity(vector.multiply(0.004 + (getValue(Ability.GRAPPLER, playerData) / 25000))); } } } }","@EventHandler public void grappler(PlayerFishEvent event) { if (blockDisabled(Ability.GRAPPLER)) return; if (event.getCaught() != null) { if (!(event.getCaught() instanceof Item)) { PlayerData playerData = plugin.getPlayerManager().getPlayerData(event.getPlayer()); if (playerData != null) { Player player = event.getPlayer(); if (blockAbility(player)) return; Vector vector = player.getLocation().toVector().subtract(event.getCaught().getLocation().toVector()); Vector result = vector.multiply(0.004 + (getValue(Ability.GRAPPLER, playerData) / 25000)); if (isUnsafeVelocity(result)) { // Prevent excessive velocity warnings return; } event.getCaught().setVelocity(result); } } } }",Fix excessive velocity crash with Grappler,https://github.com/Archy-X/AuraSkills/commit/a20bae5ddb32e41fd75bfb6750e4bcf1bd6d200c,,,src/main/java/com/archyx/aureliumskills/skills/fishing/FishingAbilities.java,3,java,False,2021-08-27T04:30:26Z "@Override public void run() { // init firstValidVersionId firstValidVersionId = checkpointManager.getFirstValidWALVersionId(); if (firstValidVersionId == Long.MIN_VALUE) { // roll wal log writer to delete current wal file if (buffer.getCurrentWALFileSize() > 0) { rollWALFile(); } // update firstValidVersionId firstValidVersionId = checkpointManager.getFirstValidWALVersionId(); if (firstValidVersionId == Long.MIN_VALUE) { firstValidVersionId = buffer.getCurrentWALFileVersion(); } } logger.debug( ""Start deleting outdated wal files for wal node-{}, the first valid version id is {}, and the safely deleted search index is {}."", identifier, firstValidVersionId, safelyDeletedSearchIndex); // delete outdated files deleteOutdatedFiles(); // wal is used to search, cannot optimize files deletion if (safelyDeletedSearchIndex != DEFAULT_SAFELY_DELETED_SEARCH_INDEX) { return; } // calculate effective information ratio long costOfActiveMemTables = checkpointManager.getTotalCostOfActiveMemTables(); long costOfFlushedMemTables = totalCostOfFlushedMemTables.get(); double effectiveInfoRatio = (double) costOfActiveMemTables / (costOfActiveMemTables + costOfFlushedMemTables); logger.debug( ""Effective information ratio is {}, active memTables cost is {}, flushed memTables cost is {}"", effectiveInfoRatio, costOfActiveMemTables, costOfFlushedMemTables); // effective information ratio is too small // update first valid version id by snapshotting or flushing memTable, // then delete old .wal files again if (effectiveInfoRatio < config.getWalMinEffectiveInfoRatio()) { logger.info( ""Effective information ratio {} of wal node-{} is below wal min effective info ratio {}, some mamTables will be snapshot or flushed."", effectiveInfoRatio, identifier, config.getWalMinEffectiveInfoRatio()); snapshotOrFlushMemTable(); run(); } }","@Override public void run() { // init firstValidVersionId firstValidVersionId = checkpointManager.getFirstValidWALVersionId(); if (firstValidVersionId == Long.MIN_VALUE) { // roll wal log writer to delete current wal file if (buffer.getCurrentWALFileSize() > 0) { rollWALFile(); } // update firstValidVersionId firstValidVersionId = checkpointManager.getFirstValidWALVersionId(); if (firstValidVersionId == Long.MIN_VALUE) { firstValidVersionId = buffer.getCurrentWALFileVersion(); } } logger.debug( ""Start deleting outdated wal files for wal node-{}, the first valid version id is {}, and the safely deleted search index is {}."", identifier, firstValidVersionId, safelyDeletedSearchIndex); // delete outdated files deleteOutdatedFiles(); // wal is used to search, cannot optimize files deletion if (safelyDeletedSearchIndex != DEFAULT_SAFELY_DELETED_SEARCH_INDEX) { return; } // calculate effective information ratio long costOfActiveMemTables = checkpointManager.getTotalCostOfActiveMemTables(); long costOfFlushedMemTables = totalCostOfFlushedMemTables.get(); long totalCost = costOfActiveMemTables + costOfFlushedMemTables; if (totalCost == 0) { return; } double effectiveInfoRatio = (double) costOfActiveMemTables / totalCost; logger.debug( ""Effective information ratio is {}, active memTables cost is {}, flushed memTables cost is {}"", effectiveInfoRatio, costOfActiveMemTables, costOfFlushedMemTables); // effective information ratio is too small // update first valid version id by snapshotting or flushing memTable, // then delete old .wal files again if (effectiveInfoRatio < config.getWalMinEffectiveInfoRatio()) { logger.info( ""Effective information ratio {} (active memTables cost is {}, flushed memTables cost is {}) of wal node-{} is below wal min effective info ratio {}, some mamTables will be snapshot or flushed."", effectiveInfoRatio, costOfActiveMemTables, costOfFlushedMemTables, identifier, config.getWalMinEffectiveInfoRatio()); if (snapshotOrFlushMemTable() && recursionTime < MAX_RECURSION_TIME) { run(); recursionTime++; } } }",[IOTDB-3649] Fix stack overflow when deleting wal (#6432),https://github.com/apache/iotdb/commit/bf36ca3a3f3bc034c8ef29c3594b42815c103f39,,,server/src/main/java/org/apache/iotdb/db/wal/node/WALNode.java,3,java,False,2022-06-25T05:30:25Z "@SubscribeEvent public static void update(ServerTickEvent event) { if (event.phase == Phase.END) { try { Iterator it = networks.iterator(); while (it.hasNext()) { ITickableNetwork net = it.next(); if (net.getSize() == 0) { it.remove(); } else { net.tick(); } } } catch (ConcurrentModificationException exception) { exception.printStackTrace(); } } }","@SubscribeEvent public static void update(ServerTickEvent event) { if (event.phase == Phase.END) { try { networks.removeAll(remove); remove.clear(); Iterator it = networks.iterator(); while (it.hasNext()) { ITickableNetwork net = it.next(); if (net.getSize() == 0) { deregister(net); } else { net.tick(); } } } catch (ConcurrentModificationException exception) { exception.printStackTrace(); } } }","Make network safer, buff pumps, fix pipe crash, cleanup, fix concurrency",https://github.com/aurilisdev/Electrodynamics/commit/58998695a03e3d954c0dec5e0d04c0917c4fd1da,,,src/main/java/electrodynamics/common/network/NetworkRegistry.java,3,java,False,2021-04-11T15:16:55Z "@Override public void execute() throws OnmsUpgradeException { Writer out = null; try { final DocumentBuilderFactory docFactory = DocumentBuilderFactory.newInstance(); final DocumentBuilder docBuilder = docFactory.newDocumentBuilder(); final Document doc = docBuilder.parse(m_configFile); final NodeList found = doc.getElementsByTagName(""discovery-configuration""); if (found.getLength() == 1 && found.item(0) instanceof Element) { final Element el = (Element)found.item(0); el.removeAttribute(""threads""); final Transformer tf = TransformerFactory.newInstance().newTransformer(); tf.setOutputProperty(OutputKeys.ENCODING, StandardCharsets.UTF_8.name()); tf.setOutputProperty(OutputKeys.INDENT, ""yes""); out = new StringWriter(); tf.transform(new DOMSource(doc), new StreamResult(out)); FileUtils.write(m_configFile, out.toString()); } else { throw new OnmsUpgradeException(""Unsure how to handle XML node(s): "" + found); } } catch (final IOException | SAXException | ParserConfigurationException | TransformerException e) { throw new OnmsUpgradeException(""Failed to upgrade discovery-configuration.xml"", e); } finally { IOUtils.closeQuietly(out); } }","@Override public void execute() throws OnmsUpgradeException { try { final DocumentBuilderFactory docFactory = DocumentBuilderFactory.newInstance(); docFactory.setFeature(""http://apache.org/xml/features/disallow-doctype-decl"", true); final DocumentBuilder docBuilder = docFactory.newDocumentBuilder(); final Document doc = docBuilder.parse(m_configFile); final NodeList found = doc.getElementsByTagName(""discovery-configuration""); if (found.getLength() == 1 && found.item(0) instanceof Element) { final Element el = (Element)found.item(0); el.removeAttribute(""threads""); TransformerFactory factory = TransformerFactory.newInstance(); factory.setAttribute(XMLConstants.ACCESS_EXTERNAL_DTD, """"); factory.setAttribute(XMLConstants.ACCESS_EXTERNAL_STYLESHEET, """"); final Transformer tf = factory.newTransformer(); tf.setOutputProperty(OutputKeys.ENCODING, StandardCharsets.UTF_8.name()); tf.setOutputProperty(OutputKeys.INDENT, ""yes""); try (Writer out = new StringWriter()) { tf.transform(new DOMSource(doc), new StreamResult(out)); FileUtils.write(m_configFile, out.toString(), Charset.defaultCharset()); } } else { throw new OnmsUpgradeException(""Unsure how to handle XML node(s): "" + found); } } catch (final IOException | SAXException | ParserConfigurationException | TransformerException e) { throw new OnmsUpgradeException(""Failed to upgrade discovery-configuration.xml"", e); } }","SonarCLoud bug and code smell fix Code Smell: o Replace the type specification in this constructor call with the diamond operator (""<>""). o Remove the unnecessary boolean literal. o Remove this ""Long"" constructor o Replace this ""for"" loop with a ""while"" loop Bug: o Call ""Optional#isPresent()"" or ""!Optional#isEmpty()"" before accessing the value. o Use try-with-resources or close this ""Stream"" in a ""finally"" clause DEVJAM - Project Periscope",https://github.com/OpenNMS/opennms/commit/0557a2338eb0adba13e1b657a5a201b328ba1a47,,,core/upgrade/src/main/java/org/opennms/upgrade/implementations/DiscoveryConfigurationMigratorOffline.java,3,java,False,2022-09-12T19:22:34Z "int getAvailIdx() throws MemoryAccessException { return (int) memoryMap.load(driver + VIRTQ_AVAIL_IDX, Sizes.SIZE_16_LOG2) & 0xFFFF; }","short getAvailIdx() throws MemoryAccessException { return (short) memoryMap.load(driver + VIRTQ_AVAIL_IDX, Sizes.SIZE_16_LOG2); }","Use shorts where we actually have shorts, fixes potential infinite loop when next available index is exactly the wrap point (0x8000, which as int will never equal a short value).",https://github.com/fnuecke/sedna/commit/ae93820014397840d62f2572e720b710ac368276,,,src/main/java/li/cil/sedna/device/virtio/AbstractVirtIODevice.java,3,java,False,2022-07-19T21:31:56Z "@Override public boolean hasNext() { while ( next == null && iterator.hasNext() ) { Entry e = iterator.next(); if ( PropertiesAsMap.matches( e ) ) { next = e; break; } } return next != null; }","@Override public boolean hasNext() { return next != null; }",[MNG-7597] Fix infinite loop when iterating PropertiesAsMap (#872),https://github.com/apache/maven/commit/6a27f5f2f6e9ab44c44692b32e5ba41063106de5,,,maven-core/src/main/java/org/apache/maven/internal/impl/PropertiesAsMap.java,3,java,False,2022-11-21T08:37:42Z "@Override public Collection
getCustomRequestHeaders(HttpSession session, HttpServletRequest originalRequest, String targetServiceName) { // Don't use this provider for trusted request if (isPreAuthorized(session) || isAnnonymous()) { return Collections.emptyList(); } synchronized (session) { Optional> cached = getCachedHeaders(session, targetServiceName); return cached.orElseGet(() -> { Collection
headers = collectHeaders(session, targetServiceName); setCachedHeaders(session, headers, targetServiceName); return headers; }); } }","@Override public Collection
getCustomRequestHeaders(HttpSession session, HttpServletRequest originalRequest, String targetServiceName) { // Don't use this provider for trusted request if (isPreAuthorized(originalRequest) || isAnnonymous()) { return Collections.emptyList(); } synchronized (session) { Optional> cached = getCachedHeaders(session, targetServiceName); return cached.orElseGet(() -> { Collection
headers = collectHeaders(session, targetServiceName); setCachedHeaders(session, headers, targetServiceName); return headers; }); } }","Set pre-auth as a property of the request, not the session Using the http Session object to hold a per-request property can result in a race condition and a security attack vector. ProxyTrustAnotherProxy works on a per-request basis, so it makes all sense to set the pre-auth attribute on the request instead.",https://github.com/georchestra/georchestra/commit/b9637b7a4cee6fedf0fba7dcc9996e4dd5732499,,,security-proxy/src/main/java/org/georchestra/security/LdapUserDetailsRequestHeaderProvider.java,3,java,False,2021-04-20T21:40:04Z "public void doFilter(ServletRequest req, ServletResponse res, FilterChain chain) throws IOException, ServletException { HttpServletRequest request = (HttpServletRequest) req; HttpServletResponse response = (HttpServletResponse) res; try { String uri = RequestUtils.getUri(request); if (excludedPatterns != null && prepare.isUrlExcluded(request, excludedPatterns)) { LOG.trace(""Request {} is excluded from handling by Struts, passing request to other filters"", uri); chain.doFilter(request, response); } else { LOG.trace(""Checking if {} is a static resource"", uri); boolean handled = execute.executeStaticResourceRequest(request, response); if (!handled) { LOG.trace(""Uri {} is not a static resource, assuming action"", uri); prepare.setEncodingAndLocale(request, response); prepare.createActionContext(request, response); prepare.assignDispatcherToThread(); HttpServletRequest wrappedRequest = prepare.wrapRequest(request); ActionMapping mapping = prepare.findActionMapping(wrappedRequest, response, true); if (mapping == null) { LOG.trace(""Cannot find mapping for {}, passing to other filters"", uri); chain.doFilter(request, response); } else { LOG.trace(""Found mapping {} for {}"", mapping, uri); execute.executeAction(wrappedRequest, response, mapping); } } } } finally { prepare.cleanupRequest(request); } }","public void doFilter(ServletRequest req, ServletResponse res, FilterChain chain) throws IOException, ServletException { HttpServletRequest request = (HttpServletRequest) req; HttpServletResponse response = (HttpServletResponse) res; try { String uri = RequestUtils.getUri(request); if (isRequestExcluded(request)) { LOG.trace(""Request: {} is excluded from handling by Struts, passing request to other filters"", uri); chain.doFilter(request, response); } else { tryHandleRequest(chain, request, response, uri); } } finally { prepare.cleanupRequest(request); } }",WW-5276 Cleans up also wrapper request to avoid resource leak and potential DoS attack,https://github.com/apache/struts/commit/05d7196e6cf451426eb301effc0416b2554b20f3,,,core/src/main/java/org/apache/struts2/dispatcher/filter/StrutsPrepareAndExecuteFilter.java,3,java,False,2023-01-22T10:04:58Z "@Override public String execute( final Context context, final Map params ) throws PluginException { final String link = params.get( PARAM_LINK ); String text = params.get( PARAM_TEXT ); boolean linkAllowed = true; if( link == null ) { throw new PluginException( ""Denounce: No parameter ""+PARAM_LINK+"" defined!"" ); } if( !isLinkValid( link ) ) { throw new PluginException( ""Denounce: Not a valid link "" + link ); } final HttpServletRequest request = context.getHttpRequest(); if( request != null ) { linkAllowed = !matchHeaders( request ); } if( text == null ) { text = link; } if( linkAllowed ) { return """" + TextUtil.replaceEntities( text ) + """"; } return c_denounceText; }","@Override public String execute( final Context context, final Map params ) throws PluginException { final String link = TextUtil.replaceEntities( params.get( PARAM_LINK ) ); //final String link = params.get( PARAM_LINK ); String text = params.get( PARAM_TEXT ); boolean linkAllowed = true; if( link == null ) { throw new PluginException( ""Denounce: No parameter ""+PARAM_LINK+"" defined!"" ); } if( !isLinkValid( link ) ) { throw new PluginException( ""Denounce: Not a valid link "" + link ); } final HttpServletRequest request = context.getHttpRequest(); if( request != null ) { linkAllowed = !matchHeaders( request ); } if( text == null ) { text = link; } if( linkAllowed ) { return """" + TextUtil.replaceEntities( text ) + """"; } return c_denounceText; }","2.11.3-git-03 / xss protection Denounce plugin: sanities the plugin attributes to protect against xss attack.",https://github.com/apache/jspwiki/commit/d7e57a3f5d9b8dc140621dc26016985d306c00c7,,,jspwiki-main/src/main/java/org/apache/wiki/plugin/Denounce.java,3,java,False,2022-03-15T21:26:55Z "@Override public IngestDocument execute(IngestDocument ingestDocument) throws Exception { throw new UnsupportedOperationException(""this method should not get executed""); }","@Override public IngestDocument execute(IngestDocument ingestDocument) throws Exception { assert isAsync() == false; final boolean matches = evaluate(ingestDocument); if (matches) { long startTimeInNanos = relativeTimeProvider.getAsLong(); try { metric.preIngest(); return processor.execute(ingestDocument); } catch (Exception e) { metric.ingestFailed(); throw e; } finally { long ingestTimeInNanos = relativeTimeProvider.getAsLong() - startTimeInNanos; metric.postIngest(ingestTimeInNanos); } } return ingestDocument; }","Iteratively execute synchronous ingest processors (#84250) Iteratively executes ingest processors that are not asynchronous. This resolves the issue of stack overflows that could occur in large ingest pipelines. As a secondary effect, it dramatically reduces the depth of the stack during ingest pipeline execution which reduces the performance cost of gathering a stack trace for any exceptions instantiated during pipeline execution. The aggregate performance effect of these changes has been observed to be a 10-15% improvement in some larger pipelines.",https://github.com/elastic/elasticsearch/commit/cce3d924754a06634a8e353fa227be3af2eeca62,,,server/src/main/java/org/elasticsearch/ingest/ConditionalProcessor.java,3,java,False,2022-04-12T13:39:46Z "public void closeFactory() { // shutdown persistence engine if (factory != null) { if (factory instanceof SessionFactoryImpl) { SessionFactoryImpl sf = (SessionFactoryImpl) factory; ConnectionProvider conn = sf.getConnectionProvider(); if (conn instanceof C3P0ConnectionProvider) { ((C3P0ConnectionProvider)conn).stop(); } } factory.close(); } }","public void closeFactory() { // shutdown persistence engine if (factory != null) { factory.close(); } }",updated hibernate lib and dependencies 4.3 -> 5.6.14 (fix for CVE-2020-25638),https://github.com/yawlfoundation/yawl/commit/bd5e37ff0a25f15cfc12796f2a0be8712d59cc17,,,src/org/yawlfoundation/yawl/engine/YPersistenceManager.java,3,java,False,2023-02-09T06:21:10Z "static void setupAuthHandlers(final Server server, final Router router, final boolean isInternalListener) { final Optional jaas = getJaasAuthHandler(server); final KsqlSecurityExtension securityExtension = server.getSecurityExtension(); final Optional authenticationPlugin = server.getAuthenticationPlugin(); final Optional> pluginHandler = authenticationPlugin.map(plugin -> new AuthenticationPluginHandler(server, plugin)); final Optional systemAuthenticationHandler = getSystemAuthenticationHandler(server, isInternalListener); systemAuthenticationHandler.ifPresent(handler -> registerAuthHandler(router, handler)); if (jaas.isPresent() || authenticationPlugin.isPresent()) { registerAuthHandler( router, rc -> selectHandler(rc, jaas.isPresent(), pluginHandler.isPresent())); // set up using JAAS jaas.ifPresent(h -> registerAuthHandler(router, wrappedHandler(h, Provider.JAAS))); registerAuthHandler( router, wrappedHandler(new RoleBasedAuthZHandler( server.getConfig().getList(KsqlRestConfig.AUTHENTICATION_ROLES_CONFIG)), Provider.JAAS)); // set up using PLUGIN pluginHandler.ifPresent(h -> registerAuthHandler(router, wrappedHandler(h, Provider.PLUGIN))); // For authorization use auth provider configured via security extension (if any) securityExtension.getAuthorizationProvider() .ifPresent(ksqlAuthorizationProvider -> registerAuthHandler( router, new KsqlAuthorizationProviderHandler(server, ksqlAuthorizationProvider))); // since we're done with all the authorization plugins, we can resume the // request context router.route().handler(AuthHandlers::resumeHandler); } }","static void setupAuthHandlers(final Server server, final Router router, final boolean isInternalListener) { final Optional jaas = getJaasAuthHandler(server); final KsqlSecurityExtension securityExtension = server.getSecurityExtension(); final Optional authenticationPlugin = server.getAuthenticationPlugin(); final Optional> pluginHandler = authenticationPlugin.map(plugin -> new AuthenticationPluginHandler(server, plugin)); final Optional systemAuthenticationHandler = getSystemAuthenticationHandler(server, isInternalListener); systemAuthenticationHandler.ifPresent(handler -> registerAuthHandler(router, handler)); if (jaas.isPresent() || authenticationPlugin.isPresent()) { final List skipPaths = server.getConfig() .getList(KsqlRestConfig.AUTHENTICATION_SKIP_PATHS_CONFIG); final Pattern skipPathPattern = getAuthenticationSkipPathPattern(skipPaths); registerAuthHandler( router, rc -> selectHandler(rc, skipPathPattern, jaas.isPresent(), pluginHandler.isPresent())); // set up using JAAS jaas.ifPresent(h -> registerAuthHandler(router, selectiveHandler(h, Provider.JAAS::equals))); registerAuthHandler( router, selectiveHandler(new RoleBasedAuthZHandler( server.getConfig().getList(KsqlRestConfig.AUTHENTICATION_ROLES_CONFIG)), Provider.JAAS::equals)); // set up using PLUGIN pluginHandler.ifPresent(h -> registerAuthHandler(router, selectiveHandler(h, Provider.PLUGIN::equals))); // For authorization use auth provider configured via security extension (if any) securityExtension.getAuthorizationProvider() .ifPresent(ksqlAuthorizationProvider -> registerAuthHandler( router, selectiveHandler( new KsqlAuthorizationProviderHandler(server, ksqlAuthorizationProvider), provider -> provider == Provider.JAAS || provider == Provider.PLUGIN ))); // since we're done with all the authorization plugins, we can resume the // request context router.route().handler(AuthHandlers::resumeHandler); } }",fix: also skip basic authentication for authentication.skip.paths,https://github.com/confluentinc/ksql/commit/a1e25d706182f50b7a922230ef992e87c956f2a9,,,ksqldb-rest-app/src/main/java/io/confluent/ksql/api/server/AuthHandlers.java,3,java,False,2022-10-26T10:23:11Z "@RequiresPermissions(""link:edit"") @PostMapping(""/edit"") @BussinessLog(""编辑友情链接"") public ResponseVO edit(Link link) { try { linkService.updateSelective(link); } catch (Exception e) { e.printStackTrace(); return ResultUtil.error(""友情链接修改失败!""); } return ResultUtil.success(ResponseStatus.SUCCESS); }","@RequiresPermissions(""link:edit"") @PostMapping(""/edit"") @BussinessLog(""编辑友情链接"") public ResponseVO edit(Link link) { if (!RegexUtils.isUrl(link.getUrl())) { throw new ZhydLinkException(""链接地址无效!""); } try { linkService.updateSelective(link); } catch (Exception e) { e.printStackTrace(); return ResultUtil.error(""友情链接修改失败!""); } return ResultUtil.success(ResponseStatus.SUCCESS); }",修复部分 XSS,https://github.com/zhangyd-c/OneBlog/commit/6caba5babb4c1763d78502c062a4860b7414f36b,,,blog-admin/src/main/java/com/zyd/blog/controller/RestLinkController.java,3,java,False,2021-08-07T02:44:58Z "int cap_free(void *data_p) { if ( good_cap_t(data_p) ) { data_p = -1 + (__u32 *) data_p; memset(data_p, 0, sizeof(__u32) + sizeof(struct _cap_struct)); free(data_p); data_p = NULL; return 0; } if ( good_cap_string(data_p) ) { int length = strlen(data_p) + sizeof(__u32); data_p = -1 + (__u32 *) data_p; memset(data_p, 0, length); free(data_p); data_p = NULL; return 0; } _cap_debug(""don't recognize what we're supposed to liberate""); errno = EINVAL; return -1; }","int cap_free(void *data_p) { if ( !data_p ) return 0; if ( good_cap_t(data_p) ) { data_p = -1 + (__u32 *) data_p; memset(data_p, 0, sizeof(__u32) + sizeof(struct _cap_struct)); free(data_p); data_p = NULL; return 0; } if ( good_cap_string(data_p) ) { size_t length = strlen(data_p) + sizeof(__u32); data_p = -1 + (__u32 *) data_p; memset(data_p, 0, length); free(data_p); data_p = NULL; return 0; } _cap_debug(""don't recognize what we're supposed to liberate""); errno = EINVAL; return -1; }","Merge pull request #906 from proftpd/cap-updated-libcap-issue902 Issue #902: Update the bundled `libcap` library to the latest from",https://github.com/proftpd/proftpd/commit/d726fcbf3cdb32c3b6fe287bd8eda310db956f2f,,,lib/libcap/cap_alloc.c,3,c,False,2020-02-18T19:40:16Z "protected boolean setDocument( String stringXML, FileObject file, boolean isInXMLField, boolean readurl) throws HopException { this.prevRow = buildEmptyRow(); // pre-allocate previous row try { SAXReader reader = Dom4JUtil.getSAXReader(null); data.stopPruning = false; // Validate XML against specified schema? if (meta.isValidating()) { reader.setValidation(true); reader.setFeature(""http://apache.org/xml/features/validation/schema"", true); } else { // Ignore DTD declarations reader.setEntityResolver(new IgnoreDtdEntityResolver()); } // Ignore comments? if (meta.isIgnoreComments()) { reader.setIgnoreComments(true); } if (data.prunePath != null) { // when pruning is on: reader.read() below will wait until all is processed in the handler if (log.isDetailed()) { logDetailed(BaseMessages.getString(PKG, ""GetXMLData.Log.StreamingMode.Activated"")); } if (data.PathValue.equals(data.prunePath)) { // Edge case, but if true, there will only ever be one item in the list data.an = new ArrayList<>(1); // pre-allocate array and sizes data.an.add(null); } reader.addHandler( data.prunePath, new ElementHandler() { @Override public void onStart(ElementPath path) { // do nothing here... } @Override public void onEnd(ElementPath path) { long rowLimit = meta.getRowLimit(); if (isStopped() || (rowLimit > 0 && data.rownr > rowLimit)) { // when a large file is processed and it should be stopped it is still reading the // hole thing // the only solution I see is to prune / detach the document and this will lead // into a // NPE or other errors depending on the parsing location - this will be treated in // the catch part below // any better idea is welcome if (log.isBasic()) { logBasic(BaseMessages.getString(PKG, ""GetXMLData.Log.StreamingMode.Stopped"")); } data.stopPruning = true; path.getCurrent().getDocument().detach(); // trick to stop reader return; } // process a ROW element if (log.isDebug()) { logDebug( BaseMessages.getString(PKG, ""GetXMLData.Log.StreamingMode.StartProcessing"")); } Element row = path.getCurrent(); try { // Pass over the row instead of just the document. If // if there's only one row, there's no need to // go back to the whole document. processStreaming(row); } catch (Exception e) { // catch the HopException or others and forward to caller, e.g. when applyXPath() // has a problem throw new RuntimeException(e); } // prune the tree row.detach(); if (log.isDebug()) { logDebug( BaseMessages.getString(PKG, ""GetXMLData.Log.StreamingMode.EndProcessing"")); } } }); } if (isInXMLField) { // read string to parse data.document = reader.read(new StringReader(stringXML)); } else if (readurl && HopVfs.startsWithScheme(stringXML)) { data.document = reader.read(HopVfs.getInputStream(stringXML)); } else if (readurl) { // read url as source HttpClient client = HttpClientManager.getInstance().createDefaultClient(); HttpGet method = new HttpGet(stringXML); method.addHeader(""Accept-Encoding"", ""gzip""); HttpResponse response = client.execute(method); Header contentEncoding = response.getFirstHeader(""Content-Encoding""); HttpEntity responseEntity = response.getEntity(); if (responseEntity != null) { if (contentEncoding != null) { String acceptEncodingValue = contentEncoding.getValue(); if (acceptEncodingValue.contains(""gzip"")) { GZIPInputStream in = new GZIPInputStream(responseEntity.getContent()); data.document = reader.read(in); } } else { data.document = reader.read(responseEntity.getContent()); } } } else { // get encoding. By default UTF-8 String encoding = ""UTF-8""; if (!Utils.isEmpty(meta.getEncoding())) { encoding = meta.getEncoding(); } InputStream is = HopVfs.getInputStream(file); try { data.document = reader.read(is, encoding); } finally { BaseTransform.closeQuietly(is); } } if (meta.isNamespaceAware()) { prepareNSMap(data.document.getRootElement()); } } catch (Exception e) { if (data.stopPruning) { // ignore error when pruning return false; } else { throw new HopException(e); } } return true; }","protected boolean setDocument( String stringXML, FileObject file, boolean isInXMLField, boolean readurl) throws HopException { this.prevRow = buildEmptyRow(); // pre-allocate previous row try { SAXReader reader = Dom4JUtil.getSAXReader(); data.stopPruning = false; // Validate XML against specified schema? if (meta.isValidating()) { reader.setValidation(true); reader.setFeature(""http://apache.org/xml/features/validation/schema"", true); } else { // Ignore DTD declarations reader.setEntityResolver(new IgnoreDtdEntityResolver()); } // Ignore comments? if (meta.isIgnoreComments()) { reader.setIgnoreComments(true); } if (data.prunePath != null) { // when pruning is on: reader.read() below will wait until all is processed in the handler if (log.isDetailed()) { logDetailed(BaseMessages.getString(PKG, ""GetXMLData.Log.StreamingMode.Activated"")); } if (data.PathValue.equals(data.prunePath)) { // Edge case, but if true, there will only ever be one item in the list data.an = new ArrayList<>(1); // pre-allocate array and sizes data.an.add(null); } reader.addHandler( data.prunePath, new ElementHandler() { @Override public void onStart(ElementPath path) { // do nothing here... } @Override public void onEnd(ElementPath path) { long rowLimit = meta.getRowLimit(); if (isStopped() || (rowLimit > 0 && data.rownr > rowLimit)) { // when a large file is processed and it should be stopped it is still reading the // hole thing // the only solution I see is to prune / detach the document and this will lead // into a // NPE or other errors depending on the parsing location - this will be treated in // the catch part below // any better idea is welcome if (log.isBasic()) { logBasic(BaseMessages.getString(PKG, ""GetXMLData.Log.StreamingMode.Stopped"")); } data.stopPruning = true; path.getCurrent().getDocument().detach(); // trick to stop reader return; } // process a ROW element if (log.isDebug()) { logDebug( BaseMessages.getString(PKG, ""GetXMLData.Log.StreamingMode.StartProcessing"")); } Element row = path.getCurrent(); try { // Pass over the row instead of just the document. If // if there's only one row, there's no need to // go back to the whole document. processStreaming(row); } catch (Exception e) { // catch the HopException or others and forward to caller, e.g. when applyXPath() // has a problem throw new RuntimeException(e); } // prune the tree row.detach(); if (log.isDebug()) { logDebug( BaseMessages.getString(PKG, ""GetXMLData.Log.StreamingMode.EndProcessing"")); } } }); } if (isInXMLField) { // read string to parse data.document = reader.read(new StringReader(stringXML)); } else if (readurl && HopVfs.startsWithScheme(stringXML)) { data.document = reader.read(HopVfs.getInputStream(stringXML)); } else if (readurl) { // read url as source HttpClient client = HttpClientManager.getInstance().createDefaultClient(); HttpGet method = new HttpGet(stringXML); method.addHeader(""Accept-Encoding"", ""gzip""); HttpResponse response = client.execute(method); Header contentEncoding = response.getFirstHeader(""Content-Encoding""); HttpEntity responseEntity = response.getEntity(); if (responseEntity != null) { if (contentEncoding != null) { String acceptEncodingValue = contentEncoding.getValue(); if (acceptEncodingValue.contains(""gzip"")) { GZIPInputStream in = new GZIPInputStream(responseEntity.getContent()); data.document = reader.read(in); } } else { data.document = reader.read(responseEntity.getContent()); } } } else { // get encoding. By default UTF-8 String encoding = ""UTF-8""; if (!Utils.isEmpty(meta.getEncoding())) { encoding = meta.getEncoding(); } InputStream is = HopVfs.getInputStream(file); try { data.document = reader.read(is, encoding); } finally { BaseTransform.closeQuietly(is); } } if (meta.isNamespaceAware()) { prepareNSMap(data.document.getRootElement()); } } catch (Exception e) { if (data.stopPruning) { // ignore error when pruning return false; } else { throw new HopException(e); } } return true; }",[DOC] fix request url for /hop/status/,https://github.com/apache/hop/commit/de1c01506ab207b40179b38ae100342be66218c2,,,plugins/transforms/xml/src/main/java/org/apache/hop/pipeline/transforms/xml/getxmldata/GetXmlData.java,3,java,False,2022-03-25T04:34:29Z "ActivityInfo resolveActivity(Intent intent, ResolveInfo rInfo, int startFlags, ProfilerInfo profilerInfo) { final ActivityInfo aInfo = rInfo != null ? rInfo.activityInfo : null; if (aInfo != null) { // Store the found target back into the intent, because now that // we have it we never want to do this again. For example, if the // user navigates back to this point in the history, we should // always restart the exact same activity. intent.setComponent(new ComponentName( aInfo.applicationInfo.packageName, aInfo.name)); // Don't debug things in the system process if (!aInfo.processName.equals(""system"")) { if ((startFlags & (START_FLAG_DEBUG | START_FLAG_NATIVE_DEBUGGING | START_FLAG_TRACK_ALLOCATION)) != 0 || profilerInfo != null) { // Mimic an AMS synchronous call by passing a message to AMS and wait for AMS // to notify us that the task has completed. // TODO(b/80414790) look into further untangling for the situation where the // caller is on the same thread as the handler we are posting to. synchronized (mService.mGlobalLock) { // Post message to AMS. final Message msg = PooledLambda.obtainMessage( ActivityManagerInternal::setDebugFlagsForStartingActivity, mService.mAmInternal, aInfo, startFlags, profilerInfo, mService.mGlobalLock); mService.mH.sendMessage(msg); try { mService.mGlobalLock.wait(); } catch (InterruptedException ignore) { } } } } final String intentLaunchToken = intent.getLaunchToken(); if (aInfo.launchToken == null && intentLaunchToken != null) { aInfo.launchToken = intentLaunchToken; } } return aInfo; }","ActivityInfo resolveActivity(Intent intent, ResolveInfo rInfo, int startFlags, ProfilerInfo profilerInfo) { final ActivityInfo aInfo = rInfo != null ? rInfo.activityInfo : null; if (aInfo != null) { // Store the found target back into the intent, because now that // we have it we never want to do this again. For example, if the // user navigates back to this point in the history, we should // always restart the exact same activity. intent.setComponent(new ComponentName( aInfo.applicationInfo.packageName, aInfo.name)); final boolean requestDebug = (startFlags & (START_FLAG_DEBUG | START_FLAG_NATIVE_DEBUGGING | START_FLAG_TRACK_ALLOCATION)) != 0; final boolean requestProfile = profilerInfo != null; if (requestDebug || requestProfile) { final boolean debuggable = (Build.IS_DEBUGGABLE || (aInfo.applicationInfo.flags & ApplicationInfo.FLAG_DEBUGGABLE) != 0) && !aInfo.processName.equals(""system""); if ((requestDebug && !debuggable) || (requestProfile && (!debuggable && !aInfo.applicationInfo.isProfileableByShell()))) { Slog.w(TAG, ""Ignore debugging for non-debuggable app: "" + aInfo.packageName); } else { // Mimic an AMS synchronous call by passing a message to AMS and wait for AMS // to notify us that the task has completed. // TODO(b/80414790) look into further untangling for the situation where the // caller is on the same thread as the handler we are posting to. synchronized (mService.mGlobalLock) { // Post message to AMS. mService.mH.post(() -> { try { mService.mAmInternal.setDebugFlagsForStartingActivity(aInfo, startFlags, profilerInfo, mService.mGlobalLock); } catch (Throwable e) { // Simply ignore it because the debugging doesn't take effect. Slog.w(TAG, e); synchronized (mService.mGlobalLockWithoutBoost) { mService.mGlobalLockWithoutBoost.notifyAll(); } } }); try { mService.mGlobalLock.wait(); } catch (InterruptedException ignore) { } } } } final String intentLaunchToken = intent.getLaunchToken(); if (aInfo.launchToken == null && intentLaunchToken != null) { aInfo.launchToken = intentLaunchToken; } } return aInfo; }","Fix system crash by debug parameters of activity launch Since AMS and ATMS use different lock, setDebugFlagsForStartingActivity is posted to execute so it won't run on binder thread. And it may throw security exception if not debuggable, that causes crash on system server's thread (android.display). Except dealing with the exception, it is more efficient to check before calling setDebugFlagsForStartingActivity. And the check also avoids the case of setDebugApp that enforces permission which is always passed on non binder thread. 3 cases on a non-debuggable device (Build.IS_DEBUGGABLE is false): 1. adb shell am start -n com.android.settings/.Settings -S -D > Debugger dialog should not popup. 2. adb shell am start -n com.android.settings/.Settings -S \ --start-profiler /data/local/tmp/p > System should not crash. 3. Call IActivityTaskManager#startActivity by reflection to launch a non-debuggable app with debug flags. > System should not crash. Bug: 208266893 Bug: 192247102 Test: atest AmProfileTests AmStartOptionsTests Change-Id: I086635a50d8750580127f0b2868e5a241ac5f913",https://github.com/PixelExperience/frameworks_base/commit/138c2dc68b7c46805ed92d0045e304bd252258ee,,,services/core/java/com/android/server/wm/ActivityTaskSupervisor.java,3,java,False,2021-12-27T09:49:18Z "@Implementation(minSdk = N) protected SubscriptionInfo getActiveSubscriptionInfoForSimSlotIndex(int slotIndex) { if (subscriptionList == null) { return null; } for (SubscriptionInfo info : subscriptionList) { if (info.getSimSlotIndex() == slotIndex) { return info; } } return null; }","@Implementation(minSdk = N) protected SubscriptionInfo getActiveSubscriptionInfoForSimSlotIndex(int slotIndex) { checkReadPhoneStatePermission(); if (subscriptionList == null) { return null; } for (SubscriptionInfo info : subscriptionList) { if (info.getSimSlotIndex() == slotIndex) { return info; } } return null; }","Add ShadowSubscriptionManager#checkReadPhoneStatePermission. ShadowSubscriptionManager#checkReadPhoneStatePermission allows to test permission errors. When set to false, methods that require READ_PHONE_STATE permissions will now throw a SecurityException. By default the permissions are granted for backwards compatibility. PiperOrigin-RevId: 460603937",https://github.com/robolectric/robolectric/commit/b14d8bd98f6a3f695acee4d6f5967632e11f8c48,,,shadows/framework/src/main/java/org/robolectric/shadows/ShadowSubscriptionManager.java,3,java,False,2022-07-13T02:12:56Z "@Override public void adviceTransformations(AdviceTransformation transformation) { String advice = getClass().getName() + ""$DisableAsyncAdvice""; transformation.applyAdvice(named(""schedulePeriodically"").and(isDeclaredBy(RX_WORKERS)), advice); transformation.applyAdvice( named(""call"").and(isDeclaredBy(named(""rx.internal.operators.OperatorTimeoutBase""))), advice); transformation.applyAdvice(named(""connect"").and(isDeclaredBy(NETTY_UNSAFE)), advice); transformation.applyAdvice( named(""init"") .and(isDeclaredBy(named(""io.grpc.internal.ServerImpl$ServerTransportListenerImpl""))), advice); transformation.applyAdvice( named(""startTimer"") .and(isDeclaredBy(named(""com.amazonaws.http.timers.request.HttpRequestTimer""))), advice); transformation.applyAdvice( named(""scheduleTimeout"") .and(isDeclaredBy(named(""io.netty.handler.timeout.WriteTimeoutHandler""))), advice); transformation.applyAdvice( named(""rescheduleIdleTimer"").and(isDeclaredBy(GRPC_MANAGED_CHANNEL)), advice); transformation.applyAdvice( namedOneOf(""scheduleAtFixedRate"", ""scheduleWithFixedDelay"") .and(isDeclaredBy(named(""java.util.concurrent.ScheduledThreadPoolExecutor""))), advice); transformation.applyAdvice( named(""start"").and(isDeclaredBy(named(""rx.internal.util.ObjectPool""))), advice); transformation.applyAdvice( named(""put"").and(isDeclaredBy(named(""okhttp3.ConnectionPool""))), advice); transformation.applyAdvice( named(""sendMessage"") .and(isDeclaredBy(named(""org.elasticsearch.transport.netty4.Netty4TcpChannel""))), advice); transformation.applyAdvice( named(""createEntry"") .and(isDeclaredBy(named(""org.springframework.cglib.core.internal.LoadingCache""))), advice); transformation.applyAdvice( isTypeInitializer().and(isDeclaredBy(REACTOR_DISABLED_TYPE_INITIALIZERS)), advice); }","@Override public void adviceTransformations(AdviceTransformation transformation) { String advice = getClass().getName() + ""$DisableAsyncAdvice""; transformation.applyAdvice(named(""schedulePeriodically"").and(isDeclaredBy(RX_WORKERS)), advice); transformation.applyAdvice( named(""call"").and(isDeclaredBy(named(""rx.internal.operators.OperatorTimeoutBase""))), advice); transformation.applyAdvice(named(""connect"").and(isDeclaredBy(NETTY_UNSAFE)), advice); transformation.applyAdvice( named(""init"") .and(isDeclaredBy(named(""io.grpc.internal.ServerImpl$ServerTransportListenerImpl""))), advice); transformation.applyAdvice( named(""startTimer"") .and(isDeclaredBy(named(""com.amazonaws.http.timers.request.HttpRequestTimer""))), advice); transformation.applyAdvice( named(""scheduleTimeout"") .and(isDeclaredBy(named(""io.netty.handler.timeout.WriteTimeoutHandler""))), advice); transformation.applyAdvice( named(""rescheduleIdleTimer"").and(isDeclaredBy(GRPC_MANAGED_CHANNEL)), advice); transformation.applyAdvice( namedOneOf(""scheduleAtFixedRate"", ""scheduleWithFixedDelay"") .and(isDeclaredBy(named(""java.util.concurrent.ScheduledThreadPoolExecutor""))), advice); transformation.applyAdvice( named(""start"").and(isDeclaredBy(named(""rx.internal.util.ObjectPool""))), advice); transformation.applyAdvice( named(""put"").and(isDeclaredBy(named(""okhttp3.ConnectionPool""))), advice); transformation.applyAdvice( named(""sendMessage"") .and(isDeclaredBy(named(""org.elasticsearch.transport.netty4.Netty4TcpChannel""))), advice); transformation.applyAdvice( named(""createEntry"") .and(isDeclaredBy(named(""org.springframework.cglib.core.internal.LoadingCache""))), advice); transformation.applyAdvice( named(""runOnEventLoop"") .and( isDeclaredBy( named( ""com.datastax.oss.driver.internal.core.channel.DefaultWriteCoalescer$Flusher""))), advice); transformation.applyAdvice( isTypeInitializer().and(isDeclaredBy(REACTOR_DISABLED_TYPE_INITIALIZERS)), advice); }",prevent leaking into flusher event loop,https://github.com/DataDog/dd-trace-java/commit/bd55a1ee174d18463da7b8bec7abc954e945557a,,,dd-java-agent/instrumentation/java-concurrent/src/main/java/datadog/trace/instrumentation/java/concurrent/AsyncPropagatingDisableInstrumentation.java,3,java,False,2021-07-23T12:36:12Z "@Override public ByteBuffer readableBuffer() { final ByteBuffer buf; if (hasReadableArray()) { buf = bbslice(ByteBuffer.wrap(readableArray()), readableArrayOffset(), readableArrayLength()); } else { buf = PlatformDependent.directBuffer(address + roff, readableBytes()); } return buf.asReadOnlyBuffer(); }","@Override public ByteBuffer readableBuffer() { final ByteBuffer buf; if (hasReadableArray()) { buf = bbslice(ByteBuffer.wrap(readableArray()), readableArrayOffset(), readableArrayLength()); } else { buf = PlatformDependent.directBuffer(address + roff, readableBytes(), memory); } return buf.asReadOnlyBuffer(); }","ByteBuffer from component iteration must keep unsafe memory alive (#12036) Motivation: It is possible to use forEachReadable or forEachWritable to create a ByteBuffer that is backed by native memory from a Buffer. If we are using Unsafe, then we cannot rely on the underlying ByteBuffer implementation to keep the native memory alive for as long as it is accessible. We must guard against the situation where forEachReadable/Writable is used on an UnsafeBuffer, then a readable/writeableBuffer is created, and this buffer is siphoned out of the iteration, and then kept alive for longer than the UnsafeBuffer. We can only keep the UnsafeMemory alive, though. We cannot guard against use-after-free, because we don't have a way to nerf a ByteBuffer once it has been released. Modification: Change the PlatformDependent.directBuffer method to take an attachment object, and pass it to the DirectByteBuffer constructor. Then use this from the UnsafeBuffer *Component implementation to ensure that the underlying UnsafeMemory is kept alive and strongly reachable by any ByteBuffer instances we create. Result: Reduce the possibility of causing JVM crash through misuse of the ability to get ByteBuffers out of an UnsafeBuffer.",https://github.com/netty/netty/commit/71d829a342361fdec2b18b1d91992bea8a40e348,,,buffer/src/main/java/io/netty/buffer/api/unsafe/UnsafeBuffer.java,3,java,False,2022-01-24T08:13:29Z "@Override protected void onDetachedFromWindow() { super.onDetachedFromWindow(); getUdfpsAnimation().onDestroy(); }","@Override protected void onDetachedFromWindow() { super.onDetachedFromWindow(); if (getUdfpsAnimation() != null) { getUdfpsAnimation().onDestroy(); } }","Fix NPE crashes during UDFPS BiometricPrompt BiometricPrompt for UDFPS used to be working by coincidence. We were always passing null into non-null places. Just it actually broke now. Fixes: 181884785 Test: manual Test: atest com.android.systemui.biometrics Change-Id: Iae22966f0a3ea0bfc543cd01e4b3373d1cead937",https://github.com/omnirom/android_frameworks_base/commit/9e5e59b55201d50f9c251c1a2c72231c9bb21808,,,packages/SystemUI/src/com/android/systemui/biometrics/UdfpsAnimationView.java,3,java,False,2021-03-05T01:53:11Z "@Override public void doFilter(ServletRequest servletRequest, ServletResponse response, FilterChain chain) throws IOException, ServletException { _logger.trace(""WebXssRequestFilter""); boolean isWebXss = false; HttpServletRequest request= ((HttpServletRequest)servletRequest); String requestURI=request.getRequestURI(); _logger.trace(""getContextPath "" +request.getContextPath()); _logger.trace(""getRequestURL "" + ((HttpServletRequest)request).getRequestURI()); _logger.trace(""URL "" +requestURI.substring(request.getContextPath().length())); if(skipUrlMap.containsKey(requestURI.substring(request.getContextPath().length()))) { isWebXss = false; }else { Enumeration parameterNames = request.getParameterNames(); while (parameterNames.hasMoreElements()) { String key = (String) parameterNames.nextElement(); String value = request.getParameter(key); _logger.trace(""parameter name ""+key +"" , value "" + value); String tempValue = value; if(!StringEscapeUtils.escapeHtml4(tempValue).equals(value) ||tempValue.toLowerCase().indexOf(""script"")>-1 ||tempValue.toLowerCase().replace("" "", """").indexOf(""eval("")>-1) { isWebXss = true; _logger.error(""parameter name ""+key +"" , value "" + value + "", contains dangerous content ! ""); break; } } } if(!isWebXss) { chain.doFilter(request, response); } }","@Override public void doFilter(ServletRequest servletRequest, ServletResponse response, FilterChain chain) throws IOException, ServletException { _logger.trace(""WebXssRequestFilter""); boolean isWebXss = false; HttpServletRequest request= ((HttpServletRequest)servletRequest); String requestURI=request.getRequestURI(); _logger.trace(""getContextPath "" +request.getContextPath()); _logger.trace(""getRequestURL "" + ((HttpServletRequest)request).getRequestURI()); _logger.trace(""URL "" +requestURI.substring(request.getContextPath().length())); if(skipUrlMap.containsKey(requestURI.substring(request.getContextPath().length()))) { isWebXss = false; }else { Enumeration parameterNames = request.getParameterNames(); while (parameterNames.hasMoreElements()) { String key = (String) parameterNames.nextElement(); if(skipParameterName.containsKey(key)) {continue;} String value = request.getParameter(key); _logger.trace(""parameter name ""+key +"" , value "" + value); String tempValue = value; if(!StringEscapeUtils.escapeHtml4(tempValue).equals(value) ||tempValue.toLowerCase().indexOf(""script"")>-1 ||tempValue.toLowerCase().replace("" "", """").indexOf(""eval("")>-1) { isWebXss = true; _logger.error(""parameter name ""+key +"" , value "" + value + "", contains dangerous content ! ""); break; } } } if(!isWebXss) { chain.doFilter(request, response); } }",Xss,https://github.com/dromara/MaxKey/commit/02fcbc870c82f3ba33daca7d75e1cd4c9f2f0af0,,,maxkey-core/src/main/java/org/maxkey/web/WebXssRequestFilter.java,3,java,False,2022-01-25T06:35:06Z "public void clearOnTuneEventListener() { mOnTuneEventListener = null; mOnTunerEventExecutor = null; }","public void clearOnTuneEventListener() { synchronized (mOnTuneEventLock) { mOnTuneEventListener = null; mOnTuneEventExecutor = null; } }","Tuner APIs: add locks to avoid crashes caused by NPE Bug: 193604292 Test: atest android.media.tv.tuner.cts.TunerTest Change-Id: I08aaf38489ab7ea29f99e416b0e1082a3d0ee249",https://github.com/PixelExperience/frameworks_base/commit/5558cb1cc931e0022b3583a7c0e12e25d573547d,,,media/java/android/media/tv/tuner/Tuner.java,3,java,False,2021-07-15T01:43:32Z "public UserAuthentication getOrCreateUser(App app, String accessToken) { UserAuthentication userAuth = null; User user = new User(); String secret = Para.getConfig().getSettingForApp(app, ""app_secret_key"", app.getSecret()); try { SignedJWT jwt = SignedJWT.parse(accessToken); String email = jwt.getJWTClaimsSet().getStringClaim(Config._EMAIL); String name = jwt.getJWTClaimsSet().getStringClaim(Config._NAME); String identifier = jwt.getJWTClaimsSet().getStringClaim(Config._IDENTIFIER); String groups = jwt.getJWTClaimsSet().getStringClaim(Config._GROUPS); String picture = jwt.getJWTClaimsSet().getStringClaim(""picture""); String appid = app.getAppIdentifier(); User u = new User(); u.setAppid(appid); u.setIdentifier(identifier); u.setEmail(email); user = User.readUserForIdentifier(u); String userSecret = user != null ? user.getTokenSecret() : """"; if (SecurityUtils.isValidJWToken(secret, jwt) || SecurityUtils.isValidJWToken(app.getSecret() + userSecret, jwt)) { // NOTE TO SELF: // do not overwrite 'u' here - overwrites the password hash! if (user == null) { user = new User(); user.setActive(true); user.setAppid(appid); user.setName(name); user.setGroups(StringUtils.isBlank(groups) ? User.Groups.USERS.toString() : groups); user.setIdentifier(identifier); user.setEmail(email); user.setPicture(picture); // allow temporary first-time login without verifying email address user.create(); } else { if (updateUserInfo(user, picture, email, name, accessToken, groups)) { user.update(); } } userAuth = new UserAuthentication(new AuthenticatedUserDetails(user)); } else { logger.info(""Authentication request failed because the provided JWT token is invalid. appid: '"" + app.getAppIdentifier() + ""', user found: "" + (user == null ? ""none"" : user.getId()) + "", "" + ""user queried: "" + identifier); } } catch (ParseException e) { logger.warn(""Invalid token: "" + e.getMessage()); } return SecurityUtils.checkIfActive(userAuth, user, false); }","public UserAuthentication getOrCreateUser(App app, String accessToken) { UserAuthentication userAuth = null; User user = new User(); String secret = Para.getConfig().getSettingForApp(app, ""app_secret_key"", app.getSecret()); try { SignedJWT jwt = SignedJWT.parse(accessToken); String email = jwt.getJWTClaimsSet().getStringClaim(Config._EMAIL); String name = jwt.getJWTClaimsSet().getStringClaim(Config._NAME); String identifier = jwt.getJWTClaimsSet().getStringClaim(Config._IDENTIFIER); String groups = jwt.getJWTClaimsSet().getStringClaim(Config._GROUPS); String picture = jwt.getJWTClaimsSet().getStringClaim(""picture""); String appid = app.getAppIdentifier(); identifier = StringUtils.startsWith(identifier, Config.PASSWORDLESS_PREFIX) ? identifier : Config.PASSWORDLESS_PREFIX + identifier; User u = new User(); u.setAppid(appid); u.setIdentifier(identifier); u.setEmail(email); user = User.readUserForIdentifier(u); String userSecret = user != null ? user.getTokenSecret() : """"; if (SecurityUtils.isValidJWToken(secret, jwt) || SecurityUtils.isValidJWToken(app.getSecret() + userSecret, jwt)) { // NOTE TO SELF: // do not overwrite 'u' here - overwrites the password hash! if (user == null) { user = new User(); user.setActive(true); user.setAppid(appid); user.setName(name); user.setGroups(StringUtils.isBlank(groups) ? User.Groups.USERS.toString() : groups); user.setIdentifier(identifier); user.setEmail(email); user.setPicture(picture); // allow temporary first-time login without verifying email address user.create(); } else { if (updateUserInfo(user, picture, email, name, accessToken, groups)) { user.update(); } } userAuth = new UserAuthentication(new AuthenticatedUserDetails(user)); } else { logger.info(""Authentication request failed because the provided JWT token is invalid. appid: '"" + app.getAppIdentifier() + ""', user found: "" + (user == null ? ""none"" : user.getId()) + "", "" + ""user queried: "" + identifier); } } catch (ParseException e) { logger.warn(""Invalid token: "" + e.getMessage()); } return SecurityUtils.checkIfActive(userAuth, user, false); }","added user identifier validation and error message, custom: identifier prefix now mandatory for passwordless auth",https://github.com/Erudika/para/commit/1439e5fa56f274e263e048215dc300b60de4c6d2,,,para-server/src/main/java/com/erudika/para/server/security/filters/PasswordlessAuthFilter.java,3,java,False,2023-01-03T13:56:08Z "private static boolean matchWhile(DoStatement stat) { // search for an if condition at the entrance of the loop Statement first = stat.getFirst(); while (first.type == Statement.TYPE_SEQUENCE) { first = first.getFirst(); } // found an if statement if (first.type == Statement.TYPE_IF) { IfStatement firstif = (IfStatement)first; if (firstif.getFirst().getExprents().isEmpty()) { if (firstif.iftype == IfStatement.IFTYPE_IF) { if (firstif.getIfstat() == null) { StatEdge ifedge = firstif.getIfEdge(); if (isDirectPath(stat, ifedge.getDestination()) || addContinueOrBreak(stat, ifedge)) { // exit condition identified stat.setLooptype(DoStatement.LOOP_WHILE); // negate condition (while header) IfExprent ifexpr = (IfExprent)firstif.getHeadexprent().copy(); ifexpr.negateIf(); if (stat.getConditionExprent() != null) { ifexpr.getCondition().addBytecodeOffsets(stat.getConditionExprent().bytecode); } ifexpr.getCondition().addBytecodeOffsets(firstif.getHeadexprent().bytecode); stat.setConditionExprent(ifexpr.getCondition()); // remove edges firstif.getFirst().removeSuccessor(ifedge); firstif.removeSuccessor(firstif.getAllSuccessorEdges().get(0)); if (stat.getAllSuccessorEdges().isEmpty()) { ifedge.setSource(stat); if (ifedge.closure == stat) { ifedge.closure = stat.getParent(); } stat.addSuccessor(ifedge); } // remove empty if statement as it is now part of the loop if (firstif == stat.getFirst()) { BasicBlockStatement bstat = new BasicBlockStatement(new BasicBlock( DecompilerContext.getCounterContainer().getCounterAndIncrement(CounterContainer.STATEMENT_COUNTER))); bstat.setExprents(new ArrayList<>()); stat.replaceStatement(firstif, bstat); } else { // precondition: sequence must contain more than one statement! Statement sequence = firstif.getParent(); sequence.getStats().removeWithKey(firstif.id); if (!sequence.getStats().isEmpty()) { sequence.setFirst(sequence.getStats().get(0)); } else { SequenceHelper.destroyAndFlattenStatement(sequence); } } return true; } } //else { // fix infinite loops StatEdge elseEdge = firstif.getAllSuccessorEdges().get(0); boolean directlyConnectedToExit = directlyConnectedToExit(stat, elseEdge.getDestination().getParent(), elseEdge.getDestination()); if (isDirectPath(stat, elseEdge.getDestination()) || directlyConnectedToExit) { // FIXME: This is horrible and bad!! Needs an extraction step before loop merging!! if (isIif(firstif.getHeadexprent().getCondition())) { return false; } // Lift sequences // Loops that are directly connected to the exit have statements inside that need to lifted out of the loop if (directlyConnectedToExit) { // Statement contained within loop Statement firstStat = stat.getFirst(); // Make sure the inside of the loop is a sequence that has at least the if statement and another block if (firstStat.type == Statement.TYPE_SEQUENCE && firstStat.getStats().size() > 1) { // Get continues List continues = firstStat.getStats().getLast().getSuccessorEdges(StatEdge.TYPE_CONTINUE); if (!continues.isEmpty() && continues.get(0).getDestination() == stat) { // Cannot make loop- continue would be lifted to the outside of the loop! [TestInlineNoSuccessor] return false; } else { // Discard loops that have continues when blocks are inlined // FIXME: whole system needs rewrite Statement temp = firstStat; while (true) { int size = temp.getStats().size(); if (size <= 1) { break; } List breaks = temp.getStats().getLast().getSuccessorEdges(StatEdge.TYPE_BREAK); if (!breaks.isEmpty() && breaks.get(0).getDestination().type != Statement.TYPE_DUMMYEXIT) { break; } if (!temp.getStats().getLast().getSuccessorEdges(StatEdge.TYPE_CONTINUE).isEmpty()) { return false; } temp = temp.getStats().get(temp.getStats().size() - 2); if (temp.type != Statement.TYPE_SEQUENCE) { break; } } } // Found basic block, delegate to loop extractor Statement firstSt = firstStat.getStats().get(0); if (firstSt.type == Statement.TYPE_IF && ((IfStatement)firstSt).getIfstat().type != Statement.TYPE_SEQUENCE && ((IfStatement) firstSt).getIfstat().getStats().isEmpty()) { return false; } List toAdd = new ArrayList<>(); // Skip first statement as that is the if that contains the while loop condition for (int idx = 1; idx < firstStat.getStats().size(); idx++) { Statement st = firstStat.getStats().get(idx); // Add to temp list toAdd.add(st); } for (Statement st : toAdd) { // Remove the statement from the loop body firstStat.getStats().removeWithKey(st.id); } liftToParent(stat, toAdd); } } // exit condition identified stat.setLooptype(DoStatement.LOOP_WHILE); // no need to negate the while condition IfExprent ifexpr = (IfExprent)firstif.getHeadexprent().copy(); if (stat.getConditionExprent() != null) { ifexpr.getCondition().addBytecodeOffsets(stat.getConditionExprent().bytecode); } ifexpr.getCondition().addBytecodeOffsets(firstif.getHeadexprent().bytecode); stat.setConditionExprent(ifexpr.getCondition()); // remove edges StatEdge ifedge = firstif.getIfEdge(); firstif.getFirst().removeSuccessor(ifedge); firstif.removeSuccessor(elseEdge); if (stat.getAllSuccessorEdges().isEmpty()) { elseEdge.setSource(stat); if (elseEdge.closure == stat) { elseEdge.closure = stat.getParent(); } stat.addSuccessor(elseEdge); } if (firstif.getIfstat() == null) { BasicBlockStatement bstat = new BasicBlockStatement(new BasicBlock( DecompilerContext.getCounterContainer().getCounterAndIncrement(CounterContainer.STATEMENT_COUNTER))); bstat.setExprents(new ArrayList<>()); ifedge.setSource(bstat); bstat.addSuccessor(ifedge); // TODO: has the potential of breaking if firstif isn't found due to our changes stat.replaceStatement(firstif, bstat); } else { // replace the if statement with its content first.getParent().replaceStatement(first, firstif.getIfstat()); // lift closures for (StatEdge prededge : elseEdge.getDestination().getPredecessorEdges(StatEdge.TYPE_BREAK)) { if (stat.containsStatementStrict(prededge.closure)) { stat.addLabeledEdge(prededge); } } LabelHelper.lowClosures(stat); } return true; } } } } return false; }","private static boolean matchWhile(DoStatement stat) { // search for an if condition at the entrance of the loop Statement first = stat.getFirst(); while (first.type == Statement.TYPE_SEQUENCE) { first = first.getFirst(); } // found an if statement if (first.type == Statement.TYPE_IF) { IfStatement firstif = (IfStatement)first; if (firstif.getFirst().getExprents().isEmpty()) { if (firstif.iftype == IfStatement.IFTYPE_IF) { if (firstif.getIfstat() == null) { StatEdge ifedge = firstif.getIfEdge(); if (isDirectPath(stat, ifedge.getDestination()) || addContinueOrBreak(stat, ifedge)) { // exit condition identified stat.setLooptype(DoStatement.LOOP_WHILE); // negate condition (while header) IfExprent ifexpr = (IfExprent)firstif.getHeadexprent().copy(); ifexpr.negateIf(); if (stat.getConditionExprent() != null) { ifexpr.getCondition().addBytecodeOffsets(stat.getConditionExprent().bytecode); } ifexpr.getCondition().addBytecodeOffsets(firstif.getHeadexprent().bytecode); stat.setConditionExprent(ifexpr.getCondition()); // remove edges firstif.getFirst().removeSuccessor(ifedge); firstif.removeSuccessor(firstif.getAllSuccessorEdges().get(0)); if (stat.getAllSuccessorEdges().isEmpty()) { ifedge.setSource(stat); if (ifedge.closure == stat) { ifedge.closure = stat.getParent(); } stat.addSuccessor(ifedge); } // remove empty if statement as it is now part of the loop if (firstif == stat.getFirst()) { BasicBlockStatement bstat = new BasicBlockStatement(new BasicBlock( DecompilerContext.getCounterContainer().getCounterAndIncrement(CounterContainer.STATEMENT_COUNTER))); bstat.setExprents(new ArrayList<>()); stat.replaceStatement(firstif, bstat); } else { // precondition: sequence must contain more than one statement! Statement sequence = firstif.getParent(); sequence.getStats().removeWithKey(firstif.id); if (!sequence.getStats().isEmpty()) { sequence.setFirst(sequence.getStats().get(0)); } else { SequenceHelper.destroyAndFlattenStatement(sequence); } } return true; } } //else { // fix infinite loops StatEdge elseEdge = firstif.getAllSuccessorEdges().get(0); if (isDirectPath(stat, elseEdge.getDestination())) { // FIXME: This is horrible and bad!! Needs an extraction step before loop merging!! if (isIif(firstif.getHeadexprent().getCondition())) { return false; } // exit condition identified stat.setLooptype(DoStatement.LOOP_WHILE); // no need to negate the while condition IfExprent ifexpr = (IfExprent)firstif.getHeadexprent().copy(); if (stat.getConditionExprent() != null) { ifexpr.getCondition().addBytecodeOffsets(stat.getConditionExprent().bytecode); } ifexpr.getCondition().addBytecodeOffsets(firstif.getHeadexprent().bytecode); stat.setConditionExprent(ifexpr.getCondition()); // remove edges StatEdge ifedge = firstif.getIfEdge(); firstif.getFirst().removeSuccessor(ifedge); firstif.removeSuccessor(elseEdge); if (stat.getAllSuccessorEdges().isEmpty()) { elseEdge.setSource(stat); if (elseEdge.closure == stat) { elseEdge.closure = stat.getParent(); } stat.addSuccessor(elseEdge); } if (firstif.getIfstat() == null) { BasicBlockStatement bstat = new BasicBlockStatement(new BasicBlock( DecompilerContext.getCounterContainer().getCounterAndIncrement(CounterContainer.STATEMENT_COUNTER))); bstat.setExprents(new ArrayList<>()); ifedge.setSource(bstat); bstat.addSuccessor(ifedge); // TODO: has the potential of breaking if firstif isn't found due to our changes stat.replaceStatement(firstif, bstat); } else { // replace the if statement with its content first.getParent().replaceStatement(first, firstif.getIfstat()); // lift closures for (StatEdge prededge : elseEdge.getDestination().getPredecessorEdges(StatEdge.TYPE_BREAK)) { if (stat.containsStatementStrict(prededge.closure)) { stat.addLabeledEdge(prededge); } } LabelHelper.lowClosures(stat); } return true; } } } } return false; }",Fix IOOBE in ternary processor,https://github.com/Vineflower/vineflower/commit/4400c8d14afeb97a151c47817138dd1f8da023d4,,,src/org/jetbrains/java/decompiler/modules/decompiler/MergeHelper.java,3,java,False,2022-01-06T05:29:48Z "public Set getChildren() { if (children == null) { children = new HashSet<>(); childrenLookup.apply(value.getName()) .forEach(name -> children.add(lookup.apply(name))); } return children; }","public Set getChildren() { if (children == null) { String name = getName(); children = new HashSet<>(); childrenLookup.apply(value.getName()) .stream() .filter(childName -> !name.equals(childName)) .forEach(childName -> children.add(lookup.apply(childName))); } return children; }",Prevent inheritance graph infinite loops with 'x extends x' logic,https://github.com/Col-E/Recaf/commit/53da1d3adf0e831e89f5f580c1bf4e08d81c9a6c,,,recaf-core/src/main/java/me/coley/recaf/graph/InheritanceVertex.java,3,java,False,2022-01-08T08:33:46Z "public String getUserNameFromJwtToken(String token) { return Jwts.parser() .setSigningKey(this.keyPair.getPublic()) .parseClaimsJws(token) .getBody() .getSubject(); }","public String getUserNameFromJwtToken(String token) throws ParseException { // Parse without verifying token signature return JWTParser.parse(token).getJWTClaimsSet().getSubject(); }","Centralized JWT Provider (#148) * Added jwt token verify api endpoint * Added tests for token verify endpoint * Added Identity Service URL env variable to workshop and community service * Chore: Fixed response code for token verify endpoint * Migrated to using Identity service for token verification in Community service * Fixed community service build * Fixed formatting issue * Migrated to using Identity service for token verification in Workshop service * Fixed unittests in workshop service * Fixed response status code of jwt verify endpoint * Removed JWT_SECRET variable from workshop and community services * - Added private key for jwt in all deployment methods - Modified identity service entrypoint to load private key as env variables * Updated identity service to use user provided private key * Replaced PEM file with JWKS.json and serving jwks.json from well-known * Fixed public jwks.json format * Updated Postman Collections Co-authored-by: Roshan Piyush ",https://github.com/OWASP/crAPI/commit/ff8ee954ddc0eb12990474e0662a21e1c0a8c63a,,,services/identity/src/main/java/com/crapi/config/JwtProvider.java,3,java,False,2022-11-13T15:46:29Z "@Override public void applyTo(HTTPRequest httpRequest) { }","@Override public void applyTo(HTTPRequest httpRequest) { if (httpRequest.getMethod() != HTTPRequest.Method.POST) { throw new SerializeException(""The HTTP request method must be POST""); } else { ContentType ct = httpRequest.getEntityContentType(); if (ct == null) { throw new SerializeException(""Missing HTTP Content-Type header""); } else if (!ct.matches(ContentType.APPLICATION_URLENCODED)) { throw new SerializeException(""The HTTP Content-Type header must be "" + ContentType.APPLICATION_URLENCODED); } else { Map> params = httpRequest.getQueryParameters(); params.putAll(this.toParameters()); String queryString = URLUtils.serializeParameters(params); httpRequest.setQuery(queryString); } } }","fix: request oauth tokens correctly for jwt auth The customJwtAuthentication class did not provide the same behavior as the JwtAuthentication class of nimbusds library. The fix for #437 is not sufficient to use workload-identity with this msal library. I updated the customJwtAuthentication to make sure it sets the correct body when requesting oauth tokens.",https://github.com/AzureAD/microsoft-authentication-library-for-java/commit/101759aea5ad641f83bb38c30b84529ecb6aae18,,,src/main/java/com/microsoft/aad/msal4j/CustomJWTAuthentication.java,3,java,False,2022-02-07T13:04:34Z "private Map> setupUploadBatches(Iterator renders) { Map> map = new Reference2ObjectLinkedOpenHashMap<>(); while (renders.hasNext()) { ChunkBuildResult result = renders.next(); RenderSection render = result.render; if (!render.canAcceptBuildResults(result)) { result.delete(); continue; } RenderRegion region = this.regions.get(RenderRegion.getRegionKeyForChunk(render.getChunkX(), render.getChunkY(), render.getChunkZ())); if (region == null) { throw new NullPointerException(""Couldn't find region for chunk: "" + render); } List uploadQueue = map.computeIfAbsent(region, k -> new ArrayList<>()); uploadQueue.add(result); } return map; }","private Map> setupUploadBatches(Iterator renders) { Map> map = new Reference2ObjectLinkedOpenHashMap<>(); while (renders.hasNext()) { ChunkBuildResult result = renders.next(); RenderSection render = result.render; if (!render.canAcceptBuildResults(result)) { result.delete(); continue; } RenderRegion region = this.regions.get(RenderRegion.getRegionKeyForChunk(render.getChunkX(), render.getChunkY(), render.getChunkZ())); if (region == null) { // Discard the result if the region is no longer loaded result.delete(); continue; } List uploadQueue = map.computeIfAbsent(region, k -> new ArrayList<>()); uploadQueue.add(result); } return map; }",fix: Discard lagged uploads for unloaded regions instead of crashing,https://github.com/embeddedt/embeddium/commit/e654dfe066e3a51babbecbf41a7eee7645674afc,,,src/main/java/me/jellysquid/mods/sodium/client/render/chunk/region/RenderRegionManager.java,3,java,False,2021-08-28T19:54:11Z "@Override public boolean processRow() throws HopException { Object[] row = getRow(); if (row == null) { // no more input to be expected... setOutputDone(); return false; } if (first) { first = false; data.outputRowMeta = getInputRowMeta().clone(); meta.getFields(data.outputRowMeta, getTransformName(), null, null, this, metadataProvider); // Check if The result field is given if (Utils.isEmpty(meta.getResultfieldname())) { // Result Field is missing ! logError(BaseMessages.getString(PKG, ""Xslt.Log.ErrorResultFieldMissing"")); throw new HopTransformException( BaseMessages.getString(PKG, ""Xslt.Exception.ErrorResultFieldMissing"")); } // Check if The XML field is given if (Utils.isEmpty(meta.getFieldname())) { // Result Field is missing ! logError(BaseMessages.getString(PKG, ""Xslt.Exception.ErrorXMLFieldMissing"")); throw new HopTransformException( BaseMessages.getString(PKG, ""Xslt.Exception.ErrorXMLFieldMissing"")); } // Try to get XML Field index data.fieldposition = getInputRowMeta().indexOfValue(meta.getFieldname()); // Let's check the Field if (data.fieldposition < 0) { // The field is unreachable ! logError( BaseMessages.getString(PKG, ""Xslt.Log.ErrorFindingField"") + ""["" + meta.getFieldname() + ""]""); throw new HopTransformException( BaseMessages.getString(PKG, ""Xslt.Exception.CouldnotFindField"", meta.getFieldname())); } // Check if the XSL Filename is contained in a column if (meta.useXSLField()) { if (Utils.isEmpty(meta.getXSLFileField())) { // The field is missing // Result field is missing ! logError(BaseMessages.getString(PKG, ""Xslt.Log.ErrorXSLFileFieldMissing"")); throw new HopTransformException( BaseMessages.getString(PKG, ""Xslt.Exception.ErrorXSLFileFieldMissing"")); } // Try to get Field index data.fielxslfiledposition = getInputRowMeta().indexOfValue(meta.getXSLFileField()); // Let's check the Field if (data.fielxslfiledposition < 0) { // The field is unreachable ! logError( BaseMessages.getString(PKG, ""Xslt.Log.ErrorXSLFileFieldFinding"") + ""["" + meta.getXSLFileField() + ""]""); throw new HopTransformException( BaseMessages.getString( PKG, ""Xslt.Exception.ErrorXSLFileFieldFinding"", meta.getXSLFileField())); } } else { if (Utils.isEmpty(meta.getXslFilename())) { logError(BaseMessages.getString(PKG, ""Xslt.Log.ErrorXSLFile"")); throw new HopTransformException( BaseMessages.getString(PKG, ""Xslt.Exception.ErrorXSLFile"")); } // Check if XSL File exists! data.xslfilename = resolve(meta.getXslFilename()); FileObject file = null; try { file = HopVfs.getFileObject(data.xslfilename); if (!file.exists()) { logError( BaseMessages.getString(PKG, ""Xslt.Log.ErrorXSLFileNotExists"", data.xslfilename)); throw new HopTransformException( BaseMessages.getString( PKG, ""Xslt.Exception.ErrorXSLFileNotExists"", data.xslfilename)); } if (file.getType() != FileType.FILE) { logError(BaseMessages.getString(PKG, ""Xslt.Log.ErrorXSLNotAFile"", data.xslfilename)); throw new HopTransformException( BaseMessages.getString(PKG, ""Xslt.Exception.ErrorXSLNotAFile"", data.xslfilename)); } } catch (Exception e) { throw new HopTransformException(e); } finally { try { if (file != null) { file.close(); } } catch (Exception e) { /* Ignore */ } } } // Check output parameters int nrOutputProps = meta.getOutputPropertyName() == null ? 0 : meta.getOutputPropertyName().length; if (nrOutputProps > 0) { data.outputProperties = new Properties(); for (int i = 0; i < nrOutputProps; i++) { data.outputProperties.put( meta.getOutputPropertyName()[i], resolve(meta.getOutputPropertyValue()[i])); } data.setOutputProperties = true; } // Check parameters data.nrParams = meta.getParameterField() == null ? 0 : meta.getParameterField().length; if (data.nrParams > 0) { data.indexOfParams = new int[data.nrParams]; data.nameOfParams = new String[data.nrParams]; for (int i = 0; i < data.nrParams; i++) { String name = resolve(meta.getParameterName()[i]); String field = resolve(meta.getParameterField()[i]); if (Utils.isEmpty(field)) { throw new HopTransformException( BaseMessages.getString(PKG, ""Xslt.Exception.ParameterFieldMissing"", name, i)); } data.indexOfParams[i] = getInputRowMeta().indexOfValue(field); if (data.indexOfParams[i] < 0) { throw new HopTransformException( BaseMessages.getString(PKG, ""Xslt.Exception.ParameterFieldNotFound"", name)); } data.nameOfParams[i] = name; } data.useParameters = true; } data.factory = TransformerFactory.newInstance(); if (meta.getXSLFactory().equals(""SAXON"")) { // Set the TransformerFactory to the SAXON implementation. data.factory = new net.sf.saxon.TransformerFactoryImpl(); } } // end if first // Get the field value String xmlValue = getInputRowMeta().getString(row, data.fieldposition); if (meta.useXSLField()) { // Get the value data.xslfilename = getInputRowMeta().getString(row, data.fielxslfiledposition); if (log.isDetailed()) { logDetailed( BaseMessages.getString( PKG, ""Xslt.Log.XslfileNameFromFied"", data.xslfilename, meta.getXSLFileField())); } } try { if (log.isDetailed()) { if (meta.isXSLFieldIsAFile()) { logDetailed(BaseMessages.getString(PKG, ""Xslt.Log.Filexsl"") + data.xslfilename); } else { logDetailed(BaseMessages.getString(PKG, ""Xslt.Log.XslStream"", data.xslfilename)); } } // Get the template from the cache Transformer transformer = data.getTemplate(data.xslfilename, data.xslIsAfile); // Do we need to set output properties? if (data.setOutputProperties) { transformer.setOutputProperties(data.outputProperties); } // Do we need to pass parameters? if (data.useParameters) { for (int i = 0; i < data.nrParams; i++) { transformer.setParameter(data.nameOfParams[i], row[data.indexOfParams[i]]); } } Source source = new StreamSource(new StringReader(xmlValue)); // Prepare output stream StreamResult result = new StreamResult(new StringWriter()); // transform xml source transformer.transform(source, result); String xmlString = result.getWriter().toString(); if (log.isDetailed()) { logDetailed(BaseMessages.getString(PKG, ""Xslt.Log.FileResult"")); logDetailed(xmlString); } Object[] outputRowData = RowDataUtil.addValueData(row, getInputRowMeta().size(), xmlString); if (log.isRowLevel()) { logRowlevel( BaseMessages.getString(PKG, ""Xslt.Log.ReadRow"") + "" "" + getInputRowMeta().getString(row)); } // add new values to the row. putRow(data.outputRowMeta, outputRowData); // copy row to output rowset(s) } catch (Exception e) { String errorMessage = e.getClass().toString() + "": "" + e.getMessage(); if (getTransformMeta().isDoingErrorHandling()) { // Simply add this row to the error row putError(getInputRowMeta(), row, 1, errorMessage, meta.getResultfieldname(), ""XSLT01""); } else { logError(BaseMessages.getString(PKG, ""Xslt.ErrorProcesing"" + "" : "" + errorMessage), e); throw new HopTransformException(BaseMessages.getString(PKG, ""Xslt.ErrorProcesing""), e); } } return true; }","@Override public boolean processRow() throws HopException { Object[] row = getRow(); if (row == null) { // no more input to be expected... setOutputDone(); return false; } if (first) { first = false; data.outputRowMeta = getInputRowMeta().clone(); meta.getFields(data.outputRowMeta, getTransformName(), null, null, this, metadataProvider); // Check if The result field is given if (Utils.isEmpty(meta.getResultfieldname())) { // Result Field is missing ! logError(BaseMessages.getString(PKG, ""Xslt.Log.ErrorResultFieldMissing"")); throw new HopTransformException( BaseMessages.getString(PKG, ""Xslt.Exception.ErrorResultFieldMissing"")); } // Check if The XML field is given if (Utils.isEmpty(meta.getFieldname())) { // Result Field is missing ! logError(BaseMessages.getString(PKG, ""Xslt.Exception.ErrorXMLFieldMissing"")); throw new HopTransformException( BaseMessages.getString(PKG, ""Xslt.Exception.ErrorXMLFieldMissing"")); } // Try to get XML Field index data.fieldposition = getInputRowMeta().indexOfValue(meta.getFieldname()); // Let's check the Field if (data.fieldposition < 0) { // The field is unreachable ! logError( BaseMessages.getString(PKG, ""Xslt.Log.ErrorFindingField"") + ""["" + meta.getFieldname() + ""]""); throw new HopTransformException( BaseMessages.getString(PKG, ""Xslt.Exception.CouldnotFindField"", meta.getFieldname())); } // Check if the XSL Filename is contained in a column if (meta.useXSLField()) { if (Utils.isEmpty(meta.getXSLFileField())) { // The field is missing // Result field is missing ! logError(BaseMessages.getString(PKG, ""Xslt.Log.ErrorXSLFileFieldMissing"")); throw new HopTransformException( BaseMessages.getString(PKG, ""Xslt.Exception.ErrorXSLFileFieldMissing"")); } // Try to get Field index data.fielxslfiledposition = getInputRowMeta().indexOfValue(meta.getXSLFileField()); // Let's check the Field if (data.fielxslfiledposition < 0) { // The field is unreachable ! logError( BaseMessages.getString(PKG, ""Xslt.Log.ErrorXSLFileFieldFinding"") + ""["" + meta.getXSLFileField() + ""]""); throw new HopTransformException( BaseMessages.getString( PKG, ""Xslt.Exception.ErrorXSLFileFieldFinding"", meta.getXSLFileField())); } } else { if (Utils.isEmpty(meta.getXslFilename())) { logError(BaseMessages.getString(PKG, ""Xslt.Log.ErrorXSLFile"")); throw new HopTransformException( BaseMessages.getString(PKG, ""Xslt.Exception.ErrorXSLFile"")); } // Check if XSL File exists! data.xslfilename = resolve(meta.getXslFilename()); FileObject file = null; try { file = HopVfs.getFileObject(data.xslfilename); if (!file.exists()) { logError( BaseMessages.getString(PKG, ""Xslt.Log.ErrorXSLFileNotExists"", data.xslfilename)); throw new HopTransformException( BaseMessages.getString( PKG, ""Xslt.Exception.ErrorXSLFileNotExists"", data.xslfilename)); } if (file.getType() != FileType.FILE) { logError(BaseMessages.getString(PKG, ""Xslt.Log.ErrorXSLNotAFile"", data.xslfilename)); throw new HopTransformException( BaseMessages.getString(PKG, ""Xslt.Exception.ErrorXSLNotAFile"", data.xslfilename)); } } catch (Exception e) { throw new HopTransformException(e); } finally { try { if (file != null) { file.close(); } } catch (Exception e) { /* Ignore */ } } } // Check output parameters int nrOutputProps = meta.getOutputPropertyName() == null ? 0 : meta.getOutputPropertyName().length; if (nrOutputProps > 0) { data.outputProperties = new Properties(); for (int i = 0; i < nrOutputProps; i++) { data.outputProperties.put( meta.getOutputPropertyName()[i], resolve(meta.getOutputPropertyValue()[i])); } data.setOutputProperties = true; } // Check parameters data.nrParams = meta.getParameterField() == null ? 0 : meta.getParameterField().length; if (data.nrParams > 0) { data.indexOfParams = new int[data.nrParams]; data.nameOfParams = new String[data.nrParams]; for (int i = 0; i < data.nrParams; i++) { String name = resolve(meta.getParameterName()[i]); String field = resolve(meta.getParameterField()[i]); if (Utils.isEmpty(field)) { throw new HopTransformException( BaseMessages.getString(PKG, ""Xslt.Exception.ParameterFieldMissing"", name, i)); } data.indexOfParams[i] = getInputRowMeta().indexOfValue(field); if (data.indexOfParams[i] < 0) { throw new HopTransformException( BaseMessages.getString(PKG, ""Xslt.Exception.ParameterFieldNotFound"", name)); } data.nameOfParams[i] = name; } data.useParameters = true; } data.factory = XmlHandler.createSecureTransformerFactory(); if (meta.getXSLFactory().equals(""SAXON"")) { // Set the TransformerFactory to the SAXON implementation. data.factory = new net.sf.saxon.TransformerFactoryImpl(); } } // end if first // Get the field value String xmlValue = getInputRowMeta().getString(row, data.fieldposition); if (meta.useXSLField()) { // Get the value data.xslfilename = getInputRowMeta().getString(row, data.fielxslfiledposition); if (log.isDetailed()) { logDetailed( BaseMessages.getString( PKG, ""Xslt.Log.XslfileNameFromFied"", data.xslfilename, meta.getXSLFileField())); } } try { if (log.isDetailed()) { if (meta.isXSLFieldIsAFile()) { logDetailed(BaseMessages.getString(PKG, ""Xslt.Log.Filexsl"") + data.xslfilename); } else { logDetailed(BaseMessages.getString(PKG, ""Xslt.Log.XslStream"", data.xslfilename)); } } // Get the template from the cache Transformer transformer = data.getTemplate(data.xslfilename, data.xslIsAfile); // Do we need to set output properties? if (data.setOutputProperties) { transformer.setOutputProperties(data.outputProperties); } // Do we need to pass parameters? if (data.useParameters) { for (int i = 0; i < data.nrParams; i++) { transformer.setParameter(data.nameOfParams[i], row[data.indexOfParams[i]]); } } Source source = new StreamSource(new StringReader(xmlValue)); // Prepare output stream StreamResult result = new StreamResult(new StringWriter()); // transform xml source transformer.transform(source, result); String xmlString = result.getWriter().toString(); if (log.isDetailed()) { logDetailed(BaseMessages.getString(PKG, ""Xslt.Log.FileResult"")); logDetailed(xmlString); } Object[] outputRowData = RowDataUtil.addValueData(row, getInputRowMeta().size(), xmlString); if (log.isRowLevel()) { logRowlevel( BaseMessages.getString(PKG, ""Xslt.Log.ReadRow"") + "" "" + getInputRowMeta().getString(row)); } // add new values to the row. putRow(data.outputRowMeta, outputRowData); // copy row to output rowset(s) } catch (Exception e) { String errorMessage = e.getClass().toString() + "": "" + e.getMessage(); if (getTransformMeta().isDoingErrorHandling()) { // Simply add this row to the error row putError(getInputRowMeta(), row, 1, errorMessage, meta.getResultfieldname(), ""XSLT01""); } else { logError(BaseMessages.getString(PKG, ""Xslt.ErrorProcesing"" + "" : "" + errorMessage), e); throw new HopTransformException(BaseMessages.getString(PKG, ""Xslt.ErrorProcesing""), e); } } return true; }",Fix #1859 : Sonar Vulnerability issues,https://github.com/apache/hop/commit/562dc41d7efe4bd7bb43ac0910a8e1e63b2951c1,,,plugins/transforms/xml/src/main/java/org/apache/hop/pipeline/transforms/xml/xslt/Xslt.java,3,java,False,2022-12-01T11:21:34Z "@Packet public void onFlying(WrappedInFlyingPacket packet, long timeStamp) { if(packet.isPos() && (data.playerInfo.deltaXZ > 0 || data.playerInfo.deltaY != 0)) { /* We check if the player is in ground, since theoretically the y should be zero. */ double lDeltaY = data.playerInfo.lClientGround ? 0 : data.playerInfo.lDeltaY; boolean onGround = data.playerInfo.clientGround; double predicted = onGround ? lDeltaY : (lDeltaY - 0.08) * mult; if(data.playerInfo.lClientGround && !onGround && data.playerInfo.deltaY > 0) { predicted = MovementUtils.getJumpHeight(data); } /* Basically, this bug would only occur if the client's movement is less than a certain amount. If it is, it won't send any position packet. Usually this only occurs when the magnitude of motionY is less than 0.005 and it rounds it to 0. The easiest way I found to produce this oddity is by putting myself in a corner and just jumping. */ if(Math.abs(predicted) < 0.005 && ProtocolVersion.getGameVersion().isBelow(ProtocolVersion.V1_9)) { predicted = 0; } if(timeStamp - lastPos > 60L) { double toCheck = (predicted - 0.08) * mult; if(Math.abs(data.playerInfo.deltaY - toCheck) < Math.abs(data.playerInfo.deltaY - predicted)) predicted = toCheck; } double deltaPredict = MathUtils.getDelta(data.playerInfo.deltaY, predicted); boolean flagged = false; if(!data.playerInfo.flightCancel && data.playerInfo.lastBlockPlace.isPassed(5) && data.playerInfo.lastVelocity.isPassed(3) && !data.playerInfo.serverGround && data.playerInfo.lastGhostCollision.isPassed(3) && data.playerInfo.climbTimer.isPassed(15) && data.playerInfo.blockAboveTimer.isPassed(5) && deltaPredict > 0.016) { flagged = true; if(++buffer > 5) { ++vl; flag(""dY=%.3f p=%.3f dx=%.3f"", data.playerInfo.deltaY, predicted, data.playerInfo.deltaXZ); fixMovementBugs(); } } else buffer-= buffer > 0 ? 0.25f : 0; debug((flagged ? Color.Green : """") +""pos=%s deltaY=%.3f predicted=%.3f d=%.3f ground=%s lpass=%s cp=%s air=%s buffer=%.1f sg=%s cb=%s fc=%s "", packet.getY(), data.playerInfo.deltaY, predicted, deltaPredict, onGround, data.playerInfo.liquidTimer.getPassed(), data.playerInfo.climbTimer.getPassed(), data.playerInfo.kAirTicks, buffer, data.playerInfo.serverGround, data.playerInfo.climbTimer.getPassed(), data.playerInfo.flightCancel); lastPos = timeStamp; } }","@Packet public void onFlying(WrappedInFlyingPacket packet, long timeStamp) { if(packet.isPos() && (data.playerInfo.deltaXZ > 0 || data.playerInfo.deltaY != 0)) { /* We check if the player is in ground, since theoretically the y should be zero. */ double lDeltaY = data.playerInfo.lClientGround ? 0 : data.playerInfo.lDeltaY; boolean onGround = data.playerInfo.clientGround; double predicted = onGround ? lDeltaY : (lDeltaY - 0.08) * mult; if(data.playerInfo.lClientGround && !onGround && data.playerInfo.deltaY > 0) { predicted = MovementUtils.getJumpHeight(data); } /* Basically, this bug would only occur if the client's movement is less than a certain amount. If it is, it won't send any position packet. Usually this only occurs when the magnitude of motionY is less than 0.005 and it rounds it to 0. The easiest way I found to produce this oddity is by putting myself in a corner and just jumping. */ if(Math.abs(predicted) < 0.005 && ProtocolVersion.getGameVersion().isBelow(ProtocolVersion.V1_9)) { predicted = 0; } if(timeStamp - lastPos > 60L) { double toCheck = (predicted - 0.08) * mult; if(Math.abs(data.playerInfo.deltaY - toCheck) < Math.abs(data.playerInfo.deltaY - predicted)) predicted = toCheck; } double deltaPredict = MathUtils.getDelta(data.playerInfo.deltaY, predicted); boolean flagged = false; if(!data.playerInfo.flightCancel && data.playerInfo.lastBlockPlace.isPassed(1) && data.playerInfo.lastVelocity.isPassed(3) && (!data.playerInfo.clientGround || !data.playerInfo.serverGround) && data.playerInfo.climbTimer.isPassed(15) && data.playerInfo.blockAboveTimer.isPassed(5) && deltaPredict > 0.016) { flagged = true; if(++buffer > 5) { ++vl; flag(""dY=%.3f p=%.3f dx=%.3f"", data.playerInfo.deltaY, predicted, data.playerInfo.deltaXZ); fixMovementBugs(); } } else buffer-= buffer > 0 ? 0.25f : 0; debug((flagged ? Color.Green : """") +""pos=%s deltaY=%.3f predicted=%.3f d=%.3f ground=%s lpass=%s cp=%s air=%s buffer=%.1f s"" + ""g=%s cb=%s fc=%s gc=%s"", packet.getY(), data.playerInfo.deltaY, predicted, deltaPredict, onGround, data.playerInfo.liquidTimer.getPassed(), data.playerInfo.climbTimer.getPassed(), data.playerInfo.kAirTicks, buffer, data.playerInfo.serverGround, data.playerInfo.climbTimer.getPassed(), data.playerInfo.flightCancel, data.playerInfo.generalCancel); lastPos = timeStamp; } }",Fixing potential avenues for bypass,https://github.com/funkemunky/Kauri/commit/fe3f8f602ff7ffc71d271b168605b7c033b157a4,,,Detections/src/main/java/dev/brighten/anticheat/check/impl/movement/fly/FlyA.java,3,java,False,2022-05-14T18:57:06Z "private FederatedResponse createResponse(FederatedRequest[] requests, String remoteHost) throws DMLPrivacyException, FederatedWorkerHandlerException, Exception { FederatedResponse response = null; // last response boolean containsCLEAR = false; long clearReqPid = -1; var event = new EventModel(); final String coordinatorHostIdFormat = ""%s-%d""; event.setCoordinatorHostId(String.format(coordinatorHostIdFormat, remoteHost, requests[0].getPID())); for(int i = 0; i < requests.length; i++) { final FederatedRequest request = requests[i]; final RequestType t = request.getType(); final ExecutionContextMap ecm = _flt.getECM(remoteHost, request.getPID()); logRequests(request, i, requests.length); PrivacyMonitor.setCheckPrivacy(request.checkPrivacy()); PrivacyMonitor.clearCheckedConstraints(); var eventStage = new EventStageModel(); // execute command and handle privacy constraints final FederatedResponse tmp = executeCommand(request, ecm, eventStage); if (DMLScript.STATISTICS) { var requestStat = new RequestModel(request.getType().name(), 1L); requestStat.setCoordinatorHostId(String.format(coordinatorHostIdFormat, remoteHost, request.getPID())); FederatedStatistics.addWorkerRequest(requestStat); event.stages.add(eventStage); } conditionalAddCheckedConstraints(request, tmp); // select the response if(!tmp.isSuccessful()) { LOG.error(""Command "" + t + "" resulted in error:\n"" + tmp.getErrorMessage()); if (DMLScript.STATISTICS) FederatedStatistics.addEvent(event); return tmp; // Return first error without executing anything further } else if(t == RequestType.GET_VAR) { // If any of the requests was a GET_VAR then set it as output. if(response != null) { String message = ""Multiple GET_VAR are not supported in single batch of requests.""; LOG.error(message); if (DMLScript.STATISTICS) FederatedStatistics.addEvent(event); throw new FederatedWorkerHandlerException(message); } response = tmp; } else if(response == null && i == requests.length - 1) { response = tmp; // return last } if (DMLScript.STATISTICS) { if(t == RequestType.PUT_VAR || t == RequestType.EXEC_UDF) { for (int paramIndex = 0; paramIndex < request.getNumParams(); paramIndex++) { FederatedStatistics.incFedTransfer(request.getParam(paramIndex), _remoteAddress, request.getPID()); } } if(t == RequestType.GET_VAR) { var data = response.getData(); for (int dataObjIndex = 0; dataObjIndex < Arrays.stream(data).count(); dataObjIndex++) { FederatedStatistics.incFedTransfer(data[dataObjIndex], _remoteAddress, request.getPID()); } } } if(t == RequestType.CLEAR) { containsCLEAR = true; clearReqPid = request.getPID(); } } if(containsCLEAR) { _flt.removeECM(remoteHost, clearReqPid); printStatistics(); } if (DMLScript.STATISTICS) FederatedStatistics.addEvent(event); return response; }","private FederatedResponse createResponse(FederatedRequest[] requests, String remoteHost) throws DMLPrivacyException, FederatedWorkerHandlerException, Exception { FederatedResponse response = null; // last response boolean containsCLEAR = false; long clearReqPid = -1; int numGETrequests = 0; var event = new EventModel(); final String coordinatorHostIdFormat = ""%s-%d""; event.setCoordinatorHostId(String.format(coordinatorHostIdFormat, remoteHost, requests[0].getPID())); for(int i = 0; i < requests.length; i++) { final FederatedRequest request = requests[i]; final RequestType t = request.getType(); final ExecutionContextMap ecm = _flt.getECM(remoteHost, request.getPID()); logRequests(request, i, requests.length); PrivacyMonitor.setCheckPrivacy(request.checkPrivacy()); PrivacyMonitor.clearCheckedConstraints(); var eventStage = new EventStageModel(); // execute command and handle privacy constraints final FederatedResponse tmp = executeCommand(request, ecm, eventStage); if (DMLScript.STATISTICS) { var requestStat = new RequestModel(request.getType().name(), 1L); requestStat.setCoordinatorHostId(String.format(coordinatorHostIdFormat, remoteHost, request.getPID())); FederatedStatistics.addWorkerRequest(requestStat); event.stages.add(eventStage); } conditionalAddCheckedConstraints(request, tmp); // select the response if(!tmp.isSuccessful()) { LOG.error(""Command "" + t + "" resulted in error:\n"" + tmp.getErrorMessage()); if (DMLScript.STATISTICS) FederatedStatistics.addEvent(event); return tmp; // Return first error without executing anything further } else if(t == RequestType.GET_VAR) { // If any of the requests was a GET_VAR then set it as output. if(response != null && numGETrequests > 0) { String message = ""Multiple GET_VAR are not supported in single batch of requests.""; LOG.error(message); if (DMLScript.STATISTICS) FederatedStatistics.addEvent(event); throw new FederatedWorkerHandlerException(message); } response = tmp; numGETrequests ++; } else if(response == null && (t == RequestType.EXEC_INST || t == RequestType.EXEC_UDF)) { // If there was no GET, use the EXEC INST or UDF to obtain the returned nnz response = tmp; } else if(response == null && i == requests.length - 1) { response = tmp; // return last } if (DMLScript.STATISTICS) { if(t == RequestType.PUT_VAR || t == RequestType.EXEC_UDF) { for (int paramIndex = 0; paramIndex < request.getNumParams(); paramIndex++) FederatedStatistics.incFedTransfer(request.getParam(paramIndex), _remoteAddress, request.getPID()); } if(t == RequestType.GET_VAR) { var data = response.getData(); for (int dataObjIndex = 0; dataObjIndex < Arrays.stream(data).count(); dataObjIndex++) FederatedStatistics.incFedTransfer(data[dataObjIndex], _remoteAddress, request.getPID()); } } if(t == RequestType.CLEAR) { containsCLEAR = true; clearReqPid = request.getPID(); } } if(containsCLEAR) { _flt.removeECM(remoteHost, clearReqPid); printStatistics(); } if (DMLScript.STATISTICS) FederatedStatistics.addEvent(event); return response; }","[SYSTEMDS-3451] Fix missing NNZ propagation in federated instructions For many federated operations that output federated data, no information on the number of non-zeros was propagated back to the coordinator and hence, suboptional plan choices where made during dynamic recompilation. We now generally return the nnz of instruction outputs from all EXEC_INST and EXEC_UDF types, and provide utils to obtain this info from the federated responses. The exploitation of this info was already introduced into right indexing, append, and replace which are often executed on the main federated matrix. On a scenario of training MLogReg on 3 workers and a Critero subset with 1M rows and ~98M columns after one hot encoding, this patch reduced the end-to-end execution time by more than 4x but is generally applicable. a) STATS BEFORE PATCH: Total elapsed time: 402.882 sec. Total compilation time: 2.046 sec. Total execution time: 400.837 sec. Cache hits (Mem/Li/WB/FS/HDFS): 4452/0/0/0/0. Cache writes (Li/WB/FS/HDFS): 4/1576/0/0. Cache times (ACQr/m, RLS, EXP): 0.085/0.051/0.389/0.000 sec. HOP DAGs recompiled (PRED, SB): 0/248. HOP DAGs recompile time: 1.810 sec. Functions recompiled: 1. Functions recompile time: 0.253 sec. Federated I/O (Read, Put, Get): 3/409/134. Federated Execute (Inst, UDF): 436/6. Fed Put Count (Sc/Li/Ma/Fr/MC): 0/0/378/0/31. Fed Put Bytes (Mat/Frame): 1507638888/0 Bytes. Federated prefetch count: 0. Total JIT compile time: 29.476 sec. Total JVM GC count: 18. Total JVM GC time: 0.442 sec. Heavy hitter instructions: 1 m_multiLogReg 370.387 1 2 fed_r' 221.613 29 3 fed_mmchain 53.184 63 4 fed_ba+* 36.619 62 5 fed_transformencode 17.992 1 6 n+ 13.264 121 7 * 11.882 754 8 fed_fedinit 8.670 1 9 - 4.210 361 10 +* 3.892 127 b) STATS AFTER PATCH: Total elapsed time: 88.907 sec. Total compilation time: 2.065 sec. Total execution time: 86.842 sec. Cache hits (Mem/Li/WB/FS/HDFS): 4510/0/0/0/0. Cache writes (Li/WB/FS/HDFS): 4/1634/0/0. Cache times (ACQr/m, RLS, EXP): 0.049/0.034/0.311/0.000 sec. HOP DAGs recompiled (PRED, SB): 0/248. HOP DAGs recompile time: 0.506 sec. Functions recompiled: 1. Functions recompile time: 0.268 sec. Federated I/O (Read, Put, Get): 3/380/134. Federated Execute (Inst, UDF): 378/6. Fed Put Count (Sc/Li/Ma/Fr/MC): 0/0/378/0/2. Fed Put Bytes (Mat/Frame): 1507638888/0 Bytes. Federated prefetch count: 0. Total JIT compile time: 19.534 sec. Total JVM GC count: 17. Total JVM GC time: 0.436 sec. Heavy hitter instructions: 1 m_multiLogReg 56.603 1 2 fed_mmchain 21.669 63 3 fed_transformencode 18.811 1 4 fed_ba+* 12.250 62 5 fed_fedinit 9.061 1 6 n+ 5.271 121 7 * 3.699 754 8 fed_rightIndex 1.557 2 9 fed_uack+ 1.475 2 10 +* 1.330 127",https://github.com/apache/systemds/commit/03508eec80f3a144c9d311e8d4092f979abb5dee,,,src/main/java/org/apache/sysds/runtime/controlprogram/federated/FederatedWorkerHandler.java,3,java,False,2022-10-19T19:11:19Z "public static AbstractSlackFormSelectElement normalize(AbstractSlackFormSelectElement element) { if (shouldNormalizePlaceholder(element) || shouldNormalizeLabel(element, SlackDialogFormElementLengthLimits.MAX_LABEL_LENGTH) || shouldNormalize(element.getOptionGroups(), SlackDialogFormElementLengthLimits.MAX_OPTION_GROUPS_NUMBER) || shouldNormalizeOptions(element)) { return SlackFormSelectElement.copyOf(element) .withPlaceholder(normalizePlaceholder(element)) .withLabel(normalizeLabel(element)) .withOptionGroups(normalizeOptionGroups(element)) .withOptions(normalizeOptions(element)); } return element; }","public static AbstractSlackFormSelectElement normalize(AbstractSlackFormSelectElement element) { if (shouldNormalizePlaceholder(element) || shouldNormalizeLabel(element, SlackDialogFormElementLengthLimits.MAX_LABEL_LENGTH) || shouldNormalize(element.getOptionGroups(), SlackDialogFormElementLengthLimits.MAX_OPTION_GROUPS_NUMBER) || shouldNormalizeOptions(element)) { return SlackFormSelectElement.builder() .from(element) .setPlaceholder(normalizePlaceholder(element)) .setLabel(normalizeLabel(element)) .setOptionGroups(normalizeOptionGroups(element)) .setOptions(normalizeOptions(element)) .build(); } return element; }",Fix Stackoverflow caused by cyclic constructor calls,https://github.com/HubSpot/slack-client/commit/e923f506cadc07d8986a8d884b39f6906c0e8fa4,,,slack-base/src/main/java/com/hubspot/slack/client/models/dialog/form/elements/helpers/SlackDialogElementNormalizer.java,3,java,False,2021-12-07T17:39:59Z "@Override public String toString() { final StringBuilder result = new StringBuilder( getUinfo() ); if ( !Strings.isNullOrEmpty( getPackaging() ) ) { result.append( ""["" ).append( getPackaging() ).append( ""]"" ); } return result.toString(); }","@Override public String toString() { final StringBuilder result = new StringBuilder( getUinfo() ); String packaging = getPackaging(); if ( packaging != null && !getPackaging().isEmpty() ) { result.append( ""["" ).append( getPackaging() ).append( ""]"" ); } return result.toString(); }","[MINDEXER-126] Remove guava dependency from indexer-core It suffers from multiple CVEs: * guava < 24.1.1 is vulnerable to CVE-2018-10237. * guava < 30.0 is vulnerable to CVE-2020-8908. Moving to guava 30.1 will require moving to Java 8 so it's actually simpler to just remove the dependency altogether. Signed-off-by: Alexander Kurtakov Closes #75",https://github.com/apache/maven-indexer/commit/94915762b81501bd5b3e041dcc5927580fa9e5c0,,,indexer-core/src/main/java/org/apache/maven/index/ArtifactInfo.java,3,java,False,2021-01-22T21:51:52Z "private String getKey(final MessageExecutionContext ctx, final Message message) { String key = message.attribute(CONTEXT_ATTRIBUTE_KAFKA_RECORD_KEY); if (key == null) { key = ctx.getAttribute(CONTEXT_ATTRIBUTE_KAFKA_RECORD_KEY); if (key == null) { key = message.id(); ctx.setAttribute(CONTEXT_ATTRIBUTE_KAFKA_RECORD_KEY, key); } } return key; }","private String getKey(final MessageExecutionContext ctx, final Message message) { String key = message.attribute(CONTEXT_ATTRIBUTE_KAFKA_RECORD_KEY); if (key == null) { key = ctx.getAttribute(CONTEXT_ATTRIBUTE_KAFKA_RECORD_KEY); if (key == null) { key = message.id(); } } if (key != null) { message.attribute(CONTEXT_ATTRIBUTE_KAFKA_RECORD_KEY, key); } return key; }",fix: kafka exception handling on authentication exception,https://github.com/gravitee-io/gravitee-api-management/commit/ae2abe8cc512eb7d375f36b43081e2be6164399d,,,gravitee-apim-plugin/gravitee-apim-plugin-endpoint/gravitee-apim-plugin-endpoint-kafka/src/main/java/io/gravitee/plugin/endpoint/kafka/KafkaEndpointConnector.java,3,java,False,2022-11-14T13:47:30Z "private void scheduleReceiverWarmLocked(@NonNull BroadcastProcessQueue queue) { checkState(queue.isActive(), ""isActive""); final ProcessRecord app = queue.app; final BroadcastRecord r = queue.getActive(); final Object receiver = queue.getActiveReceiver(); app.mReceivers.incrementCurReceivers(); // If someone already skipped us, finish immediately; typically due to a // component being disabled if (queue.getActiveDeliveryState() == BroadcastRecord.DELIVERY_SKIPPED) { finishReceiverLocked(queue, BroadcastRecord.DELIVERY_SKIPPED); return; } if (app.isInFullBackup()) { finishReceiverLocked(queue, BroadcastRecord.DELIVERY_SKIPPED); return; } if (mSkipPolicy.shouldSkip(r, receiver)) { finishReceiverLocked(queue, BroadcastRecord.DELIVERY_SKIPPED); return; } final Intent receiverIntent = r.getReceiverIntent(receiver); if (receiverIntent == null) { finishReceiverLocked(queue, BroadcastRecord.DELIVERY_SKIPPED); return; } if (!r.timeoutExempt) { final long timeout = r.isForeground() ? mFgConstants.TIMEOUT : mBgConstants.TIMEOUT; mLocalHandler.sendMessageDelayed( Message.obtain(mLocalHandler, MSG_DELIVERY_TIMEOUT, queue), timeout); } // TODO: apply temp allowlist exemptions // TODO: apply background activity launch exemptions if (DEBUG_BROADCAST) logv(""Scheduling "" + r + "" to warm "" + app); queue.setActiveDeliveryState(BroadcastRecord.DELIVERY_SCHEDULED); final IApplicationThread thread = app.getThread(); if (thread != null) { try { if (receiver instanceof BroadcastFilter) { thread.scheduleRegisteredReceiver( ((BroadcastFilter) receiver).receiverList.receiver, receiverIntent, r.resultCode, r.resultData, r.resultExtras, r.ordered, r.initialSticky, r.userId, app.mState.getReportedProcState()); notifyScheduleRegisteredReceiver(app, r); // TODO: consider making registered receivers of unordered // broadcasts report results to detect ANRs if (!r.ordered) { finishReceiverLocked(queue, BroadcastRecord.DELIVERY_DELIVERED); } } else { thread.scheduleReceiver(receiverIntent, ((ResolveInfo) receiver).activityInfo, null, r.resultCode, r.resultData, r.resultExtras, r.ordered, r.userId, app.mState.getReportedProcState()); notifyScheduleReceiver(app, r, receiverIntent); } } catch (RemoteException e) { finishReceiverLocked(queue, BroadcastRecord.DELIVERY_FAILURE); app.scheduleCrashLocked(TAG, CannotDeliverBroadcastException.TYPE_ID, null); } } else { finishReceiverLocked(queue, BroadcastRecord.DELIVERY_FAILURE); } }","private void scheduleReceiverWarmLocked(@NonNull BroadcastProcessQueue queue) { checkState(queue.isActive(), ""isActive""); final ProcessRecord app = queue.app; final BroadcastRecord r = queue.getActive(); final Object receiver = queue.getActiveReceiver(); // If someone already skipped us, finish immediately; typically due to a // component being disabled if (queue.getActiveDeliveryState() == BroadcastRecord.DELIVERY_SKIPPED) { finishReceiverLocked(queue, BroadcastRecord.DELIVERY_SKIPPED); return; } if (app.isInFullBackup()) { finishReceiverLocked(queue, BroadcastRecord.DELIVERY_SKIPPED); return; } if (mSkipPolicy.shouldSkip(r, receiver)) { finishReceiverLocked(queue, BroadcastRecord.DELIVERY_SKIPPED); return; } final Intent receiverIntent = r.getReceiverIntent(receiver); if (receiverIntent == null) { finishReceiverLocked(queue, BroadcastRecord.DELIVERY_SKIPPED); return; } if (!r.timeoutExempt) { final long timeout = r.isForeground() ? mFgConstants.TIMEOUT : mBgConstants.TIMEOUT; mLocalHandler.sendMessageDelayed( Message.obtain(mLocalHandler, MSG_DELIVERY_TIMEOUT, queue), timeout); } if (r.allowBackgroundActivityStarts) { app.addOrUpdateAllowBackgroundActivityStartsToken(r, r.mBackgroundActivityStartsToken); final long timeout = r.isForeground() ? mFgConstants.ALLOW_BG_ACTIVITY_START_TIMEOUT : mBgConstants.ALLOW_BG_ACTIVITY_START_TIMEOUT; final SomeArgs args = SomeArgs.obtain(); args.arg1 = app; args.arg2 = r; mLocalHandler.sendMessageDelayed( Message.obtain(mLocalHandler, MSG_BG_ACTIVITY_START_TIMEOUT, args), timeout); } if (r.options != null && r.options.getTemporaryAppAllowlistDuration() > 0) { mService.tempAllowlistUidLocked(queue.uid, r.options.getTemporaryAppAllowlistDuration(), r.options.getTemporaryAppAllowlistReasonCode(), r.toShortString(), r.options.getTemporaryAppAllowlistType(), r.callingUid); } if (DEBUG_BROADCAST) logv(""Scheduling "" + r + "" to warm "" + app); queue.setActiveDeliveryState(BroadcastRecord.DELIVERY_SCHEDULED); final IApplicationThread thread = app.getThread(); if (thread != null) { try { if (receiver instanceof BroadcastFilter) { notifyScheduleRegisteredReceiver(app, r); thread.scheduleRegisteredReceiver( ((BroadcastFilter) receiver).receiverList.receiver, receiverIntent, r.resultCode, r.resultData, r.resultExtras, r.ordered, r.initialSticky, r.userId, app.mState.getReportedProcState()); // TODO: consider making registered receivers of unordered // broadcasts report results to detect ANRs if (!r.ordered) { finishReceiverLocked(queue, BroadcastRecord.DELIVERY_DELIVERED); } } else { notifyScheduleReceiver(app, r, receiverIntent); thread.scheduleReceiver(receiverIntent, ((ResolveInfo) receiver).activityInfo, null, r.resultCode, r.resultData, r.resultExtras, r.ordered, r.userId, app.mState.getReportedProcState()); } } catch (RemoteException e) { finishReceiverLocked(queue, BroadcastRecord.DELIVERY_FAILURE); app.scheduleCrashLocked(TAG, CannotDeliverBroadcastException.TYPE_ID, null); } } else { finishReceiverLocked(queue, BroadcastRecord.DELIVERY_FAILURE); } }","BroadcastQueue: misc bookkeeping events for OS. This change brings over the remaining bookkeeping events that other parts of the OS expects, such as allowing background activity starts, temporary allowlisting for power, more complete OOM adjustments, thawing apps before dispatch, and metrics events. Fixes bug so that apps aren't able to abort broadcasts marked with NO_ABORT flag. Tests to confirm all the above behaviors are identical between both broadcast stack implementations. Bug: 245771249 Test: atest FrameworksMockingServicesTests:BroadcastQueueTest Change-Id: If3532d335c94c8138a9ebcf8d11bf3674d1c42aa",https://github.com/LineageOS/android_frameworks_base/commit/6a6e2295915440e17104151160a4b4ce21796962,,,services/core/java/com/android/server/am/BroadcastQueueModernImpl.java,3,java,False,2022-09-22T22:04:12Z "@Override public Response onCommand(SMTPSession session, Request request) { if (session.isStartTLSSupported()) { if (session.isTLSStarted()) { return TLS_ALREADY_ACTIVE; } else { String parameters = request.getArgument(); if ((parameters == null) || (parameters.length() == 0)) { return READY_FOR_STARTTLS; } else { return SYNTAX_ERROR; } } } else { return NOT_SUPPORTED; } }","@Override public Response onCommand(SMTPSession session, Request request) { if (session.isStartTLSSupported()) { if (session.isTLSStarted()) { return TLS_ALREADY_ACTIVE; } else { if (session.getUsername() != null) { // Prevents session fixation as described in https://www.usenix.org/system/files/sec21-poddebniak.pdf // Session 6.2 return ALREADY_AUTH_ERROR; } String parameters = request.getArgument(); if ((parameters == null) || (parameters.length() == 0)) { return READY_FOR_STARTTLS; } else { return SYNTAX_ERROR; } } } else { return NOT_SUPPORTED; } }","JAMES-1862 Prevent Session fixation via STARTTLS https://www.usenix.org/system/files/sec21-poddebniak.pdf Session 6.2 James allows session fixation as part of the SMTP protocol but as stated by the researchers, 'they did not come up with exploits'.",https://github.com/apache/james-project/commit/82f3c18d68b991e25a9b2f808bff748319965e73,,,protocols/smtp/src/main/java/org/apache/james/protocols/smtp/core/esmtp/StartTlsCmdHandler.java,3,java,False,2021-08-13T14:01:13Z "@Override public void onMotionEvent(MotionEvent event, MotionEvent rawEvent, int policyFlags) { if (!event.isFromSource(InputDevice.SOURCE_TOUCHSCREEN)) { super.onMotionEvent(event, rawEvent, policyFlags); return; } if (DEBUG) { Slog.d(LOG_TAG, ""Received event: "" + event + "", policyFlags=0x"" + Integer.toHexString(policyFlags)); Slog.d(LOG_TAG, mState.toString()); } mState.onReceivedMotionEvent(rawEvent); if (shouldPerformGestureDetection(event)) { if (mGestureDetector.onMotionEvent(event, rawEvent, policyFlags)) { // Event was handled by the gesture detector. return; } } if (event.getActionMasked() == ACTION_CANCEL) { clear(event, policyFlags); return; } // TODO: extract the below functions into separate handlers for each state. // Right now the number of functions and number of states make the code messy. if (mState.isClear()) { handleMotionEventStateClear(event, rawEvent, policyFlags); } else if (mState.isTouchInteracting()) { handleMotionEventStateTouchInteracting(event, rawEvent, policyFlags); } else if (mState.isTouchExploring()) { handleMotionEventStateTouchExploring(event, rawEvent, policyFlags); } else if (mState.isDragging()) { handleMotionEventStateDragging(event, rawEvent, policyFlags); } else if (mState.isDelegating()) { handleMotionEventStateDelegating(event, rawEvent, policyFlags); } else if (mState.isGestureDetecting()) { // Make sure we don't prematurely get TOUCH_INTERACTION_END // It will be delivered on gesture completion or cancelation. // Note that the delay for sending GESTURE_DETECTION_END remains in place. mSendTouchInteractionEndDelayed.cancel(); } else { Slog.e(LOG_TAG, ""Illegal state: "" + mState); clear(event, policyFlags); } }","@Override public void onMotionEvent(MotionEvent event, MotionEvent rawEvent, int policyFlags) { if (!event.isFromSource(InputDevice.SOURCE_TOUCHSCREEN)) { super.onMotionEvent(event, rawEvent, policyFlags); return; } try { checkForMalformedEvent(event); } catch (IllegalArgumentException e) { Slog.e(LOG_TAG, ""Ignoring malformed event: "" + event.toString(), e); return; } if (DEBUG) { Slog.d(LOG_TAG, ""Received event: "" + event + "", policyFlags=0x"" + Integer.toHexString(policyFlags)); Slog.d(LOG_TAG, mState.toString()); } mState.onReceivedMotionEvent(rawEvent); if (shouldPerformGestureDetection(event)) { if (mGestureDetector.onMotionEvent(event, rawEvent, policyFlags)) { // Event was handled by the gesture detector. return; } } if (event.getActionMasked() == ACTION_CANCEL) { clear(event, policyFlags); return; } // TODO: extract the below functions into separate handlers for each state. // Right now the number of functions and number of states make the code messy. if (mState.isClear()) { handleMotionEventStateClear(event, rawEvent, policyFlags); } else if (mState.isTouchInteracting()) { handleMotionEventStateTouchInteracting(event, rawEvent, policyFlags); } else if (mState.isTouchExploring()) { handleMotionEventStateTouchExploring(event, rawEvent, policyFlags); } else if (mState.isDragging()) { handleMotionEventStateDragging(event, rawEvent, policyFlags); } else if (mState.isDelegating()) { handleMotionEventStateDelegating(event, rawEvent, policyFlags); } else if (mState.isGestureDetecting()) { // Make sure we don't prematurely get TOUCH_INTERACTION_END // It will be delivered on gesture completion or cancelation. // Note that the delay for sending GESTURE_DETECTION_END remains in place. mSendTouchInteractionEndDelayed.cancel(); } else { Slog.e(LOG_TAG, ""Illegal state: "" + mState); clear(event, policyFlags); } }","TouchExplorer: log malformed events instead of crashing. Bug: 193092818 Test: atest GestureManifoldTest TouchExplorerTest AccessibilityGestureDetectorTest Change-Id: I5aee4e253479b7d3b2cbdc573b335c6edf389eb9",https://github.com/PixelExperience/frameworks_base/commit/c0b1a5b3daa6a3312fa4589a99d7c2e230ed87c2,,,services/accessibility/java/com/android/server/accessibility/gestures/TouchExplorer.java,3,java,False,2021-07-13T20:01:12Z "static PinnedConversation fromRemote(AccountRecord.PinnedConversation remote) { if (remote.hasContact()) { return forContact(new SignalServiceAddress(ServiceId.parseOrThrow(remote.getContact().getUuid()), remote.getContact().getE164())); } else if (!remote.getLegacyGroupId().isEmpty()) { return forGroupV1(remote.getLegacyGroupId().toByteArray()); } else if (!remote.getGroupMasterKey().isEmpty()) { return forGroupV2(remote.getGroupMasterKey().toByteArray()); } else { return PinnedConversation.forEmpty(); } }","static PinnedConversation fromRemote(AccountRecord.PinnedConversation remote) { if (remote.hasContact()) { ServiceId serviceId = ServiceId.parseOrNull(remote.getContact().getUuid()); if (serviceId != null) { return forContact(new SignalServiceAddress(serviceId, remote.getContact().getE164())); } else { Log.w(TAG, ""Bad serviceId on pinned contact! Length: "" + remote.getContact().getUuid()); return PinnedConversation.forEmpty(); } } else if (!remote.getLegacyGroupId().isEmpty()) { return forGroupV1(remote.getLegacyGroupId().toByteArray()); } else if (!remote.getGroupMasterKey().isEmpty()) { return forGroupV2(remote.getGroupMasterKey().toByteArray()); } else { return PinnedConversation.forEmpty(); } }",Fix crash if synced pinned contact is malformed.,https://github.com/signalapp/Signal-Android/commit/15f51ea26efbfd56ac1e2f5628c9c64149f69e08,,,libsignal/service/src/main/java/org/whispersystems/signalservice/api/storage/SignalAccountRecord.java,3,java,False,2022-03-10T16:14:55Z "@NonNull private static ArrayList getPlatformFileListForPrefix(@NonNull @Prefix String prefix) { final ArrayList list = new ArrayList<>(); final File platformFiles = getPlatformBaseDir(); if (platformFiles.exists()) { for (String name : platformFiles.list()) { // Skip when prefix doesn't match. if (!name.startsWith(prefix + ""."")) continue; list.add(new File(platformFiles, name)); } } return list; }","@NonNull private static ArrayList getPlatformFileListForPrefix(@NonNull @Prefix String prefix) { final ArrayList list = new ArrayList<>(); final File platformFiles = getPlatformBaseDir(); if (platformFiles.exists()) { final String[] files = platformFiles.list(); if (files == null) return list; Arrays.sort(files); for (String name : files) { // Skip when prefix doesn't match. if (!name.startsWith(prefix + ""."")) continue; list.add(new File(platformFiles, name)); } } return list; }","Add null check when list directory This change protect getPlatformFileListForPrefix from crashing when the directory exist but cannot be listed. This generally happens when the caller doesn't have enough permission to list. Test: atest CtsNetTestCases:android.net.cts.NetworkStatsManagerTest#testDataMigrationUtils Ignore-AOSP-First: in a topic with internal-only changes Bug: 230289468 Change-Id: I4177a8229cc9db18d76cb90c54a1b8d12ef8d98f",https://github.com/LineageOS/android_frameworks_base/commit/a9eceb80ccdecf9d228249a6e077a4c761f3b859,,,core/java/android/net/netstats/NetworkStatsDataMigrationUtils.java,3,java,False,2022-05-18T17:35:11Z "void destroyAccelGroup () { if (accelGroup == 0) return; long shellHandle = topHandle (); GTK3.gtk_window_remove_accel_group (shellHandle, accelGroup); //TEMPORARY CODE // OS.g_object_unref (accelGroup); accelGroup = 0; }","void destroyAccelGroup () { if (accelGroup == 0) return; if (menuBar != null) menuBar.removeAccelerators(accelGroup); long shellHandle = topHandle (); GTK3.gtk_window_remove_accel_group (shellHandle, accelGroup); OS.g_object_unref (accelGroup); accelGroup = 0; }","Bug 573697 - [GTK3] MenuBar leaks native memory This change ensures the GTK+ accelerator group allocated by Decorations is released upon destruction. In addition, the accelerator group is removed from menu items, upon Decorations.destroyAccelGroup() (and prior to recreating it during Decorations.fixAccelGroup()). This prevents a crash in GTK+ code, due to trying to use the now released handle. Manual snippets are also added to the set of GTK bug snippets, for future manual validation. Change-Id: Ic3befc6b627bc78393154a47ecc54b372e062d3a Signed-off-by: Simeon Andreev Reviewed-on: https://git.eclipse.org/r/c/platform/eclipse.platform.swt/+/180940 Tested-by: Platform Bot Reviewed-by: Andrey Loskutov ",https://github.com/eclipse-platform/eclipse.platform.swt/commit/623f26d8117571ac812c9802f4ae075aacc3d040,,,bundles/org.eclipse.swt/Eclipse SWT/gtk/org/eclipse/swt/widgets/Decorations.java,3,java,False,2021-05-21T14:04:09Z "public static HistoryEvent getInstanceCloseEvent( WorkflowServiceStubs service, String namespace, WorkflowExecution workflowExecution, Scope metricsScope, long timeout, TimeUnit unit) throws TimeoutException { ByteString pageToken = ByteString.EMPTY; GetWorkflowExecutionHistoryResponse response = null; // TODO: Interrupt service long poll call on timeout and on interrupt long start = System.currentTimeMillis(); HistoryEvent event; do { GetWorkflowExecutionHistoryRequest r = GetWorkflowExecutionHistoryRequest.newBuilder() .setNamespace(namespace) .setExecution(workflowExecution) .setHistoryEventFilterType( HistoryEventFilterType.HISTORY_EVENT_FILTER_TYPE_CLOSE_EVENT) .setWaitNewEvent(true) .setNextPageToken(pageToken) .build(); long elapsed = System.currentTimeMillis() - start; Deadline expiration = Deadline.after(unit.toMillis(timeout) - elapsed, TimeUnit.MILLISECONDS); if (expiration.timeRemaining(TimeUnit.MILLISECONDS) > 0) { RpcRetryOptions retryOptions = RpcRetryOptions.newBuilder() .setBackoffCoefficient(1) .setInitialInterval(Duration.ofMillis(1)) .setMaximumAttempts(Integer.MAX_VALUE) .setExpiration(Duration.ofMillis(expiration.timeRemaining(TimeUnit.MILLISECONDS))) .addDoNotRetry(Status.Code.INVALID_ARGUMENT, null) .addDoNotRetry(Status.Code.NOT_FOUND, null) .build(); response = GrpcRetryer.retryWithResult( retryOptions, () -> { long elapsedInRetry = System.currentTimeMillis() - start; Deadline expirationInRetry = Deadline.after( unit.toMillis(timeout) - elapsedInRetry, TimeUnit.MILLISECONDS); return service .blockingStub() .withOption(METRICS_TAGS_CALL_OPTIONS_KEY, metricsScope) .withOption(HISTORY_LONG_POLL_CALL_OPTIONS_KEY, true) .withDeadline(expirationInRetry) .getWorkflowExecutionHistory(r); }); } if (response == null || !response.hasHistory()) { continue; } if (timeout != 0 && System.currentTimeMillis() - start > unit.toMillis(timeout)) { throw new TimeoutException( ""WorkflowId="" + workflowExecution.getWorkflowId() + "", runId="" + workflowExecution.getRunId() + "", timeout="" + timeout + "", unit="" + unit); } pageToken = response.getNextPageToken(); History history = response.getHistory(); if (history.getEventsCount() > 0) { event = history.getEvents(0); if (!isWorkflowExecutionCompletedEvent(event)) { throw new RuntimeException(""Last history event is not completion event: "" + event); } // Workflow called continueAsNew. Start polling the new generation with new runId. if (event.getEventType() == EventType.EVENT_TYPE_WORKFLOW_EXECUTION_CONTINUED_AS_NEW) { pageToken = ByteString.EMPTY; workflowExecution = WorkflowExecution.newBuilder() .setWorkflowId(workflowExecution.getWorkflowId()) .setRunId( event .getWorkflowExecutionContinuedAsNewEventAttributes() .getNewExecutionRunId()) .build(); continue; } break; } } while (true); return event; }","public static HistoryEvent getInstanceCloseEvent( WorkflowServiceStubs service, String namespace, WorkflowExecution workflowExecution, Scope metricsScope, long timeout, TimeUnit unit) throws TimeoutException { ByteString pageToken = ByteString.EMPTY; GetWorkflowExecutionHistoryResponse response; // TODO: Interrupt service long poll call on timeout and on interrupt long start = System.currentTimeMillis(); do { GetWorkflowExecutionHistoryRequest r = GetWorkflowExecutionHistoryRequest.newBuilder() .setNamespace(namespace) .setExecution(workflowExecution) .setHistoryEventFilterType( HistoryEventFilterType.HISTORY_EVENT_FILTER_TYPE_CLOSE_EVENT) .setWaitNewEvent(true) .setNextPageToken(pageToken) .build(); long elapsed = System.currentTimeMillis() - start; long millisRemaining = unit.toMillis(timeout != 0 ? timeout : Integer.MAX_VALUE) - elapsed; if (millisRemaining > 0) { RpcRetryOptions retryOptions = RpcRetryOptions.newBuilder(GET_INSTANCE_CLOSE_EVENT_RETRY_OPTIONS) .setExpiration(Duration.ofMillis(millisRemaining)) .build(); response = GrpcRetryer.retryWithResult( retryOptions, () -> { long elapsedInRetry = System.currentTimeMillis() - start; Deadline expirationInRetry = Deadline.after( unit.toMillis(timeout) - elapsedInRetry, TimeUnit.MILLISECONDS); return service .blockingStub() .withOption(METRICS_TAGS_CALL_OPTIONS_KEY, metricsScope) .withOption(HISTORY_LONG_POLL_CALL_OPTIONS_KEY, true) .withDeadline(expirationInRetry) .getWorkflowExecutionHistory(r); }); if (response == null || !response.hasHistory()) { continue; } } else { throw new TimeoutException( ""WorkflowId="" + workflowExecution.getWorkflowId() + "", runId="" + workflowExecution.getRunId() + "", timeout="" + timeout + "", unit="" + unit); } pageToken = response.getNextPageToken(); History history = response.getHistory(); if (history.getEventsCount() > 0) { HistoryEvent event = history.getEvents(0); if (!isWorkflowExecutionCompletedEvent(event)) { throw new RuntimeException(""Last history event is not completion event: "" + event); } // Workflow called continueAsNew. Start polling the new generation with new runId. if (event.getEventType() == EventType.EVENT_TYPE_WORKFLOW_EXECUTION_CONTINUED_AS_NEW) { pageToken = ByteString.EMPTY; workflowExecution = WorkflowExecution.newBuilder() .setWorkflowId(workflowExecution.getWorkflowId()) .setRunId( event .getWorkflowExecutionContinuedAsNewEventAttributes() .getNewExecutionRunId()) .build(); continue; } return event; } } while (true); }","Fixed implementation of WorkflowExecutionUtils#getInstanceCloseEvent that previously could get into infinite loop after a timeout (#472) Issue #471",https://github.com/temporalio/sdk-java/commit/f22d431d9f999fa9e4be3562a1d9a81be963850c,,,temporal-sdk/src/main/java/io/temporal/internal/common/WorkflowExecutionUtils.java,3,java,False,2021-05-07T16:19:29Z "@Override public void onDisable() { EVENTS.remove(UpdateListener.class, this); EVENTS.remove(RenderListener.class, this); PathProcessor.releaseControls(); treeFinder = null; angleFinder = null; processor = null; tree.close(); tree = null; if(currentBlock != null) { IMC.getInteractionManager().setBreakingBlock(true); MC.interactionManager.cancelBlockBreaking(); currentBlock = null; } }","@Override public void onDisable() { EVENTS.remove(UpdateListener.class, this); EVENTS.remove(RenderListener.class, this); PathProcessor.releaseControls(); treeFinder = null; angleFinder = null; processor = null; if(tree != null) { tree.close(); tree = null; } if(currentBlock != null) { IMC.getInteractionManager().setBreakingBlock(true); MC.interactionManager.cancelBlockBreaking(); currentBlock = null; } }","Added null ckeck Before Calling tree.close(); Fixing game crash when deactivating Tree Bot caused by tree being null [STDERR]: java.lang.NullPointerException: Cannot invoke ""net.wurstclient.treebot.Tree.close()"" because ""this.tree"" is null [STDERR]: at net.wurstclient.hacks.TreeBotHack.onDisable(TreeBotHack.java:116)",https://github.com/Wurst-Imperium/Wurst7/commit/f6bf6dcb6070a01f049ea364ce874190e9953911,,,src/main/java/net/wurstclient/hacks/TreeBotHack.java,3,java,False,2021-08-16T17:51:48Z "@Primary @Bean public JwtAccessTokenConverter jwtAccessTokenConverter() { JwtAccessTokenConverter converter = new JwtAccessTokenConverter() { @Override public OAuth2AccessToken enhance( OAuth2AccessToken accessToken, OAuth2Authentication authentication) { Map additionalInfo = new HashMap<>(); if (authentication.getUserAuthentication() instanceof Authentication) { additionalInfo.put(""name"", ((Authentication) authentication.getUserAuthentication().getPrincipal()).getFullName()); additionalInfo.put(""sub"", authentication.getName()); } else if (authentication.getPrincipal() instanceof OidcUser) { DefaultOidcUser oidcUser = (DefaultOidcUser) authentication.getPrincipal(); additionalInfo.put(""name"", oidcUser.getEmail()); additionalInfo.put(""sub"", oidcUser.getEmail()); additionalInfo.put(""fullName"", oidcUser.getFullName()); additionalInfo.put(""imageUrl"", oidcUser.getPicture()); } else { additionalInfo.put(""sub"", authentication.getName()); } additionalInfo.put(""auth"", authentication.getAuthorities().stream() .map(GrantedAuthority::getAuthority) .collect(joining("",""))); additionalInfo.put(""type"", ""access""); additionalInfo.put(""fresh"", true); long currentTime = new Date().getTime() / 1000; additionalInfo.put(""iat"", currentTime); additionalInfo.put(""nbf"", currentTime); additionalInfo.put(""iss"", authenticationProperties.getIssuer()); additionalInfo.put(""aud"", authenticationProperties.getAud()); additionalInfo.put(""jti"", UUID.randomUUID().toString()); DefaultOAuth2AccessToken defaultOAuth2AccessToken = new DefaultOAuth2AccessToken(accessToken); defaultOAuth2AccessToken.setAdditionalInformation(additionalInfo); defaultOAuth2AccessToken.setValue(encode(defaultOAuth2AccessToken, authentication)); return defaultOAuth2AccessToken; } }; AuthenticationProperties.Jwt jwt = this.authenticationProperties.getJwt(); String keyValue = jwt.getKeyValue(); if (StringUtils.isNotBlank(keyValue)) { if (!keyValue.startsWith(""-----BEGIN"")) { converter.setSigningKey(keyValue); } converter.setVerifierKey(keyValue); } else if (jwt.getKeyStore() != null) { Resource keyStore = new FileSystemResource(jwt.getKeyStore().replaceFirst(""file:"", """")); char[] keyStorePassword = Base64DecodeUtil.decodePassword(jwt.getKeyStorePassword()); KeyStoreKeyFactory keyStoreKeyFactory = new KeyStoreKeyFactory(keyStore, keyStorePassword); String keyAlias = jwt.getKeyAlias(); converter.setKeyPair(keyStoreKeyFactory.getKeyPair(keyAlias, keyStorePassword)); } if (!CollectionUtils.isEmpty(this.configurers)) { AnnotationAwareOrderComparator.sort(this.configurers); for (JwtAccessTokenConverterConfigurer configurer : this.configurers) { configurer.configure(converter); } } return converter; }","@Primary @Bean public JwtAccessTokenConverter jwtAccessTokenConverter() { JwtAccessTokenConverter converter = new JwtAccessTokenConverter() { @Override public OAuth2AccessToken enhance( OAuth2AccessToken accessToken, OAuth2Authentication authentication) { Map additionalInfo = new HashMap<>(); if (authentication.getUserAuthentication() instanceof Authentication) { additionalInfo.put(""name"", ((Authentication) authentication.getUserAuthentication().getPrincipal()).getFullName()); additionalInfo.put(""sub"", authentication.getName()); } else if (authentication.getPrincipal() instanceof OidcUser) { DefaultOidcUser oidcUser = (DefaultOidcUser) authentication.getPrincipal(); additionalInfo.put(""name"", oidcUser.getEmail()); additionalInfo.put(""sub"", oidcUser.getEmail()); additionalInfo.put(""fullName"", oidcUser.getFullName()); additionalInfo.put(""imageUrl"", oidcUser.getPicture()); } else { additionalInfo.put(""sub"", authentication.getName()); } additionalInfo.put(""auth"", authentication.getAuthorities().stream() .map(GrantedAuthority::getAuthority) .collect(joining("",""))); additionalInfo.put(""type"", ""access""); additionalInfo.put(""fresh"", true); long currentTime = new Date().getTime() / 1000; additionalInfo.put(""iat"", currentTime); additionalInfo.put(""nbf"", currentTime); additionalInfo.put(""iss"", authenticationProperties.getIssuer()); additionalInfo.put(""aud"", authenticationProperties.getAud()); additionalInfo.put(""jti"", UUID.randomUUID().toString()); DefaultOAuth2AccessToken defaultOAuth2AccessToken = new DefaultOAuth2AccessToken(accessToken); defaultOAuth2AccessToken.setAdditionalInformation(additionalInfo); defaultOAuth2AccessToken.setValue(encode(defaultOAuth2AccessToken, authentication)); return defaultOAuth2AccessToken; } }; AuthenticationProperties.Jwt jwt = this.authenticationProperties.getJwt(); String keyValue = jwt.getKeyValue(); if (StringUtils.isNotBlank(keyValue)) { if (!keyValue.startsWith(""-----BEGIN"")) { converter.setSigningKey(keyValue); } converter.setVerifierKey(keyValue); } else if (jwt.getKeyStore() != null) { KeyPair keyPair = getKeyPair(authenticationProperties); converter.setKeyPair(keyPair); } if (!CollectionUtils.isEmpty(this.configurers)) { AnnotationAwareOrderComparator.sort(this.configurers); for (JwtAccessTokenConverterConfigurer configurer : this.configurers) { configurer.configure(converter); } } return converter; }","Fixed consul issue - build authentication-service, build person-service, build user-service, build kotlin-service",https://github.com/rodrigorodrigues/microservices-design-patterns/commit/94c1175351f5a077ecd11ff17d57005d2835f8e9,,,authentication-common/src/main/java/com/microservice/authentication/autoconfigure/AuthenticationCommonConfiguration.java,3,java,False,2021-12-13T22:21:27Z "private static Task checkGameState(Profile profile, VersionSetting setting, Version version) { VersionNumber gameVersion = VersionNumber.asVersion(profile.getRepository().getGameVersion(version).orElse(""Unknown"")); if (setting.isNotCheckJVM()) { return Task.composeAsync(() -> setting.getJavaVersion(gameVersion, version)) .thenApplyAsync(javaVersion -> Optional.ofNullable(javaVersion).orElseGet(JavaVersion::fromCurrentEnvironment)) .withStage(""launch.state.java""); } return Task.composeAsync(() -> { return setting.getJavaVersion(gameVersion, version); }).thenComposeAsync(Schedulers.javafx(), javaVersion -> { // Reset invalid java version if (javaVersion == null) { CompletableFuture future = new CompletableFuture<>(); Runnable continueAction = () -> future.complete(JavaVersion.fromCurrentEnvironment()); if (setting.isJavaAutoSelected()) { JavaVersionConstraint.VersionRanges range = JavaVersionConstraint.findSuitableJavaVersionRange(gameVersion, version); GameJavaVersion targetJavaVersion; if (range.getMandatory().contains(VersionNumber.asVersion(""16""))) { targetJavaVersion = GameJavaVersion.JAVA_16; } else if (range.getMandatory().contains(VersionNumber.asVersion(""1.8.0_51""))) { targetJavaVersion = GameJavaVersion.JAVA_8; } else { targetJavaVersion = null; } if (targetJavaVersion != null) { downloadJava(gameVersion.toString(), targetJavaVersion, profile) .thenAcceptAsync(downloadedJavaVersion -> { future.complete(downloadedJavaVersion); }) .exceptionally(throwable -> { LOG.log(Level.WARNING, ""Failed to download java"", throwable); Controllers.dialog(i18n(""launch.failed.no_accepted_java""), i18n(""message.warning""), MessageType.WARNING, continueAction); return null; }); } } else { Controllers.dialog(i18n(""launch.wrong_javadir""), i18n(""message.warning""), MessageType.WARNING, continueAction); setting.setJava(null); setting.setDefaultJavaPath(null); setting.setJavaVersion(JavaVersion.fromCurrentEnvironment()); } return Task.fromCompletableFuture(future); } else { return Task.completed(javaVersion); } }).thenComposeAsync(javaVersion -> { return Task.allOf(Task.completed(javaVersion), Task.supplyAsync(() -> JavaVersionConstraint.findSuitableJavaVersion(gameVersion, version))); }).thenComposeAsync(Schedulers.javafx(), javaVersions -> { JavaVersion javaVersion = (JavaVersion) javaVersions.get(0); JavaVersion suggestedJavaVersion = (JavaVersion) javaVersions.get(1); if (setting.isJavaAutoSelected()) return Task.completed(javaVersion); JavaVersionConstraint violatedMandatoryConstraint = null; JavaVersionConstraint violatedSuggestedConstraint = null; for (JavaVersionConstraint constraint : JavaVersionConstraint.ALL) { if (constraint.appliesToVersion(gameVersion, version, javaVersion)) { if (!constraint.checkJava(gameVersion, version, javaVersion)) { if (constraint.getType() == JavaVersionConstraint.RULE_MANDATORY) { violatedMandatoryConstraint = constraint; } else if (constraint.getType() == JavaVersionConstraint.RULE_SUGGESTED) { violatedSuggestedConstraint = constraint; } } } } boolean suggested = false; CompletableFuture future = new CompletableFuture<>(); Runnable continueAction = () -> future.complete(javaVersion); Runnable breakAction = () -> { future.completeExceptionally(new CancellationException(""Launch operation was cancelled by user"")); }; if (violatedMandatoryConstraint != null) { if (suggestedJavaVersion != null) { Controllers.confirm(i18n(""launch.advice.java.auto""), i18n(""message.warning""), () -> { setting.setJavaAutoSelected(); future.complete(suggestedJavaVersion); }, breakAction); return Task.fromCompletableFuture(future); } else { switch (violatedMandatoryConstraint) { case GAME_JSON: downloadJava(gameVersion.toString(), version.getJavaVersion(), profile) .thenAcceptAsync(downloadedJavaVersion -> { setting.setJavaVersion(downloadedJavaVersion); future.complete(downloadedJavaVersion); }) .exceptionally(throwable -> { LOG.log(Level.WARNING, ""Failed to download java"", throwable); breakAction.run(); return null; }); return Task.fromCompletableFuture(future); case VANILLA_JAVA_16: Controllers.confirm(i18n(""launch.advice.require_newer_java_version"", gameVersion.toString(), 16), i18n(""message.warning""), () -> { FXUtils.openLink(""https://adoptium.net/?variant=openjdk17""); }, breakAction); return null; case VANILLA_JAVA_17: Controllers.confirm(i18n(""launch.advice.require_newer_java_version"", gameVersion.toString(), 17), i18n(""message.warning""), () -> { FXUtils.openLink(""https://adoptium.net/?variant=openjdk17""); }, breakAction); return null; case VANILLA_JAVA_8: Controllers.dialog(i18n(""launch.advice.java8_1_13""), i18n(""message.error""), MessageType.ERROR, breakAction); return null; case VANILLA_LINUX_JAVA_8: if (setting.getNativesDirType() == NativesDirectoryType.VERSION_FOLDER) { Controllers.dialog(i18n(""launch.advice.vanilla_linux_java_8""), i18n(""message.error""), MessageType.ERROR, breakAction); return null; } else { break; } case VANILLA_X86: if (setting.getNativesDirType() == NativesDirectoryType.VERSION_FOLDER) { if (Architecture.SYSTEM_ARCH == Architecture.ARM64) { if (OperatingSystem.CURRENT_OS == OperatingSystem.OSX // Windows on ARM introduced translation support for x86-64 after 10.0.21277. || (OperatingSystem.CURRENT_OS == OperatingSystem.WINDOWS && OperatingSystem.SYSTEM_BUILD_NUMBER >= 21277)) { Controllers.dialog(i18n(""launch.advice.vanilla_x86.translation""), i18n(""message.error""), MessageType.ERROR, breakAction); return null; } } Controllers.dialog(i18n(""launch.advice.vanilla_x86""), i18n(""message.error""), MessageType.ERROR, breakAction); return null; } else { break; } case LAUNCH_WRAPPER: Controllers.dialog(i18n(""launch.advice.java9"") + ""\n"" + i18n(""launch.advice.uncorrected""), i18n(""message.error""), MessageType.ERROR, breakAction); return null; } } } if (Architecture.SYSTEM_ARCH == Architecture.X86_64 && javaVersion.getPlatform().getArchitecture() == Architecture.X86) { Controllers.dialog(i18n(""launch.advice.different_platform""), i18n(""message.warning""), MessageType.ERROR, continueAction); suggested = true; } // 32-bit JVM cannot make use of too much memory. if (javaVersion.getBits() == Bits.BIT_32 && setting.getMaxMemory() > 1.5 * 1024) { // 1.5 * 1024 is an inaccurate number. // Actual memory limit depends on operating system and memory. Controllers.confirm(i18n(""launch.advice.too_large_memory_for_32bit""), i18n(""message.error""), continueAction, breakAction); suggested = true; } if (!suggested && violatedSuggestedConstraint != null) { suggested = true; switch (violatedSuggestedConstraint) { case MODDED_JAVA_7: Controllers.dialog(i18n(""launch.advice.java.modded_java_7""), i18n(""message.warning""), MessageType.WARNING, continueAction); return null; case MODDED_JAVA_8: Controllers.dialog(i18n(""launch.advice.newer_java""), i18n(""message.warning""), MessageType.WARNING, continueAction); break; case VANILLA_JAVA_8_51: Controllers.dialog(i18n(""launch.advice.java8_51_1_13""), i18n(""message.warning""), MessageType.WARNING, continueAction); break; } } // Cannot allocate too much memory exceeding free space. if (!suggested && OperatingSystem.TOTAL_MEMORY > 0 && OperatingSystem.TOTAL_MEMORY < setting.getMaxMemory()) { Controllers.confirm(i18n(""launch.advice.not_enough_space"", OperatingSystem.TOTAL_MEMORY), i18n(""message.error""), continueAction, null); suggested = true; } // Forge 2760~2773 will crash game with LiteLoader. if (!suggested) { boolean hasForge2760 = version.getLibraries().stream().filter(it -> it.is(""net.minecraftforge"", ""forge"")) .anyMatch(it -> VersionNumber.VERSION_COMPARATOR.compare(""1.12.2-14.23.5.2760"", it.getVersion()) <= 0 && VersionNumber.VERSION_COMPARATOR.compare(it.getVersion(), ""1.12.2-14.23.5.2773"") < 0); boolean hasLiteLoader = version.getLibraries().stream().anyMatch(it -> it.is(""com.mumfrey"", ""liteloader"")); if (hasForge2760 && hasLiteLoader && gameVersion.compareTo(VersionNumber.asVersion(""1.12.2"")) == 0) { Controllers.confirm(i18n(""launch.advice.forge2760_liteloader""), i18n(""message.error""), continueAction, null); suggested = true; } } // OptiFine 1.14.4 is not compatible with Forge 28.2.2 and later versions. if (!suggested) { boolean hasForge28_2_2 = version.getLibraries().stream().filter(it -> it.is(""net.minecraftforge"", ""forge"")) .anyMatch(it -> VersionNumber.VERSION_COMPARATOR.compare(""1.14.4-28.2.2"", it.getVersion()) <= 0); boolean hasOptiFine = version.getLibraries().stream().anyMatch(it -> it.is(""optifine"", ""OptiFine"")); if (hasForge28_2_2 && hasOptiFine && gameVersion.compareTo(VersionNumber.asVersion(""1.14.4"")) == 0) { Controllers.confirm(i18n(""launch.advice.forge28_2_2_optifine""), i18n(""message.error""), continueAction, null); suggested = true; } } if (!suggested) { future.complete(javaVersion); } return Task.fromCompletableFuture(future); }).withStage(""launch.state.java""); }","private static Task checkGameState(Profile profile, VersionSetting setting, Version version) { VersionNumber gameVersion = VersionNumber.asVersion(profile.getRepository().getGameVersion(version).orElse(""Unknown"")); if (setting.isNotCheckJVM()) { return Task.composeAsync(() -> setting.getJavaVersion(gameVersion, version)) .thenApplyAsync(javaVersion -> Optional.ofNullable(javaVersion).orElseGet(JavaVersion::fromCurrentEnvironment)) .withStage(""launch.state.java""); } return Task.composeAsync(() -> { return setting.getJavaVersion(gameVersion, version); }).thenComposeAsync(Schedulers.javafx(), javaVersion -> { // Reset invalid java version if (javaVersion == null) { CompletableFuture future = new CompletableFuture<>(); Runnable continueAction = () -> future.complete(JavaVersion.fromCurrentEnvironment()); if (setting.isJavaAutoSelected()) { JavaVersionConstraint.VersionRanges range = JavaVersionConstraint.findSuitableJavaVersionRange(gameVersion, version); GameJavaVersion targetJavaVersion; if (range.getMandatory().contains(VersionNumber.asVersion(""16""))) { targetJavaVersion = GameJavaVersion.JAVA_16; } else if (range.getMandatory().contains(VersionNumber.asVersion(""1.8.0_51""))) { targetJavaVersion = GameJavaVersion.JAVA_8; } else { targetJavaVersion = null; } if (targetJavaVersion != null) { downloadJava(gameVersion.toString(), targetJavaVersion, profile) .thenAcceptAsync(downloadedJavaVersion -> { future.complete(downloadedJavaVersion); }) .exceptionally(throwable -> { LOG.log(Level.WARNING, ""Failed to download java"", throwable); Controllers.dialog(i18n(""launch.failed.no_accepted_java""), i18n(""message.warning""), MessageType.WARNING, continueAction); return null; }); } } else { Controllers.dialog(i18n(""launch.wrong_javadir""), i18n(""message.warning""), MessageType.WARNING, continueAction); setting.setJava(null); setting.setDefaultJavaPath(null); setting.setJavaVersion(JavaVersion.fromCurrentEnvironment()); } return Task.fromCompletableFuture(future); } else { return Task.completed(javaVersion); } }).thenComposeAsync(javaVersion -> { return Task.allOf(Task.completed(javaVersion), Task.supplyAsync(() -> JavaVersionConstraint.findSuitableJavaVersion(gameVersion, version))); }).thenComposeAsync(Schedulers.javafx(), javaVersions -> { JavaVersion javaVersion = (JavaVersion) javaVersions.get(0); JavaVersion suggestedJavaVersion = (JavaVersion) javaVersions.get(1); if (setting.isJavaAutoSelected()) return Task.completed(javaVersion); JavaVersionConstraint violatedMandatoryConstraint = null; JavaVersionConstraint violatedSuggestedConstraint = null; for (JavaVersionConstraint constraint : JavaVersionConstraint.ALL) { if (constraint.appliesToVersion(gameVersion, version, javaVersion)) { if (!constraint.checkJava(gameVersion, version, javaVersion)) { if (constraint.getType() == JavaVersionConstraint.RULE_MANDATORY) { violatedMandatoryConstraint = constraint; } else if (constraint.getType() == JavaVersionConstraint.RULE_SUGGESTED) { violatedSuggestedConstraint = constraint; } } } } boolean suggested = false; CompletableFuture future = new CompletableFuture<>(); Runnable continueAction = () -> future.complete(javaVersion); Runnable breakAction = () -> { future.completeExceptionally(new CancellationException(""Launch operation was cancelled by user"")); }; if (violatedMandatoryConstraint != null) { if (suggestedJavaVersion != null) { Controllers.confirm(i18n(""launch.advice.java.auto""), i18n(""message.warning""), () -> { setting.setJavaAutoSelected(); future.complete(suggestedJavaVersion); }, breakAction); return Task.fromCompletableFuture(future); } else { switch (violatedMandatoryConstraint) { case GAME_JSON: downloadJava(gameVersion.toString(), version.getJavaVersion(), profile) .thenAcceptAsync(downloadedJavaVersion -> { setting.setJavaVersion(downloadedJavaVersion); future.complete(downloadedJavaVersion); }) .exceptionally(throwable -> { LOG.log(Level.WARNING, ""Failed to download java"", throwable); breakAction.run(); return null; }); return Task.fromCompletableFuture(future); case VANILLA_JAVA_16: Controllers.confirm(i18n(""launch.advice.require_newer_java_version"", gameVersion.toString(), 16), i18n(""message.warning""), () -> { FXUtils.openLink(""https://adoptium.net/?variant=openjdk17""); }, breakAction); return null; case VANILLA_JAVA_17: Controllers.confirm(i18n(""launch.advice.require_newer_java_version"", gameVersion.toString(), 17), i18n(""message.warning""), () -> { FXUtils.openLink(""https://adoptium.net/?variant=openjdk17""); }, breakAction); return null; case VANILLA_JAVA_8: Controllers.dialog(i18n(""launch.advice.java8_1_13""), i18n(""message.error""), MessageType.ERROR, breakAction); return null; case VANILLA_LINUX_JAVA_8: if (setting.getNativesDirType() == NativesDirectoryType.VERSION_FOLDER) { Controllers.dialog(i18n(""launch.advice.vanilla_linux_java_8""), i18n(""message.error""), MessageType.ERROR, breakAction); return null; } else { break; } case VANILLA_X86: if (setting.getNativesDirType() == NativesDirectoryType.VERSION_FOLDER) { if (Architecture.SYSTEM_ARCH == Architecture.ARM64) { if (OperatingSystem.CURRENT_OS == OperatingSystem.OSX // Windows on ARM introduced translation support for x86-64 after 10.0.21277. || (OperatingSystem.CURRENT_OS == OperatingSystem.WINDOWS && OperatingSystem.SYSTEM_BUILD_NUMBER >= 21277)) { Controllers.dialog(i18n(""launch.advice.vanilla_x86.translation""), i18n(""message.error""), MessageType.ERROR, breakAction); return null; } } Controllers.dialog(i18n(""launch.advice.vanilla_x86""), i18n(""message.error""), MessageType.ERROR, breakAction); return null; } else { break; } case LAUNCH_WRAPPER: Controllers.dialog(i18n(""launch.advice.java9"") + ""\n"" + i18n(""launch.advice.uncorrected""), i18n(""message.error""), MessageType.ERROR, breakAction); return null; } } } if (Architecture.SYSTEM_ARCH == Architecture.X86_64 && javaVersion.getPlatform().getArchitecture() == Architecture.X86) { Controllers.dialog(i18n(""launch.advice.different_platform""), i18n(""message.warning""), MessageType.ERROR, continueAction); suggested = true; } // 32-bit JVM cannot make use of too much memory. if (javaVersion.getBits() == Bits.BIT_32 && setting.getMaxMemory() > 1.5 * 1024) { // 1.5 * 1024 is an inaccurate number. // Actual memory limit depends on operating system and memory. Controllers.confirm(i18n(""launch.advice.too_large_memory_for_32bit""), i18n(""message.error""), continueAction, breakAction); suggested = true; } if (!suggested && violatedSuggestedConstraint != null) { suggested = true; switch (violatedSuggestedConstraint) { case MODDED_JAVA_7: Controllers.dialog(i18n(""launch.advice.java.modded_java_7""), i18n(""message.warning""), MessageType.WARNING, continueAction); return null; case MODDED_JAVA_8: Controllers.dialog(i18n(""launch.advice.newer_java""), i18n(""message.warning""), MessageType.WARNING, continueAction); break; case VANILLA_JAVA_8_51: Controllers.dialog(i18n(""launch.advice.java8_51_1_13""), i18n(""message.warning""), MessageType.WARNING, continueAction); break; } } // Cannot allocate too much memory exceeding free space. if (!suggested && OperatingSystem.TOTAL_MEMORY > 0 && OperatingSystem.TOTAL_MEMORY < setting.getMaxMemory()) { Controllers.confirm(i18n(""launch.advice.not_enough_space"", OperatingSystem.TOTAL_MEMORY), i18n(""message.error""), continueAction, null); suggested = true; } // Forge 2760~2773 will crash game with LiteLoader. if (!suggested) { boolean hasForge2760 = version.getLibraries().stream().filter(it -> it.is(""net.minecraftforge"", ""forge"")) .anyMatch(it -> VersionNumber.VERSION_COMPARATOR.compare(""1.12.2-14.23.5.2760"", it.getVersion()) <= 0 && VersionNumber.VERSION_COMPARATOR.compare(it.getVersion(), ""1.12.2-14.23.5.2773"") < 0); boolean hasLiteLoader = version.getLibraries().stream().anyMatch(it -> it.is(""com.mumfrey"", ""liteloader"")); if (hasForge2760 && hasLiteLoader && gameVersion.compareTo(VersionNumber.asVersion(""1.12.2"")) == 0) { Controllers.confirm(i18n(""launch.advice.forge2760_liteloader""), i18n(""message.error""), continueAction, null); suggested = true; } } // OptiFine 1.14.4 is not compatible with Forge 28.2.2 and later versions. if (!suggested) { boolean hasForge28_2_2 = version.getLibraries().stream().filter(it -> it.is(""net.minecraftforge"", ""forge"")) .anyMatch(it -> VersionNumber.VERSION_COMPARATOR.compare(""1.14.4-28.2.2"", it.getVersion()) <= 0); boolean hasOptiFine = version.getLibraries().stream().anyMatch(it -> it.is(""optifine"", ""OptiFine"")); if (hasForge28_2_2 && hasOptiFine && gameVersion.compareTo(VersionNumber.asVersion(""1.14.4"")) == 0) { Controllers.confirm(i18n(""launch.advice.forge28_2_2_optifine""), i18n(""message.error""), continueAction, null); suggested = true; } } // CVE-2021-44228 Remote code injection in Log4j if (!suggested) { if (gameVersion.compareTo(VersionNumber.asVersion(""1.7"")) >= 0 && gameVersion.compareTo(VersionNumber.asVersion(""1.18"")) <= 0) { String xmlSha1 = Optional.ofNullable(version.getLogging().get(DownloadType.CLIENT)) .flatMap(loggingInfo -> Optional.of(loggingInfo.getFile())) .flatMap(idDownloadInfo -> Optional.ofNullable(idDownloadInfo.getSha1())) .orElse(""""); if (gameVersion.compareTo(VersionNumber.asVersion(""1.12"")) < 0) { if (UNSAFE_CLIENT_1_7_XML_SHA1.contains(xmlSha1)) { Controllers.confirm(i18n(""launch.advice.log4j_cve_2021_44228""), i18n(""message.warning""), continueAction, null); suggested = true; } } else { if (UNSAFE_CLIENT_1_12_XML_SHA1.contains(xmlSha1)) { Controllers.confirm(i18n(""launch.advice.log4j_cve_2021_44228""), i18n(""message.warning""), continueAction, null); suggested = true; } } } } if (!suggested) { future.complete(javaVersion); } return Task.fromCompletableFuture(future); }).withStage(""launch.state.java""); }",Prohibit JNDI remote invoke,https://github.com/HMCL-dev/HMCL/commit/38013a92989c529c27f39b596221bbcf5d68c3fc,,,HMCL/src/main/java/org/jackhuang/hmcl/game/LauncherHelper.java,3,java,False,2021-12-11T04:28:48Z "inline gravity_value_t convert_value2float (gravity_vm *vm, gravity_value_t v) { if (VALUE_ISA_FLOAT(v)) return v; // handle conversion for basic classes if (VALUE_ISA_INT(v)) return VALUE_FROM_FLOAT((gravity_float_t)v.n); if (VALUE_ISA_BOOL(v)) return VALUE_FROM_FLOAT(v.n); if (VALUE_ISA_NULL(v)) return VALUE_FROM_FLOAT(0); if (VALUE_ISA_UNDEFINED(v)) return VALUE_FROM_FLOAT(0); if (VALUE_ISA_STRING(v)) {return convert_string2number(VALUE_AS_STRING(v), true);} // check if class implements the Float method gravity_closure_t *closure = gravity_vm_fastlookup(vm, gravity_value_getclass(v), GRAVITY_FLOAT_INDEX); // sanity check (and break recursion) if ((!closure) || ((closure->f->tag == EXEC_TYPE_INTERNAL) && (closure->f->internal == convert_object_float))) return VALUE_FROM_ERROR(NULL); // execute closure and return its value if (gravity_vm_runclosure(vm, closure, v, NULL, 0)) return gravity_vm_result(vm); return VALUE_FROM_ERROR(NULL); }","inline gravity_value_t convert_value2float (gravity_vm *vm, gravity_value_t v) { if (VALUE_ISA_FLOAT(v)) return v; // handle conversion for basic classes if (VALUE_ISA_INT(v)) return VALUE_FROM_FLOAT((gravity_float_t)v.n); if (VALUE_ISA_BOOL(v)) return VALUE_FROM_FLOAT(v.n); if (VALUE_ISA_NULL(v)) return VALUE_FROM_FLOAT(0); if (VALUE_ISA_UNDEFINED(v)) return VALUE_FROM_FLOAT(0); if (VALUE_ISA_STRING(v)) {return convert_string2number(VALUE_AS_STRING(v), true);} // check if class implements the Float method gravity_closure_t *closure = gravity_vm_fastlookup(vm, gravity_value_getclass(v), GRAVITY_FLOAT_INDEX); // sanity check (and break recursion) if ((!closure) || ((closure->f->tag == EXEC_TYPE_INTERNAL) && (closure->f->internal == convert_object_float)) || gravity_vm_getclosure(vm) == closure) return VALUE_FROM_ERROR(NULL); // execute closure and return its value if (gravity_vm_runclosure(vm, closure, v, NULL, 0)) return gravity_vm_result(vm); return VALUE_FROM_ERROR(NULL); }",Tentative fix for issues #129 and #130,https://github.com/marcobambini/gravity/commit/d493524612edb6763c6ec07355ce584d83695e9b,,,src/runtime/gravity_core.c,3,c,False,2017-04-10T16:58:49Z "@Override public String[] getParameterValues(String name) { String[] values = super.getParameterValues(name); if (values == null) { return null; } int count = values.length; String[] encodedValues = new String[count]; for (int i = 0; i < count; i++) { encodedValues[i] = HtmlUtils.htmlEscape(values[i]); } return encodedValues; }","@Override public String[] getParameterValues(String name) { String[] values = super.getParameterValues(name); if (values == null) { return null; } int count = values.length; String[] encodedValues = new String[count]; for (int i = 0; i < count; i++) { encodedValues[i] = HtmlUtils.cleanUnSafe(values[i]); } return encodedValues; }",:zap: 使用 Jackson2ObjectMapperBuilder 构造 ObjectMapper,保留使用配置文件配置 jackson 属性的能力,以及方便用户增加自定义配置,https://github.com/ballcat-projects/ballcat/commit/d4d5d4c4aa4402bec83db4eab7007f0cf70e8e01,,,ballcat-common/ballcat-common-core/src/main/java/com/hccake/ballcat/common/core/request/wrapper/XSSRequestWrapper.java,3,java,False,2021-03-08T14:05:28Z "void gf_filter_pid_inst_del(GF_FilterPidInst *pidinst) { assert(pidinst); gf_filter_pid_inst_reset(pidinst); gf_fq_del(pidinst->packets, (gf_destruct_fun) pcki_del); gf_mx_del(pidinst->pck_mx); gf_list_del(pidinst->pck_reassembly); if (pidinst->props) { assert(pidinst->props->reference_count); if (safe_int_dec(&pidinst->props->reference_count) == 0) { //see \ref gf_filter_pid_merge_properties_internal for mutex gf_mx_p(pidinst->pid->filter->tasks_mx); gf_list_del_item(pidinst->pid->properties, pidinst->props); gf_mx_v(pidinst->pid->filter->tasks_mx); gf_props_del(pidinst->props); } } gf_free(pidinst); }","void gf_filter_pid_inst_del(GF_FilterPidInst *pidinst) { assert(pidinst); gf_filter_pid_inst_reset(pidinst); gf_fq_del(pidinst->packets, (gf_destruct_fun) pcki_del); gf_mx_del(pidinst->pck_mx); gf_list_del(pidinst->pck_reassembly); if (pidinst->props) { assert(pidinst->props->reference_count); gf_mx_p(pidinst->pid->filter->tasks_mx); //not in parent pid, may happen when reattaching a pid inst to a different pid //in this case do NOT delete the props if (gf_list_find(pidinst->pid->properties, pidinst->props)>=0) { if (safe_int_dec(&pidinst->props->reference_count) == 0) { //see \ref gf_filter_pid_merge_properties_internal for mutex gf_list_del_item(pidinst->pid->properties, pidinst->props); gf_props_del(pidinst->props); } } gf_mx_v(pidinst->pid->filter->tasks_mx); } gf_free(pidinst); }",fixed #2429,https://github.com/gpac/gpac/commit/2c055153d401b8c49422971e3a0159869652d3da,,,src/filter_core/filter_pid.c,3,c,False,2023-03-27T09:58:57Z "@Override public List getTooltipLines() { List strings = new ArrayList<>(); strings.add(new StringTextComponent(TextFormatting.GOLD + new TranslationTextComponent(""tooltip.titanium.tank.fluid"").getString()).append(tank.getFluidInTank(tankSlot).isEmpty() ? new TranslationTextComponent(""tooltip.titanium.tank.empty"").mergeStyle(TextFormatting.WHITE) : new TranslationTextComponent(tank.getFluidInTank(tankSlot).getFluid().getAttributes().getTranslationKey(tank.getFluidInTank(tankSlot)))).mergeStyle(TextFormatting.WHITE)); strings.add(new TranslationTextComponent(""tooltip.titanium.tank.amount"").mergeStyle(TextFormatting.GOLD).append(new StringTextComponent(TextFormatting.WHITE + new DecimalFormat().format(tank.getFluidInTank(tankSlot).getAmount()) + TextFormatting.GOLD + ""/"" + TextFormatting.WHITE + new DecimalFormat().format(tank.getTankCapacity(tankSlot)) + TextFormatting.DARK_AQUA + ""mb""))); if (!Minecraft.getInstance().player.inventory.getItemStack().isEmpty() && Minecraft.getInstance().player.inventory.getItemStack().getCapability(CapabilityFluidHandler.FLUID_HANDLER_ITEM_CAPABILITY).isPresent()){ Minecraft.getInstance().player.inventory.getItemStack().getCapability(CapabilityFluidHandler.FLUID_HANDLER_ITEM_CAPABILITY).ifPresent(iFluidHandlerItem -> { boolean canFillFromItem = tank.fill(iFluidHandlerItem.drain(Integer.MAX_VALUE, IFluidHandler.FluidAction.SIMULATE), IFluidHandler.FluidAction.SIMULATE) > 0; boolean canDrainFromItem = iFluidHandlerItem.fill(tank.drain(Integer.MAX_VALUE, IFluidHandler.FluidAction.SIMULATE), IFluidHandler.FluidAction.SIMULATE) > 0; if (canFillFromItem) strings.add(new TranslationTextComponent(""tooltip.titanium.tank.can_fill_from_item"").mergeStyle(TextFormatting.BLUE)); if (canDrainFromItem) strings.add(new TranslationTextComponent(""tooltip.titanium.tank.can_drain_from_item"").mergeStyle(TextFormatting.GOLD)); if (canFillFromItem) strings.add(new TranslationTextComponent(""tooltip.titanium.tank.action_fill"").mergeStyle(TextFormatting.DARK_GRAY)); if (canDrainFromItem) strings.add(new TranslationTextComponent(""tooltip.titanium.tank.action_drain"").mergeStyle(TextFormatting.DARK_GRAY)); if (!canDrainFromItem && !canFillFromItem){ strings.add(new TranslationTextComponent(""tooltip.titanium.tank.no_action"").mergeStyle(TextFormatting.RED)); } }); } else { strings.add(new TranslationTextComponent(""tooltip.titanium.tank.no_tank"").mergeStyle(TextFormatting.DARK_GRAY)); } return strings; }","@Override public List getTooltipLines() { List strings = new ArrayList<>(); strings.add(new StringTextComponent(TextFormatting.GOLD + new TranslationTextComponent(""tooltip.titanium.tank.fluid"").getString()).append(tank.getFluidInTank(tankSlot).isEmpty() ? new TranslationTextComponent(""tooltip.titanium.tank.empty"").mergeStyle(TextFormatting.WHITE) : new TranslationTextComponent(tank.getFluidInTank(tankSlot).getFluid().getAttributes().getTranslationKey(tank.getFluidInTank(tankSlot)))).mergeStyle(TextFormatting.WHITE)); strings.add(new TranslationTextComponent(""tooltip.titanium.tank.amount"").mergeStyle(TextFormatting.GOLD).append(new StringTextComponent(TextFormatting.WHITE + new DecimalFormat().format(tank.getFluidInTank(tankSlot).getAmount()) + TextFormatting.GOLD + ""/"" + TextFormatting.WHITE + new DecimalFormat().format(tank.getTankCapacity(tankSlot)) + TextFormatting.DARK_AQUA + ""mb""))); if (!Minecraft.getInstance().player.inventory.getItemStack().isEmpty() && Minecraft.getInstance().player.inventory.getItemStack().getCapability(CapabilityFluidHandler.FLUID_HANDLER_ITEM_CAPABILITY).isPresent()){ Minecraft.getInstance().player.inventory.getItemStack().getCapability(CapabilityFluidHandler.FLUID_HANDLER_ITEM_CAPABILITY).ifPresent(iFluidHandlerItem -> { boolean isBucket = Minecraft.getInstance().player.inventory.getItemStack().getItem() instanceof BucketItem; int amount = isBucket ? FluidAttributes.BUCKET_VOLUME : Integer.MAX_VALUE; boolean canFillFromItem = false; boolean canDrainFromItem = false; if (isBucket) { canFillFromItem = tank.fill(iFluidHandlerItem.drain(amount, IFluidHandler.FluidAction.SIMULATE), IFluidHandler.FluidAction.SIMULATE) == FluidAttributes.BUCKET_VOLUME; canDrainFromItem = iFluidHandlerItem.fill(tank.drain(amount, IFluidHandler.FluidAction.SIMULATE), IFluidHandler.FluidAction.SIMULATE) == FluidAttributes.BUCKET_VOLUME; } else { canFillFromItem = tank.fill(iFluidHandlerItem.drain(amount, IFluidHandler.FluidAction.SIMULATE), IFluidHandler.FluidAction.SIMULATE) > 0; canDrainFromItem = iFluidHandlerItem.fill(tank.drain(amount, IFluidHandler.FluidAction.SIMULATE), IFluidHandler.FluidAction.SIMULATE) > 0; } if (canFillFromItem) strings.add(new TranslationTextComponent(""tooltip.titanium.tank.can_fill_from_item"").mergeStyle(TextFormatting.BLUE)); if (canDrainFromItem) strings.add(new TranslationTextComponent(""tooltip.titanium.tank.can_drain_from_item"").mergeStyle(TextFormatting.GOLD)); if (canFillFromItem) strings.add(new TranslationTextComponent(""tooltip.titanium.tank.action_fill"").mergeStyle(TextFormatting.DARK_GRAY)); if (canDrainFromItem) strings.add(new TranslationTextComponent(""tooltip.titanium.tank.action_drain"").mergeStyle(TextFormatting.DARK_GRAY)); if (!canDrainFromItem && !canFillFromItem) { strings.add(new TranslationTextComponent(""tooltip.titanium.tank.no_action"").mergeStyle(TextFormatting.RED)); } }); } else { strings.add(new TranslationTextComponent(""tooltip.titanium.tank.no_tank"").mergeStyle(TextFormatting.DARK_GRAY)); } return strings; }",Fixed Tank GUI interaction bypassing bucket limits,https://github.com/InnovativeOnlineIndustries/Industrial-Foregoing/commit/4a6391d80a381ec1a808492f82a5f78e3538e4b9,,,src/main/java/com/buuz135/industrial/gui/component/ItemStackTankScreenAddon.java,3,java,False,2021-05-29T20:42:17Z "@Override public float researchPriority(Tech t) { // by raising tech cost to 1.3, we will tend to value researching lower-cost // techs that have a similar value/cost ratio as more expensive ones // iow, for each 10x in cost, there needs to be 20x value to be same priority //System.out.print(""\n""+empire.name()+"" Tech: ""+t.name()+"" score: ""+researchValue(t)+"" score before stuff: ""+t.baseValue(empire)); return researchValue(t); }","@Override public float researchPriority(Tech t) { float researchValue = researchValue(t); if(researchValue > 1) { for(EmpireView ev : empire.contacts()) { if(!ev.inEconomicRange()) continue; //If we can steal it or trade for it, we don't want to research it ourselves if(ev.spies().unknownTechs().contains(t)) { researchValue = 1; break; } } } return researchValue; }","Inofficial 0.93a (#62) * Replaced many isPlayer() by isPlayerControlled() This leads to a more fluent experience on AutoPlay. Note: the council-voting acts weird when you try that there, getting you stuck, and the News-Broadcasts also seem to use a differnt logic and are always shown. * Orion-guard-handling Avoid sending colonization-fleets, when guardian is still alive Increase guardian-power-estimate to 100,000 Don't send and count bombers towards guardian-defeat-force * Fixed Crash from a report on reddit Not sure how that could happen though. Never had this issue in games started on my computer. * Fixed crash after AI defeats orion-guard Tried to access an out-of-bounds-value because it couldn't find the System where the guardian was. So looking to find the Planet with the Orionartifact now, which does find it. * All the forgotten isPlayer()-calls Including the Base- and Modnar-AI-Diplomat * Personalities now play a role in my AI once again Instead of everyone having the same conditions for war, there's now different ones. Some are more aggressive, some are less. * Fixed issue where enemy-fleets weren's seen, when they actually were. Also added a way of guessing when enemy-fleets aren't seen so it shouldn't trickle in tiny fleets that all retreat anymore in the early-game, before they can see the enemy-fleets. And also not later because they now actually can see them. * Update AIDiplomat.java * Delete ShipCombatResults.java * Delete Empire.java * Delete TradeRoute.java * Revert ""Delete TradeRoute.java"" This reverts commit 6e5c5a8604e89bb11a9a6dc63acd5b3f27194c83. * Revert ""Delete Empire.java"" This reverts commit 1a020295e05ebc735dae761f426742eb7bdc8d35. * Revert ""Delete ShipCombatResults.java"" This reverts commit 5f9287289feb666adf1aa809524973c54fbf0cd5. * Update ShipCombatResults.java reverting pull-request... manually because I don't know of a better way 8[ * Update Empire.java * Update TradeRoute.java * Merge with Master * Update TradeRoute.java * Update TradeRoute.java github editor does not allow me to remove a newline oO * AI improvements Added parameter to make the colonizer-function return just the uncolonized planets without substracting the colony-ships. Impelemented a very differnt diplomatic behavior, that supposedly is more suitable to actually winning by waging less war, particularly when big enough to be voted for. Revoked that AI doesn't adjust to enemy-troops when it has a more defensive unit-composition. In lategame going by destructive-power of bombers hasn't much merit, when 1 bombers can pack 60ish neutronium-bombs. Fixed an issue that prevented designing extended-fuel-range-colonizers asap. This once again helps expansion-speed a lot. Security now is only spent against empires actually in range to spy, as it was intended. Contact via council should not increase paranoia. Also Xenophobic-extra-paranoia removed. * Update OrionGuardianShip.java * War-declaration behavior Electible faction will no longer declare war on someone who is at war with the other electible faction. * Fix zero-division on refreshing a trade-route that had been adjusted due to empire-shrinkage. * AI & Bugfix Leader-stuff is now overridden Should now retreat against repulsors, when no counter available Tech-nullifier hit and miss mixup fixed * AI improvements Fixed a rare crash in AutoPlay-Mode Massive overhaul of AI-ship-design Spy master now more catious about avoiding unwanted, dangerous wars due to spying on the wrong people Colony-ship-designs now will only get a weapon, if this doesn't prevent reserve-tanks or reducing their size to medium Fixed an issue where ai wouldn't retreat from ships with repulsor-beam that exploited their range-advantage Increased research-value of cloaking-tech and battle-suits Upon reaching tech-level 99 in every field, AI will produce ships non-stop even in peace-time AI will now retreat fleets from empires it doesn't want to go to war with in order to avoid trespassing-issues Fixed issue where the AI wanted to but couldn't colonize orion before it was cleared and then wouldn't colonize other systems in that time AI will no longer break non-aggression-pacts when it still has a war with someone else AI will only begin wars because of spying, if it actually feels comfortable dealing with the person who spied on them AI will now try and predict whether it will be attacked soon and enact preventive measures * Tackling some combat-issue Skipping specials when it comes to determining optimal-range. Otherwise ships with long-range-specials like warp-dissipator would never close in on their prey. Resetting the selectedWeaponIndex upon reload to consistency start with same weapons every turn. Writing new attack-method that allows to skip certain weapons like for example repulsor-beam at the beginning of the turn and fire them at the end instead. * Update NewShipTemplate.java Fixed incorrect operator ""-="" instead of ""=-"", that prevented weapons being used at all when no weapon that is strong enough for theorethical best enemy shield could be found. Also when range is required an not fitting beam can be found try missiles and when no fitting missile can be found either, try short-range weapon. Should still be better than nothing. * Diplomacy and Ship-Building Reduced suicidal tendencies. No more war-declarations against wastly superior enemies. At most they ought to be 25% stronger. Voting behavior is now deterministic. No more votes based on fear, only on who they actually like and only for those whom they have real-contact. Ship-construction is now based on relative-productivity rather than using a hard cut-off for anything lower than standard-resources. So when the empire only has poor-systems it will try to build at least a few ships still. * Orion prevented war Fixed an issue, where wanting to build a colonizer for Orion prevented wars. * Update AIGeneral.java Don't invade unless you have something in orbit. * Update AIFleetCommander.java No longer using hyperspace-communications... for now. (it produced unintentional results and error-messages) * AI improvements corrected typo in Stellar Converter Fixed trading for techs that have no value by taking the random modifier into account No longer agreeing to or offering alliances Added sophisticated behavior when it comes to offering and agreeing to joint wars Ignore existence of council in diplomatic behavior No longer needing to have positive relations for council vote, the lesser evil is good enough Improved the selection at which planets ships are being built, this time really improved rather than probably making it worse than before No longer using extended fuel-tanks when unlimited-range-tech is researched Avoid designing bombers that can overkill a planet single-handedly, instead replace part of the bombs with other weapons Scoring adjustments for special-devices, primarily no longer taking space into account for score as otherwise miniaturization would always lead to always using the old, weak specials * AI-improvements and combat-estimated fixes No longer wanting to do a NAP with preferred target Divide score for target by 3 if nap is in place, so nap now is really usefull to have with Empires outside of trading range will no longer offer joint wars Logic for whether to declare war on somone who spied on them is now same as if they were their best victim. This prevents suicidal anti-spy-wars. Prevention-war will now also be started upon invasions No longer setting retreat on arrival, as preemtively retreating may prevent retargetting something else, especially important for colony-ships early on Retreats are now also handled after the fleet-manager had the chance to do something else with these ships reduced the percentage of bombers that will be built by about half. So it can't go over 50% anymore and usually will be even lower Fixed an issue with incorrect kill-percentage estimates. After that fix the Valuefactor, which had some correcting attributes, was no longer needed and thus removed. Made sure that bombers are always designed to actually have bombs. Invaders with surrenderOnArrival are no longer considered a threat * AI and damage-simulation-stuff No longer bombing colonies of someone who isn't my enemy Asking others to join a war, when our opponent is stronger than us Agreeing to join-war request when not busy otherwise, together we'd be stronger and the asked-for-faction is our primary target anyways Restricted war over espionage even more, to only do it if we feel ready. Much better to share a few techs than to die. Wars for strategic reasons can now once again be cancelled. Doing a cost:gain-analysis for invasions, that is much more likely to invade, especially if we have previously been invaded and the planet has factories from us. It also takes the savings of not having to build a colony-ship into account. Further reduced the overkill for invasions. We want to do more of them when they are cost-efficient but still not waste our population. More planets will participate in the construction of colony-ships. When we are at war or have others in our range during the phase where we want to churn out colony-ships, we mix in combat-ships to make us less of a juicy target and be able to repel sneak-attacks better. Hostile-planets now get more population sent to. Stacks of strong individual ships about to die in combat, will consider their lessened chances of survival and may now retreat when damaged too much. Reverted change in method that I don't use anyways. Fixed shield-halving-properties of weapons like neutron-pellet-guns not being taken into account in combat-simulations using the firepower-method. Fixed bombers estimating the whole stack sharing a single bomb, which dramatically underestimated the firepower they had. * Mostly things about research Fixed that studyingFutureTech() always returned false. Fixed issue with having more research-allocation-points than possible in base- and modnar-AI when redistributing research-points to avoid researching future techs before other techs are researched Inclusion of faction-specific espionage-replies Maximum ship-maintenance now capped at 45% (5*warp-speed) before all techs are researched, then it is doubled to 90% More bombers will be built when opponents use missile-bases a lot When under siege by enemy bombers will no longer build factories but either population, ships or research depending on how destructive the bombardment is. This is to avoid investing into something that will be lost or not finished anyways. Future techs are now considered lower priority than all non-obsolete techs. Fixed missing override of baseValue for future-techs No longer allocating RP to techs which have a higher percentage to be researched next turn than the percentage of RP attributed to them. This should increase research-output slightly. Ship-stacks that have colony-ships in their fleet will no longer be much more ready to retreat because they consider the low survivability of colony-ships as a threat to themselves. Colony-ships may retreat alone, but won't always do so either. Retreat threshold is now always 1.0, meaning if they think they can win, they will stay, even if the losses equal their own kills. Allowed treasurer to gather taxes in order to save planets from nova or plague. * Making the AI even tougher Will now go to war at 75% development rather than 100%. So much more aggressive with much fewer and shorter periods of peace. Will no longer offer or agree to a peace-treaty, when it has ongoing invasions. Maximum-ship-maintenance-percentage now is a root-function of tech-level that's steeper early on and smoothes out later. During peace-time will now gather ships at centralized locations for better responsiveness. Will no longer stage an attack on the orion-guardian while having enemies. Siege-fleets will no longer wait for transports to land before doing something else. Reduced the superiority-aim for combats to 2, down from 4 to allow more simultaneous missions. When a system where ships are gathered has incoming enemy fleets, this no longer prevents the ships from going to other missions until the attacks are over, which had allowed a theoretical exploit where you could keep sending tiny fleets to make the AI not move their fleets. Instead they now substract the exact amount they think they need to defend from the ships that they can send away. Stopping to make more ships when in possession of more than 4 times the amount of all enemies combined. Making more ships when non-enemy-neigbours build more ships. Aiming for at least 1/4th of that what our strongest non-enemy-neighbor has. Decreased the importance of income of a planet to determine how usefull it is for production. No resource-bonuses are more important for that. Fixed issues with tech-slider-management caused by upcomingDiscoverChance looking at the forecast of RP that will be added rather than the RP spent at the time it is called. When only future-techs are left to research, the allocations will be shifted in a way to heavily favor propulsion and weapons as those generate by far the greatest miniaturization-benefits. No longer overestimate combat-efficiency against enemy colony-ships by counting it as a kill for each individual stack. Avoid scrapping when we still have enemies rather than just when being at war. Now taking only 3 instead of 5 colonies into account when making the decision what hull-sizes to use. This delays the usage of huge hulls further into the late-game and is meant to avoid scenarios like there's only being 2 huge bombers for 5 enemy-colonies instead of 12 large ones. The AI you watch in Autoplay-mode no longer receives difficulty-bonuses. This means you can now let it play against harder difficulty-levels. * Update Colony.java Waste-modifier for autoplay against easier-difficulty-levels was wrong. * Fixes Fixed possible crash in combat-outcome-estimation. Fixed ai-waste-modifier for below normal-difficulty-levels to be applied to the waste-generation rather than the cleanup-cost. * AI performance Instead of iterating through a triple-nestes-loop of fleets, systems and fleets, the inner loop is now buffered so that in consecutive calls there's a lot less to process. This significantly improves turn-times. Colonizers with extended range can now be sent to colonize something when they are in a fleet that otherwise couldn't travel so far. Removed unused code from AIGeneral. AIShipCaptain is now thread-save due to no longer manipulating stack and instead strong the target in their own local member-variable. Specials are now properly used in the right order. All specials except repulsor-beam and stasis-field are now cast before the other weapons. Now fleeing from ship with repulsor if our optimal-range is outranged, not just our maximum-range. Also now considering that the repulsor-stack can protect more than itself (up to 3 more stacks when they are in a corner). Will now design and use huge colonizers when stranded in a constellation that otherwise can't be escaped. The logic to determine that might still be a little flawed, though. Repulsor now will be countered even if it is only researched and not installed in a ship yet since only reacting once it's seen could be too late. Made shipComonentCanAttack public for improved logic in attacking. Included fix from /u/albertinix that caused a crash when hitting pause in auto-combat. UncolonizedPlanetsInRange-Methods in empire.java now actually only return uncolonized planets. Fixed an issue where shield-reduction would be applied twice in combat-simulation. Capped the amount of estimated kills at the amount of targets destroyed. * Update AIFleetCommander.java Increased colonization-bonus for unlockig additional systems. * Update AIFleetCommander.java doubled the score-increase on unexplored. * Fixes and imrpvements Fixed possible double-colonization by two AIs arriving at a system in the same turn. Reenabled the usage of Hyperspace-communications. IncomingBc and Bombard-damage are now updated directly in the Hash for referencing during the same turn. Taught AI to situationally utilize huge hulls for colonizers with extended range. Techs with 0 value now actually return 0 value rather than 0 + random() More aggressive use of espionage. * Blackhole-fixes Fixed an issue that stacks killed by Blackhole-Generator only die in combat but are still alive afterwards. Fixed an issue that Blackhole-Generator would always kill at least one ship, even if it rolled low. It now can miss when the amount of enemy ships is smaller than the percentage it rolls to kill. Fixed how damage of blackhole-generator was shown as the percentage of the hitpoints of the ships rather than the total hitpoints of all ships it killed. * Update CombatStackShip.java Fixed an issue where either the target being a colony or the presence of ground-attack-only-weapons would return a preferred range of 1 rather than the combination of the two. * AI improvements No longer breaking trade-treaty with war-target to avoid giving a warning that could be used to prepare. Fixed crash related to sorting a list with random values that could change during the lifetime of the list. That random wasn't overly useful anyways. Autoresolve will no longer ignore repulsors (but only for Xilmi-AI so far). Ships will now always try to come as close as they can before shooting as a means to increase hit-chance, use short-range-specials or make it harder to dodge missiles. Added back the value of the participants for retreat-decisions, because otherwise a clearly won battle could be given up because it was slighlty cost-inefficient. No longer always countering repulsors just because someone could use them. Instead now looking at whether they are actually in use before the decision is made. * Missile-Base & Scatter-Pack Fixed that the selection which missile-type to shoot from a missile-base had no impect. Implemented automatic-selection of better missile-type in case of auto-resolve and for AIs to use. Fixed that scatter-attacks weren't taken into account in firepower-estimation. * Fix for ETA-bug when travel through nebula For a fleet that already is in transit and has a destination the ETA is now taken from the ETA set at the begining of the journey rather than recalculated from it's current position. * Update AIGovernor.java Now taking into account that building factories scales with mineral-richness, whereas building population doesn't. The result is that most races now will prefer maxing population before factories on poor and ultra-poor. * Revert ""Fix for ETA-bug when travel through nebula"" This reverts commit c67b38203313d9d57aa07f53d7cffd67c344e16d. * Update ShipFleet.java Fix for ETA-bug again but without the redirect-rallied-fleet-exploit. * Tiny change No longer blocking the slot that is reserved for scouts once large-sized colonizers with extended fuel-tanks are available. * Hybrid AI Added another option for AI: Hybrid, which uses Diplomacy- and Espionage-modules from Modnar and the rest from Xilmi. Kill-percentage no longer modified by hitpoints as hitpoints now are seperately considered. Allowed designing Huge colonizers under, hopefully the right, circumstances. * Update GroundBattleUI.java Fixed wrong animation playing for defenders in ground combat, that caused them to die over and over instead of firing their weapon and dying only once! * Update NewShipTemplate.java Keep bombers smaller for longer. * Some non-ai-fixes Production is now capped at 0 at the lower end, to no longer allow weird side-effects of negative production-output. Fixed Defense and Industry-texts to show ""None"", when there's no production. SpyConfessionIncident now looks at leaderHatesAllSpies, which is different between AIs and same as before for default-AI. * AI improvements No more autopeace for humans. No longer participating in non-aggression-pacts. No longer complaining/asking for spies to be removed as those requests usually weren't followed up with from my AI anyways. Always ignore when asked to do anything. War weariness only takes factories and colonies into account and isn't different according to leader-personality anymore. Should result in fewer peace-treaties if one side is dominating as they don't condier it a problem to lose population during invasions, only if the opponent actually fights back. Fixed that using gather-points wasn't working. Now firing before moving if the target we want to move towards is far away. No longer retreat the whole fleet if only a part of the fleet can't counter repulsors. Enforce immediate new design to counter repulsors when someone starts using them. * GitIgnore-Test This should just include a change to AI name and reversal of an attempt to a bugfix, which caused an unintended side-effect. If it also includes the artwork-mod, then gitignore doesn't work like I think it should. * Revert ""GitIgnore-Test"" This reverts commit 49600932a25dbfa19dd6aca411c7df0e94513505. * Change AI-name and revert fix cause of side-effects Side-effects were that an AI fleet teleported once. * Update AIShipCaptain.java Thanks to bot39lvl's relentless testing a bug in target-selection was fixed. * Update CombatStackColony.java Consider the damage of scatter-packs in combat-outcome-estimation * Update Empire.java Fixed crash upon a faction being eliminated. * Update AIFleetCommander.java Strategical-map improvements to attack more decisively and take into account that conquering a system will allow more systems to be attacked. * Update AIFleetCommander.java Only gather at enemy-colonies when there's an actual war, not yet during preparations. * Update AIFleetCommander.java Now treating enemy ships and enemy-missile bases seperately when it comes to calculating how much to send. This should lead to bigger attacking-fleets in cases where the defense consists of only ships. * Update AIFleetCommander.java Fixed newly introduced issue that prevented colonizing. * 0.92 findings Less aggressive early on but more aggressive if cornered. Lots of fixes and improvements about staging-points, gather-points and colony-ship-usage. Now only building the exact amount of colonizers that is wanted instead of build colonizers for so long until I have more than I want, which had the potential to heavily overshoot. Using fewer scouts early on. Ships should now skip their move when they have pushed away someone with repulsors and still can move. (untested because situation hasn't come up yet and I lost the save where it happened) * Some fixes/improvements reduced warp-speed-requirement for war attempted fix for redirected retreating ship-cheat taking mrrshan and alkari-racial into account when determining attack-fleet-size-requirements no longer bolstering systems that are under siege by an enemy fire before retreating in combat if possible avoid overestimating damage by taking maximum hit-chance into account for damage-predictions * Update AIShipCaptain.java Moving away from enemy ships after firing. * Smarter ship-commander No longer automatically becoming war-weary when behind in tech Now moving away from enemies after firing when still movementpoints left Now sticking near planet when defending and only start moving towards opponent, when first-hit can be achieved * Small fixes as wrapup for test-release. Fixed an issue with scout-production that was present in all AIs and caused by a discrepancy between the trave-time-calculations with and without considering nebulae. During war no handling pirates or a comet has lower priority. Fixed an issue where there was missing just one tick for finishing colony-ships, which led them to be delayed until factories where all built despite having started their production early. Fixed crash that happened in combination with the new defensive behavior. * Tweaks Tweaked the gather-point-calculations Reverted the cuddling with the planet while defending because it was more exploitable than beneficial * some more minor tweaks Using base-value in tech-trade rather than the tech's level. (needs testing) Calling optimalStagingPoint with a 1 instead of the fleet's speed to avoid different speed-fleets going to different staging-points. Starting to build ships also when someone else can reach us, not only when we can reach them. Tactical target-selection now simply goes for doing the most damage measured in BC. Sabotage now almost prefers rebellion as that is by far the most disruptive. * Update AISpyMaster.java I consider espionage and sabotage against darloks a bit of a fruitless endevour. * UI stuff Slight tweak to research-slider-allocation-management. Transports that are being sent this turn now are represented by negative pop-growth in the colony-screen. Fixed an issue where colony-screen would not have the system that was clicked on the main-screen preselected. * Update AIDiplomat.java Include Ray's improvements to AI-tech-trading. * Update AIDiplomat.java Including Ray's tech-trading-improvements. Tweaks to war-declaration-logic. * Update AIFleetCommander.java New smarth-pathing-algorithm implemented. It makes AI-fleets take stops instead of flying directly to the destination. * Update AIScientist.java Reverted recent change about when to stop allocating into a category and made some tiny tweaks to initial allocations. * Update AIShipDesigner.java Prevented two rare but possible lock-ups regarding scrapping all designs and fixed an issue where a weaponless-design would not be scrapped. * Update AISpyMaster.java No longer inciting rebellions on opponents not at war with. * Update NewShipTemplate.java Fixed an issue that allowed weaponless designs to be made. * Update ShipFleet.java Fixed an issue with incorrect display of ETA when fleet passed nebula or slower ships were scrapped during the travel. * Update Empire.java Fix for ships can't see other ships at 0 range after scanner-rework. * Update AIFleetCommander.java Fixed that buffering had broken hyperspace-communication-usage. Removed a previous change about overestimating how much to send to a colony. * Update AIDiplomat.java Preparations for how alliances could work. But afterall commented out because it just doesn't feel right. * Update AIDiplomat.java Hostility now impacts readyness for war and alliances. * Update AIFleetCommander.java Now giving cover to ongoing invasions * Update AIScientist.java Adjusted values of a bunch of techs. * Update AIShipCaptain.java Fixed accidental removal of range-adjustment in new target-selection-formula and removed unused code. * Update NewShipTemplate.java Allowing missiles to be used again under certain circumstances, taking ECM into account and basing weapon-decision on actual shield-levels rather than best possible. * Update TechMissileWeapon.java Fixed that 2-rack-missiles didn't have +1 speed as they should have according to official strategy-guide. * Update AIScientist.java Tech-Slider-Allocations now depend on racial-bonuses, not leader-personality. * Immersive Xilmi-AI When set to AI: Selectable, the Xilmi AI now goes in immersive-mode, once again making numerous uses of leader-traits. * Update CombatStackColony.java Fixed a bug, that planets without missile-bases always absorbed damage as if they already had a shield-built, even if they had none and even if they were in a nebula. * Tactical combat improvements Can now detect when someone protects another stack with repulsor-beams and retreats, when it cannot counter it with long-range-weapons. Optimal range for firing missiles increased by repulsor-radius so missile-ships won't be affected by the can't counter repulsors-detection. Missiles will now be held back until getting closer to prevent target from dodging them easily. Unused specials like Repulsor will no longer prevent ships from kiting. * Update AIShipCaptain.java Only kite when there's either repulsor-beam or missile-weapons installed on the ship. * Update AIFleetCommander.java Defending is only half as desirable as attacking now. * Immersive Xilmi-AI Lot's of changes for the personality-mode of Xilmi-AI. * Update DiplomaticEmbassy.java Fix for one empire still holding a grudge against the other when signing a peace-treaty. * Update AIShipCaptain.java Somehow the Xilmi-AI must have had conquered a system with a missile-base on it against another type of AI and then crashed at this place, I didn't even think it would get to for a colony. * Update AISpyMaster.java No longer consider computer-advantage for how much to spend into counter-espionage. * Race-fitting-playstyles implemented and leader-specfic-self-restrictions removed. * Update AIGeneral.java Invader-AI back to normal victim-selection. * Update AIGovernor.java Turns out espionage didn't work like I thought it would. So Darlok just building ships and relying on stealing techs was a bad idea. (You can only steal techs below your highest level in any given tree!) * Update AIDiplomat.java Fixed issue where AI wouldn't allow the player to ask for tech-trades and where they would take deals that are horrible for themselves when trading with other AIs. Trades are now usually all done within a 66%-150% tech-cost-range. * Update AIGeneral.java Giving themselves a personality/objective-combination that fits their behavior. * Update AIDiplomat.java Tech exchange only will work within same tier now. * Update AIGeneral.java Removed setting of personalities as this causes issue with missing texts. * Update AIScientist.java Fixed issue for Silicoids trading for Eco-restoration-techs. * Update ColonyDefense.java * Update ColonyDefense.java Shield will now only be built automatically under the following circumstances: There's missile-bases existing There's missile-bases needing to be upgraded There's missile-bases to be built * Update AIDiplomat.java Avoid false positives in war-declaration for incoming fleets when the system in question was only recently colonized. * Update AIShipCaptain.java Fixed a rare but not impossible crash. * Update AIDiplomat.java No longer accept joint-war-proposals from empires we like less than who they propose as victim. * Update AIGovernor.java Now building missile-bases... under very specific and rare circumstances. * Update AIShipCaptain.java Fixed crash when handling missile-bases. Individual stacks that can't find a target to attack no longer automatically retreat and instead let their behavior be governed by whether the whole fleet would want to retreat. * Update ColonyDefense.java Reverted previous changes which also happened to prevent AI from building shields. * Update CombatStackShip.java Fixed issue where multi-shot-weapons weren't reported as used when they were used. * Update AIFleetCommander.java Fleets now are split depending on their warp-speed unless they are on the way to their final-attack-target. * Update AIDiplomat.java Knowing about uncolonized systems no longer prevents wars. * Update CombatStackShip.java Revert change to shipComponentIsUsed * Update AIShipCaptain.java Moved logic that detects if a weapon has been used to this file. * Update AIScientist.java Try to avoid researching techs we know our neighbors already have since we can trade for it or steal it. * Update AIFleetCommander.java Colony ships now only ignore distance if they are huge as otherwise ignoring distance was horrible in late-game with hyperspace-communications. Keeping scout-designs around for longer. * Fixed a very annoying issue that caused eco-spending to become... insufficient and thus people to die when adjusting espionage- or security-spending. * Reserve-management-improvements Rich and Ultra-Rich planets now put their production into reserve when they would otherwise conduct research. Reserve will now try to keep an emergency-reserve for dealing with events like Supernova. Exceeding twice the amount of that reserve will always be spent so the money doesn't just lie around unused, when there's no new colonies that still need industry. * Update AIShipCaptain.java Removed an unneccessary white line 8[ * Update AIFleetCommander.java Reversed keeping scouts for longer * Update AIGovernor.java no industry, when under siege * Update AIGovernor.java Small fixed to sieged colonies building industry when they shouldn't. * Update Rotp.java Versioning 0.93a Co-authored-by: rayfowler <58891984+rayfowler@users.noreply.github.com>",https://github.com/rayfowler/rotp-public/commit/5a12028c875d802c26f3adf1352c61a7e720bfb9,,,src/rotp/model/ai/xilmi/AIScientist.java,3,java,False,2021-06-03T16:54:07Z "public void openFileSelector() { boolean noFileDialog = false; String fname = Utils.getUniquePcapFileName(this); Intent intent = new Intent(Intent.ACTION_CREATE_DOCUMENT); intent.addCategory(Intent.CATEGORY_OPENABLE); intent.setType(""*/*""); intent.putExtra(Intent.EXTRA_TITLE, fname); if(Utils.supportsFileDialog(this, intent)) { try { pcapFileLauncher.launch(intent); } catch (ActivityNotFoundException e) { noFileDialog = true; } } else noFileDialog = true; if(noFileDialog) { Log.w(TAG, ""No app found to handle file selection""); // Pick default path Uri uri = Utils.getInternalStorageFile(this, fname); if(uri != null) { usingMediaStore = true; startWithPcapFile(uri); } else Utils.showToastLong(this, R.string.no_activity_file_selection); } }","public void openFileSelector() { boolean noFileDialog = false; String fname = Utils.getUniquePcapFileName(this); Intent intent = new Intent(Intent.ACTION_CREATE_DOCUMENT); intent.addCategory(Intent.CATEGORY_OPENABLE); intent.setType(""*/*""); intent.putExtra(Intent.EXTRA_TITLE, fname); if(Utils.supportsFileDialog(this, intent)) { try { pcapFileLauncher.launch(intent); } catch (ActivityNotFoundException e) { noFileDialog = true; } } else noFileDialog = true; if(noFileDialog) { Log.w(TAG, ""No app found to handle file selection""); // Pick default path Uri uri = Utils.getInternalStorageFile(this, fname); if(uri != null) { usingMediaStore = true; // NOTE: cannot be persisted as it was not invoked via Intent startWithPcapFile(uri, false); } else Utils.showToastLong(this, R.string.no_activity_file_selection); } }","Fix SecurityException with PCAP file dump on Android TV When no file manager was available, takePersistableUriPermission was called without an Intent (and the corresponding FLAG_GRANT_PERSISTABLE_URI_PERMISSION flag), causing a SecurityException. Fixes #176",https://github.com/emanuele-f/PCAPdroid/commit/3364a4946ef4a852213271a2a57fdbd8aa57ae1d,,,app/src/main/java/com/emanuelef/remote_capture/activities/MainActivity.java,3,java,False,2022-01-20T23:17:14Z "@Override public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { if (isJettyMode() && !request.getContextPath().startsWith(CONTEXT_PATH)) { return; } if (log.isDebug()) { logDebug(BaseMessages.getString(PKG, ""GetWorkflowStatusServlet.Log.WorkflowStatusRequested"")); } PrintWriter out = response.getWriter(); // The type of information to request // String typeString = request.getParameter(PARAMETER_TYPE); // The name of the location is also in a parameter // String locationName = request.getParameter(PARAMETER_LOCATION); response.setContentType(""application/json""); response.setCharacterEncoding(Const.XML_ENCODING); try { // validate the parameters // if (StringUtils.isEmpty(typeString)) { throw new HopException( ""Please specify the type of execution information to register with parameter 'type'""); } Type type = Type.valueOf(typeString); if (StringUtils.isEmpty(locationName)) { throw new HopException( ""Please specify the name of the execution information location to register at with parameter 'location'""); } if (log.isDebug()) { logDebug( ""Execution information requested of type "" + typeString + "" and location "" + locationName); } // Look up the location in the metadata. // MultiMetadataProvider provider = pipelineMap.getHopServerConfig().getMetadataProvider(); IHopMetadataSerializer serializer = provider.getSerializer(ExecutionInfoLocation.class); ExecutionInfoLocation location = serializer.load(locationName); if (location == null) { throw new HopException(""Unable to find execution information location "" + locationName); } IExecutionInfoLocation iLocation = location.getExecutionInfoLocation(); // Initialize the location. iLocation.initialize(variables, provider); try { switch (type) { case state: { // Get the state of an execution: we need an execution ID // String id = request.getParameter(PARAMETER_ID); if (StringUtils.isEmpty(id)) { throw new HopException( ""Please specify the ID of execution state with parameter 'id'""); } ExecutionState executionState = location.getExecutionInfoLocation().getExecutionState(id); HopJson.newMapper().writeValue(out, executionState); } break; case ids: { String children = request.getParameter(PARAMETER_CHILDREN); boolean includeChildren = ""Y"".equalsIgnoreCase(children) || ""true"".equalsIgnoreCase(children); String limit = request.getParameter(PARAMETER_LIMIT); int limitNr = Const.toInt(limit, 100); List ids = location.getExecutionInfoLocation().getExecutionIds(includeChildren, limitNr); HopJson.newMapper().writeValue(out, ids); } break; case execution: { // Get an execution: we need an execution ID // String id = request.getParameter(PARAMETER_ID); if (StringUtils.isEmpty(id)) { throw new HopException(""Please specify the execution ID with parameter 'id'""); } Execution execution = location.getExecutionInfoLocation().getExecution(id); HopJson.newMapper().writeValue(out, execution); } break; case children: { String id = request.getParameter(PARAMETER_ID); if (StringUtils.isEmpty(id)) { throw new HopException( ""Please specify the parent execution ID with parameter 'id'""); } List children = location.getExecutionInfoLocation().findExecutions(id); HopJson.newMapper().writeValue(out, children); } break; case data: { // Get a execution data: we need an execution ID and its parent // String parentId = request.getParameter(PARAMETER_PARENT_ID); if (StringUtils.isEmpty(parentId)) { throw new HopException( ""Please specify the parent execution ID with parameter 'parentId'""); } String id = request.getParameter(""id""); if (StringUtils.isEmpty(id)) { throw new HopException(""Please specify the execution ID with parameter 'id'""); } ExecutionData data = location.getExecutionInfoLocation().getExecutionData(parentId, id); HopJson.newMapper().writeValue(out, data); } break; case lastExecution: { // Get the last execution: we need an execution type and a name // String name = request.getParameter(PARAMETER_NAME); if (StringUtils.isEmpty(name)) { throw new HopException( ""Please specify the name of the last execution to find with parameter 'name'""); } String execType = request.getParameter(PARAMETER_EXEC_TYPE); if (StringUtils.isEmpty(execType)) { throw new HopException( ""Please specify the type of the last execution to find with parameter 'execType'""); } ExecutionType executionType = ExecutionType.valueOf(execType); Execution execution = location.getExecutionInfoLocation().findLastExecution(executionType, name); HopJson.newMapper().writeValue(out, execution); } break; case childIds: { String execType = request.getParameter(PARAMETER_EXEC_TYPE); if (StringUtils.isEmpty(execType)) { throw new HopException( ""Please specify the type of execution to find children for with parameter 'execType'""); } ExecutionType executionType = ExecutionType.valueOf(execType); String id = request.getParameter(PARAMETER_ID); if (StringUtils.isEmpty(id)) { throw new HopException( ""Please specify the ID of execution to find children for with parameter 'id'""); } List ids = location.getExecutionInfoLocation().findChildIds(executionType, id); HopJson.newMapper().writeValue(out, ids); } break; case parentId: { String id = request.getParameter(PARAMETER_ID); if (StringUtils.isEmpty(id)) { throw new HopException( ""Please specify the child execution ID to find the parent for with parameter 'id'""); } String parentId = location.getExecutionInfoLocation().findParentId(id); HopJson.newMapper().writeValue(out, parentId); } break; default: StringBuilder message = new StringBuilder(""Unknown update type: "" + type + "". Allowed values are: ""); for (Type typeValue : Type.values()) { message.append(typeValue.name()).append("" ""); } throw new HopException(message.toString()); } } finally { iLocation.close(); } } catch (Exception e) { String message = Const.getStackTracker(e); HopJson.newMapper().writeValue(out, message); response.setStatus(500); } }","@Override public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { if (isJettyMode() && !request.getContextPath().startsWith(CONTEXT_PATH)) { return; } if (log.isDebug()) { logDebug(BaseMessages.getString(PKG, ""GetWorkflowStatusServlet.Log.WorkflowStatusRequested"")); } PrintWriter out = response.getWriter(); // The type of information to request // String typeString = request.getParameter(PARAMETER_TYPE); // The name of the location is also in a parameter // String locationName = request.getParameter(PARAMETER_LOCATION); response.setContentType(""application/json""); response.setCharacterEncoding(Const.XML_ENCODING); try { // validate the parameters // if (StringUtils.isEmpty(typeString)) { throw new HopException( ""Please specify the type of execution information to register with parameter 'type'""); } Type type = Type.valueOf(typeString); if (StringUtils.isEmpty(locationName)) { throw new HopException( ""Please specify the name of the execution information location to register at with parameter 'location'""); } if (log.isDebug()) { logDebug( ""Execution information requested of type "" + typeString + "" and location "" + locationName); } // Look up the location in the metadata. // MultiMetadataProvider provider = pipelineMap.getHopServerConfig().getMetadataProvider(); IHopMetadataSerializer serializer = provider.getSerializer(ExecutionInfoLocation.class); ExecutionInfoLocation location = serializer.load(locationName); if (location == null) { throw new HopException(""Unable to find execution information location "" + locationName); } IExecutionInfoLocation iLocation = location.getExecutionInfoLocation(); // Initialize the location. iLocation.initialize(variables, provider); try { switch (type) { case STATE: { // Get the state of an execution: we need an execution ID // String id = request.getParameter(PARAMETER_ID); if (StringUtils.isEmpty(id)) { throw new HopException( ""Please specify the ID of execution state with parameter 'id'""); } ExecutionState executionState = location.getExecutionInfoLocation().getExecutionState(id); outputExecutionStateAsJson(out, executionState); } break; case IDS: { String children = request.getParameter(PARAMETER_CHILDREN); boolean includeChildren = ""Y"".equalsIgnoreCase(children) || ""true"".equalsIgnoreCase(children); String limit = request.getParameter(PARAMETER_LIMIT); int limitNr = Const.toInt(limit, 100); List ids = location.getExecutionInfoLocation().getExecutionIds(includeChildren, limitNr); outputExecutionIdsAsJson(out, ids); } break; case EXECUTION: { // Get an execution: we need an execution ID // String id = request.getParameter(PARAMETER_ID); if (StringUtils.isEmpty(id)) { throw new HopException(""Please specify the execution ID with parameter 'id'""); } Execution execution = location.getExecutionInfoLocation().getExecution(id); outputExecutionAsJson(out, execution); } break; case CHILDREN: { String id = request.getParameter(PARAMETER_ID); if (StringUtils.isEmpty(id)) { throw new HopException( ""Please specify the parent execution ID with parameter 'id'""); } List children = location.getExecutionInfoLocation().findExecutions(id); outputExecutionChildrenAsJson(out, children); } break; case DATA: { // Get execution data: we need an execution ID and its parent // String parentId = request.getParameter(PARAMETER_PARENT_ID); if (StringUtils.isEmpty(parentId)) { throw new HopException( ""Please specify the parent execution ID with parameter 'parentId'""); } String id = request.getParameter(""id""); if (StringUtils.isEmpty(id)) { throw new HopException(""Please specify the execution ID with parameter 'id'""); } ExecutionData data = location.getExecutionInfoLocation().getExecutionData(parentId, id); outputExecutionDataAsJson(out, data); } break; case LAST_EXECUTION: { // Get the last execution: we need an execution type and a name // String name = request.getParameter(PARAMETER_NAME); if (StringUtils.isEmpty(name)) { throw new HopException( ""Please specify the name of the last execution to find with parameter 'name'""); } String execType = request.getParameter(PARAMETER_EXEC_TYPE); if (StringUtils.isEmpty(execType)) { throw new HopException( ""Please specify the type of the last execution to find with parameter 'execType'""); } ExecutionType executionType = ExecutionType.valueOf(execType); Execution execution = location.getExecutionInfoLocation().findLastExecution(executionType, name); outputExecutionAsJson(out, execution); } break; case CHILD_IDS: { String execType = request.getParameter(PARAMETER_EXEC_TYPE); if (StringUtils.isEmpty(execType)) { throw new HopException( ""Please specify the type of execution to find children for with parameter 'execType'""); } ExecutionType executionType = ExecutionType.valueOf(execType); String id = request.getParameter(PARAMETER_ID); if (StringUtils.isEmpty(id)) { throw new HopException( ""Please specify the ID of execution to find children for with parameter 'id'""); } List ids = location.getExecutionInfoLocation().findChildIds(executionType, id); outputExecutionIdsAsJson(out, ids); } break; case PARENT_ID: { String id = request.getParameter(PARAMETER_ID); if (StringUtils.isEmpty(id)) { throw new HopException( ""Please specify the child execution ID to find the parent for with parameter 'id'""); } String parentId = location.getExecutionInfoLocation().findParentId(id); outputIdAsJson(out, parentId); } break; default: StringBuilder message = new StringBuilder(""Unknown update type: "" + type + "". Allowed values are: ""); for (Type typeValue : Type.values()) { message.append(typeValue.name()).append("" ""); } throw new HopException(message.toString()); } } finally { iLocation.close(); } } catch (Exception e) { String message = Const.getStackTracker(e); try { HopJson.newMapper().writeValue(out, message); } catch (IOException | DataBindingException ex) { throw new ServletException( ""Error writing execution state as JSON to servlet output stream"", ex); } response.setStatus(500); } }",Fix #1859 : Sonar Vulnerability issues,https://github.com/apache/hop/commit/562dc41d7efe4bd7bb43ac0910a8e1e63b2951c1,,,engine/src/main/java/org/apache/hop/www/GetExecutionInfoServlet.java,3,java,False,2022-12-01T11:21:34Z "@Override public RowBuilder newRowBuilder(FieldDescriptor[] outputFieldDescriptors) { return new RowBuilder() { private Object[] values = new Object[outputFieldDescriptors.length]; @Override public void setField(String fieldName, Object fieldValue) { values[fieldDescriptorIndices.get(fieldName)] = fieldValue; } @Override public void setFields(Map valueMap) { valueMap.entrySet().forEach( entry -> values[fieldDescriptorIndices.get(entry.getKey())] = entry.getValue()); } @Override public T buildRow(byte[] dataId) { T obj = buildObject(values); Arrays.fill(values, null); return obj; } }; }","@SuppressWarnings(""unchecked"") @Override public RowBuilder newRowBuilder(FieldDescriptor[] outputFieldDescriptors) { if (dataIDReader == null) { dataIDReader = (FieldReader) FieldUtils.getDefaultReaderForClass( dataIDFieldDescriptor.bindingClass()); } return new RowBuilder() { private Object[] values = new Object[outputFieldDescriptors.length]; @Override public void setField(String fieldName, Object fieldValue) { values[fieldDescriptorIndices.get(fieldName)] = fieldValue; } @Override public void setFields(Map valueMap) { valueMap.entrySet().forEach( entry -> values[fieldDescriptorIndices.get(entry.getKey())] = entry.getValue()); } @Override public T buildRow(byte[] dataId) { final Object dataIDObject = dataIDReader.readField(dataId); T obj = buildObject(dataIDObject, values); Arrays.fill(values, null); return obj; } }; }","Fix issues and add improvements to basic data type adapters (#1867) * Fix issues and add improvements to basic data type adapters - Fix issues with the use of primitive types - Allow the data ID field to be kept separate from the other fields so that they don't get serialized twice - Allow the naming of attribute indices - Allow no field descriptors to be supplied - Update data ID serialization to use the field writer for the class instead of toString - Fix stack overflow on SimpleAbstractDataAdapter Signed-off-by: Johnathan Garrett * formatting Co-authored-by: Rich Fecher ",https://github.com/locationtech/geowave/commit/7fa4584f31e490dc2500804c6fd209cd062226b6,,,core/store/src/main/java/org/locationtech/geowave/core/store/adapter/AbstractDataTypeAdapter.java,3,java,False,2022-02-23T13:21:00Z "@Override public void tick() { boolean isNoClip = this.isNoPhysics(); Vector3d vector3d = this.getDeltaMovement(); if (this.xRotO == 0.0F && this.yRotO == 0.0F) { float f = MathHelper.sqrt(getHorizontalDistanceSqr(vector3d)); this.yRot = (float) (MathHelper.atan2(vector3d.x, vector3d.z) * (double) (180F / (float) Math.PI)); this.xRot = (float) (MathHelper.atan2(vector3d.y, (double) f) * (double) (180F / (float) Math.PI)); this.yRotO = this.yRot; this.xRotO = this.xRot; } BlockPos blockpos = this.blockPosition(); BlockState blockstate = this.level.getBlockState(blockpos); if (this.shakeTime > 0) { --this.shakeTime; } if (this.isInWaterOrRain()) { this.clearFire(); } this.inGroundTime = 0; Vector3d vector3d2 = this.position(); Vector3d vector3d3 = vector3d2.add(vector3d); RayTraceResult raytraceresult = this.level.clip(new RayTraceContext(vector3d2, vector3d3, RayTraceContext.BlockMode.COLLIDER, RayTraceContext.FluidMode.NONE, this)); if (raytraceresult.getType() != RayTraceResult.Type.MISS) { vector3d3 = raytraceresult.getLocation(); } while (!this.removed) { EntityRayTraceResult entityraytraceresult = this.findHitEntity(vector3d2, vector3d3); if (entityraytraceresult != null) { raytraceresult = entityraytraceresult; } if (raytraceresult != null && raytraceresult.getType() == RayTraceResult.Type.ENTITY) { Entity entity = ((EntityRayTraceResult) raytraceresult).getEntity(); Entity entity1 = this.getOwner(); if (entity instanceof PlayerEntity && entity1 instanceof PlayerEntity && !((PlayerEntity) entity1).canHarmPlayer((PlayerEntity) entity)) { raytraceresult = null; entityraytraceresult = null; } } if (raytraceresult != null && raytraceresult.getType() != RayTraceResult.Type.MISS && !isNoClip && !net.minecraftforge.event.ForgeEventFactory.onProjectileImpact(this, raytraceresult)) { this.onHit(raytraceresult); this.hasImpulse = true; } if (entityraytraceresult == null || this.getPierceLevel() <= 0) { break; } raytraceresult = null; } vector3d = this.getDeltaMovement(); double d3 = vector3d.x; double d4 = vector3d.y; double d0 = vector3d.z; if (this.isCritArrow()) { for (int i = 0; i < 4; ++i) { this.level.addParticle(ParticleTypes.CRIT, this.getX() + d3 * (double) i / 4.0D, this.getY() + d4 * (double) i / 4.0D, this.getZ() + d0 * (double) i / 4.0D, -d3, -d4 + 0.2D, -d0); } } double d5 = this.getX() + d3; double d1 = this.getY() + d4; double d2 = this.getZ() + d0; float f1 = MathHelper.sqrt(getHorizontalDistanceSqr(vector3d)); if (isNoClip) { this.yRot = (float) (MathHelper.atan2(-d3, -d0) * (double) (180F / (float) Math.PI)); } else { this.yRot = (float) (MathHelper.atan2(d3, d0) * (double) (180F / (float) Math.PI)); } this.xRot = (float) (MathHelper.atan2(d4, (double) f1) * (double) (180F / (float) Math.PI)); this.xRot = lerpRotation(this.xRotO, this.xRot); this.yRot = lerpRotation(this.yRotO, this.yRot); float f2 = 0.99F; float f3 = 0.05F; if (this.isInWater()) { for (int j = 0; j < 4; ++j) { float f4 = 0.25F; this.level.addParticle(ParticleTypes.BUBBLE, d5 - d3 * 0.25D, d1 - d4 * 0.25D, d2 - d0 * 0.25D, d3, d4, d0); } f2 = this.getWaterInertia(); } this.setDeltaMovement(vector3d.scale((double) f2)); if (!this.isNoGravity() && !isNoClip) { Vector3d vector3d4 = this.getDeltaMovement(); this.setDeltaMovement(vector3d4.x, vector3d4.y - (double) 0.05F, vector3d4.z); } this.setPos(d5, d1, d2); this.checkInsideBlocks(); if (level.isClientSide && tickCount > 1) { for (int i = 0; i < 10; i++) { double deltaX = getX() - xOld; double deltaY = getY() - yOld; double deltaZ = getZ() - zOld; double dist = Math.ceil(Math.sqrt(deltaX * deltaX + deltaY * deltaY + deltaZ * deltaZ) * 8); int counter = 0; for (double j = 0; j < dist; j++) { double coeff = j / dist; counter += level.random.nextInt(3); if (counter % (Minecraft.getInstance().options.particles.getId() == 0 ? 1 : 2 * Minecraft.getInstance().options.particles.getId()) == 0) { level.addParticle(GlowParticleData.createData(new ParticleColor(entityData.get(RED), entityData.get(GREEN), entityData.get(BLUE))), (float) (xo + deltaX * coeff), (float) (yo + deltaY * coeff), (float) (zo + deltaZ * coeff), 0.0125f * (random.nextFloat() - 0.5f), 0.0125f * (random.nextFloat() - 0.5f), 0.0125f * (random.nextFloat() - 0.5f)); } } } } }","@Override public void tick() { boolean isNoClip = this.isNoPhysics(); Vector3d vector3d = this.getDeltaMovement(); if (this.xRotO == 0.0F && this.yRotO == 0.0F) { float f = MathHelper.sqrt(getHorizontalDistanceSqr(vector3d)); this.yRot = (float) (MathHelper.atan2(vector3d.x, vector3d.z) * (double) (180F / (float) Math.PI)); this.xRot = (float) (MathHelper.atan2(vector3d.y, (double) f) * (double) (180F / (float) Math.PI)); this.yRotO = this.yRot; this.xRotO = this.xRot; } BlockPos blockpos = this.blockPosition(); BlockState blockstate = this.level.getBlockState(blockpos); if (this.shakeTime > 0) { --this.shakeTime; } if (this.isInWaterOrRain()) { this.clearFire(); } this.inGroundTime = 0; Vector3d vector3d2 = this.position(); Vector3d vector3d3 = vector3d2.add(vector3d); RayTraceResult raytraceresult = this.level.clip(new RayTraceContext(vector3d2, vector3d3, RayTraceContext.BlockMode.COLLIDER, RayTraceContext.FluidMode.NONE, this)); if (raytraceresult.getType() != RayTraceResult.Type.MISS) { vector3d3 = raytraceresult.getLocation(); } while (!this.removed) { EntityRayTraceResult entityraytraceresult = this.findHitEntity(vector3d2, vector3d3); if (entityraytraceresult != null) { raytraceresult = entityraytraceresult; } if (raytraceresult != null && raytraceresult.getType() == RayTraceResult.Type.ENTITY) { Entity entity = ((EntityRayTraceResult) raytraceresult).getEntity(); Entity entity1 = this.getOwner(); if(entity.noPhysics) { raytraceresult = null; entityraytraceresult = null; } else if (entity instanceof PlayerEntity && entity1 instanceof PlayerEntity && !((PlayerEntity) entity1).canHarmPlayer((PlayerEntity) entity)) { raytraceresult = null; entityraytraceresult = null; } } if (raytraceresult != null && raytraceresult.getType() != RayTraceResult.Type.MISS && !isNoClip && !net.minecraftforge.event.ForgeEventFactory.onProjectileImpact(this, raytraceresult)) { this.onHit(raytraceresult); this.hasImpulse = true; } if (entityraytraceresult == null || this.getPierceLevel() <= 0) { break; } raytraceresult = null; } vector3d = this.getDeltaMovement(); double d3 = vector3d.x; double d4 = vector3d.y; double d0 = vector3d.z; if (this.isCritArrow()) { for (int i = 0; i < 4; ++i) { this.level.addParticle(ParticleTypes.CRIT, this.getX() + d3 * (double) i / 4.0D, this.getY() + d4 * (double) i / 4.0D, this.getZ() + d0 * (double) i / 4.0D, -d3, -d4 + 0.2D, -d0); } } double d5 = this.getX() + d3; double d1 = this.getY() + d4; double d2 = this.getZ() + d0; float f1 = MathHelper.sqrt(getHorizontalDistanceSqr(vector3d)); if (isNoClip) { this.yRot = (float) (MathHelper.atan2(-d3, -d0) * (double) (180F / (float) Math.PI)); } else { this.yRot = (float) (MathHelper.atan2(d3, d0) * (double) (180F / (float) Math.PI)); } this.xRot = (float) (MathHelper.atan2(d4, (double) f1) * (double) (180F / (float) Math.PI)); this.xRot = lerpRotation(this.xRotO, this.xRot); this.yRot = lerpRotation(this.yRotO, this.yRot); float f2 = 0.99F; float f3 = 0.05F; if (this.isInWater()) { for (int j = 0; j < 4; ++j) { float f4 = 0.25F; this.level.addParticle(ParticleTypes.BUBBLE, d5 - d3 * 0.25D, d1 - d4 * 0.25D, d2 - d0 * 0.25D, d3, d4, d0); } f2 = this.getWaterInertia(); } this.setDeltaMovement(vector3d.scale((double) f2)); if (!this.isNoGravity() && !isNoClip) { Vector3d vector3d4 = this.getDeltaMovement(); this.setDeltaMovement(vector3d4.x, vector3d4.y - (double) 0.05F, vector3d4.z); } this.setPos(d5, d1, d2); this.checkInsideBlocks(); if (level.isClientSide && tickCount > 1) { for (int i = 0; i < 10; i++) { double deltaX = getX() - xOld; double deltaY = getY() - yOld; double deltaZ = getZ() - zOld; double dist = Math.ceil(Math.sqrt(deltaX * deltaX + deltaY * deltaY + deltaZ * deltaZ) * 8); int counter = 0; for (double j = 0; j < dist; j++) { double coeff = j / dist; counter += level.random.nextInt(3); if (counter % (Minecraft.getInstance().options.particles.getId() == 0 ? 1 : 2 * Minecraft.getInstance().options.particles.getId()) == 0) { level.addParticle(GlowParticleData.createData(new ParticleColor(entityData.get(RED), entityData.get(GREEN), entityData.get(BLUE))), (float) (xo + deltaX * coeff), (float) (yo + deltaY * coeff), (float) (zo + deltaZ * coeff), 0.0125f * (random.nextFloat() - 0.5f), 0.0125f * (random.nextFloat() - 0.5f), 0.0125f * (random.nextFloat() - 0.5f)); } } } } }","Fix EntitySpellArrow infinite loop when hitting Entity with noPhysics flag set. (#283) Co-authored-by: Mario Ströhlein ",https://github.com/baileyholl/Ars-Nouveau/commit/70d81855e85191f86b00d6d058040ebb93e5bfb9,,,src/main/java/com/hollingsworth/arsnouveau/common/entity/EntitySpellArrow.java,3,java,False,2021-06-16T02:13:56Z "@Inject(method = ""rebnderInner"", at = @At(value = ""INVOKE"", target = ""Lnet/fabricmc/fabric/api/renderer/v1/model/FabricBakedModel;emitBlockQuads"", ordinal = 0)) private void emitCustomBlockQuads(BlockState blockState, BlockPos blockPos, boolean defaultAo, FabricBakedModel model, MatrixStack matrixStack, CallbackInfo ci) { Block block = blockState.getBlock(); if (CustomBakedModels.shouldUseCustomModel(block, blockPos)) { ((FabricBakedModel) CustomBakedModels.models.get(block)).emitBlockQuads(region, blockState, blockPos, randomSupplier, this); } }","@Inject(method = ""rebnderInner"", at = @At(value = ""INVOKE"", target = ""Lnet/fabricmc/fabric/api/renderer/v1/model/FabricBakedModel;emitBlockQuads"", ordinal = 0)) private void emitCustomBlockQuads(BlockState blockState, BlockPos blockPos, boolean defaultAo, FabricBakedModel model, MatrixStack matrixStack, CallbackInfo ci) { Block block = blockState.getBlock(); if (CustomBakedModels.shouldUseCustomModel(block, blockPos)) { FabricBakedModel customModel = (FabricBakedModel) CustomBakedModels.models.get(block); if (customModel != null) { customModel.emitBlockQuads(region, blockState, blockPos, randomSupplier, this); } } }",fix null ptr crash in worldEaterMineHelper,https://github.com/plusls/oh-my-minecraft-client/commit/63ec4ab105bc581dd1b669b2352b13e070875991,,,src/main/java/com/plusls/ommc/mixin/feature/worldEaterMineHelper/canvas/MixinTerrainRenderContext.java,3,java,False,2021-03-13T15:45:05Z "@TaskAction public void createBom() { if (!outputFormat.get().trim().equalsIgnoreCase(""all"") && !outputFormat.get().trim().equalsIgnoreCase(""xml"") && !outputFormat.get().trim().equalsIgnoreCase(""json"")) { throw new GradleException(""Unsupported output format. Must be one of all, xml, or json""); } CycloneDxSchema.Version version = computeSchemaVersion(); logParameters(); getLogger().info(MESSAGE_RESOLVING_DEPS); final Set builtDependencies = getProject() .getRootProject() .getSubprojects() .stream() .map(p -> p.getGroup() + "":"" + p.getName() + "":"" + p.getVersion()) .collect(Collectors.toSet()); final Metadata metadata = createMetadata(); final Set configurations = getProject().getAllprojects().stream() .flatMap(p -> p.getConfigurations().stream()) .filter(configuration -> shouldIncludeConfiguration(configuration) && !shouldSkipConfiguration(configuration) && DependencyUtils.canBeResolved(configuration)) .collect(Collectors.toSet()); final Set components = new HashSet<>(); final Map dependencies = new HashMap<>(); for (Configuration configuration : configurations) { final Set componentsFromConfig = Collections.synchronizedSet(new LinkedHashSet<>()); final ResolvedConfiguration resolvedConfiguration = configuration.getResolvedConfiguration(); final List depsFromConfig = Collections.synchronizedList(new ArrayList<>()); final org.cyclonedx.model.Dependency moduleDependency = new org.cyclonedx.model.Dependency(metadata.getComponent().getPurl()); final Set directModuleDependencies = configuration.getResolvedConfiguration() .getFirstLevelModuleDependencies(); for (ResolvedDependency directModuleDependency : directModuleDependencies) { ResolvedArtifact directJarArtifact = getJarArtifact(directModuleDependency); if (directJarArtifact != null) { moduleDependency.addDependency(new org.cyclonedx.model.Dependency(generatePackageUrl(directJarArtifact))); dependencies.putAll(buildDependencyGraph(directModuleDependency, directJarArtifact)); } } dependencies.compute(metadata.getComponent().getPurl(), (k, v) -> { if (v == null) { return moduleDependency; } else if (moduleDependency.getDependencies() != null) { moduleDependency.getDependencies().stream().forEach(v::addDependency); } return v; }); resolvedConfiguration.getResolvedArtifacts().forEach(artifact -> { // Don't include other resources built from this Gradle project. final String dependencyName = DependencyUtils.getDependencyName(artifact); if (builtDependencies.contains(dependencyName)) { return; } depsFromConfig.add(dependencyName); // Convert into a Component and augment with pom metadata if available. final Component component = convertArtifact(artifact, version); augmentComponentMetadata(component, dependencyName); componentsFromConfig.add(component); }); Collections.sort(depsFromConfig); components.addAll(componentsFromConfig); } writeBom(metadata, components, dependencies.values(), version); }","@TaskAction public void createBom() { if (!outputFormat.get().trim().equalsIgnoreCase(""all"") && !outputFormat.get().trim().equalsIgnoreCase(""xml"") && !outputFormat.get().trim().equalsIgnoreCase(""json"")) { throw new GradleException(""Unsupported output format. Must be one of all, xml, or json""); } CycloneDxSchema.Version version = computeSchemaVersion(); logParameters(); getLogger().info(MESSAGE_RESOLVING_DEPS); final Set builtDependencies = getProject() .getRootProject() .getSubprojects() .stream() .map(p -> p.getGroup() + "":"" + p.getName() + "":"" + p.getVersion()) .collect(Collectors.toSet()); final Metadata metadata = createMetadata(); final Set configurations = getProject().getAllprojects().stream() .flatMap(p -> p.getConfigurations().stream()) .filter(configuration -> shouldIncludeConfiguration(configuration) && !shouldSkipConfiguration(configuration) && DependencyUtils.canBeResolved(configuration)) .collect(Collectors.toSet()); final Set components = new HashSet<>(); final Map dependencies = new HashMap<>(); for (Configuration configuration : configurations) { final Set componentsFromConfig = Collections.synchronizedSet(new LinkedHashSet<>()); final ResolvedConfiguration resolvedConfiguration = configuration.getResolvedConfiguration(); final List depsFromConfig = Collections.synchronizedList(new ArrayList<>()); final org.cyclonedx.model.Dependency moduleDependency = new org.cyclonedx.model.Dependency(metadata.getComponent().getPurl()); final Set directModuleDependencies = configuration.getResolvedConfiguration() .getFirstLevelModuleDependencies(); for (ResolvedDependency directModuleDependency : directModuleDependencies) { ResolvedArtifact directJarArtifact = getJarArtifact(directModuleDependency); if (directJarArtifact != null) { moduleDependency.addDependency(new org.cyclonedx.model.Dependency(generatePackageUrl(directJarArtifact))); buildDependencyGraph(dependencies, directModuleDependency, directJarArtifact); } } dependencies.compute(metadata.getComponent().getPurl(), (k, v) -> { if (v == null) { return moduleDependency; } else if (moduleDependency.getDependencies() != null) { moduleDependency.getDependencies().stream().forEach(v::addDependency); } return v; }); resolvedConfiguration.getResolvedArtifacts().forEach(artifact -> { // Don't include other resources built from this Gradle project. final String dependencyName = DependencyUtils.getDependencyName(artifact); if (builtDependencies.contains(dependencyName)) { return; } depsFromConfig.add(dependencyName); // Convert into a Component and augment with pom metadata if available. final Component component = convertArtifact(artifact, version); augmentComponentMetadata(component, dependencyName); componentsFromConfig.add(component); }); Collections.sort(depsFromConfig); components.addAll(componentsFromConfig); } writeBom(metadata, components, dependencies.values(), version); }","Prevent stack overflow in case of loop in the dependency graph Signed-off-by: callier ",https://github.com/CycloneDX/cyclonedx-gradle-plugin/commit/369ddaf0e7a9430f3f7647d3c83b95525889f75c,,,src/main/java/org/cyclonedx/gradle/CycloneDxTask.java,3,java,False,2022-08-31T08:09:41Z "@Override public void logout(HttpServletRequest request, HttpServletResponse response) throws ServletException { throw new UnsupportedOperationException(""Not supported yet.""); }","@Override public void logout(HttpServletRequest request, HttpServletResponse response) throws ServletException { while (request instanceof HttpServletRequestWrapper wrapper) { request = (HttpServletRequest) wrapper.getRequest(); } if (request instanceof WebApplicationRequest webAppRequest) { webAppRequest.setUserPrincipal(null); } }",Fixes issue #1888 - Update Checkstyle (#1889),https://github.com/piranhacloud/piranha/commit/977a172b9079eb6503a3834e20058525353db920,,,extension/security-file/src/main/java/cloud/piranha/extension/security/file/FileAuthenticationManager.java,3,java,False,2021-09-06T14:55:13Z "public void updateSettings() { ContentResolver resolver = mContext.getContentResolver(); boolean updateRotation = false; synchronized (mLock) { mEndcallBehavior = Settings.System.getIntForUser(resolver, Settings.System.END_BUTTON_BEHAVIOR, Settings.System.END_BUTTON_BEHAVIOR_DEFAULT, UserHandle.USER_CURRENT); mIncallPowerBehavior = Settings.Secure.getIntForUser(resolver, Settings.Secure.INCALL_POWER_BUTTON_BEHAVIOR, Settings.Secure.INCALL_POWER_BUTTON_BEHAVIOR_DEFAULT, UserHandle.USER_CURRENT); mIncallBackBehavior = Settings.Secure.getIntForUser(resolver, Settings.Secure.INCALL_BACK_BUTTON_BEHAVIOR, Settings.Secure.INCALL_BACK_BUTTON_BEHAVIOR_DEFAULT, UserHandle.USER_CURRENT); mSystemNavigationKeysEnabled = Settings.Secure.getIntForUser(resolver, Settings.Secure.SYSTEM_NAVIGATION_KEYS_ENABLED, 0, UserHandle.USER_CURRENT) == 1; mRingerToggleChord = Settings.Secure.getIntForUser(resolver, Settings.Secure.VOLUME_HUSH_GESTURE, VOLUME_HUSH_OFF, UserHandle.USER_CURRENT); mPowerButtonSuppressionDelayMillis = Settings.Global.getInt(resolver, Settings.Global.POWER_BUTTON_SUPPRESSION_DELAY_AFTER_GESTURE_WAKE, POWER_BUTTON_SUPPRESSION_DELAY_DEFAULT_MILLIS); if (!mContext.getResources() .getBoolean(com.android.internal.R.bool.config_volumeHushGestureEnabled)) { mRingerToggleChord = Settings.Secure.VOLUME_HUSH_OFF; } mTorchLongPressPowerEnabled = LineageSettings.System.getIntForUser( resolver, LineageSettings.System.TORCH_LONG_PRESS_POWER_GESTURE, 0, UserHandle.USER_CURRENT) == 1; mTorchTimeout = LineageSettings.System.getIntForUser( resolver, LineageSettings.System.TORCH_LONG_PRESS_POWER_TIMEOUT, 0, UserHandle.USER_CURRENT); // Configure wake gesture. boolean wakeGestureEnabledSetting = Settings.Secure.getIntForUser(resolver, Settings.Secure.WAKE_GESTURE_ENABLED, 0, UserHandle.USER_CURRENT) != 0; if (mWakeGestureEnabledSetting != wakeGestureEnabledSetting) { mWakeGestureEnabledSetting = wakeGestureEnabledSetting; updateWakeGestureListenerLp(); } updateKeyAssignments(); // use screen off timeout setting as the timeout for the lockscreen mLockScreenTimeout = Settings.System.getIntForUser(resolver, Settings.System.SCREEN_OFF_TIMEOUT, 0, UserHandle.USER_CURRENT); String imId = Settings.Secure.getStringForUser(resolver, Settings.Secure.DEFAULT_INPUT_METHOD, UserHandle.USER_CURRENT); boolean hasSoftInput = imId != null && imId.length() > 0; if (mHasSoftInput != hasSoftInput) { mHasSoftInput = hasSoftInput; updateRotation = true; } mLongPressOnPowerBehavior = Settings.Global.getInt(resolver, Settings.Global.POWER_BUTTON_LONG_PRESS, mContext.getResources().getInteger( com.android.internal.R.integer.config_longPressOnPowerBehavior)); mLongPressOnPowerAssistantTimeoutMs = Settings.Global.getLong( mContext.getContentResolver(), Settings.Global.POWER_BUTTON_LONG_PRESS_DURATION_MS, mContext.getResources().getInteger( com.android.internal.R.integer.config_longPressOnPowerDurationMs)); mVeryLongPressOnPowerBehavior = Settings.Global.getInt(resolver, Settings.Global.POWER_BUTTON_VERY_LONG_PRESS, mContext.getResources().getInteger( com.android.internal.R.integer.config_veryLongPressOnPowerBehavior)); mPowerVolUpBehavior = Settings.Global.getInt(resolver, Settings.Global.KEY_CHORD_POWER_VOLUME_UP, mContext.getResources().getInteger( com.android.internal.R.integer.config_keyChordPowerVolumeUp)); } if (updateRotation) { updateRotation(true); } }","public void updateSettings() { ContentResolver resolver = mContext.getContentResolver(); boolean updateRotation = false; int mDeviceHardwareWakeKeys = mContext.getResources().getInteger( org.lineageos.platform.internal.R.integer.config_deviceHardwareWakeKeys); synchronized (mLock) { mEndcallBehavior = Settings.System.getIntForUser(resolver, Settings.System.END_BUTTON_BEHAVIOR, Settings.System.END_BUTTON_BEHAVIOR_DEFAULT, UserHandle.USER_CURRENT); mIncallPowerBehavior = Settings.Secure.getIntForUser(resolver, Settings.Secure.INCALL_POWER_BUTTON_BEHAVIOR, Settings.Secure.INCALL_POWER_BUTTON_BEHAVIOR_DEFAULT, UserHandle.USER_CURRENT); mIncallBackBehavior = Settings.Secure.getIntForUser(resolver, Settings.Secure.INCALL_BACK_BUTTON_BEHAVIOR, Settings.Secure.INCALL_BACK_BUTTON_BEHAVIOR_DEFAULT, UserHandle.USER_CURRENT); mSystemNavigationKeysEnabled = Settings.Secure.getIntForUser(resolver, Settings.Secure.SYSTEM_NAVIGATION_KEYS_ENABLED, 0, UserHandle.USER_CURRENT) == 1; mRingerToggleChord = Settings.Secure.getIntForUser(resolver, Settings.Secure.VOLUME_HUSH_GESTURE, VOLUME_HUSH_OFF, UserHandle.USER_CURRENT); mPowerButtonSuppressionDelayMillis = Settings.Global.getInt(resolver, Settings.Global.POWER_BUTTON_SUPPRESSION_DELAY_AFTER_GESTURE_WAKE, POWER_BUTTON_SUPPRESSION_DELAY_DEFAULT_MILLIS); if (!mContext.getResources() .getBoolean(com.android.internal.R.bool.config_volumeHushGestureEnabled)) { mRingerToggleChord = Settings.Secure.VOLUME_HUSH_OFF; } mTorchLongPressPowerEnabled = LineageSettings.System.getIntForUser( resolver, LineageSettings.System.TORCH_LONG_PRESS_POWER_GESTURE, 0, UserHandle.USER_CURRENT) == 1; mTorchTimeout = LineageSettings.System.getIntForUser( resolver, LineageSettings.System.TORCH_LONG_PRESS_POWER_TIMEOUT, 0, UserHandle.USER_CURRENT); mWakeOnHomeKeyPress = (LineageSettings.System.getIntForUser(resolver, LineageSettings.System.HOME_WAKE_SCREEN, 1, UserHandle.USER_CURRENT) == 1) && ((mDeviceHardwareWakeKeys & KEY_MASK_HOME) != 0); mWakeOnBackKeyPress = (LineageSettings.System.getIntForUser(resolver, LineageSettings.System.BACK_WAKE_SCREEN, 0, UserHandle.USER_CURRENT) == 1) && ((mDeviceHardwareWakeKeys & KEY_MASK_BACK) != 0); mWakeOnMenuKeyPress = (LineageSettings.System.getIntForUser(resolver, LineageSettings.System.MENU_WAKE_SCREEN, 0, UserHandle.USER_CURRENT) == 1) && ((mDeviceHardwareWakeKeys & KEY_MASK_MENU) != 0); mWakeOnAssistKeyPress = (LineageSettings.System.getIntForUser(resolver, LineageSettings.System.ASSIST_WAKE_SCREEN, 0, UserHandle.USER_CURRENT) == 1) && ((mDeviceHardwareWakeKeys & KEY_MASK_ASSIST) != 0); mWakeOnAppSwitchKeyPress = (LineageSettings.System.getIntForUser(resolver, LineageSettings.System.APP_SWITCH_WAKE_SCREEN, 0, UserHandle.USER_CURRENT) == 1) && ((mDeviceHardwareWakeKeys & KEY_MASK_APP_SWITCH) != 0); mWakeOnVolumeKeyPress = (LineageSettings.System.getIntForUser(resolver, LineageSettings.System.VOLUME_WAKE_SCREEN, 0, UserHandle.USER_CURRENT) == 1) && ((mDeviceHardwareWakeKeys & KEY_MASK_VOLUME) != 0); // Configure wake gesture. boolean wakeGestureEnabledSetting = Settings.Secure.getIntForUser(resolver, Settings.Secure.WAKE_GESTURE_ENABLED, 0, UserHandle.USER_CURRENT) != 0; if (mWakeGestureEnabledSetting != wakeGestureEnabledSetting) { mWakeGestureEnabledSetting = wakeGestureEnabledSetting; updateWakeGestureListenerLp(); } updateKeyAssignments(); // use screen off timeout setting as the timeout for the lockscreen mLockScreenTimeout = Settings.System.getIntForUser(resolver, Settings.System.SCREEN_OFF_TIMEOUT, 0, UserHandle.USER_CURRENT); String imId = Settings.Secure.getStringForUser(resolver, Settings.Secure.DEFAULT_INPUT_METHOD, UserHandle.USER_CURRENT); boolean hasSoftInput = imId != null && imId.length() > 0; if (mHasSoftInput != hasSoftInput) { mHasSoftInput = hasSoftInput; updateRotation = true; } mLongPressOnPowerBehavior = Settings.Global.getInt(resolver, Settings.Global.POWER_BUTTON_LONG_PRESS, mContext.getResources().getInteger( com.android.internal.R.integer.config_longPressOnPowerBehavior)); mLongPressOnPowerAssistantTimeoutMs = Settings.Global.getLong( mContext.getContentResolver(), Settings.Global.POWER_BUTTON_LONG_PRESS_DURATION_MS, mContext.getResources().getInteger( com.android.internal.R.integer.config_longPressOnPowerDurationMs)); mVeryLongPressOnPowerBehavior = Settings.Global.getInt(resolver, Settings.Global.POWER_BUTTON_VERY_LONG_PRESS, mContext.getResources().getInteger( com.android.internal.R.integer.config_veryLongPressOnPowerBehavior)); mPowerVolUpBehavior = Settings.Global.getInt(resolver, Settings.Global.KEY_CHORD_POWER_VOLUME_UP, mContext.getResources().getInteger( com.android.internal.R.integer.config_keyChordPowerVolumeUp)); } if (updateRotation) { updateRotation(true); } }","Reimplement device hardware wake keys support Author: LuK1337 Date: Mon Jun 4 10:05:37 2018 +0200 PhoneWindowManager: Improve home button wake haptic feedback handling * This fixes an issue where haptic feedback is used when screen is off and home button wake is disabled. Change-Id: I7ac4c00598cedf7f174dc99629f55dc7b74b0d2a Author: Gabriele M Date: Mon Sep 26 00:43:08 2016 +0200 Fix volume keys wakeup status handling The same status flag is used for the three different volume keys, however nothing prevents users from pressing multiple keys at the same time. This allows to set the status flag with one volume key and clear it with the other volume key. Use one flag per key so that we never end up in an inconsistent state. This fixes the seldom power button issues that happen when the ""volume wake"" feature is enabled. Change-Id: I08f5f9ff696bef3dd840cff97d570e44ebe03e4e Author: Martin Brabham Date: Wed Dec 3 11:48:28 2014 -0800 Android Policy: handle volume key event as wake key when preference is set Change-Id: If9a61cd65553bf00f0efda1a75b1ab75b9129090 Author: willl03 Date: Mon Dec 8 11:13:28 2014 -0500 Only go HOME if screen is fully awake Avoid going home when hardware home button is used to wake the device on an insecure keyguard Change-Id: I5d5d8c4fff76967c29e70251f7b165205005ba11 Author: Matt Garnes Date: Tue Mar 31 14:39:38 2015 -0700 If a wake key is disabled by the user, do not wake from doze. Currently, any wake key will wake the device from a doze, even if that key has not been enabled as a wake key in Settings. If the device is 'dreaming' in the Doze state, check if the user has explicitly disabled the wake key (or never enabled the setting in the first place) before waking the device. Change-Id: I7397087c143161e8e1ddb84d0e23f6027fea0aac Author: Michael Bestas Date: Thu Dec 18 04:26:38 2014 +0200 Cleanup button wake settings (2/2) Change-Id: Ie37136cbd57c4c334321abbfa4543727e940bc43 Keep quiet when volume keys are used to wake up device - Userspace will make a 'beep' with it receives a key up, so consume that event as well. - Removed wake key check in music control code as it will already be disabled here. Change-Id: I93839acd39aec8a2ee40291f833a31f6b048c9f8 Wake Keys: enforce the wake keys overlay * Keys disabled as wake keys by the overlay were still being allowed to wake the device. This change enforces the hardwareWakeKeys settings. Change-Id: Ifde0491b2de64a7f61a101cf22f5589cb5e841e2 Allow disabling Search/Recents button wake (2/2) Change-Id: I6a2ac064efc4fe85413bf0b935c28aa7bde5d672 Author: Danny Baumann Date: Sun Nov 30 23:04:37 2014 -0600 fw/base: allow home button to wake device [1/2] Change-Id: I2b79561dcfa7e569b2e24bbabfffb11517d4d313 Change-Id: Ic294515c7200c1260ac514db23ef3778d374d727",https://github.com/LineageOS/android_frameworks_base/commit/6f24c9b705c82374cfc9d7cb799c14a1c5712207,,,services/core/java/com/android/server/policy/PhoneWindowManager.java,3,java,False,2017-12-25T15:54:07Z "@Override public SurveyDataTableData retrieveSurvey(String surveyName) { SQLInjectionValidator.validateSQLInput(surveyName); final String sql = ""select cf.enabled, application_table_name, registered_table_name, entity_subtype"" + "" from x_registered_table "" + "" left join c_configuration cf on x_registered_table.registered_table_name = cf.name "" + "" where exists"" + "" (select 'f'"" + "" from m_appuser_role ur "" + "" join m_role r on r.id = ur.role_id"" + "" left join m_role_permission rp on rp.role_id = r.id"" + "" left join m_permission p on p.id = rp.permission_id"" + "" where ur.appuser_id = "" + this.context.authenticatedUser().getId() + "" and registered_table_name='"" + surveyName + ""'"" + "" and (p.code in ('ALL_FUNCTIONS', 'ALL_FUNCTIONS_READ') or p.code = concat('READ_', registered_table_name))) "" + "" order by application_table_name, registered_table_name""; final SqlRowSet rs = this.jdbcTemplate.queryForRowSet(sql); SurveyDataTableData datatableData = null; while (rs.next()) { final String appTableName = rs.getString(""application_table_name""); final String registeredDatatableName = rs.getString(""registered_table_name""); final String entitySubType = rs.getString(""entity_subtype""); final boolean enabled = rs.getBoolean(""enabled""); final List columnHeaderData = this.genericDataService .fillResultsetColumnHeaders(registeredDatatableName); datatableData = SurveyDataTableData .create(DatatableData.create(appTableName, registeredDatatableName, entitySubType, columnHeaderData), enabled); } return datatableData; }","@Override public SurveyDataTableData retrieveSurvey(String surveyName) { SQLInjectionValidator.validateSQLInput(surveyName); final String sql = ""select cf.enabled, application_table_name, registered_table_name, entity_subtype"" + "" from x_registered_table "" + "" left join c_configuration cf on x_registered_table.registered_table_name = cf.name "" + "" where exists"" + "" (select 'f'"" + "" from m_appuser_role ur "" + "" join m_role r on r.id = ur.role_id"" + "" left join m_role_permission rp on rp.role_id = r.id"" + "" left join m_permission p on p.id = rp.permission_id"" + "" where ur.appuser_id = ? and registered_table_name=?"" + "" and (p.code in ('ALL_FUNCTIONS', 'ALL_FUNCTIONS_READ') or p.code = concat('READ_', registered_table_name))) "" + "" order by application_table_name, registered_table_name""; SurveyDataTableData datatableData = null; final SqlRowSet rs = this.jdbcTemplate.queryForRowSet(sql, new Object[] { this.context.authenticatedUser().getId(), surveyName }); // NOSONAR if (rs.next()) { final String appTableName = rs.getString(""application_table_name""); final String registeredDatatableName = rs.getString(""registered_table_name""); final String entitySubType = rs.getString(""entity_subtype""); final boolean enabled = rs.getBoolean(""enabled""); final List columnHeaderData = this.genericDataService .fillResultsetColumnHeaders(registeredDatatableName); datatableData = SurveyDataTableData .create(DatatableData.create(appTableName, registeredDatatableName, entitySubType, columnHeaderData), enabled); } return datatableData; }",FINERACT-1562: Excluding persistence.xml from being picked up by Spring,https://github.com/apache/fineract/commit/f22807b9442dafa0ca07d0fad4e24c2de84e8e33,,,fineract-provider/src/main/java/org/apache/fineract/infrastructure/survey/service/ReadSurveyServiceImpl.java,3,java,False,2022-03-17T13:12:10Z "def get(self, request, **kwargs): playbook_id = kwargs.get('pk') playbook = get_object_or_404(Playbook, id=playbook_id) work_path = playbook.work_dir file_key = request.query_params.get('key', '') if file_key: file_path = os.path.join(work_path, file_key) with open(file_path, 'r') as f: try: content = f.read() except UnicodeDecodeError: content = _('Unsupported file content') return Response({'content': content}) else: expand_key = request.query_params.get('expand', '') nodes = self.generate_tree(playbook, work_path, expand_key) return Response(nodes)","def get(self, request, **kwargs): playbook_id = kwargs.get('pk') playbook = get_object_or_404(Playbook, id=playbook_id) work_path = playbook.work_dir file_key = request.query_params.get('key', '') if file_key: try: file_path = safe_join(work_path, file_key) with open(file_path, 'r') as f: content = f.read() except UnicodeDecodeError: content = _('Unsupported file content') except SuspiciousFileOperation: raise JMSException(code='invalid_file_path', detail={""msg"": _(""Invalid file path"")}) return Response({'content': content}) else: expand_key = request.query_params.get('expand', '') nodes = self.generate_tree(playbook, work_path, expand_key) return Response(nodes)",perf: 优化 Playbook 文件创建逻辑,https://github.com/jumpserver/jumpserver/commit/d0321a74f1713d031560341c8fd0a1859e6510d8,,,apps/ops/api/playbook.py,3,py,False,2023-09-19T10:04:24Z "@Override public void invoke(Object... args) { String result = (String) args[0]; if (result == ""granted"") { mLocationManager.getCurrentLocationData(options, success, error); } else { error.invoke(PositionError.buildError(PositionError.PERMISSION_DENIED, ""Location permission was not granted."")); } }","@Override public void invoke(Object... args) { WritableNativeMap result = (WritableNativeMap) args[0]; if (result.getString(Manifest.permission.ACCESS_COARSE_LOCATION) == ""granted"") { mLocationManager.getCurrentLocationData(options, success, error); } else { error.invoke(PositionError.buildError(PositionError.PERMISSION_DENIED, ""Location permission was not granted."")); } }",feat(android): fix permission crash,https://github.com/michalchudziak/react-native-geolocation/commit/06b2a8e85a6c7957a79b8faffec255030f25b16e,,,android/src/main/java/com/reactnativecommunity/geolocation/GeolocationModule.java,3,java,False,2022-08-21T20:19:40Z "private void doAuthentication(AuthData clientData) throws Exception { AuthData brokerData = authState.authenticate(clientData); // authentication has completed, will send newConnected command. if (authState.isComplete()) { clientAuthRole = authState.getAuthRole(); if (LOG.isDebugEnabled()) { LOG.debug(""[{}] Client successfully authenticated with {} role {}"", remoteAddress, authMethod, clientAuthRole); } completeConnect(clientData); return; } // auth not complete, continue auth with client side. ctx.writeAndFlush(Commands.newAuthChallenge(authMethod, brokerData, protocolVersionToAdvertise)) .addListener(ChannelFutureListener.FIRE_EXCEPTION_ON_FAILURE); if (LOG.isDebugEnabled()) { LOG.debug(""[{}] Authentication in progress client by method {}."", remoteAddress, authMethod); } state = State.Connecting; }","private void doAuthentication(AuthData clientData) throws Exception { AuthData brokerData = authState.authenticate(clientData); // authentication has completed, will send newConnected command. if (authState.isComplete()) { clientAuthRole = authState.getAuthRole(); if (LOG.isDebugEnabled()) { LOG.debug(""[{}] Client successfully authenticated with {} role {}"", remoteAddress, authMethod, clientAuthRole); } // First connection if (this.connectionPool == null || state == State.Connecting) { // authentication has completed, will send newConnected command. completeConnect(clientData); } return; } // auth not complete, continue auth with client side. ctx.writeAndFlush(Commands.newAuthChallenge(authMethod, brokerData, protocolVersionToAdvertise)) .addListener(ChannelFutureListener.FIRE_EXCEPTION_ON_FAILURE); if (LOG.isDebugEnabled()) { LOG.debug(""[{}] Authentication in progress client by method {}."", remoteAddress, authMethod); } state = State.Connecting; }","[fix][proxy] Fix refresh client auth (#17831) * [fix][proxy] Fix refresh client auth Signed-off-by: Zixuan Liu * Fix style Signed-off-by: Zixuan Liu ",https://github.com/apache/pulsar/commit/c952f3c9f891f85ff4b6cee6e28b6f68db3b5bcd,,,pulsar-proxy/src/main/java/org/apache/pulsar/proxy/server/ProxyConnection.java,3,java,False,2022-09-29T10:48:38Z "@Override public Object call(Object who, Method method, Object... args) throws Throwable { if (isFakeLocationEnable()) { Object transport = ArrayUtils.getFirst(args, mirror.android.location.LocationManager.GpsStatusListenerTransport.TYPE); Object locationManager = mirror.android.location.LocationManager.GpsStatusListenerTransport.this$0.get(transport); mirror.android.location.LocationManager.GpsStatusListenerTransport.onGpsStarted.call(transport); mirror.android.location.LocationManager.GpsStatusListenerTransport.onFirstFix.call(transport, 0); if (mirror.android.location.LocationManager.GpsStatusListenerTransport.mListener.get(transport) != null) { MockLocationHelper.invokeSvStatusChanged(transport); } else { MockLocationHelper.invokeNmeaReceived(transport); } GPSListenerThread.get().addListenerTransport(locationManager); return true; } return super.call(who, method, args); }","@Override public Object call(final Object who, Method method, Object... args) throws Throwable { if (Build.VERSION.SDK_INT > Build.VERSION_CODES.JELLY_BEAN) { LocationRequest request = (LocationRequest) args[0]; fixLocationRequest(request); } if (isFakeLocationEnable()) { Object transport = ArrayUtils.getFirst(args, mirror.android.location.LocationManager.ListenerTransport.TYPE); if (transport != null) { Object locationManager = mirror.android.location.LocationManager.ListenerTransport.this$0.get(transport); MockLocationHelper.setGpsStatus(locationManager); GPSListenerThread.get().addListenerTransport(locationManager); } return 0; } if (Build.VERSION.SDK_INT >= 30) { args[3] = VirtualCore.get().getContext().getPackageName(); } return super.call(who, method, args); }",Android 11: Fix SecurityException on requestLocationUpdates call,https://github.com/android-hacker/VirtualXposed/commit/9516bd4b41db6373e5aaa14a07c4b8eda38d29f7,,,VirtualApp/lib/src/main/java/com/lody/virtual/client/hook/proxies/location/MethodProxies.java,3,java,False,2021-11-26T14:19:35Z "public static boolean deleteFiles(String path) { if (!path.endsWith(File.separator)) { path = path + File.separator; } File dirFile = new File(path); if (!dirFile.exists() || !dirFile.isDirectory()) { return false; } boolean flag = true; File[] files = dirFile.listFiles(); if (files == null) { return false; } for (int i = 0; i < files.length; i++) { if (files[i].isFile()) { flag = deleteFile(files[i].getAbsolutePath()); if (!flag) { break; } } else { flag = deleteFiles(files[i].getAbsolutePath()); if (!flag) { break; } } } return flag; }","public static boolean deleteFiles(String path) { if (!path.endsWith(File.separator)) { path = path + File.separator; } File dirFile = new File(CleanPathUtil.cleanString(path)); if (!dirFile.exists() || !dirFile.isDirectory()) { return false; } boolean flag = true; File[] files = dirFile.listFiles(); if (files == null) { return false; } for (int i = 0; i < files.length; i++) { if (files[i].isFile()) { flag = deleteFile(files[i].getAbsolutePath()); if (!flag) { break; } } else { flag = deleteFiles(files[i].getAbsolutePath()); if (!flag) { break; } } } return flag; }",fix security scan,https://github.com/WeBankBlockchain/WeBASE-Front/commit/7c14dcde8af19c79357bfb337e00c948fe62d673,,,src/main/java/com/webank/webase/front/util/CommonUtils.java,3,java,False,2021-04-01T09:17:57Z "private byte[] receiveMessage() throws ErrnoException, InterruptedIOException { final byte[] lengthBits = new byte[4]; Os.read(mPipe, lengthBits, 0, lengthBits.length); final ByteBuffer bb = ByteBuffer.wrap(lengthBits); bb.order(ByteOrder.LITTLE_ENDIAN); final int msgLen = bb.getInt(); final byte[] msg = new byte[msgLen]; Os.read(mPipe, msg, 0, msg.length); return msg; }","private byte[] receiveMessage() throws ErrnoException, InterruptedIOException, EOFException { final byte[] lengthBits = new byte[4]; readFully(mPipe, lengthBits, 0, lengthBits.length); final ByteBuffer bb = ByteBuffer.wrap(lengthBits); bb.order(ByteOrder.LITTLE_ENDIAN); final int msgLen = bb.getInt(); final byte[] msg = new byte[msgLen]; readFully(mPipe, msg, 0, msg.length); return msg; }","Add wrappers around IO functions to check the return values Os.read and Os.write don't throw exceptions if `fd` is closed on the other end. Bug: 231345789 Test: save a snapshot Test: use clipboard both, check if there is no Test: infinite loops which sets the clipboard Signed-off-by: Roman Kiryanov Change-Id: If98fb3adf58f2e4e13d483b78ea05ea9d8d61b58 Merged-In: If98fb3adf58f2e4e13d483b78ea05ea9d8d61b58",https://github.com/LineageOS/android_frameworks_base/commit/1555d1d2108d3afe89968eb7aa76f16062d20811,,,services/core/java/com/android/server/clipboard/EmulatorClipboardMonitor.java,3,java,False,2022-05-10T02:35:11Z "@Implementation(minSdk = LOLLIPOP_MR1) protected int getActiveSubscriptionInfoCount() { return subscriptionList == null ? 0 : subscriptionList.size(); }","@Implementation(minSdk = LOLLIPOP_MR1) protected int getActiveSubscriptionInfoCount() { checkReadPhoneStatePermission(); return subscriptionList == null ? 0 : subscriptionList.size(); }","Add ShadowSubscriptionManager#checkReadPhoneStatePermission. ShadowSubscriptionManager#checkReadPhoneStatePermission allows to test permission errors. When set to false, methods that require READ_PHONE_STATE permissions will now throw a SecurityException. By default the permissions are granted for backwards compatibility. PiperOrigin-RevId: 460603937",https://github.com/robolectric/robolectric/commit/b14d8bd98f6a3f695acee4d6f5967632e11f8c48,,,shadows/framework/src/main/java/org/robolectric/shadows/ShadowSubscriptionManager.java,3,java,False,2022-07-13T02:12:56Z "@ModifyArg(method = ""render"", index = 5, at = @At(value = ""INVOKE"", target = ""Lnet/minecraft/client/gui/DrawableHelper;drawWithShadow(Lnet/minecraft/client/util/math/MatrixStack;Lnet/minecraft/client/font/TextRenderer;Lnet/minecraft/text/OrderedText;III)V"")) public int redirect(int x) { if (Gaslight.removedIndexes.contains(index)) { return 0xFFFF0000; } if (fromReportedPlayer) { return 0xFFFFFFFF; } return -1593835521; }","@ModifyArg(method = ""render"", index = 5, at = @At(value = ""INVOKE"", target = ""Lnet/minecraft/client/gui/DrawableHelper;drawWithShadow(Lnet/minecraft/client/util/math/MatrixStack;Lnet/minecraft/client/font/TextRenderer;Lnet/minecraft/text/OrderedText;III)V"")) public int redirect(int x) { if (Gaslight.removedMessages.contains(this.truncatedContent.getString())) { return 0xFFFF0000; } if (fromReportedPlayer) { return 0xFFFFFFFF; } return -1593835521; }",We are now releasing pre-release 5 for Minecraft 1.19.1. This pre-release includes the remaining fixes for a known exploit regarding player report context,https://github.com/nodusclient/gaslight/commit/2055c0ae93927aa5ca70460bf35b10db4b358a42,,,src/main/java/gg/nodus/gaslight/mixin/MixinMessageEntry.java,3,java,False,2022-07-27T17:16:47Z "private void setDistantFleetsToRetreat() { List fleets = galaxy().ships.notInTransitFleets(empire.id); float range = empire.tech().scoutRange(); for (ShipFleet fl: fleets) { int sysId = fl.sysId(); if (!empire.sv.withinRange(sysId, range)) { //ail: no retreating, if I can still bomb the enemy if(empire.enemies().contains(fl.system().empire()) && fl.expectedBombardDamage() > 0) { continue; } setRetreatFleetPlan(sysId); fleetPlans.add(empire.sv.fleetPlan(sysId)); } } }","private void setDistantFleetsToRetreat() { List fleets = galaxy().ships.notInTransitFleets(empire.id); float range = empire.tech().scoutRange(); for (ShipFleet fl: fleets) { int sysId = fl.sysId(); if (!empire.sv.withinRange(sysId, range)) { //ail: no retreating, if I can still bomb the enemy if(empire.enemies().contains(fl.system().empire()) && fl.expectedBombardDamage() > 0) { continue; } setRetreatFleetPlan(sysId); fleetPlans.add(empire.sv.fleetPlan(sysId)); } //we also want to retreat fleets that are trespassing to avoid prevention-wars if(fl.system().empire()!= null && !empire.enemies().contains(fl.system().empire()) && !empire.allies().contains(fl.system().empire()) && empire != fl.system().empire()) { setRetreatFleetPlan(sysId); fleetPlans.add(empire.sv.fleetPlan(sysId)); } } }","Branch for beta 2.18 or 0.9 or whatever it will be (#48) * Replaced many isPlayer() by isPlayerControlled() This leads to a more fluent experience on AutoPlay. Note: the council-voting acts weird when you try that there, getting you stuck, and the News-Broadcasts also seem to use a differnt logic and are always shown. * Orion-guard-handling Avoid sending colonization-fleets, when guardian is still alive Increase guardian-power-estimate to 100,000 Don't send and count bombers towards guardian-defeat-force * Fixed Crash from a report on reddit Not sure how that could happen though. Never had this issue in games started on my computer. * Fixed crash after AI defeats orion-guard Tried to access an out-of-bounds-value because it couldn't find the System where the guardian was. So looking to find the Planet with the Orionartifact now, which does find it. * All the forgotten isPlayer()-calls Including the Base- and Modnar-AI-Diplomat * Personalities now play a role in my AI once again Instead of everyone having the same conditions for war, there's now different ones. Some are more aggressive, some are less. * Fixed issue where enemy-fleets weren's seen, when they actually were. Also added a way of guessing when enemy-fleets aren't seen so it shouldn't trickle in tiny fleets that all retreat anymore in the early-game, before they can see the enemy-fleets. And also not later because they now actually can see them. * Update AIDiplomat.java * Delete ShipCombatResults.java * Delete Empire.java * Delete TradeRoute.java * Revert ""Delete TradeRoute.java"" This reverts commit 6e5c5a8604e89bb11a9a6dc63acd5b3f27194c83. * Revert ""Delete Empire.java"" This reverts commit 1a020295e05ebc735dae761f426742eb7bdc8d35. * Revert ""Delete ShipCombatResults.java"" This reverts commit 5f9287289feb666adf1aa809524973c54fbf0cd5. * Update ShipCombatResults.java reverting pull-request... manually because I don't know of a better way 8[ * Update Empire.java * Update TradeRoute.java * Merge with Master * Update TradeRoute.java * Update TradeRoute.java github editor does not allow me to remove a newline oO * AI improvements Added parameter to make the colonizer-function return just the uncolonized planets without substracting the colony-ships. Impelemented a very differnt diplomatic behavior, that supposedly is more suitable to actually winning by waging less war, particularly when big enough to be voted for. Revoked that AI doesn't adjust to enemy-troops when it has a more defensive unit-composition. In lategame going by destructive-power of bombers hasn't much merit, when 1 bombers can pack 60ish neutronium-bombs. Fixed an issue that prevented designing extended-fuel-range-colonizers asap. This once again helps expansion-speed a lot. Security now is only spent against empires actually in range to spy, as it was intended. Contact via council should not increase paranoia. Also Xenophobic-extra-paranoia removed. * Update OrionGuardianShip.java * War-declaration behavior Electible faction will no longer declare war on someone who is at war with the other electible faction. * Fix zero-division on refreshing a trade-route that had been adjusted due to empire-shrinkage. * AI & Bugfix Leader-stuff is now overridden Should now retreat against repulsors, when no counter available Tech-nullifier hit and miss mixup fixed * AI improvements Fixed a rare crash in AutoPlay-Mode Massive overhaul of AI-ship-design Spy master now more catious about avoiding unwanted, dangerous wars due to spying on the wrong people Colony-ship-designs now will only get a weapon, if this doesn't prevent reserve-tanks or reducing their size to medium Fixed an issue where ai wouldn't retreat from ships with repulsor-beam that exploited their range-advantage Increased research-value of cloaking-tech and battle-suits Upon reaching tech-level 99 in every field, AI will produce ships non-stop even in peace-time AI will now retreat fleets from empires it doesn't want to go to war with in order to avoid trespassing-issues Fixed issue where the AI wanted to but couldn't colonize orion before it was cleared and then wouldn't colonize other systems in that time AI will no longer break non-aggression-pacts when it still has a war with someone else AI will only begin wars because of spying, if it actually feels comfortable dealing with the person who spied on them AI will now try and predict whether it will be attacked soon and enact preventive measures * Tackling some combat-issue Skipping specials when it comes to determining optimal-range. Otherwise ships with long-range-specials like warp-dissipator would never close in on their prey. Resetting the selectedWeaponIndex upon reload to consistency start with same weapons every turn. Writing new attack-method that allows to skip certain weapons like for example repulsor-beam at the beginning of the turn and fire them at the end instead. * Update NewShipTemplate.java Fixed incorrect operator ""-="" instead of ""=-"", that prevented weapons being used at all when no weapon that is strong enough for theorethical best enemy shield could be found. Also when range is required an not fitting beam can be found try missiles and when no fitting missile can be found either, try short-range weapon. Should still be better than nothing. * Diplomacy and Ship-Building Reduced suicidal tendencies. No more war-declarations against wastly superior enemies. At most they ought to be 25% stronger. Voting behavior is now deterministic. No more votes based on fear, only on who they actually like and only for those whom they have real-contact. Ship-construction is now based on relative-productivity rather than using a hard cut-off for anything lower than standard-resources. So when the empire only has poor-systems it will try to build at least a few ships still. * Orion prevented war Fixed an issue, where wanting to build a colonizer for Orion prevented wars. * Update AIGeneral.java Don't invade unless you have something in orbit. * Update AIFleetCommander.java No longer using hyperspace-communications... for now. (it produced unintentional results and error-messages) Co-authored-by: rayfowler <58891984+rayfowler@users.noreply.github.com>",https://github.com/rayfowler/rotp-public/commit/5de4de9f996eddaa73b90b341940561e62c18e49,,,src/rotp/model/ai/xilmi/AIFleetCommander.java,3,java,False,2021-04-02T21:15:47Z "protected void readPdf() throws IOException { String version = tokens.checkPdfHeader(); try { this.headerPdfVersion = PdfVersion.fromString(version); } catch (IllegalArgumentException exc) { throw new PdfException(KernelExceptionMessageConstant.PDF_VERSION_IS_NOT_VALID, version); } try { readXref(); } catch (RuntimeException ex) { Logger logger = LoggerFactory.getLogger(PdfReader.class); logger.error(IoLogMessageConstant.XREF_ERROR_WHILE_READING_TABLE_WILL_BE_REBUILT, ex); rebuildXref(); } pdfDocument.getXref().markReadingCompleted(); readDecryptObj(); }","protected void readPdf() throws IOException { String version = tokens.checkPdfHeader(); try { this.headerPdfVersion = PdfVersion.fromString(version); } catch (IllegalArgumentException exc) { throw new PdfException(KernelExceptionMessageConstant.PDF_VERSION_IS_NOT_VALID, version); } try { readXref(); } catch (XrefCycledReferencesException ex) { // Throws an exception when xref stream has cycled references(due to lack of opportunity to fix such an // issue) or xref tables have cycled references and PdfReader.StrictnessLevel set to CONSERVATIVE. throw ex; } catch (RuntimeException ex) { Logger logger = LoggerFactory.getLogger(PdfReader.class); logger.error(IoLogMessageConstant.XREF_ERROR_WHILE_READING_TABLE_WILL_BE_REBUILT, ex); rebuildXref(); } pdfDocument.getXref().markReadingCompleted(); readDecryptObj(); }","Add safeguards to avoid infinite loop in xref structure DEVSIX-6235",https://github.com/itext/itext-java/commit/e7a7258b082ce9d5b18aca2cc9273570cdab9735,,,kernel/src/main/java/com/itextpdf/kernel/pdf/PdfReader.java,3,java,False,2022-01-11T21:33:01Z void toBinary(ByteBuffer buffer);,"@Override public void toBinary(final ByteBuffer buffer) { VarintUtils.writeUnsignedInt(nameBytes.length, buffer); buffer.put(nameBytes); VarintUtils.writeUnsignedInt(parameterClassBytes.length, buffer); buffer.put(parameterClassBytes); if (mutator.getParameterTypes()[0].isPrimitive()) { buffer.put((byte) 1); } else { buffer.put((byte) 0); } }","Fix issues and add improvements to basic data type adapters (#1867) * Fix issues and add improvements to basic data type adapters - Fix issues with the use of primitive types - Allow the data ID field to be kept separate from the other fields so that they don't get serialized twice - Allow the naming of attribute indices - Allow no field descriptors to be supplied - Update data ID serialization to use the field writer for the class instead of toString - Fix stack overflow on SimpleAbstractDataAdapter Signed-off-by: Johnathan Garrett * formatting Co-authored-by: Rich Fecher ",https://github.com/locationtech/geowave/commit/7fa4584f31e490dc2500804c6fd209cd062226b6,,,core/store/src/main/java/org/locationtech/geowave/core/store/adapter/BasicDataTypeAdapter.java,3,java,False,2022-02-23T13:21:00Z "@Override public void verify(DecodedJWT jwt) throws SignatureVerificationException { try { byte[] signatureBytes = Base64.getUrlDecoder().decode(jwt.getSignature()); ECPublicKey publicKey = keyProvider.getPublicKeyById(jwt.getKeyId()); if (publicKey == null) { throw new IllegalStateException(""The given Public Key is null.""); } boolean valid = crypto.verifySignatureFor(getDescription(), publicKey, jwt.getHeader(), jwt.getPayload(), JOSEToDER(signatureBytes)); if (!valid) { throw new SignatureVerificationException(this); } } catch (NoSuchAlgorithmException | SignatureException | InvalidKeyException | IllegalStateException | IllegalArgumentException e) { throw new SignatureVerificationException(this, e); } }","@Override public void verify(DecodedJWT jwt) throws SignatureVerificationException { try { byte[] signatureBytes = Base64.getUrlDecoder().decode(jwt.getSignature()); ECPublicKey publicKey = keyProvider.getPublicKeyById(jwt.getKeyId()); if (publicKey == null) { throw new IllegalStateException(""The given Public Key is null.""); } validateSignatureStructure(signatureBytes, publicKey); boolean valid = crypto.verifySignatureFor(getDescription(), publicKey, jwt.getHeader(), jwt.getPayload(), JOSEToDER(signatureBytes)); if (!valid) { throw new SignatureVerificationException(this); } } catch (NoSuchAlgorithmException | SignatureException | InvalidKeyException | IllegalStateException | IllegalArgumentException e) { throw new SignatureVerificationException(this, e); } }",Added protection against CVE-2022-21449,https://github.com/auth0/java-jwt/commit/05b54499be0cc06478467d66c801d9bc3da3fecc,,,lib/src/main/java/com/auth0/jwt/algorithms/ECDSAAlgorithm.java,3,java,False,2022-05-03T13:46:47Z "@Override public StructureTemplate.StructureBlockInfo processBlock(LevelReader worldReader, BlockPos pos, BlockPos pos2, StructureTemplate.StructureBlockInfo infoIn1, StructureTemplate.StructureBlockInfo infoIn2, StructurePlaceSettings settings) { ChunkPos currentChunkPos = new ChunkPos(infoIn2.pos); if(infoIn2.state.is(Blocks.STRUCTURE_VOID) || !infoIn2.state.getFluidState().isEmpty()) return infoIn2; if(!GeneralUtils.isFullCube(worldReader, infoIn2.pos, infoIn2.state) || !infoIn2.state.getMaterial().blocksMotion()){ ChunkAccess currentChunk = worldReader.getChunk(currentChunkPos.x, currentChunkPos.z); if(ifAirInWorld && !currentChunk.getBlockState(infoIn2.pos).isAir()) return infoIn2; // Remove fluid sources in adjacent horizontal blocks across chunk boundaries and above as well BlockPos.MutableBlockPos mutable = new BlockPos.MutableBlockPos(); for (Direction direction : Direction.values()) { if(ignoreDown && direction == Direction.DOWN) continue; mutable.set(infoIn2.pos).move(direction); if (currentChunkPos.x != mutable.getX() >> 4 || currentChunkPos.z != mutable.getZ() >> 4) { currentChunk = worldReader.getChunk(mutable); currentChunkPos = new ChunkPos(mutable); } FluidState fluidState = currentChunk.getFluidState(mutable); if (fluidState.isSource()) { Random random = new WorldgenRandom(); random.setSeed(mutable.asLong() * mutable.getY()); Block replacementBlock = GeneralUtils.getRandomEntry(weightedReplacementBlocks, random); currentChunk.setBlockState(mutable, replacementBlock.defaultBlockState(), false); } } } return infoIn2; }","@Override public StructureTemplate.StructureBlockInfo processBlock(LevelReader worldReader, BlockPos pos, BlockPos pos2, StructureTemplate.StructureBlockInfo infoIn1, StructureTemplate.StructureBlockInfo infoIn2, StructurePlaceSettings settings) { ChunkPos currentChunkPos = new ChunkPos(infoIn2.pos); if(infoIn2.state.is(Blocks.STRUCTURE_VOID) || !infoIn2.state.getFluidState().isEmpty()) return infoIn2; if(!GeneralUtils.isFullCube(worldReader, infoIn2.pos, infoIn2.state) || !infoIn2.state.getMaterial().blocksMotion()){ ChunkAccess currentChunk = worldReader.getChunk(currentChunkPos.x, currentChunkPos.z); if(ifAirInWorld && !currentChunk.getBlockState(infoIn2.pos).isAir()) return infoIn2; // Remove fluid sources in adjacent horizontal blocks across chunk boundaries and above as well BlockPos.MutableBlockPos mutable = new BlockPos.MutableBlockPos(); for (Direction direction : Direction.values()) { if(ignoreDown && direction == Direction.DOWN) continue; mutable.set(infoIn2.pos).move(direction); if (mutable.getY() < currentChunk.getMinBuildHeight() || mutable.getY() >= currentChunk.getMaxBuildHeight()){ continue; } if (currentChunkPos.x != mutable.getX() >> 4 || currentChunkPos.z != mutable.getZ() >> 4) { currentChunk = worldReader.getChunk(mutable); currentChunkPos = new ChunkPos(mutable); } // Copy what vanilla ores do. // This bypasses the PaletteContainer's lock as it was throwing `Accessing PalettedContainer from multiple threads` crash // even though everything seemed to be safe and fine. int sectionYIndex = currentChunk.getSectionIndex(mutable.getY()); LevelChunkSection levelChunkSection = currentChunk.getOrCreateSection(sectionYIndex); if (levelChunkSection == LevelChunk.EMPTY_SECTION) continue; FluidState fluidState = levelChunkSection.getFluidState( SectionPos.sectionRelative(mutable.getX()), SectionPos.sectionRelative(mutable.getY()), SectionPos.sectionRelative(mutable.getZ())); if (fluidState.isSource()) { Random random = new WorldgenRandom(); random.setSeed(mutable.asLong() * mutable.getY()); Block replacementBlock = GeneralUtils.getRandomEntry(weightedReplacementBlocks, random); levelChunkSection.setBlockState( SectionPos.sectionRelative(mutable.getX()), SectionPos.sectionRelative(mutable.getY()), SectionPos.sectionRelative(mutable.getZ()), replacementBlock.defaultBlockState(), false); } } } return infoIn2; }","tried fixing PalettedContainer crash by being unsafe https://github.com/TelepathicGrunt/RepurposedStructures-Fabric/issues/141 https://github.com/TelepathicGrunt/RepurposedStructures-Fabric/issues/129",https://github.com/TelepathicGrunt/RepurposedStructures-Quilt/commit/8ee182ae023aabd54652132d87a9aa820a016a3e,,,src/main/java/com/telepathicgrunt/repurposedstructures/world/processors/CloseOffFluidSourcesProcessor.java,3,java,False,2021-08-22T03:00:55Z "def _call_downloader(self, tmpfilename, info_dict): """""" Either overwrite this or implement _make_cmd """""" cmd = [encodeArgument(a) for a in self._make_cmd(tmpfilename, info_dict)] self._debug_cmd(cmd) if 'fragments' not in info_dict: _, stderr, returncode = self._call_process(cmd, info_dict) if returncode and stderr: self.to_stderr(stderr) return returncode skip_unavailable_fragments = self.params.get('skip_unavailable_fragments', True) retry_manager = RetryManager(self.params.get('fragment_retries'), self.report_retry, frag_index=None, fatal=not skip_unavailable_fragments) for retry in retry_manager: _, stderr, returncode = self._call_process(cmd, info_dict) if not returncode: break # TODO: Decide whether to retry based on error code # https://aria2.github.io/manual/en/html/aria2c.html#exit-status if stderr: self.to_stderr(stderr) retry.error = Exception() continue if not skip_unavailable_fragments and retry_manager.error: return -1 decrypt_fragment = self.decrypter(info_dict) dest, _ = self.sanitize_open(tmpfilename, 'wb') for frag_index, fragment in enumerate(info_dict['fragments']): fragment_filename = '%s-Frag%d' % (tmpfilename, frag_index) try: src, _ = self.sanitize_open(fragment_filename, 'rb') except OSError as err: if skip_unavailable_fragments and frag_index > 1: self.report_skip_fragment(frag_index, err) continue self.report_error(f'Unable to open fragment {frag_index}; {err}') return -1 dest.write(decrypt_fragment(fragment, src.read())) src.close() if not self.params.get('keep_fragments', False): self.try_remove(encodeFilename(fragment_filename)) dest.close() self.try_remove(encodeFilename('%s.frag.urls' % tmpfilename)) return 0","def _call_downloader(self, tmpfilename, info_dict): ffpp = FFmpegPostProcessor(downloader=self) if not ffpp.available: self.report_error('m3u8 download detected but ffmpeg could not be found. Please install') return False ffpp.check_version() args = [ffpp.executable, '-y'] for log_level in ('quiet', 'verbose'): if self.params.get(log_level, False): args += ['-loglevel', log_level] break if not self.params.get('verbose'): args += ['-hide_banner'] args += traverse_obj(info_dict, ('downloader_options', 'ffmpeg_args'), default=[]) # These exists only for compatibility. Extractors should use # info_dict['downloader_options']['ffmpeg_args'] instead args += info_dict.get('_ffmpeg_args') or [] seekable = info_dict.get('_seekable') if seekable is not None: # setting -seekable prevents ffmpeg from guessing if the server # supports seeking(by adding the header `Range: bytes=0-`), which # can cause problems in some cases # https://github.com/ytdl-org/youtube-dl/issues/11800#issuecomment-275037127 # http://trac.ffmpeg.org/ticket/6125#comment:10 args += ['-seekable', '1' if seekable else '0'] env = None proxy = self.params.get('proxy') if proxy: if not re.match(r'^[\da-zA-Z]+://', proxy): proxy = 'http://%s' % proxy if proxy.startswith('socks'): self.report_warning( '%s does not support SOCKS proxies. Downloading is likely to fail. ' 'Consider adding --hls-prefer-native to your command.' % self.get_basename()) # Since December 2015 ffmpeg supports -http_proxy option (see # http://git.videolan.org/?p=ffmpeg.git;a=commit;h=b4eb1f29ebddd60c41a2eb39f5af701e38e0d3fd) # We could switch to the following code if we are able to detect version properly # args += ['-http_proxy', proxy] env = os.environ.copy() env['HTTP_PROXY'] = proxy env['http_proxy'] = proxy protocol = info_dict.get('protocol') if protocol == 'rtmp': player_url = info_dict.get('player_url') page_url = info_dict.get('page_url') app = info_dict.get('app') play_path = info_dict.get('play_path') tc_url = info_dict.get('tc_url') flash_version = info_dict.get('flash_version') live = info_dict.get('rtmp_live', False) conn = info_dict.get('rtmp_conn') if player_url is not None: args += ['-rtmp_swfverify', player_url] if page_url is not None: args += ['-rtmp_pageurl', page_url] if app is not None: args += ['-rtmp_app', app] if play_path is not None: args += ['-rtmp_playpath', play_path] if tc_url is not None: args += ['-rtmp_tcurl', tc_url] if flash_version is not None: args += ['-rtmp_flashver', flash_version] if live: args += ['-rtmp_live', 'live'] if isinstance(conn, list): for entry in conn: args += ['-rtmp_conn', entry] elif isinstance(conn, str): args += ['-rtmp_conn', conn] start_time, end_time = info_dict.get('section_start') or 0, info_dict.get('section_end') selected_formats = info_dict.get('requested_formats') or [info_dict] for i, fmt in enumerate(selected_formats): cookies = self.ydl.cookiejar.get_cookies_for_url(fmt['url']) if cookies: args.extend(['-cookies', ''.join( f'{cookie.name}={cookie.value}; path={cookie.path}; domain={cookie.domain};\r\n' for cookie in cookies)]) if fmt.get('http_headers') and re.match(r'^https?://', fmt['url']): # Trailing \r\n after each HTTP header is important to prevent warning from ffmpeg/avconv: # [http @ 00000000003d2fa0] No trailing CRLF found in HTTP header. args.extend(['-headers', ''.join(f'{key}: {val}\r\n' for key, val in fmt['http_headers'].items())]) if start_time: args += ['-ss', str(start_time)] if end_time: args += ['-t', str(end_time - start_time)] args += self._configuration_args((f'_i{i + 1}', '_i')) + ['-i', fmt['url']] if not (start_time or end_time) or not self.params.get('force_keyframes_at_cuts'): args += ['-c', 'copy'] if info_dict.get('requested_formats') or protocol == 'http_dash_segments': for i, fmt in enumerate(selected_formats): stream_number = fmt.get('manifest_stream_number', 0) args.extend(['-map', f'{i}:{stream_number}']) if self.params.get('test', False): args += ['-fs', str(self._TEST_FILE_SIZE)] ext = info_dict['ext'] if protocol in ('m3u8', 'm3u8_native'): use_mpegts = (tmpfilename == '-') or self.params.get('hls_use_mpegts') if use_mpegts is None: use_mpegts = info_dict.get('is_live') if use_mpegts: args += ['-f', 'mpegts'] else: args += ['-f', 'mp4'] if (ffpp.basename == 'ffmpeg' and ffpp._features.get('needs_adtstoasc')) and (not info_dict.get('acodec') or info_dict['acodec'].split('.')[0] in ('aac', 'mp4a')): args += ['-bsf:a', 'aac_adtstoasc'] elif protocol == 'rtmp': args += ['-f', 'flv'] elif ext == 'mp4' and tmpfilename == '-': args += ['-f', 'mpegts'] elif ext == 'unknown_video': ext = determine_ext(remove_end(tmpfilename, '.part')) if ext == 'unknown_video': self.report_warning( 'The video format is unknown and cannot be downloaded by ffmpeg. ' 'Explicitly set the extension in the filename to attempt download in that format') else: self.report_warning(f'The video format is unknown. Trying to download as {ext} according to the filename') args += ['-f', EXT_TO_OUT_FORMATS.get(ext, ext)] else: args += ['-f', EXT_TO_OUT_FORMATS.get(ext, ext)] args += self._configuration_args(('_o1', '_o', '')) args = [encodeArgument(opt) for opt in args] args.append(encodeFilename(ffpp._ffmpeg_filename_argument(tmpfilename), True)) self._debug_cmd(args) piped = any(fmt['url'] in ('-', 'pipe:') for fmt in selected_formats) with Popen(args, stdin=subprocess.PIPE, env=env) as proc: if piped: self.on_process_started(proc, proc.stdin) try: retval = proc.wait() except BaseException as e: # subprocces.run would send the SIGKILL signal to ffmpeg and the # mp4 file couldn't be played, but if we ask ffmpeg to quit it # produces a file that is playable (this is mostly useful for live # streams). Note that Windows is not affected and produces playable # files (see https://github.com/ytdl-org/youtube-dl/issues/8300). if isinstance(e, KeyboardInterrupt) and sys.platform != 'win32' and not piped: proc.communicate_or_kill(b'q') else: proc.kill(timeout=None) raise return retval","[fd/external] Scope cookies - ffmpeg: Calculate cookies from cookiejar and pass with `-cookies` arg instead of `-headers` - aria2c, curl, wget: Write cookiejar to file and use external FD built-in cookiejar support - httpie: Calculate cookies from cookiejar instead of `http_headers` - axel: Calculate cookies from cookiejar and disable http redirection if cookies are passed - May break redirects, but axel simply don't have proper cookie support Ref: https://github.com/yt-dlp/yt-dlp/security/advisories/GHSA-v8mc-9377-rwjj Authored by: bashonly, coletdjnz",https://github.com/yt-dlp/yt-dlp/commit/1ceb657bdd254ad961489e5060f2ccc7d556b729,,,yt_dlp/downloader/external.py,3,py,False,2023-07-05T20:16:28Z "def upload_ssh_key(name: str, user_group: str, key: str) -> bool: try: key = paramiko.pkey.load_private_key(key) except Exception as e: print(f'error: Cannot save SSH key file: {e}') return False lib_path = get_config.get_config_var('main', 'lib_path') full_dir = f'{lib_path}/keys/' ssh_keys = f'{name}.pem' try: _check_split = name.split('_')[1] split_name = True except Exception: split_name = False if not os.path.isfile(ssh_keys) and not split_name: name = f'{name}_{user_group}' if not os.path.exists(full_dir): os.makedirs(full_dir) ssh_keys = f'{full_dir}{name}.pem' try: key.write_private_key_file(ssh_keys) except Exception as e: print(f'error: Cannot save SSH key file: {e}') return False else: print(f'success: SSH key has been saved into: {ssh_keys}') try: os.chmod(ssh_keys, 0o600) except IOError as e: roxywi_common.logging('Roxy-WI server', e.args[0], roxywi=1) return False roxywi_common.logging(""Roxy-WI server"", f""A new SSH cert has been uploaded {ssh_keys}"", roxywi=1, login=1) return True","def upload_ssh_key(name: str, user_group: str, key: str) -> bool: if '..' in name: print('error: nice try') return False try: key = paramiko.pkey.load_private_key(key) except Exception as e: print(f'error: Cannot save SSH key file: {e}') return False lib_path = get_config.get_config_var('main', 'lib_path') full_dir = f'{lib_path}/keys/' ssh_keys = f'{name}.pem' try: _check_split = name.split('_')[1] split_name = True except Exception: split_name = False if not os.path.isfile(ssh_keys) and not split_name: name = f'{name}_{user_group}' if not os.path.exists(full_dir): os.makedirs(full_dir) ssh_keys = f'{full_dir}{name}.pem' try: key.write_private_key_file(ssh_keys) except Exception as e: print(f'error: Cannot save SSH key file: {e}') return False else: print(f'success: SSH key has been saved into: {ssh_keys}') try: os.chmod(ssh_keys, 0o600) except IOError as e: roxywi_common.logging('Roxy-WI server', e.args[0], roxywi=1) return False roxywi_common.logging(""Roxy-WI server"", f""A new SSH cert has been uploaded {ssh_keys}"", roxywi=1, login=1) return True","v6.3.6.0 Changelog: https://roxy-wi.org/changelog#6_3_6",https://github.com/hap-wi/roxy-wi/commit/0054f25da7cf8c7480452f48e39308b5e392dc67,,,app/modules/server/ssh.py,3,py,False,2023-02-22T07:36:20Z "public BasicHttpToken authenticate(String authorization) { String usr = """"; String pwd = """"; if (authorization != null && authorization.length() > 0) { String token = authorization.substring(AUTH_TYPE_BASIC.length() + 1); String decode = new String(Base64.getDecoder().decode(token)); String[] arr = decode.split("":""); usr = arr[0]; if (arr.length >= 2) { pwd = arr[1]; } } return authenticate(usr, pwd); }","public BasicHttpToken authenticate(String authorization) { String usr = """"; String pwd = """"; if (authorization != null && authorization.length() > 0) { String token = authorization.substring(AUTH_TYPE_BASIC.length() + 1); String decode = new String(Base64.getDecoder().decode(token)); String[] arr = decode.split("":""); if (arr.length >= 1) { usr = arr[0]; } if (arr.length >= 2) { pwd = arr[1]; } } return authenticate(usr, pwd); }",fix: base authentication array out of bound exception(#252),https://github.com/monkeyWie/proxyee/commit/b3c0f3fb6aa77f307a01998c03f60713f0ac4b7d,,,src/main/java/com/github/monkeywie/proxyee/server/auth/BasicHttpProxyAuthenticationProvider.java,3,java,False,2022-12-14T05:37:25Z "@Override public SignValidity validate(final byte[] sign, final Properties params) throws RuntimeConfigNeededException, IOException { AcroFields af; try { final PdfReader reader = new PdfReader(sign); af = reader.getAcroFields(); } catch (final Exception e) { return new SignValidity(SIGN_DETAIL_TYPE.KO, VALIDITY_ERROR.NO_SIGN); } final List signNames = af.getSignatureNames(); // Si no hay firmas, no hay nada que comprobar if (signNames.size() == 0) { return new SignValidity(SIGN_DETAIL_TYPE.KO, VALIDITY_ERROR.NO_SIGN); } for (final String name : signNames) { // Valimamos la firma final PdfPKCS7 pk = af.verifySignature(name); // Comprobamos que el algoritmo de hash este bien declarado, supliendo asi la flexibilidad de iText que permite // cargar firmas que usan algoritmos de firma como algoritmos de hash if (pk.getStrictHashAlgorithm() == null) { return new SignValidity(SIGN_DETAIL_TYPE.KO, VALIDITY_ERROR.ALGORITHM_NOT_SUPPORTED); } // Comprobamos si es una firma o un sello final PdfDictionary pdfDictionary = af.getSignatureDictionary(name); // Si no es un sello, comprobamos el PKCS#1 if (!PDFNAME_ETSI_RFC3161.equals(pdfDictionary.get(PdfName.SUBFILTER)) && !PDFNAME_DOCTIMESTAMP.equals(pdfDictionary.get(PdfName.SUBFILTER))) { try { if (!pk.verify()) { return new SignValidity(SIGN_DETAIL_TYPE.KO, VALIDITY_ERROR.NO_MATCH_DATA); } } catch (final Exception e) { LOGGER.warning(""Error validando una de las firmas del PDF: "" + e); //$NON-NLS-1$ return new SignValidity(SIGN_DETAIL_TYPE.KO, VALIDITY_ERROR.CORRUPTED_SIGN, e); } } final boolean checkCertificates = Boolean.parseBoolean(params.getProperty(PdfExtraParams.CHECK_CERTIFICATES, Boolean.TRUE.toString())); if (checkCertificates) { final X509Certificate signCert = pk.getSigningCertificate(); try { signCert.checkValidity(); } catch (final CertificateExpiredException e) { // Certificado caducado return new SignValidity(SIGN_DETAIL_TYPE.KO, VALIDITY_ERROR.CERTIFICATE_EXPIRED, e); } catch (final CertificateNotYetValidException e) { // Certificado aun no valido return new SignValidity(SIGN_DETAIL_TYPE.KO, VALIDITY_ERROR.CERTIFICATE_NOT_VALID_YET, e); } } } final String allowShadowAttackProp = params.getProperty(PdfExtraParams.ALLOW_SHADOW_ATTACK); final boolean allowPdfShadowAttack = Boolean.parseBoolean(allowShadowAttackProp); final String pagesToCheck = params.getProperty(PdfExtraParams.PAGES_TO_CHECK_PSA, DEFAULT_PAGES_TO_CHECK_PSA); // Si se debe comprobar si se ha producido un PDF Shadow Attack // (modificacion de un documento tras la firma), se encuentran varias // revisiones en el documento y hay al menos una posterior a la ultima // firma (la de la posicion 0), se comprueba si el documento ha sufrido // un PSA. if (!allowPdfShadowAttack && af.getTotalRevisions() > 1 && af.getRevision(signNames.get(0)) < af.getTotalRevisions()) { // La revision firmada mas reciente se encuentra en el primer lugar de la lista, por ello se accede a la posicion 0 try (final InputStream lastReviewStream = af.extractRevision(signNames.get(0))) { SignValidity validity = DataAnalizerUtil.checkPdfShadowAttack(sign, lastReviewStream, pagesToCheck); // Si se devolvio informacion de validez, la firma no es completamente valida if (validity != null) { // Se comprueba si se debe consultar al usuario y si se // cumplen los requisitos para ello if (validity.getValidity() == SignValidity.SIGN_DETAIL_TYPE.PENDING_CONFIRM_BY_USER && allowShadowAttackProp == null) { throw new SuspectedPSAException(""PDF sospechoso de haber sufrido PDF Shadow Attack""); //$NON-NLS-1$ } // Si habia que consultar y no se cumplen los requisitos, // se considera que la firma no es valida if (validity.getValidity() == SignValidity.SIGN_DETAIL_TYPE.PENDING_CONFIRM_BY_USER) { validity = new SignValidity(SIGN_DETAIL_TYPE.KO, validity.getError()); } return validity; } } } return new SignValidity(SIGN_DETAIL_TYPE.OK, null); }","@Override public SignValidity validate(final byte[] sign, final Properties params) throws RuntimeConfigNeededException, IOException { AcroFields af; PdfReader reader; try { reader = new PdfReader(sign); af = reader.getAcroFields(); } catch (final Exception e) { return new SignValidity(SIGN_DETAIL_TYPE.KO, VALIDITY_ERROR.NO_SIGN); } final List signNames = af.getSignatureNames(); // Si no hay firmas, no hay nada que comprobar if (signNames.size() == 0) { return new SignValidity(SIGN_DETAIL_TYPE.KO, VALIDITY_ERROR.NO_SIGN); } for (final String name : signNames) { // Valimamos la firma final PdfPKCS7 pk = af.verifySignature(name); // Comprobamos que el algoritmo de hash este bien declarado, supliendo asi la flexibilidad de iText que permite // cargar firmas que usan algoritmos de firma como algoritmos de hash if (pk.getStrictHashAlgorithm() == null) { return new SignValidity(SIGN_DETAIL_TYPE.KO, VALIDITY_ERROR.ALGORITHM_NOT_SUPPORTED); } // Comprobamos si es una firma o un sello final PdfDictionary pdfDictionary = af.getSignatureDictionary(name); // Si no es un sello, comprobamos el PKCS#1 if (!PDFNAME_ETSI_RFC3161.equals(pdfDictionary.get(PdfName.SUBFILTER)) && !PDFNAME_DOCTIMESTAMP.equals(pdfDictionary.get(PdfName.SUBFILTER))) { try { if (!pk.verify()) { return new SignValidity(SIGN_DETAIL_TYPE.KO, VALIDITY_ERROR.NO_MATCH_DATA); } } catch (final Exception e) { LOGGER.warning(""Error validando una de las firmas del PDF: "" + e); //$NON-NLS-1$ return new SignValidity(SIGN_DETAIL_TYPE.KO, VALIDITY_ERROR.CORRUPTED_SIGN, e); } } final boolean checkCertificates = Boolean.parseBoolean(params.getProperty(PdfExtraParams.CHECK_CERTIFICATES, Boolean.TRUE.toString())); if (checkCertificates) { final X509Certificate signCert = pk.getSigningCertificate(); try { signCert.checkValidity(); } catch (final CertificateExpiredException e) { // Certificado caducado return new SignValidity(SIGN_DETAIL_TYPE.KO, VALIDITY_ERROR.CERTIFICATE_EXPIRED, e); } catch (final CertificateNotYetValidException e) { // Certificado aun no valido return new SignValidity(SIGN_DETAIL_TYPE.KO, VALIDITY_ERROR.CERTIFICATE_NOT_VALID_YET, e); } } } // COMPROBACION DE CAMBIOS EN LOS FORMULARIOS PDF final String allowSignModifiedFormProp = params.getProperty(PdfExtraParams.ALLOW_SIGN_MODIFIED_FORM); final boolean allowSignModifiedForm = Boolean.parseBoolean(allowSignModifiedFormProp); // Si se debe comprobar que no haya cambios en los valores de los formularios, lo hacemos // si hay mas de una revision y ha habido cambios desde la ultima firma, comprobamos si ha // habido cambios en campos de formularios if (!allowSignModifiedForm && af.getTotalRevisions() > 1 && af.getRevision(signNames.get(0)) < af.getTotalRevisions()) { final Map errors = DataAnalizerUtil.checkPDFForm(reader); if (errors != null && !errors.isEmpty()) { // Si no estaba definido un comportamiento concreto, consultaremos al usuario. if (allowSignModifiedFormProp == null) { throw new PdfFormModifiedException(""Se han detectado cambios en un formulario posteriores a la primera firma""); //$NON-NLS-1$ } return new SignValidity(SIGN_DETAIL_TYPE.KO, VALIDITY_ERROR.MODIFIED_FORM); } } // COMPROBACION DE PDF SHADOW ATTACK final String allowShadowAttackProp = params.getProperty(PdfExtraParams.ALLOW_SHADOW_ATTACK); final boolean allowPdfShadowAttack = Boolean.parseBoolean(allowShadowAttackProp); final String pagesToCheck = params.getProperty(PdfExtraParams.PAGES_TO_CHECK_PSA, DEFAULT_PAGES_TO_CHECK_PSA); // La comprobacion de PDF Shadow Attack detecta tambien los cambios en los formularios PDF, // asi que estos cambios impiden que se pueda hacer una comprobacion realista de esta // situacion. Por tanto, si se permiten los cambios en los formularios, se ignorara la // validacion de PDF Shadow Attack // Por otra parte, si se debe comprobar si se ha producido un PDF Shadow Attack // (modificacion de un documento tras la firma), se encuentran varias revisiones // en el documento y hay al menos una posterior a la ultima firma (la de la // posicion 0), se comprueba si el documento ha sufrido un PSA. if (!allowSignModifiedForm && !allowPdfShadowAttack && af.getTotalRevisions() > 1 && af.getRevision(signNames.get(0)) < af.getTotalRevisions()) { // La revision firmada mas reciente se encuentra en el primer lugar de la lista, por ello se accede a la posicion 0 try (final InputStream lastReviewStream = af.extractRevision(signNames.get(0))) { SignValidity validity = DataAnalizerUtil.checkPdfShadowAttack(sign, lastReviewStream, pagesToCheck); // Si se devolvio informacion de validez, la firma no es completamente valida if (validity != null) { // Se comprueba si se debe consultar al usuario y si se // cumplen los requisitos para ello if (validity.getValidity() == SignValidity.SIGN_DETAIL_TYPE.PENDING_CONFIRM_BY_USER && allowShadowAttackProp == null) { throw new SuspectedPSAException(""PDF sospechoso de haber sufrido PDF Shadow Attack""); //$NON-NLS-1$ } // Si habia que consultar y no se cumplen los requisitos, // se considera que la firma no es valida if (validity.getValidity() == SignValidity.SIGN_DETAIL_TYPE.PENDING_CONFIRM_BY_USER) { validity = new SignValidity(SIGN_DETAIL_TYPE.KO, validity.getError()); } return validity; } } } return new SignValidity(SIGN_DETAIL_TYPE.OK, null); }","Validación de formularios PDF - Se incluye a la validación de firmas PDF la comprobación de que los formularios no se hayan modificado después de firmar el documento. - Se incorpora la identificación de los cambios en los formularios PDF en el proceso de firma trifásica. - Se agrega la información de la validación de formularios y de PDF Shadow Attack a la ayuda integrada de AutoFirma.",https://github.com/ctt-gob-es/clienteafirma/commit/09ae16ec502c0e9df812f44f1654f337032df7ef,,,afirma-crypto-validation/src/main/java/es/gob/afirma/signvalidation/ValidatePdfSignature.java,3,java,False,2022-09-14T14:03:06Z "private static ItemStack createHead(Player targetPlayer, Player GUIholder) { ItemStack i = nms.createItemStack(nms.materialPlayerHead().toString(), 1, (short) 3); i = nms.setSkullOwner(i, targetPlayer); ItemMeta im = i.getItemMeta(); im.setDisplayName(getMsg(GUIholder, Messages.ARENA_SPECTATOR_TELEPORTER_GUI_HEAD_NAME) .replace(""{prefix}"", BedWars.getChatSupport().getPrefix(targetPlayer)) .replace(""{suffix}"", BedWars.getChatSupport().getSuffix(targetPlayer)) .replace(""{player}"", targetPlayer.getDisplayName())); List lore = new ArrayList<>(); String health = String.valueOf((int)targetPlayer.getHealth() * 100 / targetPlayer.getHealthScale()); for (String s : getList(GUIholder, Messages.ARENA_SPECTATOR_TELEPORTER_GUI_HEAD_LORE)) { lore.add(s.replace(""{health}"", health).replace(""{food}"", String.valueOf(targetPlayer.getFoodLevel()))); } im.setLore(lore); i.setItemMeta(im); return nms.addCustomData(i, NBT_SPECTATOR_TELEPORTER_GUI_HEAD + targetPlayer.getName()); }","private static ItemStack createHead(Player targetPlayer, Player GUIholder) { ItemStack i = nms.getPlayerHead(targetPlayer, null); ItemMeta im = i.getItemMeta(); assert im != null; im.setDisplayName(getMsg(GUIholder, Messages.ARENA_SPECTATOR_TELEPORTER_GUI_HEAD_NAME) .replace(""{prefix}"", BedWars.getChatSupport().getPrefix(targetPlayer)) .replace(""{suffix}"", BedWars.getChatSupport().getSuffix(targetPlayer)) .replace(""{player}"", targetPlayer.getDisplayName())); List lore = new ArrayList<>(); String health = String.valueOf((int)targetPlayer.getHealth() * 100 / targetPlayer.getHealthScale()); for (String s : getList(GUIholder, Messages.ARENA_SPECTATOR_TELEPORTER_GUI_HEAD_LORE)) { lore.add(s.replace(""{health}"", health).replace(""{food}"", String.valueOf(targetPlayer.getFoodLevel()))); } im.setLore(lore); i.setItemMeta(im); return nms.addCustomData(i, NBT_SPECTATOR_TELEPORTER_GUI_HEAD + targetPlayer.getName()); }",fixed server crash issue due to setSkullOwner(v1_16_R3.java:386),https://github.com/andrei1058/BedWars1058/commit/4263e91a530556a2f842006c8415e4a03fecdcb5,,,bedwars-plugin/src/main/java/com/andrei1058/bedwars/arena/spectator/TeleporterGUI.java,3,java,False,2021-06-23T21:14:35Z "public void writeTo(PDVOutputStream out, String tsuid) throws IOException { if (tsuid.equals(info.tsuid)) { try (InputStream fis = info.getInputStream()) { long skip = info.fmiEndPos; while (skip > 0) skip -= fis.skip(skip); out.copyFrom(fis); } } else if (tsuid.equals(DCM4CHEE_URI_REFERENCED_TS_UID)) { DicomObject attrs; DicomInputStream dis = new DicomInputStream(info.getInputStream()); try { dis.setHandler(new StopTagInputHandler(Tag.PixelData)); attrs = dis.readDicomObject(); } finally { dis.close(); } try (DicomOutputStream dos = new DicomOutputStream(out)) { attrs.putString(Tag.RetrieveURI, VR.UT, info.toString()); dos.writeDataset(attrs, tsuid); } } else { DicomInputStream dis = new DicomInputStream(info.getInputStream()); try { DicomOutputStream dos = new DicomOutputStream(out); dos.setTransferSyntax(tsuid); TranscoderInputHandler h = new TranscoderInputHandler(dos, transcoderBufferSize); dis.setHandler(h); dis.readDicomObject(); } finally { dis.close(); } } }","public void writeTo(PDVOutputStream out, String tsuid) throws IOException { if (tsuid.equals(info.tsuid)) { try (InputStream fis = info.getInputStream()) { long skip = info.fmiEndPos; skipExactly(fis, skip); out.copyFrom(fis); } } else if (tsuid.equals(DCM4CHEE_URI_REFERENCED_TS_UID)) { DicomObject attrs; DicomInputStream dis = new DicomInputStream(info.getInputStream()); try { dis.setHandler(new StopTagInputHandler(Tag.PixelData)); attrs = dis.readDicomObject(); } finally { dis.close(); } try (DicomOutputStream dos = new DicomOutputStream(out)) { attrs.putString(Tag.RetrieveURI, VR.UT, info.toString()); dos.writeDataset(attrs, tsuid); } } else { DicomInputStream dis = new DicomInputStream(info.getInputStream()); try { DicomOutputStream dos = new DicomOutputStream(out); dos.setTransferSyntax(tsuid); TranscoderInputHandler h = new TranscoderInputHandler(dos, transcoderBufferSize); dis.setHandler(h); dis.readDicomObject(); } finally { dis.close(); } } }","[C-MOVE] Fix problem related with infinite loop if skip IS returns 0 (#638) * [C-MOVE] Fix problem related with infinite loop if the skip method of InputStream implementantion does not do the job and returns 0 * Eagerly read data to array on system property - make safeguard on file inputstream impls opt-in * Reimplement skipping in DicoogleDcmSend#writeTo - use also reads to ensure consumption without getting stuck --------- Co-authored-by: Eduardo Pinho ",https://github.com/bioinformatics-ua/dicoogle/commit/031537a9fc2498942b326369f79c4d9f2a5f751e,,,dicoogle/src/main/java/pt/ua/dicoogle/server/queryretrieve/DicoogleDcmSend.java,3,java,False,2023-02-13T09:58:03Z "def add_module(parent, name, uri, options, conf, **kwargs): if uri is None: # options add only, lookup from existing modules uri = modules[name].urlstring target_dir = join(subproject_dir, name) target_dir_rp = os.path.join(os.path.realpath(target_dir), '') if not target_dir_rp.startswith(source_dir_rp): raise QuarkError("""""" Subproject `%s` (URI: %s) is trying to escape from the main project directory (`%s`) subproject realpath: %s main project realpath: %s"""""" % (name, uri, source_dir, target_dir_rp, source_dir_rp)) newmodule = Subproject.create(name, uri, target_dir, options, conf, **kwargs) mod = modules.setdefault(name, newmodule) if mod is newmodule: mod.parents.add(parent) if update: mod.update() else: if newmodule.exclude_from_cmake != mod.exclude_from_cmake: children_conf = [join(parent.directory, dependency_file) for parent in mod.parents] parent_conf = join(parent.directory, dependency_file) raise ValueError(""Conflicting value of 'exclude_from_cmake'"" "" attribute for module '%s': %r required by %s and %r required by %s"" % (name, mod.exclude_from_cmake, children_conf, newmodule.exclude_from_cmake, parent_conf) ) if not newmodule.same_checkout(mod) and uri is not None: children = [join(parent.directory, dependency_file) for parent in mod.parents] parent = join(parent.directory, dependency_file) raise ValueError( ""Conflicting URLs for module '%s': '%s' required by %s and '%s' required by '%s'"" % (name, mod.urlstring, children, newmodule.urlstring, parent)) else: for key, value in options.items(): mod.options.setdefault(key, value) if mod.options[key] != value: raise ValueError( ""Conflicting values option '%s' of module '%s'"" % (key, mod.name) ) stack.append(mod) parent.children.add(mod)","def add_module(parent, name, uri, options, conf, **kwargs): if uri is None: # options add only, lookup from existing modules uri = modules[name].urlstring target_dir = join(subproject_dir, name) target_dir_rp = os.path.join(os.path.abspath(target_dir), '') if not target_dir_rp.startswith(source_dir_rp): raise QuarkError("""""" Subproject `%s` (URI: %s) is trying to escape from the main project directory (`%s`) subproject abspath: %s main project abspath: %s"""""" % (name, uri, source_dir, target_dir_rp, source_dir_rp)) newmodule = Subproject.create(name, uri, target_dir, options, conf, **kwargs) mod = modules.setdefault(name, newmodule) if mod is newmodule: mod.parents.add(parent) if update: mod.update() else: if newmodule.exclude_from_cmake != mod.exclude_from_cmake: children_conf = [join(parent.directory, dependency_file) for parent in mod.parents] parent_conf = join(parent.directory, dependency_file) raise ValueError(""Conflicting value of 'exclude_from_cmake'"" "" attribute for module '%s': %r required by %s and %r required by %s"" % (name, mod.exclude_from_cmake, children_conf, newmodule.exclude_from_cmake, parent_conf) ) if not newmodule.same_checkout(mod) and uri is not None: children = [join(parent.directory, dependency_file) for parent in mod.parents] parent = join(parent.directory, dependency_file) raise ValueError( ""Conflicting URLs for module '%s': '%s' required by %s and '%s' required by '%s'"" % (name, mod.urlstring, children, newmodule.urlstring, parent)) else: for key, value in options.items(): mod.options.setdefault(key, value) if mod.options[key] != value: raise ValueError( ""Conflicting values option '%s' of module '%s'"" % (key, mod.name) ) stack.append(mod) parent.children.add(mod)","Path traversal: use abspath instead of realpath It blocks naive .. stuff anyway, but still allows developers leeway to play tricks with symlinks outside of the sandbox",https://github.com/comelz/quark/commit/9b73dec942dcdf075bc026cc4de7007e564d23f3,,,quark/subproject.py,3,py,False,2019-03-26T09:52:29Z "protected final void checkOpen() throws SQLException { if (pointer == 0) throw new SQLException(""statement is not executing""); }","protected final void checkOpen() throws SQLException { if (pointer.isClosed()) throw new SQLException(""statement is not executing""); }",Wrap Statement Pointers to prevent use after free race,https://github.com/xerial/sqlite-jdbc/commit/e1d282cb2887ef427c7ad93d4fe7dd05a6c11473,,,src/main/java/org/sqlite/core/CoreStatement.java,3,java,False,2022-07-29T03:54:01Z "@Override public TokensList getCompletionsFromTokenInLocalScope(IModule module, ICompletionState state, boolean searchSameLevelMods, boolean lookForArgumentCompletion, ILocalScope localScope) throws CompletionRecursionException { TokensList tokens; //now, if we have to look for arguments and search things in the local scope, let's also //check for assert (isinstance...) in this scope with the given variable. List lookForClass = localScope.getPossibleClassesForActivationToken(state .getActivationToken()); if (lookForClass.size() > 0) { List lst = new ArrayList<>(lookForClass.size()); for (ITypeInfo s : lookForClass) { Object nodeObject = s.getNode(); if (nodeObject instanceof Subscript) { Subscript subscript = (Subscript) nodeObject; if (isNodeTypingUnionSubscript(module, subscript)) { List subscriptValues = NodeUtils.extractValuesFromSubscriptSlice(subscript.slice); for (String token : subscriptValues) { lst.add(new TypeInfo(token.trim())); } } lst.add(s.getPackedType()); } else if (nodeObject instanceof BinOp) { BinOp binOp = (BinOp) nodeObject; List binOpValues = NodeUtils.extractValuesFromBinOp(binOp, BinOp.BitOr); for (String token : binOpValues) { lst.add(new TypeInfo(token.trim())); } } else { lst.add(s.getPackedType()); } } lookForClass = lst; TokensList completionsForClassInLocalScope = getCompletionsForClassInLocalScope(module, state, searchSameLevelMods, lookForArgumentCompletion, lookForClass); if (completionsForClassInLocalScope.size() > 0) { return completionsForClassInLocalScope; } else { //Give a chance to find it without the scope //Try to deal with some token that's not imported TokensList ret = getCompletionsFromTypeRepresentation(state, lookForClass, module); if (ret != null && ret.size() > 0) { return ret; } } } //ok, didn't find in assert isinstance... keep going //if there was no assert for the class, get from extensions / local scope interface tokens = CompletionParticipantsHelper.getCompletionsForMethodParameter(state, localScope); if (tokens != null && tokens.size() > 0) { return tokens; } return null; }","@Override public TokensList getCompletionsFromTokenInLocalScope(IModule module, ICompletionState state, boolean searchSameLevelMods, boolean lookForArgumentCompletion, ILocalScope localScope) throws CompletionRecursionException { if (state.pushGettingCompletionsFromTokenInLocalScope(module, state.getActivationToken(), localScope)) { try { return getCompletionsFromTokenInLocalScopeInternal(module, state, searchSameLevelMods, lookForArgumentCompletion, localScope); } finally { state.popGettingCompletionsFromTokenInLocalScope(module, state.getActivationToken(), localScope); } } return new TokensList(); }",Fix stack overflow checking for unexisting class used with typing.cast / Fix issue where values for typing.cast could be gotten from the wrong scope.,https://github.com/fabioz/Pydev/commit/51c135aedd1d2f6ce33422c0b0f50bd3d61e5264,,,plugins/org.python.pydev.ast/src/org/python/pydev/ast/codecompletion/revisited/AbstractASTManager.java,3,java,False,2023-01-21T16:28:21Z "@Override public String getQueryString() { String value = super.getQueryString(); if (value == null) { return null; } return HtmlUtils.htmlEscape(value); }","@Override public String getQueryString() { String value = super.getQueryString(); if (value == null) { return null; } return HtmlUtils.cleanUnSafe(value); }",:zap: 使用 Jackson2ObjectMapperBuilder 构造 ObjectMapper,保留使用配置文件配置 jackson 属性的能力,以及方便用户增加自定义配置,https://github.com/ballcat-projects/ballcat/commit/d4d5d4c4aa4402bec83db4eab7007f0cf70e8e01,,,ballcat-common/ballcat-common-core/src/main/java/com/hccake/ballcat/common/core/request/wrapper/XSSRequestWrapper.java,3,java,False,2021-03-08T14:05:28Z "private boolean updateUserPictureAndName(Profile showUser, String picture, String name) { boolean updateProfile = false; boolean updateUser = false; User u = showUser.getUser(); if (Config.getConfigBoolean(""avatar_edits_enabled"", true) && !StringUtils.isBlank(picture)) { AvatarStorageResult result = avatarRepository.store(showUser, picture); updateProfile = result.isProfileChanged(); updateUser = result.isUserChanged(); } if (Config.getConfigBoolean(""name_edits_enabled"", true) && !StringUtils.isBlank(name)) { showUser.setName(name); if (StringUtils.isBlank(showUser.getOriginalName())) { showUser.setOriginalName(name); } if (!u.getName().equals(name)) { u.setName(name); updateUser = true; } updateProfile = true; } if (updateUser) { utils.getParaClient().update(u); } return updateProfile; }","private boolean updateUserPictureAndName(Profile showUser, String picture, String name) { boolean updateProfile = false; boolean updateUser = false; User u = showUser.getUser(); if (Config.getConfigBoolean(""avatar_edits_enabled"", true) && !StringUtils.isBlank(picture)) { updateProfile = avatarRepository.store(showUser, picture); } if (Config.getConfigBoolean(""name_edits_enabled"", true) && !StringUtils.isBlank(name)) { showUser.setName(name); if (StringUtils.isBlank(showUser.getOriginalName())) { showUser.setOriginalName(name); } if (!u.getName().equals(name)) { u.setName(name); updateUser = true; } updateProfile = true; } if (updateUser) { utils.getParaClient().update(u); } return updateProfile; }","added ImgurAvatarRepository, removed support for adding insecure custom avatar links",https://github.com/Erudika/scoold/commit/78f60b679d20a48f98ced178b9d93206e02c2637,,,src/main/java/com/erudika/scoold/controllers/ProfileController.java,3,java,False,2022-01-19T16:36:35Z "private static Throwable getRootCause(Throwable throwable) { Throwable t = throwable; while (true) { if (t.getCause() == null) { return t; } t = t.getCause(); } }","private static Throwable getRootCause(Throwable throwable) { Throwable t = throwable; List causes = new ArrayList<>(); while (true) { if (t.getCause() == null || causes.contains(t)) { return t; } causes.add(t); t = t.getCause(); } }",Prevent infinite loops in getRootCause,https://github.com/arteam/simple-json-rpc/commit/dc60da897af0f681d04c2617836f47c8f6696641,,,server/src/main/java/com/github/arteam/simplejsonrpc/server/JsonRpcServer.java,3,java,False,2022-03-15T08:04:57Z "private void sendAuthorizationConsent(HttpServletRequest request, HttpServletResponse response, OAuth2AuthorizationCodeRequestAuthenticationToken authorizationCodeRequestAuthentication, OAuth2AuthorizationConsentAuthenticationToken authorizationConsentAuthentication) throws IOException { String clientId = authorizationConsentAuthentication.getClientId(); Authentication principal = (Authentication) authorizationConsentAuthentication.getPrincipal(); Set requestedScopes = authorizationCodeRequestAuthentication.getScopes(); Set authorizedScopes = authorizationConsentAuthentication.getScopes(); String state = authorizationConsentAuthentication.getState(); if (hasConsentUri()) { String redirectUri = UriComponentsBuilder.fromUriString(resolveConsentUri(request)) .queryParam(OAuth2ParameterNames.SCOPE, String.join("" "", requestedScopes)) .queryParam(OAuth2ParameterNames.CLIENT_ID, clientId) .queryParam(OAuth2ParameterNames.STATE, state) .toUriString(); this.redirectStrategy.sendRedirect(request, response, redirectUri); } else { DefaultConsentPage.displayConsent(request, response, clientId, principal, requestedScopes, authorizedScopes, state); } }","private void sendAuthorizationConsent(HttpServletRequest request, HttpServletResponse response, OAuth2AuthorizationCodeRequestAuthenticationToken authorizationCodeRequestAuthentication, OAuth2AuthorizationConsentAuthenticationToken authorizationConsentAuthentication) throws IOException { String clientId = authorizationConsentAuthentication.getClientId(); Authentication principal = (Authentication) authorizationConsentAuthentication.getPrincipal(); Set requestedScopes = authorizationCodeRequestAuthentication.getScopes(); Set authorizedScopes = authorizationConsentAuthentication.getScopes(); String state = authorizationConsentAuthentication.getState(); if (hasConsentUri()) { UriComponentsBuilder uriBuilder = UriComponentsBuilder.fromUriString(resolveConsentUri(request)) .queryParam(OAuth2ParameterNames.SCOPE, String.join("" "", requestedScopes)) .queryParam(OAuth2ParameterNames.CLIENT_ID, clientId) .queryParam(OAuth2ParameterNames.STATE, ""{state}""); HashMap queryParameters = new HashMap<>(1); queryParameters.put(OAuth2ParameterNames.STATE, state); String redirectUri = uriBuilder.build(queryParameters).toString(); this.redirectStrategy.sendRedirect(request, response, redirectUri); } else { DefaultConsentPage.displayConsent(request, response, clientId, principal, requestedScopes, authorizedScopes, state); } }","Fix URL encoding for authorization request state parameter Closes gh-875",https://github.com/spring-projects/spring-authorization-server/commit/356d669a78ea860f9e018791e21fc600eb30e4b5,,,oauth2-authorization-server/src/main/java/org/springframework/security/oauth2/server/authorization/web/OAuth2AuthorizationEndpointFilter.java,3,java,False,2022-10-24T19:45:32Z "public static String readUTF(DataInput in) throws IOException { String s; if (in instanceof BufferInput) { s = ((BufferInput) in).readSafeUTF(); } else if (in instanceof PofInputStream) { s = in.readUTF(); } else { int cb = readInt(in); if (cb < 0) { return null; } else if (cb == 0) { return """"; } // get the ""UTF binary"" byte[] ab = new byte[cb]; in.readFully(ab); s = convertUTF(ab, 0, cb, new char[cb]); } return s; }","public static String readUTF(DataInput in) throws IOException { String s; if (in instanceof BufferInput) { s = ((BufferInput) in).readSafeUTF(); } else if (in instanceof PofInputStream) { s = in.readUTF(); } else { int cb = readInt(in); if (cb < 0) { return null; } else if (cb == 0) { return """"; } // get the ""UTF binary"" byte[] ab; if (cb < CHUNK_THRESHOLD) { ab = new byte[cb]; in.readFully(ab); } else { ab = readLargeByteArray(in, cb); } s = convertUTF(ab, 0, cb, new char[cb]); } return s; }","Bug 32470544 - [32421840->14.1.1.0.6-CE] T3 AND IIOP DESERIALIZATION - DOS ATTACKS BY CONSTRUCTING MALICIOUS BYTECODE. RQ: http://home.us.oracle.com/internal/coherence/coherence-ce/release/coherence-ce-v14.1.1.0/job.jsp?id=job.9.20210721215426.21598 [git-p4: depot-paths = ""//dev/coherence-ce/release/coherence-ce-v14.1.1.0/"": change = 87310]",https://github.com/oracle/coherence/commit/c0b0c2cdebdc04908f359d88b187083cc979d3e1,,,prj/coherence-core/src/main/java/com/tangosol/util/ExternalizableHelper.java,3,java,False,2021-07-22T01:38:01Z "public boolean isAbsolute() { return isValid() && parsed().scheme() != null; }","public boolean isAbsolute() { return parsed().absolute(); }",[FIX] URI Parsing: Stack Overflow. Closes #2087,https://github.com/BaseXdb/basex/commit/f57694ba156b60696e3ef4bec10d44d366dfc418,,,basex-core/src/main/java/org/basex/query/value/item/Uri.java,3,java,False,2022-04-11T16:54:06Z "public boolean skipTutorial() { if (getLocation().onTutorialIsland()) { if (inCombat()) { message(""You cannot do that whilst fighting!""); return false; } if (isBusy()) { return false; } if (getCache().hasKey(""tutorial"")) { getCache().remove(""tutorial""); } teleport(getConfig().RESPAWN_LOCATION_X, getConfig().RESPAWN_LOCATION_Y, false); message(""Skipped tutorial, welcome to Lumbridge""); ActionSender.sendPlayerOnTutorial(this); return true; } return false; }","public boolean skipTutorial() { if (getLocation().onTutorialIsland() && this.getWorld().getServer().getConfig().SHOW_TUTORIAL_SKIP_OPTION) { if (inCombat()) { message(""You cannot do that whilst fighting!""); return false; } if (isBusy()) { return false; } if (getCache().hasKey(""tutorial"")) { getCache().remove(""tutorial""); } teleport(getConfig().RESPAWN_LOCATION_X, getConfig().RESPAWN_LOCATION_Y, false); message(""Skipped tutorial, welcome to Lumbridge""); ActionSender.sendPlayerOnTutorial(this); return true; } return false; }",CF-3001 | Moved show_tutorial_skip_option to skipTutorial function to avoid bypassing the tutorial via ::skiptutorial,https://github.com/Open-RSC/Core-Framework/commit/7ff993f96a077756e1b0e7ff96d72f8c40c585b9,,,server/src/com/openrsc/server/model/entity/player/Player.java,3,java,False,2021-09-16T03:49:28Z "@Override protected void initChannel(final Channel ch) { ch.pipeline() .addLast(READ_TIMEOUT, new ReadTimeoutHandler(this.server.getConfiguration().getReadTimeout(), TimeUnit.MILLISECONDS)) .addLast(LEGACY_PING_DECODER, new LegacyPingDecoder()) .addLast(FRAME_DECODER, new MinecraftVarintFrameDecoder()) .addLast(LEGACY_PING_ENCODER, LegacyPingEncoder.INSTANCE) .addLast(FRAME_ENCODER, MinecraftVarintLengthEncoder.INSTANCE) .addLast(MINECRAFT_DECODER, new MinecraftDecoder(ProtocolUtils.Direction.SERVERBOUND)) .addLast(MINECRAFT_ENCODER, new MinecraftEncoder(ProtocolUtils.Direction.CLIENTBOUND)); final MinecraftConnection connection = new MinecraftConnection(ch, this.server); connection.setSessionHandler(new HandshakeSessionHandler(connection, this.server)); ch.pipeline().addLast(Connections.HANDLER, connection); if (this.server.getConfiguration().isProxyProtocol()) { ch.pipeline().addFirst(new HAProxyMessageDecoder()); } }","@Override protected void initChannel(final Channel ch) { ch.pipeline() .addLast(LEGACY_PING_DECODER, new LegacyPingDecoder()) .addLast(FRAME_DECODER, new MinecraftVarintFrameDecoder()) .addLast(READ_TIMEOUT, new ReadTimeoutHandler(this.server.getConfiguration().getReadTimeout(), TimeUnit.MILLISECONDS)) .addLast(LEGACY_PING_ENCODER, LegacyPingEncoder.INSTANCE) .addLast(FRAME_ENCODER, MinecraftVarintLengthEncoder.INSTANCE) .addLast(MINECRAFT_DECODER, new MinecraftDecoder(ProtocolUtils.Direction.SERVERBOUND)) .addLast(MINECRAFT_ENCODER, new MinecraftEncoder(ProtocolUtils.Direction.CLIENTBOUND)); final MinecraftConnection connection = new MinecraftConnection(ch, this.server); connection.setSessionHandler(new HandshakeSessionHandler(connection, this.server)); ch.pipeline().addLast(Connections.HANDLER, connection); if (this.server.getConfiguration().isProxyProtocol()) { ch.pipeline().addFirst(new HAProxyMessageDecoder()); } }","Move timeout handler to after frame decoder Mitigates attacks like the one described in SpigotMC/BungeeCord#3066. This cannot be considered a full protection, only a mitigation that expects full packets. The attack described is essentially the infamous Slowloris attack.",https://github.com/PaperMC/Velocity/commit/f1cb3eb1a28bc5003d8dd844b5cdf990970ab89d,,,proxy/src/main/java/com/velocitypowered/proxy/network/ServerChannelInitializer.java,3,java,False,2021-04-16T02:56:37Z "public @Nullable Typeface getTypeface( String fontFamilyName, int style, int weight, AssetManager assetManager) { if (mCustomTypefaceCache.containsKey(fontFamilyName)) { Typeface typeface = mCustomTypefaceCache.get(fontFamilyName); if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.P && weight >= 100 && weight <= 1000) { return Typeface.create(typeface, weight, (style & Typeface.ITALIC) != 0); } return Typeface.create(typeface, style); } FontFamily fontFamily = mFontCache.get(fontFamilyName); if (fontFamily == null) { fontFamily = new FontFamily(); mFontCache.put(fontFamilyName, fontFamily); } Typeface typeface = fontFamily.getTypeface(style); if (typeface == null) { typeface = createTypeface(fontFamilyName, style, assetManager); if (typeface != null) { fontFamily.setTypeface(style, typeface); } } return typeface; }","public Typeface getTypeface( String fontFamilyName, int style, int weight, AssetManager assetManager) { return getTypeface(fontFamilyName, new TypefaceStyle(style, weight), assetManager); }","RN: Unify Typeface Logic (Android) Summary: Refactors how `Typeface` style and weight are applied in React Native on Android. - Unifies all style and weight normalization logic into a new `TypefaceStyle` class. - Fixes font weight support for the Fabric renderer. - De-duplicates code with `TextAttributeProps`. - Simplified normalization logic. - Fixes a rare crash due to `Typeface.sDefaultTypeface` (Android SDK) being `null`. - Adds a new example to test font weights in `TextInput`. - Adds missing `Nullsafe` and `Nullable` annotations. - Clean up a bunch of obsolete inline comments. Changelog: [Android][Fixed] - Fixed a rare crash due to `Typeface.sDefaultTypeface` (Android SDK) being `null`. [Android][Fixed] - Fixed font weight support for the Fabric renderer. [Android][Added] - Added a new example to test font weights in `TextInput`. Reviewed By: JoshuaGross Differential Revision: D29631134 fbshipit-source-id: 3f227d84253104fa828a5561b77ba7a9cbc030c4",https://github.com/react-native-tvos/react-native-tvos/commit/9d2fedc6e22ca1b45fbc2059971cd194de5d0170,,,ReactAndroid/src/main/java/com/facebook/react/views/text/ReactFontManager.java,3,java,False,2021-07-13T05:16:00Z "private ServiceResponse executePut(ServiceRequest request, ServiceResponse response) { PersistenceManager pm = null; try { if (request.getUrlPath() == null || request.getUrlPath().equals(""/"")) { return errorResponse(response, 400, ""PATCH only allowed on Entities.""); } pm = getPm(); return handlePut(pm, request, response); } catch (IncompleteEntityException | IOException | RuntimeException e) { LOGGER.error("""", e); if (pm != null) { pm.rollbackAndClose(); } return errorResponse(response, 400, e.getMessage()); } finally { maybeRollbackAndClose(); } }","private ServiceResponse executePut(ServiceRequest request, ServiceResponse response) { PersistenceManager pm = null; try { if (request.getUrlPath() == null || request.getUrlPath().equals(""/"")) { return errorResponse(response, 400, ""PATCH only allowed on Entities.""); } pm = getPm(); return handlePut(pm, request, response); } catch (UnauthorizedException e) { rollbackAndClose(pm); return errorResponse(response, 401, e.getMessage()); } catch (ForbiddenException e) { rollbackAndClose(pm); return errorResponse(response, 403, e.getMessage()); } catch (IncompleteEntityException | IOException | RuntimeException e) { LOGGER.error("""", e); rollbackAndClose(pm); return errorResponse(response, 400, e.getMessage()); } finally { maybeRollbackAndClose(); } }",Added Forbidden- and UnauthorizedExceptions,https://github.com/FraunhoferIOSB/FROST-Server/commit/e72e4ee2e7d33b58da29c434d0ff63de5f656ee4,,,FROST-Server.Core/src/main/java/de/fraunhofer/iosb/ilt/frostserver/service/Service.java,3,java,False,2021-12-01T19:48:43Z "@Override protected void handleProducer(final CommandProducer cmdProducer) { checkArgument(state == State.Connected); final long producerId = cmdProducer.getProducerId(); final long requestId = cmdProducer.getRequestId(); // Use producer name provided by client if present final String producerName = cmdProducer.hasProducerName() ? cmdProducer.getProducerName() : service.generateUniqueProducerName(); final long epoch = cmdProducer.getEpoch(); final boolean userProvidedProducerName = cmdProducer.getUserProvidedProducerName(); final boolean isEncrypted = cmdProducer.getEncrypted(); final Map metadata = CommandUtils.metadataFromCommand(cmdProducer); final SchemaData schema = cmdProducer.hasSchema() ? getSchema(cmdProducer.getSchema()) : null; TopicName topicName = validateTopicName(cmdProducer.getTopic(), requestId, cmdProducer); if (topicName == null) { return; } if (invalidOriginalPrincipal(originalPrincipal)) { final String msg = ""Valid Proxy Client role should be provided while creating producer ""; log.warn(""[{}] {} with role {} and proxyClientAuthRole {} on topic {}"", remoteAddress, msg, authRole, originalPrincipal, topicName); commandSender.sendErrorResponse(requestId, ServerError.AuthorizationError, msg); return; } CompletableFuture isAuthorizedFuture = isTopicOperationAllowed( topicName, TopicOperation.PRODUCE ); isAuthorizedFuture.thenApply(isAuthorized -> { if (isAuthorized) { if (log.isDebugEnabled()) { log.debug(""[{}] Client is authorized to Produce with role {}"", remoteAddress, getPrincipal()); } CompletableFuture producerFuture = new CompletableFuture<>(); CompletableFuture existingProducerFuture = producers.putIfAbsent(producerId, producerFuture); if (existingProducerFuture != null) { if (existingProducerFuture.isDone() && !existingProducerFuture.isCompletedExceptionally()) { Producer producer = existingProducerFuture.getNow(null); log.info(""[{}] Producer with the same id is already created:"" + "" producerId={}, producer={}"", remoteAddress, producerId, producer); commandSender.sendProducerSuccessResponse(requestId, producer.getProducerName(), producer.getSchemaVersion()); return null; } else { // There was an early request to create a producer with // same producerId. This can happen when // client // timeout is lower the broker timeouts. We need to wait // until the previous producer creation // request // either complete or fails. ServerError error = null; if(!existingProducerFuture.isDone()) { error = ServerError.ServiceNotReady; } else { error = getErrorCode(existingProducerFuture); // remove producer with producerId as it's already completed with exception producers.remove(producerId, existingProducerFuture); } log.warn(""[{}][{}] Producer with id is already present on the connection,"" + "" producerId={}"", remoteAddress, topicName, producerId); commandSender.sendErrorResponse(requestId, error, ""Producer is already present on the connection""); return null; } } log.info(""[{}][{}] Creating producer. producerId={}"", remoteAddress, topicName, producerId); service.getOrCreateTopic(topicName.toString()).thenAccept((Topic topic) -> { // Before creating producer, check if backlog quota exceeded // on topic if (topic.isBacklogQuotaExceeded(producerName)) { IllegalStateException illegalStateException = new IllegalStateException( ""Cannot create producer on topic with backlog quota exceeded""); BacklogQuota.RetentionPolicy retentionPolicy = topic.getBacklogQuota().getPolicy(); if (retentionPolicy == BacklogQuota.RetentionPolicy.producer_request_hold) { commandSender.sendErrorResponse(requestId, ServerError.ProducerBlockedQuotaExceededError, illegalStateException.getMessage()); } else if (retentionPolicy == BacklogQuota.RetentionPolicy.producer_exception) { commandSender.sendErrorResponse(requestId, ServerError.ProducerBlockedQuotaExceededException, illegalStateException.getMessage()); } producerFuture.completeExceptionally(illegalStateException); producers.remove(producerId, producerFuture); return; } // Check whether the producer will publish encrypted messages or not if ((topic.isEncryptionRequired() || encryptionRequireOnProducer) && !isEncrypted) { String msg = String.format(""Encryption is required in %s"", topicName); log.warn(""[{}] {}"", remoteAddress, msg); commandSender.sendErrorResponse(requestId, ServerError.MetadataError, msg); producers.remove(producerId, producerFuture); return; } disableTcpNoDelayIfNeeded(topicName.toString(), producerName); CompletableFuture schemaVersionFuture = tryAddSchema(topic, schema); schemaVersionFuture.exceptionally(exception -> { commandSender.sendErrorResponse(requestId, BrokerServiceException.getClientErrorCode(exception), exception.getMessage()); producers.remove(producerId, producerFuture); return null; }); schemaVersionFuture.thenAccept(schemaVersion -> { Producer producer = new Producer(topic, ServerCnx.this, producerId, producerName, getPrincipal(), isEncrypted, metadata, schemaVersion, epoch, userProvidedProducerName); try { topic.addProducer(producer); if (isActive()) { if (producerFuture.complete(producer)) { log.info(""[{}] Created new producer: {}"", remoteAddress, producer); commandSender.sendProducerSuccessResponse(requestId, producerName, producer.getLastSequenceId(), producer.getSchemaVersion()); return; } else { // The producer's future was completed before by // a close command producer.closeNow(true); log.info(""[{}] Cleared producer created after timeout on client side {}"", remoteAddress, producer); } } else { producer.closeNow(true); log.info(""[{}] Cleared producer created after connection was closed: {}"", remoteAddress, producer); producerFuture.completeExceptionally( new IllegalStateException(""Producer created after connection was closed"")); } } catch (Exception ise) { log.error(""[{}] Failed to add producer to topic {}: {}"", remoteAddress, topicName, ise.getMessage()); commandSender.sendErrorResponse(requestId, BrokerServiceException.getClientErrorCode(ise), ise.getMessage()); producerFuture.completeExceptionally(ise); } producers.remove(producerId, producerFuture); }); }).exceptionally(exception -> { Throwable cause = exception.getCause(); if (cause instanceof NoSuchElementException) { cause = new TopicNotFoundException(""Topic Not Found.""); log.info(""[{}] Failed to load topic {}, producerId={}: Topic not found"", remoteAddress, topicName, producerId); } else if (!Exceptions.areExceptionsPresentInChain(cause, ServiceUnitNotReadyException.class, ManagedLedgerException.class)) { // Do not print stack traces for expected exceptions log.error(""[{}] Failed to create topic {}, producerId={}"", remoteAddress, topicName, producerId, exception); } // If client timed out, the future would have been completed // by subsequent close. Send error back to // client, only if not completed already. if (producerFuture.completeExceptionally(exception)) { commandSender.sendErrorResponse(requestId, BrokerServiceException.getClientErrorCode(cause), cause.getMessage()); } producers.remove(producerId, producerFuture); return null; }); } else { String msg = ""Client is not authorized to Produce""; log.warn(""[{}] {} with role {}"", remoteAddress, msg, getPrincipal()); ctx.writeAndFlush(Commands.newError(requestId, ServerError.AuthorizationError, msg)); } return null; }).exceptionally(ex -> { logAuthException(remoteAddress, ""producer"", getPrincipal(), Optional.of(topicName), ex); commandSender.sendErrorResponse(requestId, ServerError.AuthorizationError, ex.getMessage()); return null; }); }","@Override protected void handleProducer(final CommandProducer cmdProducer) { checkArgument(state == State.Connected); final long producerId = cmdProducer.getProducerId(); final long requestId = cmdProducer.getRequestId(); // Use producer name provided by client if present final String producerName = cmdProducer.hasProducerName() ? cmdProducer.getProducerName() : service.generateUniqueProducerName(); final long epoch = cmdProducer.getEpoch(); final boolean userProvidedProducerName = cmdProducer.getUserProvidedProducerName(); final boolean isEncrypted = cmdProducer.getEncrypted(); final Map metadata = CommandUtils.metadataFromCommand(cmdProducer); final SchemaData schema = cmdProducer.hasSchema() ? getSchema(cmdProducer.getSchema()) : null; TopicName topicName = validateTopicName(cmdProducer.getTopic(), requestId, cmdProducer); if (topicName == null) { return; } if (invalidOriginalPrincipal(originalPrincipal)) { final String msg = ""Valid Proxy Client role should be provided while creating producer ""; log.warn(""[{}] {} with role {} and proxyClientAuthRole {} on topic {}"", remoteAddress, msg, authRole, originalPrincipal, topicName); commandSender.sendErrorResponse(requestId, ServerError.AuthorizationError, msg); return; } CompletableFuture isAuthorizedFuture = isTopicOperationAllowed( topicName, TopicOperation.PRODUCE, getAuthenticationData() ); isAuthorizedFuture.thenApply(isAuthorized -> { if (isAuthorized) { if (log.isDebugEnabled()) { log.debug(""[{}] Client is authorized to Produce with role {}"", remoteAddress, getPrincipal()); } CompletableFuture producerFuture = new CompletableFuture<>(); CompletableFuture existingProducerFuture = producers.putIfAbsent(producerId, producerFuture); if (existingProducerFuture != null) { if (existingProducerFuture.isDone() && !existingProducerFuture.isCompletedExceptionally()) { Producer producer = existingProducerFuture.getNow(null); log.info(""[{}] Producer with the same id is already created:"" + "" producerId={}, producer={}"", remoteAddress, producerId, producer); commandSender.sendProducerSuccessResponse(requestId, producer.getProducerName(), producer.getSchemaVersion()); return null; } else { // There was an early request to create a producer with // same producerId. This can happen when // client // timeout is lower the broker timeouts. We need to wait // until the previous producer creation // request // either complete or fails. ServerError error = null; if(!existingProducerFuture.isDone()) { error = ServerError.ServiceNotReady; } else { error = getErrorCode(existingProducerFuture); // remove producer with producerId as it's already completed with exception producers.remove(producerId, existingProducerFuture); } log.warn(""[{}][{}] Producer with id is already present on the connection,"" + "" producerId={}"", remoteAddress, topicName, producerId); commandSender.sendErrorResponse(requestId, error, ""Producer is already present on the connection""); return null; } } log.info(""[{}][{}] Creating producer. producerId={}"", remoteAddress, topicName, producerId); service.getOrCreateTopic(topicName.toString()).thenAccept((Topic topic) -> { // Before creating producer, check if backlog quota exceeded // on topic if (topic.isBacklogQuotaExceeded(producerName)) { IllegalStateException illegalStateException = new IllegalStateException( ""Cannot create producer on topic with backlog quota exceeded""); BacklogQuota.RetentionPolicy retentionPolicy = topic.getBacklogQuota().getPolicy(); if (retentionPolicy == BacklogQuota.RetentionPolicy.producer_request_hold) { commandSender.sendErrorResponse(requestId, ServerError.ProducerBlockedQuotaExceededError, illegalStateException.getMessage()); } else if (retentionPolicy == BacklogQuota.RetentionPolicy.producer_exception) { commandSender.sendErrorResponse(requestId, ServerError.ProducerBlockedQuotaExceededException, illegalStateException.getMessage()); } producerFuture.completeExceptionally(illegalStateException); producers.remove(producerId, producerFuture); return; } // Check whether the producer will publish encrypted messages or not if ((topic.isEncryptionRequired() || encryptionRequireOnProducer) && !isEncrypted) { String msg = String.format(""Encryption is required in %s"", topicName); log.warn(""[{}] {}"", remoteAddress, msg); commandSender.sendErrorResponse(requestId, ServerError.MetadataError, msg); producers.remove(producerId, producerFuture); return; } disableTcpNoDelayIfNeeded(topicName.toString(), producerName); CompletableFuture schemaVersionFuture = tryAddSchema(topic, schema); schemaVersionFuture.exceptionally(exception -> { commandSender.sendErrorResponse(requestId, BrokerServiceException.getClientErrorCode(exception), exception.getMessage()); producers.remove(producerId, producerFuture); return null; }); schemaVersionFuture.thenAccept(schemaVersion -> { Producer producer = new Producer(topic, ServerCnx.this, producerId, producerName, getPrincipal(), isEncrypted, metadata, schemaVersion, epoch, userProvidedProducerName); try { topic.addProducer(producer); if (isActive()) { if (producerFuture.complete(producer)) { log.info(""[{}] Created new producer: {}"", remoteAddress, producer); commandSender.sendProducerSuccessResponse(requestId, producerName, producer.getLastSequenceId(), producer.getSchemaVersion()); return; } else { // The producer's future was completed before by // a close command producer.closeNow(true); log.info(""[{}] Cleared producer created after timeout on client side {}"", remoteAddress, producer); } } else { producer.closeNow(true); log.info(""[{}] Cleared producer created after connection was closed: {}"", remoteAddress, producer); producerFuture.completeExceptionally( new IllegalStateException(""Producer created after connection was closed"")); } } catch (Exception ise) { log.error(""[{}] Failed to add producer to topic {}: {}"", remoteAddress, topicName, ise.getMessage()); commandSender.sendErrorResponse(requestId, BrokerServiceException.getClientErrorCode(ise), ise.getMessage()); producerFuture.completeExceptionally(ise); } producers.remove(producerId, producerFuture); }); }).exceptionally(exception -> { Throwable cause = exception.getCause(); if (cause instanceof NoSuchElementException) { cause = new TopicNotFoundException(""Topic Not Found.""); log.info(""[{}] Failed to load topic {}, producerId={}: Topic not found"", remoteAddress, topicName, producerId); } else if (!Exceptions.areExceptionsPresentInChain(cause, ServiceUnitNotReadyException.class, ManagedLedgerException.class)) { // Do not print stack traces for expected exceptions log.error(""[{}] Failed to create topic {}, producerId={}"", remoteAddress, topicName, producerId, exception); } // If client timed out, the future would have been completed // by subsequent close. Send error back to // client, only if not completed already. if (producerFuture.completeExceptionally(exception)) { commandSender.sendErrorResponse(requestId, BrokerServiceException.getClientErrorCode(cause), cause.getMessage()); } producers.remove(producerId, producerFuture); return null; }); } else { String msg = ""Client is not authorized to Produce""; log.warn(""[{}] {} with role {}"", remoteAddress, msg, getPrincipal()); ctx.writeAndFlush(Commands.newError(requestId, ServerError.AuthorizationError, msg)); } return null; }).exceptionally(ex -> { logAuthException(remoteAddress, ""producer"", getPrincipal(), Optional.of(topicName), ex); commandSender.sendErrorResponse(requestId, ServerError.AuthorizationError, ex.getMessage()); return null; }); }","Avoid AuthenticationDataSource mutation for subscription name (#16065) The `authenticationData` field in `ServerCnx` is being mutated to add the `subscription` field that will be passed on to the authorization plugin. The problem is that `authenticationData` is scoped to the whole connection and it should be getting mutated for each consumer that is created on the connection. The current code leads to a race condition where the subscription name used in the authz plugin is already modified while we're looking at it. Instead, we should create a new object and enforce the final modifier. (cherry picked from commit e6b12c64b043903eb5ff2dc5186fe8030f157cfc)",https://github.com/apache/pulsar/commit/b40e6eb7712821a8456880ca58de673bbc4bac36,,,pulsar-broker/src/main/java/org/apache/pulsar/broker/service/ServerCnx.java,3,java,False,2022-06-15T07:00:28Z "private CompletableFuture createConnection(InetSocketAddress unresolvedAddress) { int port; CompletableFuture> resolvedAddress; try { if (isSniProxy) { URI proxyURI = new URI(clientConfig.getProxyServiceUrl()); port = proxyURI.getPort(); resolvedAddress = resolveName(proxyURI.getHost()); } else { port = unresolvedAddress.getPort(); resolvedAddress = resolveName(unresolvedAddress.getHostString()); } return resolvedAddress.thenCompose( inetAddresses -> connectToResolvedAddresses(inetAddresses.iterator(), port, isSniProxy ? unresolvedAddress : null)); } catch (URISyntaxException e) { log.error(""Invalid Proxy url {}"", clientConfig.getProxyServiceUrl(), e); return FutureUtil .failedFuture(new InvalidServiceURL(""Invalid url "" + clientConfig.getProxyServiceUrl(), e)); } }","private CompletableFuture createConnection(InetSocketAddress unresolvedAddress) { CompletableFuture> resolvedAddress; try { if (isSniProxy) { URI proxyURI = new URI(clientConfig.getProxyServiceUrl()); resolvedAddress = resolveName(InetSocketAddress.createUnresolved(proxyURI.getHost(), proxyURI.getPort())); } else { resolvedAddress = resolveName(unresolvedAddress); } return resolvedAddress.thenCompose( inetAddresses -> connectToResolvedAddresses(inetAddresses.iterator(), isSniProxy ? unresolvedAddress : null)); } catch (URISyntaxException e) { log.error(""Invalid Proxy url {}"", clientConfig.getProxyServiceUrl(), e); return FutureUtil .failedFuture(new InvalidServiceURL(""Invalid url "" + clientConfig.getProxyServiceUrl(), e)); } }","[Proxy/Client] Fix DNS server denial-of-service issue when DNS entry expires (#15403) (cherry picked from commit 40d71691dab2a09d3457f8fa638b19ebc2e28dd7)",https://github.com/apache/pulsar/commit/3673973a89525f89da27ec6f3c875e8658be5ad3,,,pulsar-client/src/main/java/org/apache/pulsar/client/impl/ConnectionPool.java,3,java,False,2022-05-03T02:59:19Z "private List getCwes(final Object value) { if (value instanceof String) { final String cweIds = (String)value; final List cwes = new ArrayList<>(); for (final String s : cweIds.split("","")) { final Cwe cwe = CweResolver.getInstance().lookup(Integer.valueOf(s)); if (cwe != null) { cwes.add(cwe); } } return cwes; } else { return null; } }","private List getCwes(final Object value) { if (value instanceof String) { final String cweIds = (String)value; if (cweIds.isEmpty()) { return null; } final List cwes = new ArrayList<>(); for (final String s : cweIds.split("","")) { final Cwe cwe = CweResolver.getInstance().lookup(Integer.valueOf(s)); if (cwe != null) { cwes.add(cwe); } } return cwes; } else { return null; } }","Fix NumberFormatException when no CWE is set for internal vulnerability Fixes #1664 Signed-off-by: nscuro ",https://github.com/DependencyTrack/dependency-track/commit/e78c0b557e1a5c4a0f60e6092ca1aeb37b0d9c7c,,,src/main/java/org/dependencytrack/model/Finding.java,3,java,False,2022-05-27T20:38:21Z "private void enforcePermission( String callingPackage, int callingUid, boolean checkCarrierPrivileges) { mAppOps.checkPackage(callingUid, callingPackage); // To gain access through the DUMP permission, the OEM has to allow this package explicitly // via sysconfig and privileged permissions. if (mBugreportWhitelistedPackages.contains(callingPackage) && mContext.checkCallingOrSelfPermission(android.Manifest.permission.DUMP) == PackageManager.PERMISSION_GRANTED) { return; } // For carrier privileges, this can include user-installed apps. This is essentially a // function of the current active SIM(s) in the device to let carrier apps through. if (checkCarrierPrivileges && mTelephonyManager.checkCarrierPrivilegesForPackageAnyPhone(callingPackage) == TelephonyManager.CARRIER_PRIVILEGE_STATUS_HAS_ACCESS) { return; } String message = callingPackage + "" does not hold the DUMP permission or is not bugreport-whitelisted "" + (checkCarrierPrivileges ? ""and does not have carrier privileges "" : """") + ""to request a bugreport""; Slog.w(TAG, message); throw new SecurityException(message); }","private void enforcePermission( String callingPackage, int callingUid, boolean checkCarrierPrivileges) { mAppOps.checkPackage(callingUid, callingPackage); // To gain access through the DUMP permission, the OEM has to allow this package explicitly // via sysconfig and privileged permissions. if (mBugreportWhitelistedPackages.contains(callingPackage) && mContext.checkCallingOrSelfPermission(android.Manifest.permission.DUMP) == PackageManager.PERMISSION_GRANTED) { return; } // For carrier privileges, this can include user-installed apps. This is essentially a // function of the current active SIM(s) in the device to let carrier apps through. final long token = Binder.clearCallingIdentity(); try { if (checkCarrierPrivileges && mTelephonyManager.checkCarrierPrivilegesForPackageAnyPhone(callingPackage) == TelephonyManager.CARRIER_PRIVILEGE_STATUS_HAS_ACCESS) { return; } } finally { Binder.restoreCallingIdentity(token); } String message = callingPackage + "" does not hold the DUMP permission or is not bugreport-whitelisted "" + (checkCarrierPrivileges ? ""and does not have carrier privileges "" : """") + ""to request a bugreport""; Slog.w(TAG, message); throw new SecurityException(message); }","Security fix: enforce read privilege permission to check package privileges in TelephonyManager Bug: 180938364 Test: cts Change-Id: I08c346c46b9e87dceaa1faf35fa36b954d88f9b0",https://github.com/omnirom/android_frameworks_base/commit/46160dc2c638ee91b07662786fd1c5ff46432985,,,services/core/java/com/android/server/os/BugreportManagerServiceImpl.java,3,java,False,2021-04-15T21:18:15Z "public static void checkSidebarRemoved(SPacketScoreboardObjective scoreboardObjective) { if (scoreboardObjective.getAction() != 1 || !scoreboardObjective.getObjectiveName().equals(sidebarObjectiveName)) { return; } objectivesPosition = 0; objectivesEnd = 0; // Sidebar scoreboard is removed removeAllObjectives(); }","public static void checkSidebarRemoved(SPacketScoreboardObjective scoreboardObjective) { if (scoreboardObjective.getAction() != 1 || !scoreboardObjective.getObjectiveName().equals(sidebarObjectiveName)) { return; } objectivesPosition = 0; // Sidebar scoreboard is removed removeAllObjectives(); }","Fix 14 issues found in ticket backlog (#502) * Fix IndexOutOfBoundsException in QuestBookListPage Signed-off-by: kristofbolyai * Fix crash if OverlayConfig.GameUpdate.INSTANCE.messageMaxLength is 1 Signed-off-by: kristofbolyai * Fix crash related to deleting chat tabs and ChatGUI not updating Signed-off-by: kristofbolyai * Fix crash related to deleting chat tabs and ChatGUI not updating Signed-off-by: kristofbolyai * Fix translation cache becoming null Signed-off-by: kristofbolyai * Fix objective parsing if player is in party Signed-off-by: kristofbolyai * Fix guild objective not being removed upon completion Signed-off-by: kristofbolyai * Fix race condition in ServerEvents Signed-off-by: kristofbolyai * Fix race condition in ClientEvents Signed-off-by: kristofbolyai * Fix NPE in ServerEvents Signed-off-by: kristofbolyai * Fix AreaDPS value not being correct Signed-off-by: kristofbolyai * Fix NPE in fix :) Signed-off-by: kristofbolyai * Fix quest dialogue spoofing Signed-off-by: kristofbolyai * Fix Keyholder related crash Signed-off-by: kristofbolyai * Fix totem tracking Signed-off-by: kristofbolyai * Dialogue Page gets updated correctly Signed-off-by: kristofbolyai * Register ChatGUI correctly Signed-off-by: kristofbolyai * Use MC's GameSettings to check for isKeyDown Signed-off-by: kristofbolyai * Make multi line if have braces Signed-off-by: kristofbolyai ",https://github.com/Wynntils/Wynntils/commit/c8f6effe187ff68f17bcff809d2bc440ec07128d,,,src/main/java/com/wynntils/modules/utilities/overlays/hud/ObjectivesOverlay.java,3,java,False,2022-04-15T17:16:00Z "SortStrategy createSortStrategy(File dir) throws IOException { switch (sortStrategyType) { case STORE_AND_SORT: log.info(""Using StoreAndSortStrategy""); return new StoreAndSortStrategy(nodeStateEntryTraverserFactory.create(new LastModifiedRange(0, Long.MAX_VALUE)), comparator, entryWriter, dir, useZip); case TRAVERSE_WITH_SORT: log.info(""Using TraverseWithSortStrategy""); return new TraverseWithSortStrategy(nodeStateEntryTraverserFactory.create(new LastModifiedRange(0, Long.MAX_VALUE)), comparator, entryWriter, dir, useZip); case MULTITHREADED_TRAVERSE_WITH_SORT: log.info(""Using MultithreadedTraverseWithSortStrategy""); return new MultithreadedTraverseWithSortStrategy(nodeStateEntryTraverserFactory, lastModifiedBreakPoints, comparator, blobStore, dir, existingDataDumpDirs, useZip, getMemoryManager()); } throw new IllegalStateException(""Not a valid sort strategy value "" + sortStrategyType); }","SortStrategy createSortStrategy(File dir) throws IOException { switch (sortStrategyType) { case STORE_AND_SORT: log.info(""Using StoreAndSortStrategy""); return new StoreAndSortStrategy(nodeStateEntryTraverserFactory, comparator, entryWriter, dir, useZip); case TRAVERSE_WITH_SORT: log.info(""Using TraverseWithSortStrategy""); return new TraverseWithSortStrategy(nodeStateEntryTraverserFactory, comparator, entryWriter, dir, useZip); case MULTITHREADED_TRAVERSE_WITH_SORT: log.info(""Using MultithreadedTraverseWithSortStrategy""); return new MultithreadedTraverseWithSortStrategy(nodeStateEntryTraverserFactory, lastModifiedBreakPoints, comparator, blobStore, dir, existingDataDumpDirs, useZip, memoryManager); } throw new IllegalStateException(""Not a valid sort strategy value "" + sortStrategyType); }","OAK-9576: Multithreaded download synchronization issues (#383) * OAK-9576 - Multithreaded download synchronization issues * Fixing a problem with test * OAK-9576: Multithreaded download synchronization issues * Fixing synchronization issues * Fixing OOM issue * Adding delay between download retries * OAK-9576: Multithreaded download synchronization issues * Using linkedlist in tasks for freeing memory early * Dumping if data is greater than one MB * OAK-9576: Multithreaded download synchronization issues * Closing node state entry traversors using try with * trivial - removing unused object * OAK-9576: Multithreaded download synchronization issues * Incorporating some feedback from review comments * OAK-9576: Multithreaded download synchronization issues * Replacing explicit synchronization with atomic operations * OAK-9576: Multithreaded download synchronization issues * Using same memory manager across retries * trivial - removing unwanted method * OAK-9576: Multithreaded download synchronization issues * Moving retry delay to exception block * trivial - correcting variable name Co-authored-by: amrverma ",https://github.com/apache/jackrabbit-oak/commit/c04aff5d970beccd41ff15c1c907f7ea6d0720fb,,,oak-run-commons/src/main/java/org/apache/jackrabbit/oak/index/indexer/document/flatfile/FlatFileNodeStoreBuilder.java,3,java,False,2021-12-01T07:03:04Z "@Override protected void onUseLocal(LiveV aValue, Local local) { aValue.used = true; }","@Override protected void onUseLocal(LiveV aValue, Local local) { if (aValue != null) { aValue.used = true; } }",Add null check to UnSSATransformer#onUseLocal to avoid NPE crashes,https://github.com/Guardsquare/proguard-core/commit/75f2a30f7ec96b5b112e8b95f5dd023bdd3c6ad3,,,android/src/main/java/proguard/dexfile/ir/ts/UnSSATransformer.java,3,java,False,2022-12-05T14:27:02Z "protected void installLibraries(@NonNull Installer installer, @NonNull Manifest manifest, @NonNull File librariesDir, @NonNull List sources) throws InterruptedException { VersionManifest versionManifest = manifest.getVersionManifest(); Iterable allLibraries = versionManifest.getLibraries(); for (LoaderManifest loader : manifest.getLoaders().values()) { allLibraries = Iterables.concat(allLibraries, loader.getLibraries()); } for (Library library : allLibraries) { if (library.matches(environment)) { checkInterrupted(); Library.Artifact artifact = library.getArtifact(environment); String path = artifact.getPath(); long size = artifact.getSize(); if (size <= 0) size = LIBRARY_SIZE_ESTIMATE; File targetFile = new File(librariesDir, path); if (!targetFile.exists()) { List urls = new ArrayList(); for (URL sourceUrl : sources) { try { urls.add(concat(sourceUrl, path)); } catch (MalformedURLException e) { log.log(Level.WARNING, ""Bad source URL for library: "" + sourceUrl); } } File tempFile = installer.getDownloader().download(urls, """", size, library.getName() + "".jar""); log.info(""Fetching "" + path + "" from "" + urls); installer.queue(new FileMover(tempFile, targetFile)); if (artifact.getSha1() != null) { installer.queue(new FileVerify(targetFile, library.getName(), artifact.getSha1())); } } } } }","protected void installLibraries(@NonNull Installer installer, @NonNull Manifest manifest, @NonNull File librariesDir, @NonNull List sources) throws InterruptedException, IOException { VersionManifest versionManifest = manifest.getVersionManifest(); Iterable allLibraries = versionManifest.getLibraries(); for (LoaderManifest loader : manifest.getLoaders().values()) { allLibraries = Iterables.concat(allLibraries, loader.getLibraries()); } for (Library library : allLibraries) { if (library.matches(environment)) { checkInterrupted(); Library.Artifact artifact = library.getArtifact(environment); String path = artifact.getPath(); long size = artifact.getSize(); if (size <= 0) size = LIBRARY_SIZE_ESTIMATE; File targetFile = new File(librariesDir, path); if (!targetFile.exists()) { List urls = new ArrayList(); for (URL sourceUrl : sources) { try { urls.add(concat(sourceUrl, path)); } catch (MalformedURLException e) { log.log(Level.WARNING, ""Bad source URL for library: "" + sourceUrl); } } File tempFile = installer.getDownloader().download(urls, """", size, library.getName() + "".jar""); log.info(""Fetching "" + path + "" from "" + urls); installer.queue(new FileMover(tempFile, targetFile)); if (artifact.getSha1() != null) { installer.queue(new FileVerify(targetFile, library.getName(), artifact.getSha1())); } } } } // Fetch logging config if (versionManifest.getLogging() != null) { VersionManifest.LoggingConfig config = versionManifest.getLogging().getClient(); VersionManifest.Artifact file = config.getFile(); File targetFile = new File(librariesDir, file.getId()); if (!targetFile.exists() || !Objects.equals(config.getFile().getHash(), FileUtils.getShaHash(targetFile))) { File tempFile = installer.getDownloader().download(url(file.getUrl()), file.getHash(), file.getSize(), file.getId()); log.info(""Downloading logging config "" + file.getId() + "" from "" + file.getUrl()); installer.queue(new FileMover(tempFile, targetFile)); } } }","Support downloading logging config files from the version manifest This update is required to mitigate the log4j2 vulnerability",https://github.com/SKCraft/Launcher/commit/5fbf5598b4b7e1a4dbc465ed2aa5ac3469483ca6,,,launcher/src/main/java/com/skcraft/launcher/update/BaseUpdater.java,3,java,False,2021-12-10T13:55:23Z "private ServiceResponse executeGet(ServiceRequest request, ServiceResponse response) { PersistenceManager pm = getPm(); try { return handleGet(pm, request, response); } catch (Exception e) { LOGGER.error("""", e); if (pm != null) { pm.rollbackAndClose(); } return errorResponse(response, 500, ""Failed to execute query. See logs for details.""); } finally { maybeRollbackAndClose(); } }","private ServiceResponse executeGet(ServiceRequest request, ServiceResponse response) { PersistenceManager pm = getPm(); try { return handleGet(pm, request, response); } catch (UnauthorizedException e) { rollbackAndClose(pm); return errorResponse(response, 401, e.getMessage()); } catch (ForbiddenException e) { rollbackAndClose(pm); return errorResponse(response, 403, e.getMessage()); } catch (Exception e) { LOGGER.error("""", e); rollbackAndClose(pm); return errorResponse(response, 500, ""Failed to execute query. See logs for details.""); } finally { maybeRollbackAndClose(); } }",Added Forbidden- and UnauthorizedExceptions,https://github.com/FraunhoferIOSB/FROST-Server/commit/e72e4ee2e7d33b58da29c434d0ff63de5f656ee4,,,FROST-Server.Core/src/main/java/de/fraunhofer/iosb/ilt/frostserver/service/Service.java,3,java,False,2021-12-01T19:48:43Z "private void handleException(final Exception e) throws OsgpException { // Rethrow exception if it already is a functional or technical // exception, otherwise throw new technical exception. if (e instanceof OsgpException) { throw (OsgpException) e; } else { throw new TechnicalException(COMPONENT_WS_CORE, e); } }","private void handleException(final Exception e) throws OsgpException { // Rethrow exception if it already is a functional or technical // exception, otherwise throw new technical exception. if (e instanceof ConstraintViolationException) { throw new FunctionalException( FunctionalExceptionType.VALIDATION_ERROR, ComponentType.WS_CORE, new ValidationException(((ConstraintViolationException) e).getConstraintViolations())); } else if (e instanceof OsgpException) { throw (OsgpException) e; } else { throw new TechnicalException(COMPONENT_WS_CORE, e); } }","FDP-244 sonar fixes and duplicate code refactoring (#624) * FDP-244: Fixes a number of blocker/critical Sonar issues * FDP-244: Fixes a number of blocker/critical Sonar issues, refactored duplicate code * FDP-244: Fixes a number of Sonar security vulnerabilities",https://github.com/OSGP/open-smart-grid-platform/commit/767d5e5a86eec2bc94685088678bd78e93977729,,,osgp/platform/osgp-adapter-ws-core/src/main/java/org/opensmartgridplatform/adapter/ws/core/endpoints/FirmwareManagementEndpoint.java,3,java,False,2021-05-10T08:01:12Z "@Override public void consume(String record) { setPluginError(null); try { statementsProcessor.setDBConnection(contexts); statementsProcessor.setFastenApiClient(fastenApiClient); var jsonRecord = new JSONObject(record); var payload = findPayload(jsonRecord); if(payload != null) { var ecosystem = payload.getString(""forge""); var packageName = getPackageName(payload); var version = payload.getString(""version""); logger.info(""Processing package update for forge \"""" + ecosystem + ""\"": "" + packageName + "":"" + version); statementsProcessor.updatePackageVersion(ecosystem, packageName, version); } else { logger.error(""Could not parse payload in message: "" + record); } } catch (Exception e) { var error = ""Error processing package update: "" + e; logger.error(error); setPluginError(e); throw(e); } }","@Override public void consume(String record) { setPluginError(null); try { statementsProcessor.setDBConnection(contexts); statementsProcessor.setFastenApiClient(fastenApiClient); var jsonRecord = new JSONObject(record); var payload = findPayload(jsonRecord); if(payload != null) { var ecosystem = payload.getString(""forge""); var packageName = getPackageName(payload); var version = payload.getString(""version""); logger.info(""Processing package update for forge \"""" + ecosystem + ""\"": "" + packageName + "":"" + version); statementsProcessor.updateNewPackageVersion(ecosystem, packageName, version); } else { logger.error(""Could not parse payload in message: "" + record); } } catch (Exception e) { var error = ""Error processing package update: "" + e; logger.error(error); setPluginError(e); throw(e); } }","Added methods to clean up existing vulnerability data in package versions and callables, prior to adding the new data.",https://github.com/fasten-project/fasten/commit/c2cc86b44e4b65f0f1e541cece1da2b239cd6809,,,analyzer/vulnerability-packages-listener/src/main/java/eu/fasten/analyzer/vulnerabilitypackageslistener/VulnerabilityPackagesListener.java,3,java,False,2022-01-15T22:32:55Z "@Override public SolverAllocatedMemoryRpcResponse execute(SolverAllocatedMemoryRpcRequest request, SessionContext context) { long memUsage = 0; switch (request.getSolverId().charAt(0)) { case 'C': memUsage = solverServerService.getCourseSolverContainer().getMemUsage(request.getSolverId().substring(1)); break; case 'X': memUsage = solverServerService.getExamSolverContainer().getMemUsage(request.getSolverId().substring(1)); break; case 'S': memUsage = solverServerService.getStudentSolverContainer().getMemUsage(request.getSolverId().substring(1)); break; case 'I': memUsage = solverServerService.getInstructorSchedulingContainer().getMemUsage(request.getSolverId().substring(1)); break; case 'O': if (request.getSolverId().indexOf(':') >= 0) { String[] idHost = request.getSolverId().substring(1).split("":""); OnlineSectioningServer server = solverServerService.getServer(idHost[0]).getOnlineStudentSchedulingContainer().getSolver(idHost[1]); if (server != null) memUsage = server.getMemUsage(); } else { memUsage = solverServerService.getOnlineStudentSchedulingContainer().getMemUsage(request.getSolverId().substring(1)); } break; } if (memUsage == 0) return null; else return new SolverAllocatedMemoryRpcResponse(new DecimalFormat(""0.00"").format(memUsage / 1048576.0) + ""M""); }","@Override public SolverAllocatedMemoryRpcResponse execute(SolverAllocatedMemoryRpcRequest request, SessionContext context) { long memUsage = 0; switch (request.getSolverId().charAt(0)) { case 'C': memUsage = solverServerService.getCourseSolverContainer().getMemUsage(request.getSolverId().substring(1)); break; case 'X': memUsage = solverServerService.getExamSolverContainer().getMemUsage(request.getSolverId().substring(1)); break; case 'S': memUsage = solverServerService.getStudentSolverContainer().getMemUsage(request.getSolverId().substring(1)); break; case 'I': memUsage = solverServerService.getInstructorSchedulingContainer().getMemUsage(request.getSolverId().substring(1)); break; case 'O': if (request.getSolverId().indexOf(':') >= 0) { String[] idHost = request.getSolverId().substring(1).split("":""); OnlineSectioningServer server = solverServerService.getServer(idHost[0]).getOnlineStudentSchedulingContainer().getSolver(idHost[1]); if (server != null) memUsage = server.getMemUsage(); } else { memUsage = solverServerService.getOnlineStudentSchedulingContainer().getMemUsage(request.getSolverId().substring(1)); } break; } if (memUsage <= 0) return new SolverAllocatedMemoryRpcResponse(""""); else return new SolverAllocatedMemoryRpcResponse(new DecimalFormat(""0.00"").format(memUsage / 1048576.0) + ""M""); }","Added Support for JDK 16+ - various dependencies updated to avoid illegal access exceptions - Spring core libraries updated to version 5.3.6 (was 4.3.40) - Jackson updated to 2.11.3 (was 2.6.1) - Spring security updated to 5.4.6 (was 4.2.20) - MD5 password encoder provided (MD5 is no longer available out of the box in Spring security) - Spring integration updated to 5.4.6 (was 4.3.24) - MemoryCounter updated to avoid illegal access calls (using the Unsafe access instead) - this change also removes the dependency on Spring Framework 4 that has reached its end of life in December 31, 2020 - this also fixes a Spring Security vulnerability CVE-2021-22112 (high severity)",https://github.com/UniTime/unitime/commit/226836050b7941fe1a1d0fdfe17ccaf1071d82e1,,,JavaSource/org/unitime/timetable/server/SolverAllocatedMemoryBackend.java,3,java,False,2021-05-11T07:40:48Z "private void ensureCapacityFor(@NotNull final Binary v) { if(v.length() == 0 || innerBuffer.remaining() >= v.length() + Integer.BYTES) { return; } final int currentCapacity = innerBuffer.capacity(); final int currentPosition = innerBuffer.position(); final long requiredCapacity = (long)currentPosition + v.length() + Integer.BYTES; if(requiredCapacity > Integer.MAX_VALUE) { throw new IllegalStateException(""Unable to write "" + requiredCapacity + "" values""); } int newCapacity = currentCapacity; while(newCapacity < requiredCapacity) { newCapacity = Math.min(Integer.MAX_VALUE, newCapacity * 2); } final ByteBuffer newBuf = allocator.allocate(newCapacity); newBuf.order(ByteOrder.LITTLE_ENDIAN); newBuf.mark(); innerBuffer.limit(innerBuffer.position()); innerBuffer.reset(); newBuf.put(innerBuffer); allocator.release(innerBuffer); innerBuffer = newBuf; }","private void ensureCapacityFor(@NotNull final Binary v) { if(v.length() == 0 || innerBuffer.remaining() >= v.length() + Integer.BYTES) { return; } final int currentCapacity = innerBuffer.capacity(); final int currentPosition = innerBuffer.position(); final long requiredCapacity = (long)currentPosition + v.length() + Integer.BYTES; if(requiredCapacity > MAXIMUM_TOTAL_CAPACITY) { throw new IllegalStateException(""Unable to write "" + requiredCapacity + "" values. (Maximum capacity: "" + MAXIMUM_TOTAL_CAPACITY + "".)""); } int newCapacity = currentCapacity; while(newCapacity < requiredCapacity) { newCapacity = (int) Math.min(MAXIMUM_TOTAL_CAPACITY, newCapacity * 2L); } final ByteBuffer newBuf = allocator.allocate(newCapacity); newBuf.order(ByteOrder.LITTLE_ENDIAN); newBuf.mark(); innerBuffer.limit(innerBuffer.position()); innerBuffer.reset(); newBuf.put(innerBuffer); allocator.release(innerBuffer); innerBuffer = newBuf; }","Fix infinite loop caused by integer overflow in ParquetTools.writeTable() (#3332) * Handle integer overflow while ensuring capacity. * Introduce a MAX_ARRAY_SIZE constant",https://github.com/deephaven/deephaven-core/commit/5c8095dbcbee623f84f8132b5e51d5f0929ddaf0,,,extensions/parquet/base/src/main/java/io/deephaven/parquet/base/PlainBinaryChunkedWriter.java,3,java,False,2023-01-20T23:29:16Z "def get_value(doctype, fieldname, filters=None, as_dict=True, debug=False, parent=None): '''Returns a value form a document :param doctype: DocType to be queried :param fieldname: Field to be returned (default `name`) :param filters: dict or string for identifying the record''' if frappe.is_table(doctype): check_parent_permission(parent, doctype) if not frappe.has_permission(doctype): frappe.throw(_(""No permission for {0}"".format(doctype)), frappe.PermissionError) filters = get_safe_filters(filters) try: fieldname = json.loads(fieldname) except (TypeError, ValueError): # name passed, not json pass # check whether the used filters were really parseable and usable # and did not just result in an empty string or dict if not filters: filters = None return frappe.db.get_value(doctype, filters, fieldname, as_dict=as_dict, debug=debug)","def get_value(doctype, fieldname, filters=None, as_dict=True, debug=False, parent=None): '''Returns a value form a document :param doctype: DocType to be queried :param fieldname: Field to be returned (default `name`) :param filters: dict or string for identifying the record''' if frappe.is_table(doctype): check_parent_permission(parent, doctype) if not frappe.has_permission(doctype): frappe.throw(_(""No permission for {0}"".format(doctype)), frappe.PermissionError) filters = get_safe_filters(filters) if isinstance(filters, string_types): filters = {""name"": filters} try: fields = json.loads(fieldname) except (TypeError, ValueError): # name passed, not json fields = [fieldname] # check whether the used filters were really parseable and usable # and did not just result in an empty string or dict if not filters: filters = None if frappe.get_meta(doctype).issingle: value = frappe.db.get_values_from_single(fields, filters, doctype, as_dict=as_dict, debug=debug) else: value = frappe.get_list(doctype, filters=filters, fields=fields, debug=debug, limit=1) if as_dict: value = value[0] if value else {} else: value = value[0].fieldname return value",Merge branch 'version-12-hotfix' into fix-2fa-response,https://github.com/frappe/frappe/commit/de6cacaf88b6a10a8de89c37484bbdaf4a9291fd,,,frappe/client.py,3,py,False,2020-08-24T05:36:21Z "@Override public java.net.URL parseTextRepresentation(final ValueSemanticsProvider.Context context, final String text) { val input = _Strings.blankToNullOrTrim(text); if(input==null) { return null; } try { return new java.net.URL(input); } catch (final MalformedURLException ex) { throw new IllegalArgumentException(""Not parseable as an URL ('"" + input + ""')"", ex); } }","@Override public java.net.URL parseTextRepresentation(final ValueSemanticsProvider.Context context, final String text) { val input = _Strings.blankToNullOrTrim(text); if(input==null) { return null; } return _Strings.toUrlWithXssGuard(input).orElse(null); }","ISIS-3077: restore non-escaped output rendering for certain value types - also harden LocalResourcePath, URL and Markup (value types) against XSS attacks",https://github.com/apache/causeway/commit/5def8575ed74e212624a70c6b794e5ee886da7fd,,,core/metamodel/src/main/java/org/apache/isis/core/metamodel/valuesemantics/URLValueSemantics.java,3,java,False,2022-06-15T17:59:22Z "@Override public UserCredentials requestPasswordReset(TenantId tenantId, String email) { log.trace(""Executing requestPasswordReset email [{}]"", email); validateString(email, ""Incorrect email "" + email); DataValidator.validateEmail(email); User user = userDao.findByEmail(tenantId, email); if (user == null) { throw new IncorrectParameterException(String.format(""Unable to find user by email [%s]"", email)); } UserCredentials userCredentials = userCredentialsDao.findByUserId(tenantId, user.getUuidId()); if (!userCredentials.isEnabled()) { throw new IncorrectParameterException(""Unable to reset password for inactive user""); } userCredentials.setResetToken(RandomStringUtils.randomAlphanumeric(DEFAULT_TOKEN_LENGTH)); return saveUserCredentials(tenantId, userCredentials); }","@Override public UserCredentials requestPasswordReset(TenantId tenantId, String email) { log.trace(""Executing requestPasswordReset email [{}]"", email); validateString(email, ""Incorrect email "" + email); DataValidator.validateEmail(email); User user = userDao.findByEmail(tenantId, email); if (user == null) { throw new UsernameNotFoundException(String.format(""Unable to find user by email [%s]"", email)); } UserCredentials userCredentials = userCredentialsDao.findByUserId(tenantId, user.getUuidId()); if (!userCredentials.isEnabled()) { throw new DisabledException(String.format(""User credentials not enabled [%s]"", email)); } userCredentials.setResetToken(RandomStringUtils.randomAlphanumeric(DEFAULT_TOKEN_LENGTH)); return saveUserCredentials(tenantId, userCredentials); }","[PROD-678] Authorization and password reset vulnerability fix (#4569) * Fixed vulnerabilities for password reset and authorization * Improvements to check user and credentials for null * Correct messages and logs * Improvements * Reset Password Test: added delay after resetting password to synchronize test with server * Executor removed from controller * Correct method calling * Formatting cleaned",https://github.com/thingsboard/thingsboard-edge/commit/228fddb8cd92bf4ec89f16760aef7f190a45bb96,,,dao/src/main/java/org/thingsboard/server/dao/user/UserServiceImpl.java,3,java,False,2021-07-06T14:24:35Z "protected Object lookup(Context ctx, String name) throws NamingException { try { return ctx.lookup(name); } catch (NameNotFoundException e) { LogLog.error(""Could not find name ["" + name + ""].""); throw e; } }","protected Object lookup(Context ctx, String name) throws NamingException { Object result = JNDIUtil.lookupObject(ctx, name); if (result == null) { String msg = ""Could not find name ["" + name + ""].""; throw new NamingException(msg); } return result; }","fix Fix CVE-2021-4104 aka issue REL-2) Signed-off-by: Ceki Gulcu ",https://github.com/qos-ch/reload4j/commit/fb7b1ff1c8beb8544933248d00a46e9e30547e87,,,src/main/java/org/apache/log4j/net/JMSAppender.java,3,java,False,2022-01-11T20:39:02Z "void resetRetryCounter(byte id, byte[] buffer, short offset, short length) throws ISOException { // // PRE-CONDITIONS // // PRE-CONDITION 1 - The LOCAL PIN must be enabled if (!config.readFlag(Config.CONFIG_PIN_ENABLE_LOCAL)) { ISOException.throwIt(SW_REFERENCE_NOT_FOUND); } // PRE-CONDITION 2 - The PUK must be enabled if (!config.readFlag(Config.CONFIG_PUK_ENABLED)) { ISOException.throwIt(ISO7816.SW_SECURITY_STATUS_NOT_SATISFIED); } // PRE-CONDITION 3 - Check if we are permitted to use this command over the contactless // interface. // NOTE: We must check this for both the PIN and the PUK /* Truth table because there's a few balls in the air here: IS_CTLESS IGNORE_ACL PIN_PERMIT PUK_PERMIT RESULT ---------------------------------------------------- FALSE X X X FALSE TRUE TRUE X X FALSE TRUE FALSE TRUE TRUE FALSE TRUE FALSE TRUE FALSE TRUE TRUE FALSE FALSE TRUE TRUE TRUE FALSE FALSE FALSE TRUE */ if (cspPIV.getIsContactless() && !config.readFlag(Config.OPTION_IGNORE_CONTACTLESS_ACL) && !(config.readFlag(Config.CONFIG_PIN_PERMIT_CONTACTLESS) && config.readFlag(Config.CONFIG_PUK_PERMIT_CONTACTLESS))) { ISOException.throwIt(ISO7816.SW_SECURITY_STATUS_NOT_SATISFIED); } // PRE-CONDITION 4 - The supplied ID must be the Card PIN // The only key reference allowed in the P2 parameter of the RESET RETRY COUNTER command is the // PIV Card Application PIN. If a key reference is specified in P2 that is not supported by the // card, the PIV Card Application shall return the status word '6A 88'. if (id != ID_CVM_LOCAL_PIN) ISOException.throwIt(SW_REFERENCE_NOT_FOUND); PIN pin = cspPIV.getPIN(id); if (pin == null) { ISOException.throwIt(SW_REFERENCE_NOT_FOUND); return; // Keep compiler happy } // PRE-CONDITION 5 - The supplied length must equal the PUK + NEW PIN lengths byte pinLength = config.readValue(Config.CONFIG_PIN_MAX_LENGTH); short expectedLength = (short) (config.readValue(Config.CONFIG_PUK_LENGTH) + pinLength); if (length != expectedLength) ISOException.throwIt(SW_OPERATION_BLOCKED); // PRE-CONDITION 6 - The PUK must not be blocked // If the current value of the PUK's retry counter is zero, then the PIN's retry counter shall // not be reset and the PIV Card Application shall return the status word '69 83'. PIN puk = cspPIV.getPIN(ID_CVM_PUK); if (puk == null) { ISOException.throwIt(ISO7816.SW_SECURITY_STATUS_NOT_SATISFIED); return; // Keep compiler happy } if (puk.getTriesRemaining() == ZERO) ISOException.throwIt(SW_OPERATION_BLOCKED); // PRE-CONDITION 7 - Verify the PUK value // If the reset retry counter authentication data (PUK) in the command data field of the command // does not match reference data associated with the PUK, then the PIV Card Application shall // return the status word '63 CX'. if (!puk.check(buffer, offset, pinLength)) { // Reset the PIN's security condition (see paragraph below for explanation) pin.reset(); // Check again if we are blocked if (puk.getTriesRemaining() == ZERO) { ISOException.throwIt(SW_OPERATION_BLOCKED); } else { // Return the number of retries remaining ISOException.throwIt((short) (SW_RETRIES_REMAINING | (short) puk.getTriesRemaining())); } } // Move to the start of the new PIN offset += config.readValue(Config.CONFIG_PUK_LENGTH); // PRE-CONDITION 8 - Check the format of the NEW pin value // If the new reference data (PIN) in the command data field of the command does not satisfy the // criteria in Section 2.4.3, then the PIV Card Application shall return the status word '6A // 80'. if (!verifyPinFormat(buffer, offset, pinLength)) { ISOException.throwIt(ISO7816.SW_WRONG_DATA); } // Since this will be the new value, apply our PIN complexity rules if (!verifyPinRules(buffer, offset, pinLength)) { ISOException.throwIt(ISO7816.SW_WRONG_DATA); } // If the reset retry counter authentication data (PUK) in the command data field of the command // does not match reference data associated with the PUK and the new reference data (PIN) in the // command data field of the command does not satisfy the criteria in Section 2.4.3, then the // PIV Card Application shall return either status word '6A 80' or '63 CX'. If the PIV Card // Application returns status word '6A 80', then the retry counter associated with the PIN shall // not be reset, the security status of the PIN's key reference shall remain unchanged, and the // PUK's retry counter shall remain unchanged.11 If the PIV Card Application returns status word // '63 CX', then the retry counter associated with the PIN shall not be reset, the security // status of the PIN's key reference shall be set to FALSE, and the PUK's retry counter shall // be decremented by one. // NOTES: // - We implicitly decrement the PUK counter if the PUK is incorrect (63CX) // - Because we validate the PIN format before checking the PUK, we return WRONG DATA (6A80) in // this case // - If the PUK check fails, we explicitly reset the PIN's security condition // If the card command succeeds, then the PIN's retry counter shall be set to its reset retry // value. Optionally, the PUK's retry counter may be set to its initial reset retry value. // The security status of the PIN's key reference shall not be changed. // NOTE: Since the PUK was verified, the OwnerPIN object automatically resets the PUK counter, // which governs the above behaviour // Update, reset and unblock the PIN cspPIV.updatePIN(id, buffer, offset, pinLength, config.readValue(Config.CONFIG_PIN_HISTORY)); }","void resetRetryCounter(byte id, byte[] buffer, short offset, short length) throws ISOException { // // PRE-CONDITIONS // // PRE-CONDITION 1 - The LOCAL PIN must be enabled if (!config.readFlag(Config.CONFIG_PIN_ENABLE_LOCAL)) { ISOException.throwIt(SW_REFERENCE_NOT_FOUND); } // PRE-CONDITION 2 - The PUK must be enabled if (!config.readFlag(Config.CONFIG_PUK_ENABLED)) { ISOException.throwIt(ISO7816.SW_SECURITY_STATUS_NOT_SATISFIED); } // PRE-CONDITION 3 - Check if we are permitted to use this command over the contactless // interface. // NOTE: We must check this for both the PIN and the PUK /* Truth table because there are a few balls in the air here: IS_CTLESS IGNORE_ACL PIN_PERMIT PUK_PERMIT RESULT ---------------------------------------------------- FALSE X X X FALSE TRUE TRUE X X FALSE TRUE FALSE TRUE TRUE FALSE TRUE FALSE TRUE FALSE TRUE TRUE FALSE FALSE TRUE TRUE TRUE FALSE FALSE FALSE TRUE */ if (cspPIV.getIsContactless() && !config.readFlag(Config.OPTION_IGNORE_CONTACTLESS_ACL) && !(config.readFlag(Config.CONFIG_PIN_PERMIT_CONTACTLESS) && config.readFlag(Config.CONFIG_PUK_PERMIT_CONTACTLESS))) { ISOException.throwIt(ISO7816.SW_SECURITY_STATUS_NOT_SATISFIED); } // PRE-CONDITION 4 - The supplied ID must be the Card PIN // The only key reference allowed in the P2 parameter of the RESET RETRY COUNTER command is the // PIV Card Application PIN. If a key reference is specified in P2 that is not supported by the // card, the PIV Card Application shall return the status word '6A 88'. if (id != ID_CVM_LOCAL_PIN) ISOException.throwIt(SW_REFERENCE_NOT_FOUND); PIN pin = cspPIV.getPIN(id); if (pin == null) { ISOException.throwIt(SW_REFERENCE_NOT_FOUND); return; // Keep compiler happy } // PRE-CONDITION 5 - The supplied length must equal the PUK + NEW PIN lengths byte pinLength = config.readValue(Config.CONFIG_PIN_MAX_LENGTH); short expectedLength = (short) (config.readValue(Config.CONFIG_PUK_LENGTH) + pinLength); if (length != expectedLength) ISOException.throwIt(ISO7816.SW_FILE_INVALID); // PRE-CONDITION 6 - The PUK must not be blocked // If the current value of the PUK's retry counter is zero, then the PIN's retry counter shall // not be reset and the PIV Card Application shall return the status word '69 83'. PIN puk = cspPIV.getPIN(ID_CVM_PUK); if (puk == null) { ISOException.throwIt(ISO7816.SW_SECURITY_STATUS_NOT_SATISFIED); return; // Keep compiler happy } byte intermediateRetries = config.getIntermediatePUKRetries(); if (cspPIV.getIsContactless()) { if (puk.getTriesRemaining() <= intermediateRetries) ISOException.throwIt(ISO7816.SW_FILE_INVALID); } else { if (puk.getTriesRemaining() == ZERO) ISOException.throwIt(ISO7816.SW_FILE_INVALID); } // PRE-CONDITION 7 - Verify the PUK value // If the reset retry counter authentication data (PUK) in the command data field of the command // does not match reference data associated with the PUK, then the PIV Card Application shall // return the status word '63 CX'. if (!puk.check(buffer, offset, pinLength)) { // Reset the PIN's security condition (see paragraph below for explanation) pin.reset(); short remaining = puk.getTriesRemaining(); // For contactless, we reduce the retries by the difference between contact and contactless if (cspPIV.getIsContactless()) { remaining -= intermediateRetries; } // Check for blocked again if (remaining == (byte) 0) ISOException.throwIt(ISO7816.SW_FILE_INVALID); // Return the number of retries remaining ISOException.throwIt((short) (SW_RETRIES_REMAINING | remaining)); } // Move to the start of the new PIN offset += config.readValue(Config.CONFIG_PUK_LENGTH); // PRE-CONDITION 8 - Check the format of the NEW pin value // If the new reference data (PIN) in the command data field of the command does not satisfy the // criteria in Section 2.4.3, then the PIV Card Application shall return the status word '6A // 80'. if (!verifyPinFormat(buffer, offset, pinLength)) { ISOException.throwIt(ISO7816.SW_WRONG_DATA); } // Since this will be the new value, apply our PIN complexity rules if (!verifyPinRules(buffer, offset, pinLength)) { ISOException.throwIt(ISO7816.SW_WRONG_DATA); } // If the reset retry counter authentication data (PUK) in the command data field of the command // does not match reference data associated with the PUK and the new reference data (PIN) in the // command data field of the command does not satisfy the criteria in Section 2.4.3, then the // PIV Card Application shall return either status word '6A 80' or '63 CX'. If the PIV Card // Application returns status word '6A 80', then the retry counter associated with the PIN shall // not be reset, the security status of the PIN's key reference shall remain unchanged, and the // PUK's retry counter shall remain unchanged.11 If the PIV Card Application returns status word // '63 CX', then the retry counter associated with the PIN shall not be reset, the security // status of the PIN's key reference shall be set to FALSE, and the PUK's retry counter shall // be decremented by one. // NOTES: // - We implicitly decrement the PUK counter if the PUK is incorrect (63CX) // - Because we validate the PIN format before checking the PUK, we return WRONG DATA (6A80) in // this case // - If the PUK check fails, we explicitly reset the PIN's security condition // If the card command succeeds, then the PIN's retry counter shall be set to its reset retry // value. Optionally, the PUK's retry counter may be set to its initial reset retry value. // The security status of the PIN's key reference shall not be changed. // NOTE: Since the PUK was verified, the OwnerPIN object automatically resets the PUK counter, // which governs the above behaviour // Update, reset and unblock the PIN cspPIV.updatePIN(id, buffer, offset, pinLength, config.readValue(Config.CONFIG_PIN_HISTORY)); }",Merge branch 'master' of https://github.com/makinako/OpenFIPS201,https://github.com/makinako/OpenFIPS201/commit/e8dfba3a0fdeda6eb6f63d6d28bf5ed44b086ecf,,,src/com/makina/security/openfips201/PIV.java,3,java,False,2022-08-31T13:37:50Z "@EventHandler (ignoreCancelled = true, priority = EventPriority.MONITOR) public void onSwap(PlayerItemHeldEvent e) { Player player = e.getPlayer(); Inventory inv = player.getInventory(); // Swapping items doesn't cause any changes in the inventory, so it is // not covered by the player injection system. if (!(isEmpty(inv.getItem(e.getNewSlot())) && isEmpty(inv.getItem(e.getPreviousSlot())))) { new BukkitRunnable() { @Override public void run() { ItemStack old = inv.getItem(e.getPreviousSlot()); ItemStack current = inv.getItem(e.getNewSlot()); Bukkit.getPluginManager().callEvent(new EntityEquipmentEvent(player, EquipmentSlot.HAND, old, current)); } }.runTask(MechanicsCore.getPlugin()); } }","@EventHandler (ignoreCancelled = true, priority = EventPriority.MONITOR) public void onSwap(PlayerItemHeldEvent e) { Player player = e.getPlayer(); Inventory inv = player.getInventory(); // Swapping items doesn't cause any changes in the inventory, so it is // not covered by the player injection system. if (!(isEmpty(inv.getItem(e.getNewSlot())) && isEmpty(inv.getItem(e.getPreviousSlot())))) { ItemStack old = inv.getItem(e.getPreviousSlot()); ItemStack current = inv.getItem(e.getNewSlot()); Bukkit.getPluginManager().callEvent(new EntityEquipmentEvent(player, EquipmentSlot.HAND, old, current)); } }",Fix for weapon equip delay bypass #112,https://github.com/WeaponMechanics/MechanicsMain/commit/9c098409f6133dedd306e48669ea999e6900480c,,,MechanicsCore/src/main/java/me/deecaad/core/events/triggers/EquipListener.java,3,java,False,2022-08-18T09:07:56Z "@Override public void serverTick(ServerLevel serverLevel, BlockPos blockPos) { try { // Paper only if (spawnDelay > 0 && --tickDelay > 0) return; tickDelay = serverLevel.paperConfig.mobSpawnerTickRate; if (tickDelay == -1) return; } catch (Throwable ignored) { // If not running Paper, we want the tickDelay to be set to 1. tickDelay = 1; } WStackedSpawner stackedSpawner = this.stackedSpawner.get(); if (stackedSpawner == null) { super.serverTick(serverLevel, blockPos); return; } if (!serverLevel.hasNearbyAlivePlayer(blockPos.getX() + 0.5D, blockPos.getY() + 0.5D, blockPos.getZ() + 0.5D, this.requiredPlayerRange)) { failureReason = ""There are no nearby players.""; if (stackedSpawner.isDebug()) Debug.debug(""StackedBaseSpawner"", ""serverTick"", ""No nearby players in range ("" + this.requiredPlayerRange + "")""); return; } if (this.spawnDelay <= -tickDelay) resetSpawnDelay(serverLevel, blockPos); if (this.spawnDelay > 0) { this.spawnDelay -= tickDelay; return; } if (this.demoEntity == null) { if (stackedSpawner.isDebug()) Debug.debug(""StackedBaseSpawner"", ""serverTick"", ""Demo entity is null""); super.serverTick(serverLevel, blockPos); failureReason = """"; return; } CompoundTag entityToSpawn = this.nextSpawnData.getEntityToSpawn(); Optional> entityTypesOptional = EntityType.by(entityToSpawn); if (!entityTypesOptional.isPresent()) { if (stackedSpawner.isDebug()) Debug.debug(""StackedBaseSpawner"", ""serverTick"", ""No valid entity to spawn""); resetSpawnDelay(serverLevel, blockPos); failureReason = """"; return; } EntityType entityToSpawnType = entityTypesOptional.get(); Entity demoEntity = ((CraftEntity) this.demoEntity.getLivingEntity()).getHandle(); if (demoEntity.getType() != entityToSpawnType) { updateDemoEntity(serverLevel, blockPos); if (this.demoEntity == null) { if (stackedSpawner.isDebug()) Debug.debug(""StackedBaseSpawner"", ""serverTick"", ""Demo entity is null after trying to update it""); super.serverTick(serverLevel, blockPos); failureReason = """"; return; } updateUpgrade(stackedSpawner.getUpgradeId()); demoEntity = ((CraftEntity) this.demoEntity.getLivingEntity()).getHandle(); } int stackAmount = stackedSpawner.getStackAmount(); if (stackedSpawner.isDebug()) Debug.debug(""StackedBaseSpawner"", ""serverTick"", ""stackAmount="" + stackAmount); List nearbyEntities = serverLevel.getEntitiesOfClass( demoEntity.getClass(), new AABB(blockPos.getX(), blockPos.getY(), blockPos.getZ(), blockPos.getX() + 1, blockPos.getY() + 1, blockPos.getZ() + 1).inflate(this.spawnRange)); StackedEntity targetEntity = getTargetEntity(stackedSpawner, this.demoEntity, nearbyEntities); if (stackedSpawner.isDebug()) Debug.debug(""StackedBaseSpawner"", ""serverTick"", ""targetEntity="" + targetEntity); if (targetEntity == null && nearbyEntities.size() >= this.maxNearbyEntities) { if (stackedSpawner.isDebug()) Debug.debug(""StackedBaseSpawner"", ""serverTick"", ""There are too many nearby entities ("" + nearbyEntities.size() + "">"" + this.maxNearbyEntities + "")""); failureReason = ""There are too many nearby entities.""; return; } boolean spawnStacked = plugin.getSettings().entitiesStackingEnabled && EventsCaller.callSpawnerStackedEntitySpawnEvent(stackedSpawner.getSpawner()); failureReason = """"; if (stackedSpawner.isDebug()) Debug.debug(""StackedBaseSpawner"", ""serverTick"", ""spawnStacked="" + spawnStacked); int spawnCount = !spawnStacked || !this.demoEntity.isCached() ? Random.nextInt(1, this.spawnCount, stackAmount) : Random.nextInt(1, this.spawnCount, stackAmount, 1.5); if (stackedSpawner.isDebug()) Debug.debug(""StackedBaseSpawner"", ""serverTick"", ""spawnCount="" + spawnCount); int amountPerEntity = 1; int mobsToSpawn; short particlesAmount = 0; // Try stacking into the target entity first if (targetEntity != null && EventsCaller.callEntityStackEvent(targetEntity, this.demoEntity)) { if (stackedSpawner.isDebug()) Debug.debug(""StackedBaseSpawner"", ""serverTick"", ""Stacking into the target entity""); int targetEntityStackLimit = targetEntity.getStackLimit(); int currentStackAmount = targetEntity.getStackAmount(); int increaseStackAmount = Math.min(spawnCount, targetEntityStackLimit - currentStackAmount); if (increaseStackAmount != spawnCount) { mobsToSpawn = spawnCount - increaseStackAmount; } else { mobsToSpawn = 0; } if (stackedSpawner.isDebug()) Debug.debug(""StackedBaseSpawner"", ""serverTick"", ""increaseStackAmount="" + increaseStackAmount); if (increaseStackAmount > 0) { spawnedEntities += increaseStackAmount; targetEntity.increaseStackAmount(increaseStackAmount, true); this.demoEntity.spawnStackParticle(true); if (plugin.getSettings().linkedEntitiesEnabled && targetEntity.getLivingEntity() != stackedSpawner.getLinkedEntity()) stackedSpawner.setLinkedEntity(targetEntity.getLivingEntity()); serverLevel.levelEvent(2004, blockPos, 0); particlesAmount++; } } else { if (stackedSpawner.isDebug()) Debug.debug(""StackedBaseSpawner"", ""serverTick"", ""Stacking naturally""); mobsToSpawn = spawnCount; } if (mobsToSpawn > 0 && this.demoEntity.isCached() && spawnStacked) { amountPerEntity = Math.min(mobsToSpawn, this.demoEntity.getStackLimit()); if (stackedSpawner.isDebug()) Debug.debug(""StackedBaseSpawner"", ""serverTick"", ""amountPerEntity="" + amountPerEntity); mobsToSpawn = mobsToSpawn / amountPerEntity; } if (stackedSpawner.isDebug()) Debug.debug(""StackedBaseSpawner"", ""serverTick"", ""mobsToSpawn="" + mobsToSpawn); MobSpawnResult spawnResult = MobSpawnResult.SUCCESS; try { stackedSpawner.setSpawnerOverridenTick(true); while (spawnResult == MobSpawnResult.SUCCESS && spawnedEntities < stackAmount) { spawnResult = attemptMobSpawning(serverLevel, blockPos, entityToSpawn, entityToSpawnType, mobsToSpawn, amountPerEntity, spawnCount, particlesAmount, stackedSpawner); if (stackedSpawner.isDebug()) { Debug.debug(""StackedBaseSpawner"", ""serverTick"", ""spawnResult="" + spawnResult); Debug.debug(""StackedBaseSpawner"", ""serverTick"", ""spawnedEntities="" + spawnedEntities); } } } finally { stackedSpawner.setSpawnerOverridenTick(false); } if (spawnResult == MobSpawnResult.SUCCESS || spawnResult == MobSpawnResult.ABORT_AND_RESET_DELAY) resetSpawnDelay(serverLevel, blockPos); }","@Override public void serverTick(ServerLevel serverLevel, BlockPos blockPos) { try { // Paper only if (spawnDelay > 0 && --tickDelay > 0) return; tickDelay = serverLevel.paperConfig.mobSpawnerTickRate; if (tickDelay == -1) return; } catch (Throwable ignored) { // If not running Paper, we want the tickDelay to be set to 1. tickDelay = 1; } WStackedSpawner stackedSpawner = this.stackedSpawner.get(); if (stackedSpawner == null) { super.serverTick(serverLevel, blockPos); return; } if (!serverLevel.hasNearbyAlivePlayer(blockPos.getX() + 0.5D, blockPos.getY() + 0.5D, blockPos.getZ() + 0.5D, this.requiredPlayerRange)) { failureReason = ""There are no nearby players.""; if (stackedSpawner.isDebug()) Debug.debug(""StackedBaseSpawner"", ""serverTick"", ""No nearby players in range ("" + this.requiredPlayerRange + "")""); return; } if (this.spawnDelay <= -tickDelay) resetSpawnDelay(serverLevel, blockPos); if (this.spawnDelay > 0) { this.spawnDelay -= tickDelay; return; } if (this.demoEntity == null) { if (stackedSpawner.isDebug()) Debug.debug(""StackedBaseSpawner"", ""serverTick"", ""Demo entity is null""); super.serverTick(serverLevel, blockPos); failureReason = """"; return; } CompoundTag entityToSpawn = this.nextSpawnData.getEntityToSpawn(); Optional> entityTypesOptional = EntityType.by(entityToSpawn); if (!entityTypesOptional.isPresent()) { if (stackedSpawner.isDebug()) Debug.debug(""StackedBaseSpawner"", ""serverTick"", ""No valid entity to spawn""); resetSpawnDelay(serverLevel, blockPos); failureReason = """"; return; } EntityType entityToSpawnType = entityTypesOptional.get(); Entity demoEntity = ((CraftEntity) this.demoEntity.getLivingEntity()).getHandle(); if (demoEntity.getType() != entityToSpawnType) { updateDemoEntity(serverLevel, blockPos); if (this.demoEntity == null) { if (stackedSpawner.isDebug()) Debug.debug(""StackedBaseSpawner"", ""serverTick"", ""Demo entity is null after trying to update it""); super.serverTick(serverLevel, blockPos); failureReason = """"; return; } updateUpgrade(stackedSpawner.getUpgradeId()); demoEntity = ((CraftEntity) this.demoEntity.getLivingEntity()).getHandle(); } int stackAmount = stackedSpawner.getStackAmount(); if (stackedSpawner.isDebug()) Debug.debug(""StackedBaseSpawner"", ""serverTick"", ""stackAmount="" + stackAmount); List nearbyEntities = serverLevel.getEntitiesOfClass( demoEntity.getClass(), new AABB(blockPos.getX(), blockPos.getY(), blockPos.getZ(), blockPos.getX() + 1, blockPos.getY() + 1, blockPos.getZ() + 1).inflate(this.spawnRange)); AtomicInteger nearbyAndStackableCount = new AtomicInteger(0); List nearbyAndStackableEntities = new LinkedList<>(); nearbyEntities.forEach(entity -> { CraftEntity craftEntity = entity.getBukkitEntity(); if (EntityUtils.isStackable(craftEntity)) { StackedEntity stackedEntity = WStackedEntity.of(craftEntity); if (this.demoEntity.runStackCheck(stackedEntity) == StackCheckResult.SUCCESS) { nearbyAndStackableCount.set(nearbyAndStackableCount.get() + stackedEntity.getStackAmount()); nearbyAndStackableEntities.add(stackedEntity); } } }); StackedEntity targetEntity = getTargetEntity(stackedSpawner, this.demoEntity, nearbyAndStackableEntities); if (stackedSpawner.isDebug()) Debug.debug(""StackedBaseSpawner"", ""serverTick"", ""targetEntity="" + targetEntity); if (targetEntity == null && nearbyEntities.size() >= this.maxNearbyEntities) { if (stackedSpawner.isDebug()) Debug.debug(""StackedBaseSpawner"", ""serverTick"", ""There are too many nearby entities ("" + nearbyEntities.size() + "">"" + this.maxNearbyEntities + "")""); failureReason = ""There are too many nearby entities.""; return; } int minimumEntityRequirement = GeneralUtils.get(plugin.getSettings().minimumRequiredEntities, this.demoEntity, 1); int stackedEntityCount = Random.nextInt(1, this.spawnCount, stackAmount, 1.5); boolean canStackToTarget = nearbyAndStackableCount.get() + stackedEntityCount >= minimumEntityRequirement; boolean spawnStacked = plugin.getSettings().entitiesStackingEnabled && canStackToTarget && EventsCaller.callSpawnerStackedEntitySpawnEvent(stackedSpawner.getSpawner()); failureReason = """"; if (stackedSpawner.isDebug()) Debug.debug(""StackedBaseSpawner"", ""serverTick"", ""spawnStacked="" + spawnStacked); int spawnCount = !spawnStacked || !this.demoEntity.isCached() ? Random.nextInt(1, this.spawnCount, stackAmount) : stackedEntityCount; if (stackedSpawner.isDebug()) Debug.debug(""StackedBaseSpawner"", ""serverTick"", ""spawnCount="" + spawnCount); int amountPerEntity = 1; int mobsToSpawn; short particlesAmount = 0; // Try stacking into the target entity first if (targetEntity != null && canStackToTarget && EventsCaller.callEntityStackEvent(targetEntity, this.demoEntity)) { if (stackedSpawner.isDebug()) Debug.debug(""StackedBaseSpawner"", ""serverTick"", ""Stacking into the target entity""); int targetEntityStackLimit = targetEntity.getStackLimit(); int currentStackAmount = targetEntity.getStackAmount(); int increaseStackAmount = Math.min(spawnCount, targetEntityStackLimit - currentStackAmount); if (increaseStackAmount != spawnCount) { mobsToSpawn = spawnCount - increaseStackAmount; } else { mobsToSpawn = 0; } if (stackedSpawner.isDebug()) Debug.debug(""StackedBaseSpawner"", ""serverTick"", ""increaseStackAmount="" + increaseStackAmount); if (increaseStackAmount > 0) { spawnedEntities += increaseStackAmount; if (minimumEntityRequirement > 1) { // We want to stack all nearby entities into target as well. increaseStackAmount += nearbyAndStackableCount.get() - targetEntity.getStackAmount(); nearbyAndStackableEntities.forEach(nearbyEntity -> { if (nearbyEntity != targetEntity) { nearbyEntity.remove(); nearbyEntity.spawnStackParticle(true); } }); } targetEntity.increaseStackAmount(increaseStackAmount, true); this.demoEntity.spawnStackParticle(true); if (plugin.getSettings().linkedEntitiesEnabled && targetEntity.getLivingEntity() != stackedSpawner.getLinkedEntity()) stackedSpawner.setLinkedEntity(targetEntity.getLivingEntity()); serverLevel.levelEvent(2004, blockPos, 0); particlesAmount++; } } else { if (stackedSpawner.isDebug()) Debug.debug(""StackedBaseSpawner"", ""serverTick"", ""Stacking naturally""); mobsToSpawn = spawnCount; } if (mobsToSpawn > 0 && this.demoEntity.isCached() && spawnStacked) { amountPerEntity = Math.min(mobsToSpawn, this.demoEntity.getStackLimit()); if (stackedSpawner.isDebug()) Debug.debug(""StackedBaseSpawner"", ""serverTick"", ""amountPerEntity="" + amountPerEntity); mobsToSpawn = mobsToSpawn / amountPerEntity; } if (stackedSpawner.isDebug()) Debug.debug(""StackedBaseSpawner"", ""serverTick"", ""mobsToSpawn="" + mobsToSpawn); MobSpawnResult spawnResult = MobSpawnResult.SUCCESS; try { stackedSpawner.setSpawnerOverridenTick(true); while (spawnResult == MobSpawnResult.SUCCESS && spawnedEntities < stackAmount) { spawnResult = attemptMobSpawning(serverLevel, blockPos, entityToSpawn, entityToSpawnType, mobsToSpawn, amountPerEntity, spawnCount, particlesAmount, stackedSpawner); if (stackedSpawner.isDebug()) { Debug.debug(""StackedBaseSpawner"", ""serverTick"", ""spawnResult="" + spawnResult); Debug.debug(""StackedBaseSpawner"", ""serverTick"", ""spawnedEntities="" + spawnedEntities); } } } finally { stackedSpawner.setSpawnerOverridenTick(false); } if (spawnResult == MobSpawnResult.SUCCESS || spawnResult == MobSpawnResult.ABORT_AND_RESET_DELAY) resetSpawnDelay(serverLevel, blockPos); }",Fixed entities spawn from spawners bypass minimum-required checks (#670),https://github.com/BG-Software-LLC/WildStacker/commit/9b63a964dc0b78b1a6a49738f4214ffb4fdf0df4,,,v1181/src/main/java/com/bgsoftware/wildstacker/nms/v1181/spawner/StackedBaseSpawner.java,3,java,False,2022-11-20T14:00:43Z "@Override public String upload(MultipartFile file) throws Exception { String temp = WebUtils.getAppDir(""temp""); File saveFile = new File(temp, file.getOriginalFilename()); // delete when exists if (saveFile.exists()) { saveFile.delete(); } // save file to temp dir FileUtils.writeByteArrayToFile(saveFile, file.getBytes()); return saveFile.getAbsolutePath(); }","@Override public String upload(MultipartFile file) throws Exception { String temp = WebUtils.getAppDir(""temp""); File saveFile = new File(temp, Objects.requireNonNull(file.getOriginalFilename())); // delete when exists if (saveFile.exists()) { saveFile.delete(); } // save file to temp dir file.transferTo(saveFile); return saveFile.getAbsolutePath(); }","[hotfix] upload file oom bug fixed. (#693) * [hotfix] upload file oom bug fixed.",https://github.com/apache/incubator-streampark/commit/c5d73984d97d74b84ace3eec5547e94ba681a52c,,,streamx-console/streamx-console-service/src/main/java/com/streamxhub/streamx/console/core/service/impl/ApplicationServiceImpl.java,3,java,False,2022-02-07T08:33:41Z "@Override public org.bukkit.inventory.ItemStack getPlayerHead(Player player, org.bukkit.inventory.ItemStack copyTagFrom) { org.bukkit.inventory.ItemStack head = new org.bukkit.inventory.ItemStack(materialPlayerHead()); if (copyTagFrom != null) { ItemStack i = CraftItemStack.asNMSCopy(head); i.setTag(CraftItemStack.asNMSCopy(copyTagFrom).getTag()); head = CraftItemStack.asBukkitCopy(i); } SkullMeta headMeta = (SkullMeta) head.getItemMeta(); Field profileField; try { //noinspection ConstantConditions profileField = headMeta.getClass().getDeclaredField(""profile""); profileField.setAccessible(true); profileField.set(headMeta, ((CraftPlayer) player).getProfile()); } catch (NoSuchFieldException | IllegalArgumentException | IllegalAccessException e1) { e1.printStackTrace(); } head.setItemMeta(headMeta); return head; }","@Override public org.bukkit.inventory.ItemStack getPlayerHead(Player player, org.bukkit.inventory.ItemStack copyTagFrom) { org.bukkit.inventory.ItemStack head = new org.bukkit.inventory.ItemStack(materialPlayerHead()); if (copyTagFrom != null) { ItemStack i = CraftItemStack.asNMSCopy(head); i.setTag(CraftItemStack.asNMSCopy(copyTagFrom).getTag()); head = CraftItemStack.asBukkitCopy(i); } SkullMeta headMeta = (SkullMeta) head.getItemMeta(); // FIXME: current hotfix will get rate limited! how the hell do we set head texture now? // wtf is this: SkullOwner:{Id:[I;-1344581477,-1919271229,-1306015584,-647763423],Name:""andrei1058""} // Field profileField; // try { // //noinspection ConstantConditions // profileField = headMeta.getClass().getDeclaredField(""profile""); // profileField.setAccessible(true); // profileField.set(headMeta, ((CraftPlayer) player).getProfile()); // } catch (NoSuchFieldException | IllegalArgumentException | IllegalAccessException e1) { // e1.printStackTrace(); // } assert headMeta != null; headMeta.setOwningPlayer(player); head.setItemMeta(headMeta); return head; }","fix player skull crashing the server (#233) * fix #210 * hotfix for #223 and #210",https://github.com/andrei1058/BedWars1058/commit/927a5858bdbf0271212f0126c57e92be0a255f81,,,versionsupport_v1_17_R1/src/main/java/com/andrei1058/bedwars/support/version/v1_17_R1/v1_17_R1.java,3,java,False,2022-02-02T18:01:07Z "@Inject(method = ""mouseClicked"", at = @At(""HEAD""), cancellable = true) public void mouseClicked(double mouseX, double mouseY, int button, CallbackInfoReturnable cir) { if (button == 0) { switch (buttonHovered) { case 0 -> { if (index == 0) { return; } MinecraftClient.getInstance().getSoundManager().play(PositionedSoundInstance.master(SoundEvents.UI_BUTTON_CLICK, 1.0F)); swapMessages(index, index - 1); refreshScreen(); cir.setReturnValue(true); } case 1 -> { var chatLog = (AccessorChatLogImplMixin) ((AccessorMixinChatSelectionScreen) MinecraftClient.getInstance().currentScreen).getReporter().chatLog(); if (index == ((ChatLogImpl) chatLog).getMaxIndex()) { return; } MinecraftClient.getInstance().getSoundManager().play(PositionedSoundInstance.master(SoundEvents.UI_BUTTON_CLICK, 1.0F)); swapMessages(index, index + 1); refreshScreen(); cir.setReturnValue(true); } case 2 -> { if (!Gaslight.removedIndexes.remove(index)) { Gaslight.removedIndexes.add(index); } if (this.isSelected()) { this.toggle(); } MinecraftClient.getInstance().getSoundManager().play(PositionedSoundInstance.master(SoundEvents.UI_BUTTON_CLICK, 1.0F)); cir.setReturnValue(true); } default -> { if (Gaslight.removedIndexes.contains(index)) { cir.setReturnValue(true); } } } } }","@Inject(method = ""mouseClicked"", at = @At(""HEAD""), cancellable = true) public void mouseClicked(double mouseX, double mouseY, int button, CallbackInfoReturnable cir) { if (button == 0) { if (buttonHovered == 2) { if (!Gaslight.removedMessages.remove(this.truncatedContent.getString())) { System.out.println(this.truncatedContent.getString()); Gaslight.removedMessages.add(this.truncatedContent.getString()); } if (this.isSelected()) { this.toggle(); } MinecraftClient.getInstance().getSoundManager().play(PositionedSoundInstance.master(SoundEvents.UI_BUTTON_CLICK, 1.0F)); cir.setReturnValue(true); } else { if (Gaslight.removedMessages.contains(this.truncatedContent.getString())) { cir.setReturnValue(true); } } } }",We are now releasing pre-release 5 for Minecraft 1.19.1. This pre-release includes the remaining fixes for a known exploit regarding player report context,https://github.com/nodusclient/gaslight/commit/2055c0ae93927aa5ca70460bf35b10db4b358a42,,,src/main/java/gg/nodus/gaslight/mixin/MixinMessageEntry.java,3,java,False,2022-07-27T17:16:47Z "private static boolean hasUriPermission(final Context c, final Uri uri, boolean readPermission) { final List list = c.getContentResolver().getPersistedUriPermissions(); boolean found = false; for(UriPermission up : list) { if(up.getUri().equals(uri)) { if((up.isReadPermission() && readPermission) || (up.isWritePermission() && !readPermission)) { found = true; break; } } } return found; }","public static boolean hasUriPermission(final Context c, final Uri uri, boolean readPermission) { final List list = c.getContentResolver().getPersistedUriPermissions(); boolean found = false; for(UriPermission up : list) { if(up.getUri().equals(uri)) { if((up.isReadPermission() && readPermission) || (up.isWritePermission() && !readPermission)) { found = true; break; } } } return found; }",#22: Added a test on opening a recent file to avoid application crashes if the permission is revoked.,https://github.com/Keidan/HexViewer/commit/c0083850cf4e17b8d403c5c7a1bac775cbd2229d,,,app/src/main/java/fr/ralala/hexviewer/utils/FileHelper.java,3,java,False,2021-06-05T12:53:48Z "@Override public void setSpyingMission(EmpireView v) { // invoked for each CivView for each civ after nextTurn() processing is complete on each civ's turn // also invoked when contact is made in mid-turn // 0 = hide; 1 = sabotage; 2 = espionage DiplomaticEmbassy emb = v.embassy(); SpyNetwork spies = v.spies(); // extinct or no contact = hide if (v.empire().extinct() || !emb.contact()) { spies.beginHide(); return; } // they are our allies if (emb.alliance() || emb.unity()) { spies.beginHide(); return; } // we've been warned and they are not our enemy (i.e. no war preparations) if (!emb.isEnemy() && spies.threatened()) { spies.beginHide(); return; } boolean canEspionage = !spies.possibleTechs().isEmpty(); Leader leader = v.owner().leader(); float relations = emb.relations(); // we are in a pact or at peace if (emb.pact() || emb.atPeace()) { if (leader.isTechnologist() && canEspionage) spies.beginEspionage(); else if (leader.isPacifist() || leader.isHonorable()) spies.beginHide(); else if ((relations > 30) && canEspionage) spies.beginEspionage(); else spies.beginHide(); return; } Sabotage sabMission = bestSabotageChoice(v); boolean canSabotage = spies.canSabotage() && (sabMission != null); // we have no treaty, we might want to sabotage! if (emb.noTreaty()) { if (leader.isAggressive() || leader.isRuthless() || leader.isErratic()) { if (canEspionage) spies.beginEspionage(); else if (canSabotage) spies.beginSabotage(); else spies.beginHide(); } else if (leader.isXenophobic() && canEspionage) spies.beginEspionage(); else if (relations < -20) spies.beginHide(); else if (leader.isTechnologist() && canEspionage) spies.beginEspionage(); else if (leader.isPacifist() || leader.isHonorable()) spies.beginHide(); else spies.beginHide(); return; } // if at war, defer to war strategy: 1) steal war techs, 2) sabotage, 3) steal techs if (emb.anyWar()) { List warTechs = new ArrayList<>(); for (String tId: v.spies().possibleTechs()) { Tech t = tech(tId); if ((t.warModeFactor() > 1) && !t.isObsolete(v.owner())) warTechs.add(t); } if (!warTechs.isEmpty()) spies.beginEspionage(); else if (canSabotage) spies.beginSabotage(); else if (!v.spies().possibleTechs().isEmpty()) spies.beginEspionage(); else spies.beginHide(); return; } // default for any other treaty state (??) is to hide spies.beginHide(); }","@Override public void setSpyingMission(EmpireView v) { // invoked for each CivView for each civ after nextTurn() processing is complete on each civ's turn // also invoked when contact is made in mid-turn // 0 = hide; 1 = sabotage; 2 = espionage DiplomaticEmbassy emb = v.embassy(); SpyNetwork spies = v.spies(); // extinct or no contact = hide if (v.empire().extinct() || !emb.contact()) { spies.beginHide(); spies.maxSpies(0); return; } // they are our allies if (emb.alliance() || emb.unity()) { spies.beginHide(); spies.maxSpies(1); return; } // we've been warned and they are not our enemy (i.e. no war preparations) if (!emb.isEnemy() && spies.threatened()) { spies.beginHide(); spies.maxSpies(1); return; } boolean canEspionage = !spies.possibleTechs().isEmpty(); Sabotage sabMission = bestSabotageChoice(v); boolean canSabotage = spies.canSabotage() && (sabMission != null); // we are in a pact or at peace // ail: according to official strategy-guide two spies is supposedly the ideal number for tech-stealing etc, so always setting it to two except for hiding if (emb.pact() || emb.atPeace() || emb.noTreaty()) { if(!v.empire().warEnemies().isEmpty() && (v.empirePower() < 1.0 || v.empire() == empire.generalAI().bestVictim())) { if(canEspionage) { spies.beginEspionage(); spies.maxSpies(2); } else if(canSabotage && emb.noTreaty()) { spies.beginSabotage(); spies.maxSpies(2); } else { spies.beginHide(); spies.maxSpies(1); } } else { spies.beginHide(); spies.maxSpies(1); } return; } // if at war, defer to war strategy: 1) steal war techs, 2) sabotage, 3) steal techs if (emb.anyWar()) { if (canEspionage) { spies.beginEspionage(); spies.maxSpies(2); } else if (canSabotage) { spies.beginSabotage(); spies.maxSpies(2); } else { spies.beginHide(); spies.maxSpies(1); } return; } // default for any other treaty state (??) is to hide spies.beginHide(); }","Branch for beta 2.18 or 0.9 or whatever it will be (#48) * Replaced many isPlayer() by isPlayerControlled() This leads to a more fluent experience on AutoPlay. Note: the council-voting acts weird when you try that there, getting you stuck, and the News-Broadcasts also seem to use a differnt logic and are always shown. * Orion-guard-handling Avoid sending colonization-fleets, when guardian is still alive Increase guardian-power-estimate to 100,000 Don't send and count bombers towards guardian-defeat-force * Fixed Crash from a report on reddit Not sure how that could happen though. Never had this issue in games started on my computer. * Fixed crash after AI defeats orion-guard Tried to access an out-of-bounds-value because it couldn't find the System where the guardian was. So looking to find the Planet with the Orionartifact now, which does find it. * All the forgotten isPlayer()-calls Including the Base- and Modnar-AI-Diplomat * Personalities now play a role in my AI once again Instead of everyone having the same conditions for war, there's now different ones. Some are more aggressive, some are less. * Fixed issue where enemy-fleets weren's seen, when they actually were. Also added a way of guessing when enemy-fleets aren't seen so it shouldn't trickle in tiny fleets that all retreat anymore in the early-game, before they can see the enemy-fleets. And also not later because they now actually can see them. * Update AIDiplomat.java * Delete ShipCombatResults.java * Delete Empire.java * Delete TradeRoute.java * Revert ""Delete TradeRoute.java"" This reverts commit 6e5c5a8604e89bb11a9a6dc63acd5b3f27194c83. * Revert ""Delete Empire.java"" This reverts commit 1a020295e05ebc735dae761f426742eb7bdc8d35. * Revert ""Delete ShipCombatResults.java"" This reverts commit 5f9287289feb666adf1aa809524973c54fbf0cd5. * Update ShipCombatResults.java reverting pull-request... manually because I don't know of a better way 8[ * Update Empire.java * Update TradeRoute.java * Merge with Master * Update TradeRoute.java * Update TradeRoute.java github editor does not allow me to remove a newline oO * AI improvements Added parameter to make the colonizer-function return just the uncolonized planets without substracting the colony-ships. Impelemented a very differnt diplomatic behavior, that supposedly is more suitable to actually winning by waging less war, particularly when big enough to be voted for. Revoked that AI doesn't adjust to enemy-troops when it has a more defensive unit-composition. In lategame going by destructive-power of bombers hasn't much merit, when 1 bombers can pack 60ish neutronium-bombs. Fixed an issue that prevented designing extended-fuel-range-colonizers asap. This once again helps expansion-speed a lot. Security now is only spent against empires actually in range to spy, as it was intended. Contact via council should not increase paranoia. Also Xenophobic-extra-paranoia removed. * Update OrionGuardianShip.java * War-declaration behavior Electible faction will no longer declare war on someone who is at war with the other electible faction. * Fix zero-division on refreshing a trade-route that had been adjusted due to empire-shrinkage. * AI & Bugfix Leader-stuff is now overridden Should now retreat against repulsors, when no counter available Tech-nullifier hit and miss mixup fixed * AI improvements Fixed a rare crash in AutoPlay-Mode Massive overhaul of AI-ship-design Spy master now more catious about avoiding unwanted, dangerous wars due to spying on the wrong people Colony-ship-designs now will only get a weapon, if this doesn't prevent reserve-tanks or reducing their size to medium Fixed an issue where ai wouldn't retreat from ships with repulsor-beam that exploited their range-advantage Increased research-value of cloaking-tech and battle-suits Upon reaching tech-level 99 in every field, AI will produce ships non-stop even in peace-time AI will now retreat fleets from empires it doesn't want to go to war with in order to avoid trespassing-issues Fixed issue where the AI wanted to but couldn't colonize orion before it was cleared and then wouldn't colonize other systems in that time AI will no longer break non-aggression-pacts when it still has a war with someone else AI will only begin wars because of spying, if it actually feels comfortable dealing with the person who spied on them AI will now try and predict whether it will be attacked soon and enact preventive measures * Tackling some combat-issue Skipping specials when it comes to determining optimal-range. Otherwise ships with long-range-specials like warp-dissipator would never close in on their prey. Resetting the selectedWeaponIndex upon reload to consistency start with same weapons every turn. Writing new attack-method that allows to skip certain weapons like for example repulsor-beam at the beginning of the turn and fire them at the end instead. * Update NewShipTemplate.java Fixed incorrect operator ""-="" instead of ""=-"", that prevented weapons being used at all when no weapon that is strong enough for theorethical best enemy shield could be found. Also when range is required an not fitting beam can be found try missiles and when no fitting missile can be found either, try short-range weapon. Should still be better than nothing. * Diplomacy and Ship-Building Reduced suicidal tendencies. No more war-declarations against wastly superior enemies. At most they ought to be 25% stronger. Voting behavior is now deterministic. No more votes based on fear, only on who they actually like and only for those whom they have real-contact. Ship-construction is now based on relative-productivity rather than using a hard cut-off for anything lower than standard-resources. So when the empire only has poor-systems it will try to build at least a few ships still. * Orion prevented war Fixed an issue, where wanting to build a colonizer for Orion prevented wars. * Update AIGeneral.java Don't invade unless you have something in orbit. * Update AIFleetCommander.java No longer using hyperspace-communications... for now. (it produced unintentional results and error-messages) Co-authored-by: rayfowler <58891984+rayfowler@users.noreply.github.com>",https://github.com/rayfowler/rotp-public/commit/5de4de9f996eddaa73b90b341940561e62c18e49,,,src/rotp/model/ai/xilmi/AISpyMaster.java,3,java,False,2021-04-02T21:15:47Z "public List deleteUnusedFileReferences(File fileReferencesPath, Duration keepFileReferencesDuration, int numberToAlwaysKeep, Set fileReferencesInUse) { log.log(Level.FINE, () -> ""Keep unused file references for "" + keepFileReferencesDuration); if (!fileReferencesPath.isDirectory()) throw new RuntimeException(fileReferencesPath + "" is not a directory""); log.log(Level.FINE, () -> ""File references in use : "" + fileReferencesInUse); List candidates = sortedUnusedFileReferences(fileReferencesPath, fileReferencesInUse, keepFileReferencesDuration); // Do not delete the newest ones List fileReferencesToDelete = candidates.subList(0, Math.max(0, candidates.size() - numberToAlwaysKeep)); if (fileReferencesToDelete.size() > 0) { log.log(Level.FINE, () -> ""Will delete file references not in use: "" + fileReferencesToDelete); fileReferencesToDelete.forEach(fileReference -> { File file = new File(fileReferencesPath, fileReference); if (!IOUtils.recursiveDeleteDir(file)) log.log(Level.WARNING, ""Could not delete "" + file.getAbsolutePath()); }); } return fileReferencesToDelete; }","public List deleteUnusedFileReferences(File fileReferencesPath, Duration keepFileReferencesDuration, int numberToAlwaysKeep, Set fileReferencesInUse) { log.log(Level.FINE, () -> ""Keep unused file references for "" + keepFileReferencesDuration); if (!fileReferencesPath.isDirectory()) throw new RuntimeException(fileReferencesPath + "" is not a directory""); log.log(Level.FINE, () -> ""File references in use : "" + fileReferencesInUse); Stream candidates = sortedUnusedFileReferences(fileReferencesPath.toPath(), fileReferencesInUse, keepFileReferencesDuration); List fileReferencesDeleted = new ArrayList<>(); // Do not delete the newest ones final AtomicInteger i = new AtomicInteger(0); candidates.forEach(fileReference -> { if (i.incrementAndGet() > numberToAlwaysKeep) { fileReferencesDeleted.add(fileReference); File file = new File(fileReferencesPath, fileReference); if (!IOUtils.recursiveDeleteDir(file)) log.log(Level.WARNING, ""Could not delete "" + file.getAbsolutePath()); } }); return fileReferencesDeleted; }","Use a Stream to read files, might go OOM otherwise Slight rewrite to be able to use a stream for deleting unused file references, but still keep some of them (the last accessed ones)",https://github.com/vespa-engine/vespa/commit/987e1014e2def189bf30d3e4bc8f719b21e99784,,,filedistribution/src/main/java/com/yahoo/vespa/filedistribution/maintenance/FileDistributionCleanup.java,3,java,False,2022-10-10T11:05:11Z "private void startListeningForFace() { if (mFaceRunningState == BIOMETRIC_STATE_CANCELLING) { setFaceRunningState(BIOMETRIC_STATE_CANCELLING_RESTARTING); return; } else if (mFaceRunningState == BIOMETRIC_STATE_CANCELLING_RESTARTING) { // Waiting for ERROR_CANCELED before requesting auth again return; } if (DEBUG) Log.v(TAG, ""startListeningForFace(): "" + mFaceRunningState); int userId = getCurrentUser(); if (isUnlockWithFacePossible(userId)) { if (mFaceCancelSignal != null) { mFaceCancelSignal.cancel(); } mFaceCancelSignal = new CancellationSignal(); // This would need to be updated for multi-sensor devices final boolean supportsFaceDetection = !mFaceSensorProperties.isEmpty() && mFaceSensorProperties.get(0).supportsFaceDetection; if (isEncryptedOrLockdown(userId) && supportsFaceDetection) { mFaceManager.detectFace(mFaceCancelSignal, mFaceDetectionCallback, userId); } else { final boolean isBypassEnabled = mKeyguardBypassController != null && mKeyguardBypassController.isBypassEnabled(); mFaceManager.authenticate(null /* crypto */, mFaceCancelSignal, mFaceAuthenticationCallback, null /* handler */, userId, isBypassEnabled); } setFaceRunningState(BIOMETRIC_STATE_RUNNING); } }","private void startListeningForFace() { final int userId = getCurrentUser(); final boolean unlockPossible = isUnlockWithFacePossible(userId); if (mFaceCancelSignal != null) { Log.e(TAG, ""Cancellation signal is not null, high chance of bug in face auth lifecycle"" + "" management. Face state: "" + mFaceRunningState + "", unlockPossible: "" + unlockPossible); } if (mFaceRunningState == BIOMETRIC_STATE_CANCELLING) { setFaceRunningState(BIOMETRIC_STATE_CANCELLING_RESTARTING); return; } else if (mFaceRunningState == BIOMETRIC_STATE_CANCELLING_RESTARTING) { // Waiting for ERROR_CANCELED before requesting auth again return; } if (DEBUG) Log.v(TAG, ""startListeningForFace(): "" + mFaceRunningState); if (unlockPossible) { mFaceCancelSignal = new CancellationSignal(); // This would need to be updated for multi-sensor devices final boolean supportsFaceDetection = !mFaceSensorProperties.isEmpty() && mFaceSensorProperties.get(0).supportsFaceDetection; if (isEncryptedOrLockdown(userId) && supportsFaceDetection) { mFaceManager.detectFace(mFaceCancelSignal, mFaceDetectionCallback, userId); } else { final boolean isBypassEnabled = mKeyguardBypassController != null && mKeyguardBypassController.isBypassEnabled(); mFaceManager.authenticate(null /* crypto */, mFaceCancelSignal, mFaceAuthenticationCallback, null /* handler */, userId, isBypassEnabled); } setFaceRunningState(BIOMETRIC_STATE_RUNNING); } }","Fix KeyguardUpdateMonitor auth lifecycle issues This is split into two high-level issues which together cause strange auth behavior on keyguard: ============= Issue 1 ============= For fingerprint, auth ends when: 1) Success 2) Error For face, auth ends when: 1) Success 2) Reject 3) Error This change ensures that cancellation signal is set to null upon any of these conditions, so that there is never an opportunity of using a stale CancellationSignal. Furthermore, do not invoke stale cancellation signal when starting authentication. In the off chance the bug is re-introduced, or if some other situation can cause a cancellation signal to be non-null when keyguard requests auth again (e.g. bad state management in keyguard), do NOT invoke the stale cancellation signal's cancel method. The framework already handles this case gracefully and will automatically cancel the previous operation. ============= Issue 2 ============= We have a runnable that's scheduled to run after X ms if ERROR_CANCELED is not received after cancel() is requested. However, there are various bugs around that logic: 1) shared runnable for both fp and face, leading to unexpected and incorrect state changes (e.g. face does not respond to cancel within X ms, both fp and face will go to STATE_STOPPED, even though cancel() was never requested of fp 2) Always remove and re-add runnable when requesting cancel() though it should never occur that cancel() is requested in close temporal proximity, it never hurts to have the correct timeout before resetting the state. Bug: 195365422 Bug: 193477749 Test: manual Change-Id: I3702f41c8af7e870798f19c43012a26281a6632a",https://github.com/omnirom/android_frameworks_base/commit/a04d57070d780ca5d93e9af93c25c5c6dd36ab3a,,,packages/SystemUI/src/com/android/keyguard/KeyguardUpdateMonitor.java,3,java,False,2021-08-05T22:31:13Z "private boolean hasTokenAuth() { return systemToken != null || jwtSecret != null; }","private boolean hasTokenAuth() { return systemToken != null && jwtSecret != null; }",Fix auth test condition,https://github.com/airyhq/airy/commit/5fae51f65d4b6de0667678eaed75a111cf37b64b,,,lib/java/spring/auth/src/main/java/co/airy/spring/auth/AuthConfig.java,3,java,False,2021-09-08T07:13:55Z "public void restoreClient(Object client) { if (client != null) { clientPool.restore(client); LOG.debug(""Returned client stub {} to the pool"", client); } }","public void restoreClient(Object client) { if (client != null) { // Reset the response context associated with the current thread to allow the context to be GCed. // See https://issues.apache.org/jira/browse/CXF-7710 and https://issues.apache.org/jira/browse/CXF-7591 ClientProxy.getClient(client).getResponseContext().clear(); clientPool.restore(client); LOG.debug(""Returned client stub {} to the pool"", client); } }","Clear CXF client request context after use to allow it to be GCed. See https://issues.apache.org/jira/browse/CXF-7710. Fixed a ""use-after-free"" issue of the pooled CXF client proxy instance: The client proxy instance was accessed after it was returned to the pool.",https://github.com/oehf/ipf/commit/095dc43535a5f39f9ac6653a446d163eb3c85661,,,commons/ihe/ws/src/main/java/org/openehealth/ipf/commons/ihe/ws/JaxWsClientFactory.java,3,java,False,2021-11-04T14:34:44Z "private void revertCaches(final boolean clearPropsAndLinksCache) { if (clearPropsAndLinksCache) { propsCache.clear(); linksCache.clear(); blobStringsCache.clear(); } localCache = (EntityIterableCacheAdapter) store.getEntityIterableCache().getCacheAdapter(); mutableCache = null; mutatedInTxn = null; blobStreams = null; blobFiles = null; deferredBlobsToDelete = null; }","private void revertCaches(final boolean clearPropsAndLinksCache) { if (clearPropsAndLinksCache) { propsCache.clear(); linksCache.clear(); blobStringsCache.clear(); } localCache = (EntityIterableCacheAdapter) store.getEntityIterableCache().getCacheAdapter(); mutableCache = null; mutatedInTxn = null; if (blobStreams != null) { for (var stream : blobStreams.values()) { try { stream.close(); } catch (IOException e) { logger.error(""Error during reverting of caches."", e); } } blobStreams = null; } blobFiles = null; deferredBlobsToDelete = null; tmpBlobFiles = null; }","Issue XD-908 was fixed. (#44) Issue XD-908 was fixed. 1. Callback which allows executing version post-validation actions before data flush was added. 2. BufferedInputStreams are used instead of ByteArray streams to fall back to the stored position during the processing of stream inside EntityStore. Which should decrease the risk of OOM. 3. All streams are stored in the temporary directory before transaction flush (after validation of the transaction version) and then moved to the BlobVault location after a successful commit. That is done gracefully handling situations when streams generate errors while storing the data. 4. Passed-in streams are automatically closed during commit/flush and abort/revert of transaction.",https://github.com/JetBrains/xodus/commit/9b7d0e6387d80b3e30abb48cad5a064f12cf8b38,,,entity-store/src/main/java/jetbrains/exodus/entitystore/PersistentStoreTransaction.java,3,java,False,2023-01-24T09:44:19Z "@Method(0x80114e60L) public static FlowControl FUN_80114e60(final RunningScript a0) { final EffectManagerData6c manager = (EffectManagerData6c)scriptStatePtrArr_800bc1c0[a0.params_20[0].get()].innerStruct_00; manager._10.vec_24.component(a0.params_20[1].get()).set(a0.params_20[2].get()); return FlowControl.CONTINUE; }","@Method(0x80114e60L) public static FlowControl FUN_80114e60(final RunningScript a0) { final EffectManagerData6c manager = (EffectManagerData6c)scriptStatePtrArr_800bc1c0[a0.params_20[0].get()].innerStruct_00; final int val = switch(a0.params_20[1].get()) { case 0 -> manager._10._24 = a0.params_20[2].get(); case 1 -> manager._10._28 = a0.params_20[2].get(); case 2 -> manager._10._2c = a0.params_20[2].get(); default -> throw new RuntimeException(""Invalid value (I think)""); }; return FlowControl.CONTINUE; }",Fix more crashes,https://github.com/Legend-of-Dragoon-Modding/Severed-Chains/commit/5b0660556fc8f509cbf9bac8f07dd7bd92266a1d,,,src/main/java/legend/game/combat/SEffe.java,3,java,False,2023-01-16T00:32:13Z "public static ItemStack oldItemStackToNew(ItemStack stack, int meta) { boolean copiedTag = false; Item newItem = OLD_ITEM_TO_NEW.get(Pair.of(stack.getItem(), meta)); if (newItem != null && newItem != stack.getItem()) { ItemStack newStack = new ItemStack(newItem, stack.getCount()); newStack.setTag(stack.getTag()); stack = newStack; } else if (stack.getItem() == FILLED_MAP) { stack = stack.copy(); copiedTag = true; stack.getOrCreateTag().putInt(""map"", meta); } else if (stack.getItem() == ENCHANTED_BOOK) { if (stack.getTag() != null && stack.getTag().contains(""StoredEnchantments"", 9)) { stack = stack.copy(); copiedTag = true; assert stack.getTag() != null; oldEnchantmentListToNew(stack.getTag().getList(""StoredEnchantments"", 10)); } } else if (stack.isDamageable()) { stack = stack.copy(); copiedTag = true; stack.setDamage(meta); } else if (stack.getItem() == BAT_SPAWN_EGG) { CompoundTag entityTag = stack.getSubTag(""EntityTag""); if (entityTag != null) { String entityId = entityTag.getString(""id""); EntityType entityType = Registry.ENTITY_TYPE.get(new Identifier(entityId)); newItem = SpawnEggItem.forEntity(entityType); if (newItem != null) { ItemStack newStack = new ItemStack(newItem, stack.getCount()); newStack.setTag(stack.getTag()); stack = newStack; } } } else if (stack.getItem() instanceof BlockItem && ((BlockItem) stack.getItem()).getBlock() instanceof ShulkerBoxBlock) { if (stack.getTag() != null && stack.getTag().contains(""BlockEntityTag"", 10)) { stack = stack.copy(); copiedTag = true; assert stack.getTag() != null; CompoundTag blockEntityTag = stack.getTag().getCompound(""BlockEntityTag""); if (blockEntityTag.contains(""Items"", 9)) { ListTag items = blockEntityTag.getList(""Items"", 10); for (int i = 0; i < items.size(); i++) { CompoundTag item = items.getCompound(i); int itemMeta = item.getShort(""Damage""); int slot = item.getByte(""Slot""); ItemStack itemStack = ItemStack.fromTag(item); itemStack = oldItemStackToNew(itemStack, itemMeta); CompoundTag newItemTag = itemStack.toTag(new CompoundTag()); newItemTag.putByte(""Slot"", (byte)slot); items.set(i, newItemTag); } } } } if (stack.getItem() instanceof BannerItem || stack.getItem() == SHIELD) { stack = invertBannerColors(stack); } if (stack.getTag() != null && stack.getTag().contains(""ench"", 9)) { if (!copiedTag) { stack = stack.copy(); copiedTag = true; } assert stack.getTag() != null; ListTag enchantments = stack.getTag().getList(""ench"", 10); oldEnchantmentListToNew(enchantments); stack.getTag().put(""Enchantments"", enchantments); stack.getTag().remove(""ench""); } if (stack.hasCustomName()) { if (!copiedTag) { stack = stack.copy(); //noinspection UnusedAssignment copiedTag = true; } //noinspection ConstantConditions String displayName = stack.getSubTag(""display"").getString(""Name""); stack.setCustomName(new LiteralText(displayName)); } return stack; }","public static ItemStack oldItemStackToNew(ItemStack stack, int meta) { boolean copiedTag = false; Item newItem = OLD_ITEM_TO_NEW.get(Pair.of(stack.getItem(), meta)); if (newItem != null && newItem != stack.getItem()) { ItemStack newStack = new ItemStack(newItem, stack.getCount()); newStack.setTag(stack.getTag()); stack = newStack; } else if (stack.getItem() == FILLED_MAP) { stack = stack.copy(); copiedTag = true; stack.getOrCreateTag().putInt(""map"", meta); } else if (stack.getItem() == ENCHANTED_BOOK) { if (stack.getTag() != null && stack.getTag().contains(""StoredEnchantments"", 9)) { stack = stack.copy(); copiedTag = true; assert stack.getTag() != null; oldEnchantmentListToNew(stack.getTag().getList(""StoredEnchantments"", 10)); } } else if (stack.isDamageable()) { stack = stack.copy(); copiedTag = true; stack.setDamage(meta); } else if (stack.getItem() == BAT_SPAWN_EGG) { CompoundTag entityTag = stack.getSubTag(""EntityTag""); if (entityTag != null) { String entityId = entityTag.getString(""id""); Identifier identifier = Identifier.tryParse(entityId); if(identifier != null) { EntityType entityType = Registry.ENTITY_TYPE.get(identifier); newItem = SpawnEggItem.forEntity(entityType); if (newItem != null) { ItemStack newStack = new ItemStack(newItem, stack.getCount()); newStack.setTag(stack.getTag()); stack = newStack; } } } } else if (stack.getItem() instanceof BlockItem && ((BlockItem) stack.getItem()).getBlock() instanceof ShulkerBoxBlock) { if (stack.getTag() != null && stack.getTag().contains(""BlockEntityTag"", 10)) { stack = stack.copy(); copiedTag = true; assert stack.getTag() != null; CompoundTag blockEntityTag = stack.getTag().getCompound(""BlockEntityTag""); if (blockEntityTag.contains(""Items"", 9)) { ListTag items = blockEntityTag.getList(""Items"", 10); for (int i = 0; i < items.size(); i++) { CompoundTag item = items.getCompound(i); int itemMeta = item.getShort(""Damage""); int slot = item.getByte(""Slot""); ItemStack itemStack = ItemStack.fromTag(item); itemStack = oldItemStackToNew(itemStack, itemMeta); CompoundTag newItemTag = itemStack.toTag(new CompoundTag()); newItemTag.putByte(""Slot"", (byte)slot); items.set(i, newItemTag); } } } } if (stack.getItem() instanceof BannerItem || stack.getItem() == SHIELD) { stack = invertBannerColors(stack); } if (stack.getTag() != null && stack.getTag().contains(""ench"", 9)) { if (!copiedTag) { stack = stack.copy(); copiedTag = true; } assert stack.getTag() != null; ListTag enchantments = stack.getTag().getList(""ench"", 10); oldEnchantmentListToNew(enchantments); stack.getTag().put(""Enchantments"", enchantments); stack.getTag().remove(""ench""); } if (stack.hasCustomName()) { if (!copiedTag) { stack = stack.copy(); //noinspection UnusedAssignment copiedTag = true; } //noinspection ConstantConditions String displayName = stack.getSubTag(""display"").getString(""Name""); stack.setCustomName(new LiteralText(displayName)); } return stack; }",Prevent invalid NBT data from crashing the client (#170),https://github.com/Earthcomputer/multiconnect/commit/17b1b198e533267c64f747c32e603facc9c59f36,,,src/main/java/net/earthcomputer/multiconnect/protocols/v1_12_2/Items_1_12_2.java,3,java,False,2021-05-18T15:29:41Z