code
stringlengths
1
1.05M
repo_name
stringlengths
6
83
path
stringlengths
3
242
language
stringclasses
222 values
license
stringclasses
20 values
size
int64
1
1.05M
// Copyright 2012 The Chromium Authors // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "ui/wm/core/visibility_controller.h" #include "ui/aura/test/aura_test_base.h" #include "ui/aura/test/test_window_delegate.h" #include "ui/aura/test/test_windows.h" #include "ui/aura/window.h" #include "ui/aura/window_event_dispatcher.h" #include "ui/compositor/layer.h" #include "ui/compositor/layer_animator.h" #include "ui/compositor/scoped_animation_duration_scale_mode.h" #include "ui/compositor/scoped_layer_animation_settings.h" #include "ui/wm/core/window_animations.h" namespace wm { typedef aura::test::AuraTestBase VisibilityControllerTest; // Check that a transparency change to 0 will not cause a hide call to be // ignored. TEST_F(VisibilityControllerTest, AnimateTransparencyToZeroAndHideHides) { // We cannot disable animations for this test. ui::ScopedAnimationDurationScaleMode test_duration_mode( ui::ScopedAnimationDurationScaleMode::NON_ZERO_DURATION); VisibilityController controller; aura::client::SetVisibilityClient(root_window(), &controller); SetChildWindowVisibilityChangesAnimated(root_window()); aura::test::TestWindowDelegate d; std::unique_ptr<aura::Window> window(aura::test::CreateTestWindowWithDelegate( &d, -2, gfx::Rect(0, 0, 50, 50), root_window())); ui::ScopedLayerAnimationSettings settings(window->layer()->GetAnimator()); settings.SetTransitionDuration(base::Milliseconds(5)); EXPECT_TRUE(window->layer()->visible()); EXPECT_TRUE(window->IsVisible()); window->layer()->SetOpacity(0.0); EXPECT_TRUE(window->layer()->visible()); EXPECT_TRUE(window->IsVisible()); EXPECT_TRUE(window->layer()->GetAnimator()-> IsAnimatingProperty(ui::LayerAnimationElement::OPACITY)); EXPECT_EQ(0.0f, window->layer()->GetTargetOpacity()); // Check that the visibility is correct after the hide animation has finished. window->Hide(); window->layer()->GetAnimator()->StopAnimating(); EXPECT_FALSE(window->layer()->visible()); EXPECT_FALSE(window->IsVisible()); } // Check that a hiding animation would not change a window's bounds in screen. TEST_F(VisibilityControllerTest, HideAnimationWindowBoundsTest) { // We cannot disable animations for this test. ui::ScopedAnimationDurationScaleMode test_duration_mode( ui::ScopedAnimationDurationScaleMode::NON_ZERO_DURATION); VisibilityController controller; aura::client::SetVisibilityClient(root_window(), &controller); // Set bound expectation. gfx::Rect expected_bounds(4, 5, 123, 245); aura::test::TestWindowDelegate d; std::unique_ptr<aura::Window> window(aura::test::CreateTestWindowWithDelegate( &d, -2, expected_bounds, root_window())); window->Show(); SetWindowVisibilityChangesAnimated(window.get()); SetWindowVisibilityAnimationDuration(window.get(), base::Milliseconds(5)); SetWindowVisibilityAnimationType(window.get(), WINDOW_VISIBILITY_ANIMATION_TYPE_DROP); // Check that the bound is correct after the hide animation has finished. window->Hide(); window->layer()->GetAnimator()->StopAnimating(); EXPECT_EQ(expected_bounds, window->GetBoundsInScreen()); } // Test if SetWindowVisibilityChagngesAnimated will animate the specified // window. TEST_F(VisibilityControllerTest, SetWindowVisibilityChagnesAnimated) { // We cannot disable animations for this test. ui::ScopedAnimationDurationScaleMode test_duration_mode( ui::ScopedAnimationDurationScaleMode::NON_ZERO_DURATION); VisibilityController controller; aura::client::SetVisibilityClient(root_window(), &controller); aura::test::TestWindowDelegate d; std::unique_ptr<aura::Window> window(aura::test::CreateTestWindowWithDelegate( &d, -2, gfx::Rect(0, 0, 50, 50), root_window())); // Test using Show animation because Hide animation detaches the window's // layer. window->Hide(); ASSERT_FALSE(window->IsVisible()); SetWindowVisibilityChangesAnimated(window.get()); SetWindowVisibilityAnimationDuration(window.get(), base::Milliseconds(5)); SetWindowVisibilityAnimationType(window.get(), WINDOW_VISIBILITY_ANIMATION_TYPE_FADE); window->Show(); EXPECT_TRUE(window->layer()->GetAnimator()->is_animating()); EXPECT_EQ(1.0f, window->layer()->GetTargetOpacity()); EXPECT_EQ(0.0f, window->layer()->opacity()); window->layer()->GetAnimator()->StopAnimating(); EXPECT_EQ(1.0f, window->layer()->GetTargetOpacity()); EXPECT_EQ(1.0f, window->layer()->opacity()); } } // namespace wm
Zhao-PengFei35/chromium_src_4
ui/wm/core/visibility_controller_unittest.cc
C++
unknown
4,602
// Copyright 2012 The Chromium Authors // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "ui/wm/core/window_animations.h" #include <math.h> #include <memory> #include "base/check_op.h" #include "base/command_line.h" #include "base/compiler_specific.h" #include "base/containers/contains.h" #include "base/functional/bind.h" #include "base/memory/raw_ptr.h" #include "base/metrics/histogram_macros.h" #include "base/notreached.h" #include "base/ranges/algorithm.h" #include "base/time/time.h" #include "ui/aura/client/aura_constants.h" #include "ui/aura/window.h" #include "ui/aura/window_delegate.h" #include "ui/aura/window_observer.h" #include "ui/base/class_property.h" #include "ui/compositor/animation_throughput_reporter.h" #include "ui/compositor/compositor_observer.h" #include "ui/compositor/layer.h" #include "ui/compositor/layer_animation_observer.h" #include "ui/compositor/layer_animation_sequence.h" #include "ui/compositor/layer_animator.h" #include "ui/compositor/layer_tree_owner.h" #include "ui/compositor/scoped_animation_duration_scale_mode.h" #include "ui/compositor/scoped_layer_animation_settings.h" #include "ui/gfx/animation/animation.h" #include "ui/gfx/geometry/rect_conversions.h" #include "ui/gfx/geometry/transform_util.h" #include "ui/gfx/geometry/vector2d.h" #include "ui/gfx/geometry/vector3d_f.h" #include "ui/gfx/interpolated_transform.h" #include "ui/wm/core/window_properties.h" #include "ui/wm/core/window_util.h" #include "ui/wm/core/wm_core_switches.h" #include "ui/wm/public/animation_host.h" namespace wm { namespace { // A base class for hiding animation observer which has two roles: // 1) Notifies AnimationHost at the end of hiding animation. // 2) Detaches the window's layers for hiding animation and deletes // them upon completion of the animation. This is necessary to a) // ensure that the animation continues in the event of the window being // deleted, and b) to ensure that the animation is visible even if the // window gets restacked below other windows when focus or activation // changes. // The subclass will determine when the animation is completed. class HidingWindowAnimationObserverBase : public aura::WindowObserver { public: explicit HidingWindowAnimationObserverBase(aura::Window* window) : window_(window) { window_->SetProperty( kWindowHidingAnimationCountKey, window_->GetProperty(kWindowHidingAnimationCountKey) + 1); window_->AddObserver(this); } HidingWindowAnimationObserverBase(const HidingWindowAnimationObserverBase&) = delete; HidingWindowAnimationObserverBase& operator=( const HidingWindowAnimationObserverBase&) = delete; ~HidingWindowAnimationObserverBase() override { if (!window_) return; window_->RemoveObserver(this); window_->SetProperty( kWindowHidingAnimationCountKey, window_->GetProperty(kWindowHidingAnimationCountKey) - 1); DCHECK_GE(window_->GetProperty(kWindowHidingAnimationCountKey), 0); } // aura::WindowObserver: void OnWindowDestroying(aura::Window* window) override { DCHECK_EQ(window, window_); WindowInvalid(); } void OnWindowDestroyed(aura::Window* window) override { DCHECK_EQ(window, window_); WindowInvalid(); } // Detach the current layers and create new layers for |window_|. // Stack the original layers above |window_| and its transient // children. If the window has transient children, the original // layers will be moved above the top most transient child so that // activation change does not put the window above the animating // layer. void DetachAndRecreateLayers() { layer_owner_ = RecreateLayers(window_); if (window_->parent()) { const aura::Window::Windows& transient_children = GetTransientChildren(window_); auto iter = base::ranges::find(window_->parent()->children(), window_); DCHECK(iter != window_->parent()->children().end()); aura::Window* topmost_transient_child = nullptr; for (++iter; iter != window_->parent()->children().end(); ++iter) { if (base::Contains(transient_children, *iter)) topmost_transient_child = *iter; } if (topmost_transient_child) { window_->parent()->layer()->StackAbove( layer_owner_->root(), topmost_transient_child->layer()); } } // Reset the transform for the |window_|. Because the animation may have // changed the transform, when recreating the layers we need to reset the // transform otherwise the recreated layer has the transform installed // for the animation. window_->layer()->SetTransform(gfx::Transform()); } protected: // Invoked when the hiding animation is completed. It will delete // 'this', and no operation should be made on this object after this // point. void OnAnimationCompleted() { // Window may have been destroyed by this point. if (window_) { AnimationHost* animation_host = GetAnimationHost(window_); if (animation_host) animation_host->OnWindowHidingAnimationCompleted(); } delete this; } private: // Invoked when the window is destroyed (or destroying). void WindowInvalid() { layer_owner_->root()->SuppressPaint(); window_->RemoveObserver(this); window_ = nullptr; } raw_ptr<aura::Window> window_; // The owner of detached layers. std::unique_ptr<ui::LayerTreeOwner> layer_owner_; }; // TODO(crbug.com/1021774): Find a better home and merge with // ash::metris_util::ForSmoothness. using SmoothnessCallback = base::RepeatingCallback<void(int smoothness)>; ui::AnimationThroughputReporter::ReportCallback ForSmoothness( SmoothnessCallback callback) { return base::BindRepeating( [](SmoothnessCallback callback, const cc::FrameSequenceMetrics::CustomReportData& data) { const int smoothness = std::floor(100.0f * data.frames_produced / data.frames_expected); callback.Run(smoothness); }, std::move(callback)); } void ReportHideSmoothness(int smoothness) { UMA_HISTOGRAM_PERCENTAGE("Ash.Window.AnimationSmoothness.Hide", smoothness); } } // namespace // A HidingWindowAnimationObserver that deletes observer and detached // layers upon the completion of the implicit animation. class ImplicitHidingWindowAnimationObserver : public HidingWindowAnimationObserverBase, public ui::ImplicitAnimationObserver { public: ImplicitHidingWindowAnimationObserver( aura::Window* window, ui::ScopedLayerAnimationSettings* settings); ImplicitHidingWindowAnimationObserver( const ImplicitHidingWindowAnimationObserver&) = delete; ImplicitHidingWindowAnimationObserver& operator=( const ImplicitHidingWindowAnimationObserver&) = delete; ~ImplicitHidingWindowAnimationObserver() override {} // ui::ImplicitAnimationObserver: void OnImplicitAnimationsCompleted() override; }; namespace { const int kDefaultAnimationDurationForMenuMS = 150; const float kWindowAnimation_HideOpacity = 0.f; const float kWindowAnimation_ShowOpacity = 1.f; const float kWindowAnimation_TranslateFactor = 0.5f; const float kWindowAnimation_ScaleFactor = .95f; const int kWindowAnimation_Rotate_DurationMS = 180; const int kWindowAnimation_Rotate_OpacityDurationPercent = 90; const float kWindowAnimation_Rotate_TranslateY = -20.f; const float kWindowAnimation_Rotate_PerspectiveDepth = 500.f; const float kWindowAnimation_Rotate_DegreesX = 5.f; const float kWindowAnimation_Rotate_ScaleFactor = .99f; const float kWindowAnimation_Bounce_Scale = 1.02f; const int kWindowAnimation_Bounce_DurationMS = 180; const int kWindowAnimation_Bounce_GrowShrinkDurationPercent = 40; base::TimeDelta GetWindowVisibilityAnimationDuration( const aura::Window& window) { base::TimeDelta duration = window.GetProperty(kWindowVisibilityAnimationDurationKey); if (duration.is_zero() && window.GetType() == aura::client::WINDOW_TYPE_MENU) { return base::Milliseconds(kDefaultAnimationDurationForMenuMS); } return duration; } // Gets/sets the WindowVisibilityAnimationType associated with a window. // TODO(beng): redundant/fold into method on public api? int GetWindowVisibilityAnimationType(aura::Window* window) { int type = window->GetProperty(kWindowVisibilityAnimationTypeKey); if (type == WINDOW_VISIBILITY_ANIMATION_TYPE_DEFAULT) { return (window->GetType() == aura::client::WINDOW_TYPE_MENU || window->GetType() == aura::client::WINDOW_TYPE_TOOLTIP) ? WINDOW_VISIBILITY_ANIMATION_TYPE_FADE : WINDOW_VISIBILITY_ANIMATION_TYPE_DROP; } return type; } void GetTransformRelativeToRoot(ui::Layer* layer, gfx::Transform* transform) { const ui::Layer* root = layer; while (root->parent()) root = root->parent(); layer->GetTargetTransformRelativeTo(root, transform); } gfx::Rect GetLayerWorldBoundsAfterTransform(ui::Layer* layer, const gfx::Transform& transform) { gfx::Transform in_world = transform; GetTransformRelativeToRoot(layer, &in_world); return in_world.MapRect(layer->bounds()); } // Augment the host window so that the enclosing bounds of the full // animation will fit inside of it. void AugmentWindowSize(aura::Window* window, const gfx::Transform& end_transform) { AnimationHost* animation_host = GetAnimationHost(window); if (!animation_host) return; const gfx::Rect& world_at_start = window->bounds(); gfx::Rect world_at_end = GetLayerWorldBoundsAfterTransform(window->layer(), end_transform); gfx::Rect union_in_window_space = gfx::UnionRects(world_at_start, world_at_end); // Calculate the top left and bottom right deltas to be added to the window // bounds. gfx::Vector2d top_left_delta(world_at_start.x() - union_in_window_space.x(), world_at_start.y() - union_in_window_space.y()); gfx::Vector2d bottom_right_delta( union_in_window_space.x() + union_in_window_space.width() - (world_at_start.x() + world_at_start.width()), union_in_window_space.y() + union_in_window_space.height() - (world_at_start.y() + world_at_start.height())); DCHECK(top_left_delta.x() >= 0 && top_left_delta.y() >= 0 && bottom_right_delta.x() >= 0 && bottom_right_delta.y() >= 0); animation_host->SetHostTransitionOffsets(top_left_delta, bottom_right_delta); } // Shows a window using an animation, animating its opacity from 0.f to 1.f, // its visibility to true, and its transform from |start_transform| to // |end_transform|. void AnimateShowWindowCommon(aura::Window* window, const gfx::Transform& start_transform, const gfx::Transform& end_transform) { AugmentWindowSize(window, end_transform); window->layer()->SetOpacity(kWindowAnimation_HideOpacity); window->layer()->SetTransform(start_transform); window->layer()->SetVisible(true); { // Property sets within this scope will be implicitly animated. ui::ScopedLayerAnimationSettings settings(window->layer()->GetAnimator()); base::TimeDelta duration = GetWindowVisibilityAnimationDuration(*window); if (duration.is_positive()) settings.SetTransitionDuration(duration); window->layer()->SetTransform(end_transform); window->layer()->SetOpacity(kWindowAnimation_ShowOpacity); } } // Hides a window using an animation, animating its opacity from 1.f to 0.f, // its visibility to false, and its transform to |end_transform|. void AnimateHideWindowCommon(aura::Window* window, const gfx::Transform& end_transform) { AugmentWindowSize(window, end_transform); // Property sets within this scope will be implicitly animated. ScopedHidingAnimationSettings hiding_settings(window); // Report animation smoothness for animations created within this scope. ui::AnimationThroughputReporter reporter( hiding_settings.layer_animation_settings()->GetAnimator(), ForSmoothness(base::BindRepeating(&ReportHideSmoothness))); // Render surface caching may not provide a benefit when animating the opacity // of a single layer. if (!window->layer()->children().empty()) hiding_settings.layer_animation_settings()->CacheRenderSurface(); base::TimeDelta duration = GetWindowVisibilityAnimationDuration(*window); if (duration.is_positive()) hiding_settings.layer_animation_settings()->SetTransitionDuration(duration); window->layer()->SetOpacity(kWindowAnimation_HideOpacity); window->layer()->SetTransform(end_transform); window->layer()->SetVisible(false); } static gfx::Transform GetScaleForWindow(aura::Window* window) { gfx::Rect bounds = window->bounds(); gfx::Transform scale = gfx::GetScaleTransform( gfx::Point(kWindowAnimation_TranslateFactor * bounds.width(), kWindowAnimation_TranslateFactor * bounds.height()), kWindowAnimation_ScaleFactor); return scale; } // Show/Hide windows using a shrink animation. void AnimateShowWindow_Drop(aura::Window* window) { AnimateShowWindowCommon(window, GetScaleForWindow(window), gfx::Transform()); } void AnimateHideWindow_Drop(aura::Window* window) { AnimateHideWindowCommon(window, GetScaleForWindow(window)); } // Show/Hide windows using a vertical Glenimation. void AnimateShowWindow_Vertical(aura::Window* window) { gfx::Transform transform; transform.Translate(0, window->GetProperty( kWindowVisibilityAnimationVerticalPositionKey)); AnimateShowWindowCommon(window, transform, gfx::Transform()); } void AnimateHideWindow_Vertical(aura::Window* window) { gfx::Transform transform; transform.Translate(0, window->GetProperty( kWindowVisibilityAnimationVerticalPositionKey)); AnimateHideWindowCommon(window, transform); } // Show/Hide windows using a fade. void AnimateShowWindow_Fade(aura::Window* window) { AnimateShowWindowCommon(window, gfx::Transform(), gfx::Transform()); } void AnimateHideWindow_Fade(aura::Window* window) { AnimateHideWindowCommon(window, gfx::Transform()); } std::unique_ptr<ui::LayerAnimationElement> CreateGrowShrinkElement( aura::Window* window, bool grow) { std::unique_ptr<ui::InterpolatedTransform> scale = std::make_unique<ui::InterpolatedScale>( gfx::Point3F(kWindowAnimation_Bounce_Scale, kWindowAnimation_Bounce_Scale, 1), gfx::Point3F(1, 1, 1)); std::unique_ptr<ui::InterpolatedTransform> scale_about_pivot = std::make_unique<ui::InterpolatedTransformAboutPivot>( gfx::Point(window->bounds().width() * 0.5, window->bounds().height() * 0.5), std::move(scale)); scale_about_pivot->SetReversed(grow); std::unique_ptr<ui::LayerAnimationElement> transition = ui::LayerAnimationElement::CreateInterpolatedTransformElement( std::move(scale_about_pivot), base::Milliseconds(kWindowAnimation_Bounce_DurationMS * kWindowAnimation_Bounce_GrowShrinkDurationPercent / 100)); transition->set_tween_type(grow ? gfx::Tween::EASE_OUT : gfx::Tween::EASE_IN); return transition; } void AnimateBounce(aura::Window* window) { ui::ScopedLayerAnimationSettings scoped_settings( window->layer()->GetAnimator()); scoped_settings.SetPreemptionStrategy( ui::LayerAnimator::REPLACE_QUEUED_ANIMATIONS); std::unique_ptr<ui::LayerAnimationSequence> sequence = std::make_unique<ui::LayerAnimationSequence>(); sequence->AddElement(CreateGrowShrinkElement(window, true)); sequence->AddElement(ui::LayerAnimationElement::CreatePauseElement( ui::LayerAnimationElement::BOUNDS, base::Milliseconds( kWindowAnimation_Bounce_DurationMS * (100 - 2 * kWindowAnimation_Bounce_GrowShrinkDurationPercent) / 100))); sequence->AddElement(CreateGrowShrinkElement(window, false)); window->layer()->GetAnimator()->StartAnimation(sequence.release()); } // A HidingWindowAnimationObserver that deletes observer and detached // layers when the last_sequence has been completed or aborted. class RotateHidingWindowAnimationObserver : public HidingWindowAnimationObserverBase, public ui::LayerAnimationObserver { public: explicit RotateHidingWindowAnimationObserver(aura::Window* window) : HidingWindowAnimationObserverBase(window) {} RotateHidingWindowAnimationObserver( const RotateHidingWindowAnimationObserver&) = delete; RotateHidingWindowAnimationObserver& operator=( const RotateHidingWindowAnimationObserver&) = delete; ~RotateHidingWindowAnimationObserver() override {} // Destroys itself after |last_sequence| ends or is aborted. Does not take // ownership of |last_sequence|, which should not be nullptr. void SetLastSequence(ui::LayerAnimationSequence* last_sequence) { last_sequence->AddObserver(this); } // ui::LayerAnimationObserver: void OnLayerAnimationEnded(ui::LayerAnimationSequence* sequence) override { OnAnimationCompleted(); } void OnLayerAnimationAborted(ui::LayerAnimationSequence* sequence) override { OnAnimationCompleted(); } void OnLayerAnimationScheduled( ui::LayerAnimationSequence* sequence) override {} }; void AddLayerAnimationsForRotate(aura::Window* window, bool show) { if (show) window->layer()->SetOpacity(kWindowAnimation_HideOpacity); base::TimeDelta duration = base::Milliseconds(kWindowAnimation_Rotate_DurationMS); if (!show) { window->layer()->GetAnimator()->SchedulePauseForProperties( duration * (100 - kWindowAnimation_Rotate_OpacityDurationPercent) / 100, ui::LayerAnimationElement::OPACITY); } std::unique_ptr<ui::LayerAnimationElement> opacity = ui::LayerAnimationElement::CreateOpacityElement( show ? kWindowAnimation_ShowOpacity : kWindowAnimation_HideOpacity, duration * kWindowAnimation_Rotate_OpacityDurationPercent / 100); opacity->set_tween_type(gfx::Tween::EASE_IN_OUT); window->layer()->GetAnimator()->ScheduleAnimation( new ui::LayerAnimationSequence(std::move(opacity))); float xcenter = window->bounds().width() * 0.5; gfx::Transform transform; transform.Translate(xcenter, 0); transform.ApplyPerspectiveDepth(kWindowAnimation_Rotate_PerspectiveDepth); transform.Translate(-xcenter, 0); std::unique_ptr<ui::InterpolatedTransform> perspective = std::make_unique<ui::InterpolatedConstantTransform>(transform); std::unique_ptr<ui::InterpolatedTransform> scale = std::make_unique<ui::InterpolatedScale>( 1, kWindowAnimation_Rotate_ScaleFactor); std::unique_ptr<ui::InterpolatedTransform> scale_about_pivot = std::make_unique<ui::InterpolatedTransformAboutPivot>( gfx::Point(xcenter, kWindowAnimation_Rotate_TranslateY), std::move(scale)); std::unique_ptr<ui::InterpolatedTransform> translation = std::make_unique<ui::InterpolatedTranslation>( gfx::PointF(), gfx::PointF(0, kWindowAnimation_Rotate_TranslateY)); std::unique_ptr<ui::InterpolatedTransform> rotation = std::make_unique<ui::InterpolatedAxisAngleRotation>( gfx::Vector3dF(1, 0, 0), 0, kWindowAnimation_Rotate_DegreesX); scale_about_pivot->SetChild(std::move(perspective)); translation->SetChild(std::move(scale_about_pivot)); rotation->SetChild(std::move(translation)); rotation->SetReversed(show); std::unique_ptr<ui::LayerAnimationElement> transition = ui::LayerAnimationElement::CreateInterpolatedTransformElement( std::move(rotation), duration); ui::LayerAnimationSequence* last_sequence = new ui::LayerAnimationSequence(std::move(transition)); auto weak_last_sequence = last_sequence->AsWeakPtr(); window->layer()->GetAnimator()->ScheduleAnimation(last_sequence); // If the animation is immediate, then |last_sequence| will have been // deleted. last_sequence = nullptr; if (!show && weak_last_sequence) { // RotateHidingWindowAnimationObserver deletes itself when no longer // needed. auto* observer = new RotateHidingWindowAnimationObserver(window); observer->SetLastSequence(weak_last_sequence.get()); observer->DetachAndRecreateLayers(); } window->layer()->SetVisible(show); } void AnimateShowWindow_Rotate(aura::Window* window) { AddLayerAnimationsForRotate(window, true); } void AnimateHideWindow_Rotate(aura::Window* window) { AddLayerAnimationsForRotate(window, false); } bool AnimateShowWindow(aura::Window* window) { if (!HasWindowVisibilityAnimationTransition(window, ANIMATE_SHOW)) { if (HasWindowVisibilityAnimationTransition(window, ANIMATE_HIDE)) { // Since hide animation may have changed opacity and transform, // reset them to show the window. window->layer()->SetOpacity(kWindowAnimation_ShowOpacity); window->layer()->SetTransform(gfx::Transform()); } return false; } switch (GetWindowVisibilityAnimationType(window)) { case WINDOW_VISIBILITY_ANIMATION_TYPE_DROP: AnimateShowWindow_Drop(window); return true; case WINDOW_VISIBILITY_ANIMATION_TYPE_VERTICAL: AnimateShowWindow_Vertical(window); return true; case WINDOW_VISIBILITY_ANIMATION_TYPE_FADE: AnimateShowWindow_Fade(window); return true; case WINDOW_VISIBILITY_ANIMATION_TYPE_ROTATE: AnimateShowWindow_Rotate(window); return true; default: return false; } } bool AnimateHideWindow(aura::Window* window) { if (!HasWindowVisibilityAnimationTransition(window, ANIMATE_HIDE)) { if (HasWindowVisibilityAnimationTransition(window, ANIMATE_SHOW)) { // Since show animation may have changed opacity and transform, // reset them, though the change should be hidden. window->layer()->SetOpacity(kWindowAnimation_HideOpacity); window->layer()->SetTransform(gfx::Transform()); } return false; } switch (GetWindowVisibilityAnimationType(window)) { case WINDOW_VISIBILITY_ANIMATION_TYPE_DROP: AnimateHideWindow_Drop(window); return true; case WINDOW_VISIBILITY_ANIMATION_TYPE_VERTICAL: AnimateHideWindow_Vertical(window); return true; case WINDOW_VISIBILITY_ANIMATION_TYPE_FADE: AnimateHideWindow_Fade(window); return true; case WINDOW_VISIBILITY_ANIMATION_TYPE_ROTATE: AnimateHideWindow_Rotate(window); return true; default: return false; } } } // namespace //////////////////////////////////////////////////////////////////////////////// // ImplicitHidingWindowAnimationObserver ImplicitHidingWindowAnimationObserver::ImplicitHidingWindowAnimationObserver( aura::Window* window, ui::ScopedLayerAnimationSettings* settings) : HidingWindowAnimationObserverBase(window) { settings->AddObserver(this); } void ImplicitHidingWindowAnimationObserver::OnImplicitAnimationsCompleted() { OnAnimationCompleted(); } //////////////////////////////////////////////////////////////////////////////// // ScopedHidingAnimationSettings ScopedHidingAnimationSettings::ScopedHidingAnimationSettings( aura::Window* window) : layer_animation_settings_(window->layer()->GetAnimator()), observer_(new ImplicitHidingWindowAnimationObserver( window, &layer_animation_settings_)) { } ScopedHidingAnimationSettings::~ScopedHidingAnimationSettings() { observer_->DetachAndRecreateLayers(); } //////////////////////////////////////////////////////////////////////////////// // External interface void SetWindowVisibilityAnimationType(aura::Window* window, int type) { window->SetProperty(kWindowVisibilityAnimationTypeKey, type); } int GetWindowVisibilityAnimationType(aura::Window* window) { return window->GetProperty(kWindowVisibilityAnimationTypeKey); } void SetWindowVisibilityAnimationTransition( aura::Window* window, WindowVisibilityAnimationTransition transition) { window->SetProperty(kWindowVisibilityAnimationTransitionKey, transition); } bool HasWindowVisibilityAnimationTransition( aura::Window* window, WindowVisibilityAnimationTransition transition) { WindowVisibilityAnimationTransition prop = window->GetProperty( kWindowVisibilityAnimationTransitionKey); return (prop & transition) != 0; } void SetWindowVisibilityAnimationDuration(aura::Window* window, const base::TimeDelta& duration) { window->SetProperty(kWindowVisibilityAnimationDurationKey, duration); } base::TimeDelta GetWindowVisibilityAnimationDuration( const aura::Window& window) { return window.GetProperty(kWindowVisibilityAnimationDurationKey); } void SetWindowVisibilityAnimationVerticalPosition(aura::Window* window, float position) { window->SetProperty(kWindowVisibilityAnimationVerticalPositionKey, position); } bool AnimateOnChildWindowVisibilityChanged(aura::Window* window, bool visible) { if (WindowAnimationsDisabled(window)) return false; if (visible) return AnimateShowWindow(window); // Don't start hiding the window again if it's already being hidden. return window->layer()->GetTargetOpacity() != 0.0f && AnimateHideWindow(window); } bool AnimateWindow(aura::Window* window, WindowAnimationType type) { switch (type) { case WINDOW_ANIMATION_TYPE_BOUNCE: AnimateBounce(window); return true; default: NOTREACHED(); return false; } } bool WindowAnimationsDisabled(aura::Window* window) { // WARNING: this function is called from VisibilityController to determine // if an animation should happen when the Window's visibility changes. // Returning false results in VisibilityController applying default // handling of the transition. This can result in dramatically different // results than if an animation occurs. For example, VisibilityController // doesn't change the opacity, yet many of the animations do. Similarly, // ash's animations may change the bounds, which VisibilityController won't // do. Take care when adding a new path that returns false. // Individual windows can choose to skip animations. if (window && window->GetProperty(aura::client::kAnimationsDisabledKey)) return true; // Animations can be disabled globally for testing. if (base::CommandLine::ForCurrentProcess()->HasSwitch( switches::kWindowAnimationsDisabled)) return true; // Tests of animations themselves should still run even if the machine is // being accessed via Remote Desktop. if (ui::ScopedAnimationDurationScaleMode::duration_multiplier() == ui::ScopedAnimationDurationScaleMode::NON_ZERO_DURATION) return false; // Let the user decide whether or not to play the animation. return !gfx::Animation::ShouldRenderRichAnimation(); } } // namespace wm
Zhao-PengFei35/chromium_src_4
ui/wm/core/window_animations.cc
C++
unknown
26,957
// Copyright 2012 The Chromium Authors // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #ifndef UI_WM_CORE_WINDOW_ANIMATIONS_H_ #define UI_WM_CORE_WINDOW_ANIMATIONS_H_ #include "base/component_export.h" #include "base/memory/raw_ptr.h" #include "ui/compositor/scoped_layer_animation_settings.h" #include "ui/wm/core/window_properties.h" namespace aura { class Window; } namespace base { class TimeDelta; } namespace wm { // A variety of canned animations for window transitions. enum WindowVisibilityAnimationType { WINDOW_VISIBILITY_ANIMATION_TYPE_DEFAULT = 0, // Default. Lets the system // decide based on window // type. WINDOW_VISIBILITY_ANIMATION_TYPE_DROP, // Window shrinks in. WINDOW_VISIBILITY_ANIMATION_TYPE_VERTICAL, // Vertical Glenimation. WINDOW_VISIBILITY_ANIMATION_TYPE_FADE, // Fades in/out. WINDOW_VISIBILITY_ANIMATION_TYPE_ROTATE, // Window rotates in. // Downstream library animations start above this point. WINDOW_VISIBILITY_ANIMATION_MAX }; // Canned animations that take effect once but don't have a symmetric pair as // visibility animations do. enum WindowAnimationType { WINDOW_ANIMATION_TYPE_BOUNCE = 0, // Window scales up and down. }; // These two methods use int for type rather than WindowVisibilityAnimationType // since downstream libraries can extend the set of animations. COMPONENT_EXPORT(UI_WM) void SetWindowVisibilityAnimationType(aura::Window* window, int type); COMPONENT_EXPORT(UI_WM) int GetWindowVisibilityAnimationType(aura::Window* window); COMPONENT_EXPORT(UI_WM) void SetWindowVisibilityAnimationTransition( aura::Window* window, WindowVisibilityAnimationTransition transition); COMPONENT_EXPORT(UI_WM) bool HasWindowVisibilityAnimationTransition( aura::Window* window, WindowVisibilityAnimationTransition transition); COMPONENT_EXPORT(UI_WM) void SetWindowVisibilityAnimationDuration(aura::Window* window, const base::TimeDelta& duration); COMPONENT_EXPORT(UI_WM) base::TimeDelta GetWindowVisibilityAnimationDuration( const aura::Window& window); COMPONENT_EXPORT(UI_WM) void SetWindowVisibilityAnimationVerticalPosition(aura::Window* window, float position); class ImplicitHidingWindowAnimationObserver; // A wrapper of ui::ScopedLayerAnimationSettings for implicit hiding animations. // Use this to ensure that the hiding animation is visible even after // the window is deleted or deactivated, instead of using // ui::ScopedLayerAnimationSettings directly. class COMPONENT_EXPORT(UI_WM) ScopedHidingAnimationSettings { public: explicit ScopedHidingAnimationSettings(aura::Window* window); ScopedHidingAnimationSettings(const ScopedHidingAnimationSettings&) = delete; ScopedHidingAnimationSettings& operator=( const ScopedHidingAnimationSettings&) = delete; ~ScopedHidingAnimationSettings(); // Returns the wrapped ScopedLayeAnimationSettings instance. ui::ScopedLayerAnimationSettings* layer_animation_settings() { return &layer_animation_settings_; } private: ui::ScopedLayerAnimationSettings layer_animation_settings_; raw_ptr<ImplicitHidingWindowAnimationObserver> observer_; }; // Returns false if the |window| didn't animate. COMPONENT_EXPORT(UI_WM) bool AnimateOnChildWindowVisibilityChanged(aura::Window* window, bool visible); COMPONENT_EXPORT(UI_WM) bool AnimateWindow(aura::Window* window, WindowAnimationType type); // Returns true if window animations are disabled for |window|. Window // animations are enabled by default. If |window| is nullptr, this just checks // if the global flag disabling window animations is present. COMPONENT_EXPORT(UI_WM) bool WindowAnimationsDisabled(aura::Window* window); } // namespace wm #endif // UI_WM_CORE_WINDOW_ANIMATIONS_H_
Zhao-PengFei35/chromium_src_4
ui/wm/core/window_animations.h
C++
unknown
4,014
// Copyright 2012 The Chromium Authors // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "ui/wm/core/window_animations.h" #include <memory> #include "base/containers/contains.h" #include "base/ranges/algorithm.h" #include "base/time/time.h" #include "ui/aura/test/aura_test_base.h" #include "ui/aura/test/test_windows.h" #include "ui/aura/window.h" #include "ui/compositor/layer.h" #include "ui/compositor/layer_animator.h" #include "ui/compositor/scoped_animation_duration_scale_mode.h" #include "ui/gfx/animation/animation_container_element.h" #include "ui/gfx/geometry/vector2d.h" #include "ui/wm/core/transient_window_manager.h" #include "ui/wm/core/transient_window_stacking_client.h" #include "ui/wm/core/window_util.h" #include "ui/wm/public/animation_host.h" using aura::Window; using ui::Layer; namespace wm { namespace { template<typename T>int GetZPosition(const T* child) { const T* parent = child->parent(); const std::vector<T*> children = parent->children(); auto iter = base::ranges::find(children, child); DCHECK(iter != children.end()); return iter - children.begin(); } int GetWindowZPosition(const aura::Window* child) { return GetZPosition<aura::Window>(child); } int GetLayerZPosition(const ui::Layer* child) { return GetZPosition<ui::Layer>(child); } } // namespace class WindowAnimationsTest : public aura::test::AuraTestBase { public: WindowAnimationsTest() {} WindowAnimationsTest(const WindowAnimationsTest&) = delete; WindowAnimationsTest& operator=(const WindowAnimationsTest&) = delete; }; TEST_F(WindowAnimationsTest, LayerTargetVisibility) { std::unique_ptr<aura::Window> window( aura::test::CreateTestWindowWithId(0, NULL)); // Layer target visibility changes according to Show/Hide. window->Show(); EXPECT_TRUE(window->layer()->GetTargetVisibility()); window->Hide(); EXPECT_FALSE(window->layer()->GetTargetVisibility()); window->Show(); EXPECT_TRUE(window->layer()->GetTargetVisibility()); } TEST_F(WindowAnimationsTest, LayerTargetVisibility_AnimateShow) { // Tests if opacity and transform are reset when only show animation is // enabled. See also LayerTargetVisibility_AnimateHide. // Since the window is not visible after Hide() is called, opacity and // transform shouldn't matter in case of ANIMATE_SHOW, but we reset them // to keep consistency. std::unique_ptr<aura::Window> window( aura::test::CreateTestWindowWithId(0, NULL)); SetWindowVisibilityAnimationTransition(window.get(), ANIMATE_SHOW); // Layer target visibility and opacity change according to Show/Hide. window->Show(); AnimateOnChildWindowVisibilityChanged(window.get(), true); EXPECT_TRUE(window->layer()->GetTargetVisibility()); EXPECT_EQ(1, window->layer()->opacity()); window->Hide(); AnimateOnChildWindowVisibilityChanged(window.get(), false); EXPECT_FALSE(window->layer()->GetTargetVisibility()); EXPECT_EQ(0, window->layer()->opacity()); EXPECT_EQ(gfx::Transform(), window->layer()->transform()); window->Show(); AnimateOnChildWindowVisibilityChanged(window.get(), true); EXPECT_TRUE(window->layer()->GetTargetVisibility()); EXPECT_EQ(1, window->layer()->opacity()); } TEST_F(WindowAnimationsTest, LayerTargetVisibility_AnimateHide) { // Tests if opacity and transform are reset when only hide animation is // enabled. Hide animation changes opacity and transform in addition to // visibility, so we need to reset not only visibility but also opacity // and transform to show the window. std::unique_ptr<aura::Window> window( aura::test::CreateTestWindowWithId(0, NULL)); SetWindowVisibilityAnimationTransition(window.get(), ANIMATE_HIDE); // Layer target visibility and opacity change according to Show/Hide. window->Show(); AnimateOnChildWindowVisibilityChanged(window.get(), true); EXPECT_TRUE(window->layer()->GetTargetVisibility()); EXPECT_EQ(1, window->layer()->opacity()); EXPECT_EQ(gfx::Transform(), window->layer()->transform()); window->Hide(); AnimateOnChildWindowVisibilityChanged(window.get(), false); EXPECT_FALSE(window->layer()->GetTargetVisibility()); EXPECT_EQ(0, window->layer()->opacity()); window->Show(); AnimateOnChildWindowVisibilityChanged(window.get(), true); EXPECT_TRUE(window->layer()->GetTargetVisibility()); EXPECT_EQ(1, window->layer()->opacity()); EXPECT_EQ(gfx::Transform(), window->layer()->transform()); } TEST_F(WindowAnimationsTest, HideAnimationDetachLayers) { std::unique_ptr<aura::Window> parent( aura::test::CreateTestWindowWithId(0, NULL)); std::unique_ptr<aura::Window> other( aura::test::CreateTestWindowWithId(1, parent.get())); std::unique_ptr<aura::Window> animating_window( aura::test::CreateTestWindowWithId(2, parent.get())); SetWindowVisibilityAnimationTransition(animating_window.get(), ANIMATE_HIDE); EXPECT_EQ(0, GetWindowZPosition(other.get())); EXPECT_EQ(1, GetWindowZPosition(animating_window.get())); EXPECT_EQ(0, GetLayerZPosition(other->layer())); EXPECT_EQ(1, GetLayerZPosition(animating_window->layer())); { ui::ScopedAnimationDurationScaleMode scale_mode( ui::ScopedAnimationDurationScaleMode::FAST_DURATION); ui::Layer* animating_layer = animating_window->layer(); animating_window->Hide(); EXPECT_TRUE(AnimateOnChildWindowVisibilityChanged( animating_window.get(), false)); EXPECT_TRUE(animating_layer->GetAnimator()->is_animating()); EXPECT_FALSE(animating_layer->delegate()); // Make sure the Hide animation create another layer, and both are in // the parent layer. EXPECT_NE(animating_window->layer(), animating_layer); EXPECT_TRUE(base::Contains(parent->layer()->children(), animating_layer)); EXPECT_TRUE( base::Contains(parent->layer()->children(), animating_window->layer())); // Current layer must be already hidden. EXPECT_FALSE(animating_window->layer()->visible()); EXPECT_EQ(1, GetWindowZPosition(animating_window.get())); EXPECT_EQ(1, GetLayerZPosition(animating_window->layer())); EXPECT_EQ(2, GetLayerZPosition(animating_layer)); parent->StackChildAtTop(other.get()); EXPECT_EQ(0, GetWindowZPosition(animating_window.get())); EXPECT_EQ(1, GetWindowZPosition(other.get())); EXPECT_EQ(0, GetLayerZPosition(animating_window->layer())); EXPECT_EQ(1, GetLayerZPosition(other->layer())); // Make sure the animating layer is on top. EXPECT_EQ(2, GetLayerZPosition(animating_layer)); // Animating layer must be gone animating_layer->GetAnimator()->StopAnimating(); EXPECT_FALSE(base::Contains(parent->layer()->children(), animating_layer)); } } TEST_F(WindowAnimationsTest, HideAnimationDetachLayersWithTransientChildren) { TransientWindowStackingClient transient_stacking_client; std::unique_ptr<aura::Window> parent( aura::test::CreateTestWindowWithId(0, NULL)); std::unique_ptr<aura::Window> other( aura::test::CreateTestWindowWithId(1, parent.get())); std::unique_ptr<aura::Window> animating_window( aura::test::CreateTestWindowWithId(2, parent.get())); SetWindowVisibilityAnimationTransition(animating_window.get(), ANIMATE_HIDE); std::unique_ptr<aura::Window> transient1( aura::test::CreateTestWindowWithId(3, parent.get())); std::unique_ptr<aura::Window> transient2( aura::test::CreateTestWindowWithId(4, parent.get())); TransientWindowManager::GetOrCreate(animating_window.get()); AddTransientChild(animating_window.get(), transient1.get()); AddTransientChild(animating_window.get(), transient2.get()); EXPECT_EQ(0, GetWindowZPosition(other.get())); EXPECT_EQ(1, GetWindowZPosition(animating_window.get())); EXPECT_EQ(2, GetWindowZPosition(transient1.get())); EXPECT_EQ(3, GetWindowZPosition(transient2.get())); { ui::ScopedAnimationDurationScaleMode scale_mode( ui::ScopedAnimationDurationScaleMode::FAST_DURATION); ui::Layer* animating_layer = animating_window->layer(); animating_window->Hide(); EXPECT_TRUE(AnimateOnChildWindowVisibilityChanged( animating_window.get(), false)); EXPECT_TRUE(animating_layer->GetAnimator()->is_animating()); EXPECT_FALSE(animating_layer->delegate()); EXPECT_EQ(1, GetWindowZPosition(animating_window.get())); EXPECT_EQ(2, GetWindowZPosition(transient1.get())); EXPECT_EQ(3, GetWindowZPosition(transient2.get())); EXPECT_EQ(1, GetLayerZPosition(animating_window->layer())); EXPECT_EQ(2, GetLayerZPosition(transient1->layer())); EXPECT_EQ(3, GetLayerZPosition(transient2->layer())); EXPECT_EQ(4, GetLayerZPosition(animating_layer)); parent->StackChildAtTop(other.get()); EXPECT_EQ(0, GetWindowZPosition(animating_window.get())); EXPECT_EQ(1, GetWindowZPosition(transient1.get())); EXPECT_EQ(2, GetWindowZPosition(transient2.get())); EXPECT_EQ(3, GetWindowZPosition(other.get())); EXPECT_EQ(0, GetLayerZPosition(animating_window->layer())); EXPECT_EQ(1, GetLayerZPosition(transient1->layer())); EXPECT_EQ(2, GetLayerZPosition(transient2->layer())); EXPECT_EQ(3, GetLayerZPosition(other->layer())); // Make sure the animating layer is on top of all windows. EXPECT_EQ(4, GetLayerZPosition(animating_layer)); } } // A simple AnimationHost implementation for the NotifyHideCompleted test. class NotifyHideCompletedAnimationHost : public AnimationHost { public: NotifyHideCompletedAnimationHost() : hide_completed_(false) {} NotifyHideCompletedAnimationHost(const NotifyHideCompletedAnimationHost&) = delete; NotifyHideCompletedAnimationHost& operator=( const NotifyHideCompletedAnimationHost&) = delete; ~NotifyHideCompletedAnimationHost() override {} // Overridden from AnimationHost: void OnWindowHidingAnimationCompleted() override { hide_completed_ = true; } void SetHostTransitionOffsets(const gfx::Vector2d& top_left, const gfx::Vector2d& bottom_right) override {} bool hide_completed() const { return hide_completed_; } private: bool hide_completed_; }; TEST_F(WindowAnimationsTest, NotifyHideCompleted) { NotifyHideCompletedAnimationHost animation_host; std::unique_ptr<aura::Window> window( aura::test::CreateTestWindowWithId(0, NULL)); SetAnimationHost(window.get(), &animation_host); wm::SetWindowVisibilityAnimationType( window.get(), WINDOW_VISIBILITY_ANIMATION_TYPE_FADE); AnimateOnChildWindowVisibilityChanged(window.get(), true); EXPECT_TRUE(window->layer()->visible()); EXPECT_FALSE(animation_host.hide_completed()); AnimateOnChildWindowVisibilityChanged(window.get(), false); EXPECT_TRUE(animation_host.hide_completed()); } // The rotation animation for hiding a window should not leak the animation // observer. TEST_F(WindowAnimationsTest, RotateHideNoLeak) { ui::ScopedAnimationDurationScaleMode scale_mode( ui::ScopedAnimationDurationScaleMode::FAST_DURATION); std::unique_ptr<aura::Window> window( aura::test::CreateTestWindowWithId(0, nullptr)); ui::Layer* animating_layer = window->layer(); wm::SetWindowVisibilityAnimationType(window.get(), WINDOW_VISIBILITY_ANIMATION_TYPE_ROTATE); AnimateOnChildWindowVisibilityChanged(window.get(), true); AnimateOnChildWindowVisibilityChanged(window.get(), false); animating_layer->GetAnimator()->StopAnimating(); } // The rotation animation for hiding a window should not crash with a zero // duration. TEST_F(WindowAnimationsTest, RotateHideNoCrashZeroDuration) { std::unique_ptr<aura::Window> window( aura::test::CreateTestWindowWithId(0, nullptr)); wm::SetWindowVisibilityAnimationType(window.get(), WINDOW_VISIBILITY_ANIMATION_TYPE_ROTATE); AnimateOnChildWindowVisibilityChanged(window.get(), true); AnimateOnChildWindowVisibilityChanged(window.get(), false); } TEST_F(WindowAnimationsTest, RotateHideCreatesNewLayer) { ui::ScopedAnimationDurationScaleMode scale_mode( ui::ScopedAnimationDurationScaleMode::FAST_DURATION); std::unique_ptr<aura::Window> window( aura::test::CreateTestWindowWithId(0, nullptr)); wm::SetWindowVisibilityAnimationType(window.get(), WINDOW_VISIBILITY_ANIMATION_TYPE_ROTATE); AnimateOnChildWindowVisibilityChanged(window.get(), true); window->layer()->GetAnimator()->StopAnimating(); auto* original_layer = window->layer(); AnimateOnChildWindowVisibilityChanged(window.get(), false); // The layer should have changed, as the Layer is cloned and detached. EXPECT_NE(original_layer, window->layer()); // Need to stop the animation, otherwise there is a leak. original_layer->GetAnimator()->StopAnimating(); } // The rotation animation for hiding a window should not crash when terminated // by LayerAnimator::StopAnimating(). TEST_F(WindowAnimationsTest, RotateHideNoCrash) { ui::ScopedAnimationDurationScaleMode scale_mode( ui::ScopedAnimationDurationScaleMode::FAST_DURATION); std::unique_ptr<aura::Window> window( aura::test::CreateTestWindowWithId(0, NULL)); ui::Layer* animating_layer = window->layer(); wm::SetWindowVisibilityAnimationType(window.get(), WINDOW_VISIBILITY_ANIMATION_TYPE_ROTATE); AnimateOnChildWindowVisibilityChanged(window.get(), true); window->layer()->GetAnimator()->Step(base::TimeTicks::Now() + base::Seconds(5)); AnimateOnChildWindowVisibilityChanged(window.get(), false); animating_layer->GetAnimator()->StopAnimating(); } } // namespace wm
Zhao-PengFei35/chromium_src_4
ui/wm/core/window_animations_unittest.cc
C++
unknown
13,697
// Copyright 2012 The Chromium Authors // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "ui/wm/core/window_modality_controller.h" #include <stddef.h> #include <queue> #include "base/ranges/algorithm.h" #include "ui/aura/client/aura_constants.h" #include "ui/aura/client/capture_client.h" #include "ui/aura/env.h" #include "ui/aura/window.h" #include "ui/aura/window_event_dispatcher.h" #include "ui/base/class_property.h" #include "ui/base/ui_base_types.h" #include "ui/events/event.h" #include "ui/events/event_target.h" #include "ui/events/gestures/gesture_recognizer.h" #include "ui/wm/core/window_animations.h" #include "ui/wm/core/window_util.h" namespace wm { namespace { bool HasAncestor(const aura::Window* window, const aura::Window* ancestor) { return ancestor && ancestor->Contains(window); } bool TransientChildIsWindowModal(const aura::Window* window) { return window->GetProperty(aura::client::kModalKey) == ui::MODAL_TYPE_WINDOW; } bool TransientChildIsSystemModal(const aura::Window* window) { return window->GetProperty(aura::client::kModalKey) == ui::MODAL_TYPE_SYSTEM; } bool TransientChildIsChildModal(const aura::Window* window) { return window->GetProperty(aura::client::kModalKey) == ui::MODAL_TYPE_CHILD; } aura::Window* GetModalParent(const aura::Window* window) { return window->GetProperty(aura::client::kChildModalParentKey); } bool IsModalTransientChild(const aura::Window* transient, const aura::Window* original) { return transient->IsVisible() && (TransientChildIsWindowModal(transient) || TransientChildIsSystemModal(transient) || (TransientChildIsChildModal(transient) && HasAncestor(original, GetModalParent(transient)))); } const aura::Window* GetModalTransientChild(const aura::Window* activatable, const aura::Window* original) { for (const aura::Window* transient : GetTransientChildren(activatable)) { if (IsModalTransientChild(transient, original)) { if (GetTransientChildren(transient).empty()) return transient; const aura::Window* modal_child = GetModalTransientChild(transient, original); return modal_child ? modal_child : transient; } } return nullptr; } } // namespace void SetModalParent(aura::Window* child, aura::Window* parent) { child->SetProperty(aura::client::kChildModalParentKey, parent); } aura::Window* GetModalTransient(aura::Window* window) { return const_cast<aura::Window*>( GetModalTransient(const_cast<const aura::Window*>(window))); } const aura::Window* GetModalTransient(const aura::Window* window) { if (!window) return nullptr; // We always want to check for the transient child of the toplevel window. const aura::Window* toplevel = GetToplevelWindow(window); if (!toplevel) return nullptr; return GetModalTransientChild(toplevel, window); } //////////////////////////////////////////////////////////////////////////////// // WindowModalityController, public: WindowModalityController::WindowModalityController( ui::EventTarget* event_target, aura::Env* env) : env_(env ? env : aura::Env::GetInstance()), event_target_(event_target) { env_->AddObserver(this); DCHECK(event_target->IsPreTargetListEmpty()); event_target_->AddPreTargetHandler(this); } WindowModalityController::~WindowModalityController() { event_target_->RemovePreTargetHandler(this); env_->RemoveObserver(this); for (size_t i = 0; i < windows_.size(); ++i) windows_[i]->RemoveObserver(this); } //////////////////////////////////////////////////////////////////////////////// // WindowModalityController, aura::EventFilter implementation: void WindowModalityController::OnKeyEvent(ui::KeyEvent* event) { aura::Window* target = static_cast<aura::Window*>(event->target()); if (GetModalTransient(target)) event->SetHandled(); } void WindowModalityController::OnMouseEvent(ui::MouseEvent* event) { aura::Window* target = static_cast<aura::Window*>(event->target()); if (ProcessLocatedEvent(target, event)) event->SetHandled(); } void WindowModalityController::OnTouchEvent(ui::TouchEvent* event) { aura::Window* target = static_cast<aura::Window*>(event->target()); if (ProcessLocatedEvent(target, event)) event->SetHandled(); } base::StringPiece WindowModalityController::GetLogContext() const { return "WindowModalityController"; } //////////////////////////////////////////////////////////////////////////////// // WindowModalityController, aura::EnvObserver implementation: void WindowModalityController::OnWindowInitialized(aura::Window* window) { windows_.push_back(window); window->AddObserver(this); } //////////////////////////////////////////////////////////////////////////////// // WindowModalityController, aura::WindowObserver implementation: void WindowModalityController::OnWindowPropertyChanged(aura::Window* window, const void* key, intptr_t old) { // In tests, we sometimes create the modality relationship after a window is // visible. if (key == aura::client::kModalKey && window->GetProperty(aura::client::kModalKey) != ui::MODAL_TYPE_NONE && window->IsVisible()) { ActivateWindow(window); CancelTouchesOnTransientWindowTree(window); } } void WindowModalityController::OnWindowVisibilityChanged(aura::Window* window, bool visible) { if (visible && window->GetProperty(aura::client::kModalKey) != ui::MODAL_TYPE_NONE) { CancelTouchesOnTransientWindowTree(window); // Make sure no other window has capture, otherwise |window| won't get mouse // events. aura::Window* capture_window = aura::client::GetCaptureWindow(window); if (capture_window) { bool should_release_capture = true; if (window->GetProperty(aura::client::kModalKey) == ui::MODAL_TYPE_CHILD && !HasAncestor(capture_window, GetModalParent(window))) { // For child modal windows we only need ensure capture is not on a // descendant of the modal parent. This way we block events to the // parents subtree appropriately. should_release_capture = false; } if (should_release_capture) capture_window->ReleaseCapture(); } } } void WindowModalityController::OnWindowDestroyed(aura::Window* window) { windows_.erase(base::ranges::find(windows_, window)); window->RemoveObserver(this); } bool WindowModalityController::ProcessLocatedEvent(aura::Window* target, ui::LocatedEvent* event) { if (event->handled()) return false; aura::Window* modal_transient_child = GetModalTransient(target); if (modal_transient_child && (event->type() == ui::ET_MOUSE_PRESSED || event->type() == ui::ET_TOUCH_PRESSED)) { // Activate top window if transient child window is window modal. if (TransientChildIsWindowModal(modal_transient_child)) { aura::Window* toplevel = GetToplevelWindow(target); DCHECK(toplevel); ActivateWindow(toplevel); } AnimateWindow(modal_transient_child, WINDOW_ANIMATION_TYPE_BOUNCE); } if (event->type() == ui::ET_TOUCH_CANCELLED) return false; return !!modal_transient_child; } void WindowModalityController::CancelTouchesOnTransientWindowTree( aura::Window* window) { // Find the top level transient window. aura::Window* top_level_window = window; while (wm::GetTransientParent(top_level_window)) top_level_window = wm::GetTransientParent(top_level_window); // BFS to get all transient windows in the tree rooted to the top level // transient window. std::vector<ui::GestureConsumer*> blocked_consumers; std::queue<aura::Window*> que; que.emplace(top_level_window); while (!que.empty()) { aura::Window* parent = que.front(); que.pop(); blocked_consumers.emplace_back(parent); for (auto* w : wm::GetTransientChildren(parent)) que.emplace(w); } // Cancel touches on all the transient windows. env_->gesture_recognizer()->CancelActiveTouchesOn(blocked_consumers); } } // namespace wm
Zhao-PengFei35/chromium_src_4
ui/wm/core/window_modality_controller.cc
C++
unknown
8,378
// Copyright 2012 The Chromium Authors // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #ifndef UI_WM_CORE_WINDOW_MODALITY_CONTROLLER_H_ #define UI_WM_CORE_WINDOW_MODALITY_CONTROLLER_H_ #include <vector> #include "base/component_export.h" #include "base/memory/raw_ptr.h" #include "base/strings/string_piece.h" #include "ui/aura/env_observer.h" #include "ui/aura/window_observer.h" #include "ui/events/event_handler.h" namespace aura { class Env; } namespace ui { class EventTarget; class LocatedEvent; } // namespace ui namespace wm { // Sets the modal parent for the child. COMPONENT_EXPORT(UI_WM) void SetModalParent(aura::Window* child, aura::Window* parent); // Returns the modal transient child of |window|, or NULL if |window| does not // have any modal transient children. COMPONENT_EXPORT(UI_WM) aura::Window* GetModalTransient(aura::Window* window); COMPONENT_EXPORT(UI_WM) const aura::Window* GetModalTransient(const aura::Window* window); // WindowModalityController is an event filter that consumes events sent to // windows that are the transient parents of window-modal windows. This filter // must be added to the CompoundEventFilter so that activation works properly. class COMPONENT_EXPORT(UI_WM) WindowModalityController : public ui::EventHandler, public aura::EnvObserver, public aura::WindowObserver { public: explicit WindowModalityController(ui::EventTarget* event_target, aura::Env* env = nullptr); WindowModalityController(const WindowModalityController&) = delete; WindowModalityController& operator=(const WindowModalityController&) = delete; ~WindowModalityController() override; // Overridden from ui::EventHandler: void OnKeyEvent(ui::KeyEvent* event) override; void OnMouseEvent(ui::MouseEvent* event) override; void OnTouchEvent(ui::TouchEvent* event) override; base::StringPiece GetLogContext() const override; // Overridden from aura::EnvObserver: void OnWindowInitialized(aura::Window* window) override; // Overridden from aura::WindowObserver: void OnWindowPropertyChanged(aura::Window* window, const void* key, intptr_t old) override; void OnWindowVisibilityChanged(aura::Window* window, bool visible) override; void OnWindowDestroyed(aura::Window* window) override; private: // Processes a mouse/touch event, and returns true if the event should be // consumed. bool ProcessLocatedEvent(aura::Window* target, ui::LocatedEvent* event); // Cancel touches on the transient window tree rooted to the top level // transient window of the |window|. void CancelTouchesOnTransientWindowTree(aura::Window* window); raw_ptr<aura::Env> env_; std::vector<aura::Window*> windows_; raw_ptr<ui::EventTarget> event_target_; }; } // namespace wm #endif // UI_WM_CORE_WINDOW_MODALITY_CONTROLLER_H_
Zhao-PengFei35/chromium_src_4
ui/wm/core/window_modality_controller.h
C++
unknown
2,961
// Copyright 2018 The Chromium Authors // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "ui/wm/core/window_properties.h" #include "ui/wm/core/window_animations.h" DEFINE_EXPORTED_UI_CLASS_PROPERTY_TYPE(COMPONENT_EXPORT(UI_WM), wm::WindowVisibilityAnimationTransition) DEFINE_EXPORTED_UI_CLASS_PROPERTY_TYPE(COMPONENT_EXPORT(UI_WM), float) namespace wm { DEFINE_UI_CLASS_PROPERTY_KEY(bool, kUsesScreenCoordinatesKey, false) DEFINE_UI_CLASS_PROPERTY_KEY(base::TimeDelta, kWindowVisibilityAnimationDurationKey, base::TimeDelta()) DEFINE_UI_CLASS_PROPERTY_KEY(WindowVisibilityAnimationTransition, kWindowVisibilityAnimationTransitionKey, ANIMATE_BOTH) DEFINE_UI_CLASS_PROPERTY_KEY(int, kWindowVisibilityAnimationTypeKey, WINDOW_VISIBILITY_ANIMATION_TYPE_DEFAULT) DEFINE_UI_CLASS_PROPERTY_KEY(float, kWindowVisibilityAnimationVerticalPositionKey, 15.f) DEFINE_UI_CLASS_PROPERTY_KEY(int32_t, kWindowHidingAnimationCountKey, 0) } // namespace wm
Zhao-PengFei35/chromium_src_4
ui/wm/core/window_properties.cc
C++
unknown
1,282
// Copyright 2018 The Chromium Authors // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #ifndef UI_WM_CORE_WINDOW_PROPERTIES_H_ #define UI_WM_CORE_WINDOW_PROPERTIES_H_ #include "base/component_export.h" #include "base/time/time.h" #include "ui/base/class_property.h" namespace wm { // Type of visibility change transition that a window should animate. // Default behavior is to animate both show and hide. enum WindowVisibilityAnimationTransition { ANIMATE_SHOW = 0x1, ANIMATE_HIDE = 0x2, ANIMATE_BOTH = ANIMATE_SHOW | ANIMATE_HIDE, ANIMATE_NONE = 0x4, }; // Alphabetical sort. // Property to tell if the container uses screen coordinates for the child // windows. COMPONENT_EXPORT(UI_WM) extern const ui::ClassProperty<bool>* const kUsesScreenCoordinatesKey; COMPONENT_EXPORT(UI_WM) extern const ui::ClassProperty<base::TimeDelta>* const kWindowVisibilityAnimationDurationKey; COMPONENT_EXPORT(UI_WM) extern const ui::ClassProperty<WindowVisibilityAnimationTransition>* const kWindowVisibilityAnimationTransitionKey; COMPONENT_EXPORT(UI_WM) extern const ui::ClassProperty<int>* const kWindowVisibilityAnimationTypeKey; // Used if the animation-type is WINDOW_VISIBILITY_ANIMATION_TYPE_VERTICAL. COMPONENT_EXPORT(UI_WM) extern const ui::ClassProperty<float>* const kWindowVisibilityAnimationVerticalPositionKey; // The number of hiding animations in progress on the window. COMPONENT_EXPORT(UI_WM) extern const ui::ClassProperty<int32_t>* const kWindowHidingAnimationCountKey; } // namespace wm // These need to be declared here for jumbo builds. DECLARE_EXPORTED_UI_CLASS_PROPERTY_TYPE(COMPONENT_EXPORT(UI_WM), wm::WindowVisibilityAnimationTransition) DECLARE_EXPORTED_UI_CLASS_PROPERTY_TYPE(COMPONENT_EXPORT(UI_WM), float) #endif // UI_WM_CORE_WINDOW_PROPERTIES_H_
Zhao-PengFei35/chromium_src_4
ui/wm/core/window_properties.h
C++
unknown
1,898
// Copyright 2012 The Chromium Authors // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "ui/wm/core/window_util.h" #include "base/functional/bind.h" #include "ui/aura/client/aura_constants.h" #include "ui/aura/window.h" #include "ui/compositor/layer.h" #include "ui/compositor/layer_tree_owner.h" #include "ui/display/screen.h" #include "ui/display/types/display_constants.h" #include "ui/wm/core/transient_window_manager.h" #include "ui/wm/core/window_properties.h" #include "ui/wm/public/activation_client.h" namespace { // Invokes |map_func| on all the children of |to_clone|, adding the newly // cloned children to |parent|. If |map_func| returns nullptr on // the layer owner, all its layer's children will not be cloned. // // WARNING: It is assumed that |parent| is ultimately owned by a LayerTreeOwner. void CloneChildren(ui::Layer* to_clone, ui::Layer* parent, const wm::MapLayerFunc& map_func) { typedef std::vector<ui::Layer*> Layers; // Make a copy of the children since RecreateLayer() mutates it. Layers children(to_clone->children()); for (Layers::const_iterator i = children.begin(); i != children.end(); ++i) { ui::LayerOwner* owner = (*i)->owner(); ui::Layer* old_layer = owner ? map_func.Run(owner).release() : nullptr; if (old_layer) { parent->Add(old_layer); // RecreateLayer() moves the existing children to the new layer. Create a // copy of those. CloneChildren(owner->layer(), old_layer, map_func); } } } // Invokes Mirror() on all the children of |to_mirror|, adding the newly cloned // children to |parent|. // // WARNING: It is assumed that |parent| is ultimately owned by a LayerTreeOwner. void MirrorChildren(ui::Layer* to_mirror, ui::Layer* parent, bool sync_bounds) { for (auto* child : to_mirror->children()) { ui::Layer* mirror = child->Mirror().release(); mirror->set_sync_bounds_with_source(sync_bounds); parent->Add(mirror); MirrorChildren(child, mirror, sync_bounds); } } } // namespace namespace wm { void ActivateWindow(aura::Window* window) { DCHECK(window); DCHECK(window->GetRootWindow()); GetActivationClient(window->GetRootWindow())->ActivateWindow(window); } void DeactivateWindow(aura::Window* window) { DCHECK(window); DCHECK(window->GetRootWindow()); GetActivationClient(window->GetRootWindow())->DeactivateWindow(window); } bool IsActiveWindow(const aura::Window* window) { DCHECK(window); if (!window->GetRootWindow()) return false; const ActivationClient* client = GetActivationClient(window->GetRootWindow()); return client && client->GetActiveWindow() == window; } bool CanActivateWindow(const aura::Window* window) { DCHECK(window); if (!window->GetRootWindow()) return false; const ActivationClient* client = GetActivationClient(window->GetRootWindow()); return client && client->CanActivateWindow(window); } void SetWindowFullscreen(aura::Window* window, bool fullscreen, int64_t target_display_id) { DCHECK(window); // Should only specify display id when entering fullscreen. DCHECK(target_display_id == display::kInvalidDisplayId || fullscreen); ui::WindowShowState current_show_state = window->GetProperty(aura::client::kShowStateKey); const bool is_fullscreen = current_show_state == ui::SHOW_STATE_FULLSCREEN; if (fullscreen == is_fullscreen && target_display_id == display::kInvalidDisplayId) { return; } if (fullscreen) { // We only want the current display id if the window is rooted in a display. // Need to check for root window, otherwise GetDisplayNearestWindow() would // return the primary display by default. int64_t current_display_id = window->GetRootWindow() ? display::Screen::GetScreen()->GetDisplayNearestWindow(window).id() : display::kInvalidDisplayId; if (is_fullscreen && target_display_id == current_display_id) { // Already fullscreened on the target display. return; } // Save the current show state as its restore show state so that we can // correctly restore it after exiting the fullscreen mode. // Note `aura::client::kRestoreShowStateKey` can be overwritten later by the // window state restore history stack on Chrome OS, see the function // WindowState::UpdateWindowStateRestoreHistoryStack(). But We still set the // `aura::client::kRestoreShowStateKey` here since this function is also // used on other non-ChromeOS platforms. if (current_show_state != ui::SHOW_STATE_MINIMIZED) { window->SetProperty(aura::client::kRestoreShowStateKey, current_show_state); } // Set fullscreen display id first, so it's available when the show state // property change is processed. window->SetProperty(aura::client::kFullscreenTargetDisplayIdKey, target_display_id); window->SetProperty(aura::client::kShowStateKey, ui::SHOW_STATE_FULLSCREEN); window->ClearProperty(aura::client::kFullscreenTargetDisplayIdKey); } else { Restore(window); } } bool WindowStateIs(const aura::Window* window, ui::WindowShowState state) { return window->GetProperty(aura::client::kShowStateKey) == state; } void SetWindowState(aura::Window* window, ui::WindowShowState state) { window->SetProperty(aura::client::kShowStateKey, state); } void Restore(aura::Window* window) { window->SetProperty(aura::client::kIsRestoringKey, true); window->SetProperty(aura::client::kShowStateKey, window->GetProperty(aura::client::kRestoreShowStateKey)); window->ClearProperty(aura::client::kIsRestoringKey); } void Unminimize(aura::Window* window) { DCHECK_EQ(window->GetProperty(aura::client::kShowStateKey), ui::SHOW_STATE_MINIMIZED); Restore(window); } aura::Window* GetActivatableWindow(aura::Window* window) { ActivationClient* client = GetActivationClient(window->GetRootWindow()); return client ? client->GetActivatableWindow(window) : nullptr; } aura::Window* GetToplevelWindow(aura::Window* window) { return const_cast<aura::Window*>( GetToplevelWindow(const_cast<const aura::Window*>(window))); } const aura::Window* GetToplevelWindow(const aura::Window* window) { const ActivationClient* client = GetActivationClient(window->GetRootWindow()); return client ? client->GetToplevelWindow(window) : nullptr; } std::unique_ptr<ui::LayerTreeOwner> RecreateLayers(ui::LayerOwner* root) { DCHECK(root->OwnsLayer()); return RecreateLayersWithClosure( root, base::BindRepeating( [](ui::LayerOwner* owner) { return owner->RecreateLayer(); })); } std::unique_ptr<ui::LayerTreeOwner> RecreateLayersWithClosure( ui::LayerOwner* root, const MapLayerFunc& map_func) { DCHECK(root->OwnsLayer()); auto layer = map_func.Run(root); if (!layer) return nullptr; auto old_layer = std::make_unique<ui::LayerTreeOwner>(std::move(layer)); CloneChildren(root->layer(), old_layer->root(), map_func); return old_layer; } std::unique_ptr<ui::LayerTreeOwner> MirrorLayers( ui::LayerOwner* root, bool sync_bounds) { auto mirror = std::make_unique<ui::LayerTreeOwner>(root->layer()->Mirror()); MirrorChildren(root->layer(), mirror->root(), sync_bounds); return mirror; } aura::Window* GetTransientParent(aura::Window* window) { return const_cast<aura::Window*>(GetTransientParent( const_cast<const aura::Window*>(window))); } const aura::Window* GetTransientParent(const aura::Window* window) { const TransientWindowManager* manager = TransientWindowManager::GetIfExists(window); return manager ? manager->transient_parent() : nullptr; } const std::vector<aura::Window*>& GetTransientChildren( const aura::Window* window) { const TransientWindowManager* manager = TransientWindowManager::GetIfExists(window); if (manager) return manager->transient_children(); static std::vector<aura::Window*>* shared = new std::vector<aura::Window*>; return *shared; } aura::Window* GetTransientRoot(aura::Window* window) { while (window && GetTransientParent(window)) window = GetTransientParent(window); return window; } void AddTransientChild(aura::Window* parent, aura::Window* child) { TransientWindowManager::GetOrCreate(parent)->AddTransientChild(child); } void RemoveTransientChild(aura::Window* parent, aura::Window* child) { TransientWindowManager::GetOrCreate(parent)->RemoveTransientChild(child); } bool HasTransientAncestor(const aura::Window* window, const aura::Window* ancestor) { const aura::Window* transient_parent = GetTransientParent(window); if (transient_parent == ancestor) return true; return transient_parent ? HasTransientAncestor(transient_parent, ancestor) : false; } } // namespace wm
Zhao-PengFei35/chromium_src_4
ui/wm/core/window_util.cc
C++
unknown
9,020
// Copyright 2012 The Chromium Authors // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #ifndef UI_WM_CORE_WINDOW_UTIL_H_ #define UI_WM_CORE_WINDOW_UTIL_H_ #include <memory> #include <utility> #include <vector> #include "base/component_export.h" #include "base/functional/callback_forward.h" #include "ui/base/ui_base_types.h" #include "ui/display/types/display_constants.h" namespace aura { class Window; } namespace ui { class Layer; class LayerOwner; class LayerTreeOwner; } // namespace ui namespace wm { COMPONENT_EXPORT(UI_WM) void ActivateWindow(aura::Window* window); COMPONENT_EXPORT(UI_WM) void DeactivateWindow(aura::Window* window); COMPONENT_EXPORT(UI_WM) bool IsActiveWindow(const aura::Window* window); COMPONENT_EXPORT(UI_WM) bool CanActivateWindow(const aura::Window* window); COMPONENT_EXPORT(UI_WM) void SetWindowFullscreen( aura::Window* window, bool fullscreen, int64_t target_display_id = display::kInvalidDisplayId); // Returns true if |window|'s show state is |state|. COMPONENT_EXPORT(UI_WM) bool WindowStateIs(const aura::Window* window, ui::WindowShowState state); // Sets the window state to |state|. COMPONENT_EXPORT(UI_WM) void SetWindowState(aura::Window* window, ui::WindowShowState state); // Restores the window state from the current state to its previous applicable // state. As an example, if the current state is minimized, Restore() will // change the window's sate to its applicable pre-minimized state, which is the // same as calling Unminimize() function. COMPONENT_EXPORT(UI_WM) void Restore(aura::Window* window); // Changes a window's state to its pre-minimized state. COMPONENT_EXPORT(UI_WM) void Unminimize(aura::Window* window); // Retrieves the activatable window for |window|. If |window| is activatable, // this will just return it, otherwise it will climb the parent/transient parent // chain looking for a window that is activatable, per the ActivationClient. // If you're looking for a function to get the activatable "top level" window, // this is probably the function you're looking for. COMPONENT_EXPORT(UI_WM) aura::Window* GetActivatableWindow(aura::Window* window); // Retrieves the toplevel window for |window|. The ActivationClient makes this // determination. COMPONENT_EXPORT(UI_WM) aura::Window* GetToplevelWindow(aura::Window* window); COMPONENT_EXPORT(UI_WM) const aura::Window* GetToplevelWindow(const aura::Window* window); // Returns the existing Layer for |root| (and all its descendants) and creates // a new layer for |root| and all its descendants. This is intended for // animations that want to animate between the existing visuals and a new state. // // As a result of this |root| has freshly created layers, meaning the layers // have not yet been painted to. COMPONENT_EXPORT(UI_WM) std::unique_ptr<ui::LayerTreeOwner> RecreateLayers(ui::LayerOwner* root); using MapLayerFunc = base::RepeatingCallback<std::unique_ptr<ui::Layer>(ui::LayerOwner*)>; // Maps |map_func| over each layer of the layer tree and returns a copy of the // layer tree. The recursion stops at the level when |map_func| returns nullptr // on the owner's layer. MapLayers might return nullptr when |map_func| returns // nullptr on the root layer's owner. COMPONENT_EXPORT(UI_WM) std::unique_ptr<ui::LayerTreeOwner> RecreateLayersWithClosure( ui::LayerOwner* root, const MapLayerFunc& map_func); // Returns a layer tree that mirrors |root|. Used for live window previews. If // |sync_bounds| is true, the bounds of all mirror layers except the root are // synchronized. See |sync_bounds_with_source_| in ui::Layer. COMPONENT_EXPORT(UI_WM) std::unique_ptr<ui::LayerTreeOwner> MirrorLayers(ui::LayerOwner* root, bool sync_bounds); // Convenience functions that get the TransientWindowManager for the window and // redirect appropriately. These are preferable to calling functions on // TransientWindowManager as they handle the appropriate null checks. COMPONENT_EXPORT(UI_WM) aura::Window* GetTransientParent(aura::Window* window); COMPONENT_EXPORT(UI_WM) const aura::Window* GetTransientParent(const aura::Window* window); COMPONENT_EXPORT(UI_WM) const std::vector<aura::Window*>& GetTransientChildren( const aura::Window* window); COMPONENT_EXPORT(UI_WM) void AddTransientChild(aura::Window* parent, aura::Window* child); COMPONENT_EXPORT(UI_WM) void RemoveTransientChild(aura::Window* parent, aura::Window* child); COMPONENT_EXPORT(UI_WM) aura::Window* GetTransientRoot(aura::Window* window); // Returns true if |window| has |ancestor| as a transient ancestor. A transient // ancestor is found by following the transient parent chain of the window. COMPONENT_EXPORT(UI_WM) bool HasTransientAncestor(const aura::Window* window, const aura::Window* ancestor); // Snap the window's layer to physical pixel boundary. COMPONENT_EXPORT(UI_WM) void SnapWindowToPixelBoundary(aura::Window* window); } // namespace wm #endif // UI_WM_CORE_WINDOW_UTIL_H_
Zhao-PengFei35/chromium_src_4
ui/wm/core/window_util.h
C++
unknown
5,080
// Copyright 2014 The Chromium Authors // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "ui/wm/core/window_util.h" #include <memory> #include "base/functional/bind.h" #include "ui/aura/test/aura_test_base.h" #include "ui/aura/test/test_windows.h" #include "ui/aura/window.h" #include "ui/compositor/layer.h" #include "ui/compositor/layer_tree_owner.h" #include "ui/wm/core/window_properties.h" namespace wm { typedef aura::test::AuraTestBase WindowUtilTest; // Test if the recreate layers does not recreate layers that have // already been acquired. TEST_F(WindowUtilTest, RecreateLayers) { std::unique_ptr<aura::Window> window1( aura::test::CreateTestWindowWithId(0, NULL)); std::unique_ptr<aura::Window> window11( aura::test::CreateTestWindowWithId(1, window1.get())); std::unique_ptr<aura::Window> window12( aura::test::CreateTestWindowWithId(2, window1.get())); ASSERT_EQ(2u, window1->layer()->children().size()); std::unique_ptr<ui::Layer> acquired(window11->AcquireLayer()); EXPECT_TRUE(acquired.get()); EXPECT_EQ(acquired.get(), window11->layer()); std::unique_ptr<ui::LayerTreeOwner> tree = wm::RecreateLayers(window1.get()); // The detached layer should not have the layer that has // already been detached. ASSERT_EQ(1u, tree->root()->children().size()); // Child layer is new instance. EXPECT_NE(window11->layer(), tree->root()->children()[0]); EXPECT_NE(window12->layer(), tree->root()->children()[0]); // The original window should have both. ASSERT_EQ(2u, window1->layer()->children().size()); EXPECT_EQ(window11->layer(), window1->layer()->children()[0]); EXPECT_EQ(window12->layer(), window1->layer()->children()[1]); // Delete the window before the acquired layer is deleted. window11.reset(); } // Test if map_func is correctly executed in RecreateLayerWithClosure. TEST_F(WindowUtilTest, RecreateLayersWithClosure) { std::unique_ptr<aura::Window> window1( aura::test::CreateTestWindowWithId(0, NULL)); std::unique_ptr<aura::Window> window11( aura::test::CreateTestWindowWithId(1, window1.get())); std::unique_ptr<aura::Window> window12( aura::test::CreateTestWindowWithId(2, window1.get())); ASSERT_EQ(2u, window1->layer()->children().size()); auto tree_empty = wm::RecreateLayersWithClosure( window1.get(), base::BindRepeating( [](const aura::Window* to_filter, ui::LayerOwner* owner) -> std::unique_ptr<ui::Layer> { if (owner->layer() == to_filter->layer()) return nullptr; return owner->RecreateLayer(); }, window1.get())); // The root is filtered. RecreateLayersWithClosure should return nullptr. ASSERT_FALSE(tree_empty); auto tree = wm::RecreateLayersWithClosure( window1.get(), base::BindRepeating( [](const aura::Window* to_filter, ui::LayerOwner* owner) -> std::unique_ptr<ui::Layer> { if (owner->layer() == to_filter->layer()) return nullptr; return owner->RecreateLayer(); }, window12.get())); ASSERT_TRUE(tree); // window12 is filtered out in the above recreation logic. ASSERT_EQ(1u, tree->root()->children().size()); // Child layer is new instance. EXPECT_NE(window11->layer(), tree->root()->children()[0]); // The original window should have both. ASSERT_EQ(2u, window1->layer()->children().size()); EXPECT_EQ(window11->layer(), window1->layer()->children()[0]); EXPECT_EQ(window12->layer(), window1->layer()->children()[1]); } } // namespace wm
Zhao-PengFei35/chromium_src_4
ui/wm/core/window_util_unittest.cc
C++
unknown
3,661
// Copyright 2012 The Chromium Authors // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "ui/wm/core/wm_core_switches.h" #include "base/command_line.h" namespace wm { namespace switches { // If present animations are disabled. const char kWindowAnimationsDisabled[] = "wm-window-animations-disabled"; } // namespace switches } // namespace wm
Zhao-PengFei35/chromium_src_4
ui/wm/core/wm_core_switches.cc
C++
unknown
413
// Copyright 2012 The Chromium Authors // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #ifndef UI_WM_CORE_WM_CORE_SWITCHES_H_ #define UI_WM_CORE_WM_CORE_SWITCHES_H_ #include "base/component_export.h" #include "build/build_config.h" namespace wm { namespace switches { // Note: If you add a switch, consider if it needs to be copied to a subsequent // command line if the process executes a new copy of itself. (For example, // see `ash::GetOffTheRecordCommandLine()`.) // Please keep alphabetized. COMPONENT_EXPORT(UI_WM) extern const char kWindowAnimationsDisabled[]; } // namespace switches } // namespace wm #endif // UI_WM_CORE_WM_CORE_SWITCHES_H_
Zhao-PengFei35/chromium_src_4
ui/wm/core/wm_core_switches.h
C++
unknown
719
// Copyright 2013 The Chromium Authors // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "ui/wm/core/wm_state.h" #include "ui/events/platform/platform_event_source.h" #include "ui/wm/core/capture_controller.h" #include "ui/wm/core/transient_window_controller.h" #include "ui/wm/core/transient_window_stacking_client.h" namespace wm { WMState::WMState() : window_stacking_client_(new TransientWindowStackingClient), transient_window_client_(new TransientWindowController), capture_controller_(std::make_unique<CaptureController>()) { aura::client::SetWindowStackingClient(window_stacking_client_.get()); aura::client::SetTransientWindowClient(transient_window_client_.get()); } WMState::~WMState() { if (aura::client::GetWindowStackingClient() == window_stacking_client_.get()) aura::client::SetWindowStackingClient(NULL); if (aura::client::GetTransientWindowClient() == transient_window_client_.get()) { aura::client::SetTransientWindowClient(NULL); } } } // namespace wm
Zhao-PengFei35/chromium_src_4
ui/wm/core/wm_state.cc
C++
unknown
1,083
// Copyright 2013 The Chromium Authors // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #ifndef UI_WM_CORE_WM_STATE_H_ #define UI_WM_CORE_WM_STATE_H_ #include <memory> #include "base/component_export.h" namespace wm { class CaptureController; class TransientWindowController; class TransientWindowStackingClient; // Installs state needed by the window manager. class COMPONENT_EXPORT(UI_WM) WMState { public: WMState(); WMState(const WMState&) = delete; WMState& operator=(const WMState&) = delete; ~WMState(); private: std::unique_ptr<TransientWindowStackingClient> window_stacking_client_; std::unique_ptr<TransientWindowController> transient_window_client_; // NOTE: this is really only needed in ash std::unique_ptr<CaptureController> capture_controller_; }; } // namespace wm #endif // UI_WM_CORE_WM_STATE_H_
Zhao-PengFei35/chromium_src_4
ui/wm/core/wm_state.h
C++
unknown
900
// Copyright 2012 The Chromium Authors // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "ui/wm/public/activation_change_observer.h" #include "ui/aura/window.h" #include "ui/base/class_property.h" DEFINE_UI_CLASS_PROPERTY_TYPE(wm::ActivationChangeObserver*) namespace wm { DEFINE_UI_CLASS_PROPERTY_KEY(ActivationChangeObserver*, kActivationChangeObserverKey, nullptr) ActivationChangeObserver::~ActivationChangeObserver() { CHECK(!IsInObserverList()); } void SetActivationChangeObserver(aura::Window* window, ActivationChangeObserver* observer) { window->SetProperty(kActivationChangeObserverKey, observer); } ActivationChangeObserver* GetActivationChangeObserver(aura::Window* window) { return window ? window->GetProperty(kActivationChangeObserverKey) : NULL; } } // namespace wm
Zhao-PengFei35/chromium_src_4
ui/wm/public/activation_change_observer.cc
C++
unknown
952
// Copyright 2012 The Chromium Authors // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #ifndef UI_WM_PUBLIC_ACTIVATION_CHANGE_OBSERVER_H_ #define UI_WM_PUBLIC_ACTIVATION_CHANGE_OBSERVER_H_ #include "base/observer_list_types.h" #include "ui/wm/public/wm_public_export.h" namespace aura { class Window; } namespace wm { class WM_PUBLIC_EXPORT ActivationChangeObserver : public base::CheckedObserver { public: // The reason or cause of a window activation change. enum class ActivationReason { // When a window is activated due to a call to the ActivationClient API. ACTIVATION_CLIENT, // When a user clicks or taps a window in the 2-dimensional screen space or // when a user moves a mouse over a window while focus follows cursor is // enabled. INPUT_EVENT, // When a new window is activated as a side effect of a window // disposition changing. WINDOW_DISPOSITION_CHANGED, }; // Called when |gaining_active| will gain activation, or there is no active // window (|gaining_active| is NULL in this case.) |losing_active| refers to // the previous active window or NULL if there was no previously active // window. |reason| specifies the cause of the activation change. virtual void OnWindowActivating(ActivationReason reason, aura::Window* gaining_active, aura::Window* losing_active) {} // Called when |gained_active| gains activation, or there is no active window // (|gained_active| is NULL in this case.) |lost_active| refers to the // previous active window or NULL if there was no previously active // window. |reason| specifies the cause of the activation change. virtual void OnWindowActivated(ActivationReason reason, aura::Window* gained_active, aura::Window* lost_active) = 0; // Called when during window activation the currently active window is // selected for activation. This can happen when a window requested for // activation cannot be activated because a system modal window is active. virtual void OnAttemptToReactivateWindow(aura::Window* request_active, aura::Window* actual_active) {} ~ActivationChangeObserver() override; }; // Gets/Sets the ActivationChangeObserver for a specific window. This observer // is notified after the ActivationClient notifies all registered observers. WM_PUBLIC_EXPORT void SetActivationChangeObserver( aura::Window* window, ActivationChangeObserver* observer); WM_PUBLIC_EXPORT ActivationChangeObserver* GetActivationChangeObserver( aura::Window* window); } // namespace wm #endif // UI_WM_PUBLIC_ACTIVATION_CHANGE_OBSERVER_H_
Zhao-PengFei35/chromium_src_4
ui/wm/public/activation_change_observer.h
C++
unknown
2,812
// Copyright 2012 The Chromium Authors // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "ui/wm/public/activation_client.h" #include "ui/aura/window.h" #include "ui/base/class_property.h" DEFINE_UI_CLASS_PROPERTY_TYPE(wm::ActivationClient*) namespace wm { DEFINE_UI_CLASS_PROPERTY_KEY(ActivationClient*, kRootWindowActivationClientKey, NULL) DEFINE_UI_CLASS_PROPERTY_KEY(bool, kHideOnDeactivate, false) void SetActivationClient(aura::Window* root_window, ActivationClient* client) { root_window->SetProperty(kRootWindowActivationClientKey, client); } const ActivationClient* GetActivationClient(const aura::Window* root_window) { return root_window ? root_window->GetProperty(kRootWindowActivationClientKey) : nullptr; } ActivationClient* GetActivationClient(aura::Window* root_window) { return root_window ? root_window->GetProperty(kRootWindowActivationClientKey) : nullptr; } void SetHideOnDeactivate(aura::Window* window, bool hide_on_deactivate) { window->SetProperty(kHideOnDeactivate, hide_on_deactivate); } bool GetHideOnDeactivate(aura::Window* window) { return window->GetProperty(kHideOnDeactivate); } } // namespace wm
Zhao-PengFei35/chromium_src_4
ui/wm/public/activation_client.cc
C++
unknown
1,316
// Copyright 2012 The Chromium Authors // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #ifndef UI_WM_PUBLIC_ACTIVATION_CLIENT_H_ #define UI_WM_PUBLIC_ACTIVATION_CLIENT_H_ #include "ui/wm/public/wm_public_export.h" namespace aura { class Window; } namespace wm { class ActivationChangeObserver; // An interface implemented by an object that manages window activation. class WM_PUBLIC_EXPORT ActivationClient { public: // Adds/Removes ActivationChangeObservers. virtual void AddObserver(ActivationChangeObserver* observer) = 0; virtual void RemoveObserver(ActivationChangeObserver* observer) = 0; // Activates |window|. If |window| is NULL, nothing happens. virtual void ActivateWindow(aura::Window* window) = 0; // Deactivates |window|. What (if anything) is activated next is up to the // client. If |window| is NULL, nothing happens. virtual void DeactivateWindow(aura::Window* window) = 0; // Retrieves the active window, or NULL if there is none. aura::Window* GetActiveWindow() { return const_cast<aura::Window*>( const_cast<const ActivationClient*>(this)->GetActiveWindow()); } virtual const aura::Window* GetActiveWindow() const = 0; // Retrieves the activatable window for |window|, or NULL if there is none. // Note that this is often but not always the toplevel window (see // GetToplevelWindow() below), as the toplevel window may not be activatable // (for example it may be blocked by a modal transient, or some other // condition). virtual aura::Window* GetActivatableWindow(aura::Window* window) const = 0; // Retrieves the toplevel window for |window|, or NULL if there is none. virtual const aura::Window* GetToplevelWindow( const aura::Window* window) const = 0; // Returns true if |window| can be activated, false otherwise. If |window| has // a modal child it can not be activated. virtual bool CanActivateWindow(const aura::Window* window) const = 0; protected: virtual ~ActivationClient() {} }; // Sets/Gets the activation client on the root Window. WM_PUBLIC_EXPORT void SetActivationClient(aura::Window* root_window, ActivationClient* client); WM_PUBLIC_EXPORT ActivationClient* GetActivationClient( aura::Window* root_window); WM_PUBLIC_EXPORT const ActivationClient* GetActivationClient( const aura::Window* root_window); // Some types of transient window are only visible when active. // The transient parents of these windows may have visual appearance properties // that differ from transient parents that can be deactivated. // The presence of this property implies these traits. // TODO(beng): currently the UI framework (views) implements the actual // close-on-deactivate component of this feature but it should be // possible to implement in the aura client. WM_PUBLIC_EXPORT void SetHideOnDeactivate(aura::Window* window, bool hide_on_deactivate); WM_PUBLIC_EXPORT bool GetHideOnDeactivate(aura::Window* window); } // namespace wm #endif // UI_WM_PUBLIC_ACTIVATION_CLIENT_H_
Zhao-PengFei35/chromium_src_4
ui/wm/public/activation_client.h
C++
unknown
3,167
// Copyright 2012 The Chromium Authors // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "ui/wm/public/activation_delegate.h" #include "ui/aura/window.h" #include "ui/base/class_property.h" DEFINE_UI_CLASS_PROPERTY_TYPE(wm::ActivationDelegate*) namespace wm { DEFINE_UI_CLASS_PROPERTY_KEY(ActivationDelegate*, kActivationDelegateKey, nullptr) void SetActivationDelegate(aura::Window* window, ActivationDelegate* delegate) { window->SetProperty(kActivationDelegateKey, delegate); } ActivationDelegate* GetActivationDelegate(const aura::Window* window) { return window->GetProperty(kActivationDelegateKey); } } // namespace wm
Zhao-PengFei35/chromium_src_4
ui/wm/public/activation_delegate.cc
C++
unknown
759
// Copyright 2012 The Chromium Authors // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #ifndef UI_WM_PUBLIC_ACTIVATION_DELEGATE_H_ #define UI_WM_PUBLIC_ACTIVATION_DELEGATE_H_ #include "ui/wm/public/wm_public_export.h" namespace aura { class Window; } namespace wm { // An interface implemented by an object that configures and responds to changes // to a window's activation state. class WM_PUBLIC_EXPORT ActivationDelegate { public: // Returns true if the window should be activated. virtual bool ShouldActivate() const = 0; protected: virtual ~ActivationDelegate() {} }; // Sets/Gets the ActivationDelegate on the Window. No ownership changes. WM_PUBLIC_EXPORT void SetActivationDelegate(aura::Window* window, ActivationDelegate* delegate); WM_PUBLIC_EXPORT ActivationDelegate* GetActivationDelegate( const aura::Window* window); } // namespace wm #endif // UI_WM_PUBLIC_ACTIVATION_DELEGATE_H_
Zhao-PengFei35/chromium_src_4
ui/wm/public/activation_delegate.h
C++
unknown
1,019
// Copyright 2013 The Chromium Authors // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "ui/wm/public/animation_host.h" #include "ui/aura/window.h" #include "ui/base/class_property.h" DEFINE_UI_CLASS_PROPERTY_TYPE(wm::AnimationHost*) namespace wm { DEFINE_UI_CLASS_PROPERTY_KEY(AnimationHost*, kRootWindowAnimationHostKey, NULL) void SetAnimationHost(aura::Window* window, AnimationHost* animation_host) { DCHECK(window); window->SetProperty(kRootWindowAnimationHostKey, animation_host); } AnimationHost* GetAnimationHost(aura::Window* window) { DCHECK(window); return window->GetProperty(kRootWindowAnimationHostKey); } } // namespace wm
Zhao-PengFei35/chromium_src_4
ui/wm/public/animation_host.cc
C++
unknown
720
// Copyright 2013 The Chromium Authors // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #ifndef UI_WM_PUBLIC_ANIMATION_HOST_H_ #define UI_WM_PUBLIC_ANIMATION_HOST_H_ #include "ui/wm/public/wm_public_export.h" namespace aura { class Window; } namespace gfx { class Vector2d; } namespace wm { // Interface for top level window host of animation. Communicates additional // bounds required for animation as well as animation completion for deferring // window closes on hide. class WM_PUBLIC_EXPORT AnimationHost { public: // Ensure the host window is at least this large so that transitions have // sufficient space. // The |top_left_delta| parameter contains the offset to be subtracted from // the window bounds for the top left corner. // The |bottom_right_delta| parameter contains the offset to be added to the // window bounds for the bottom right. virtual void SetHostTransitionOffsets( const gfx::Vector2d& top_left_delta, const gfx::Vector2d& bottom_right_delta) = 0; // Called after the window has faded out on a hide. virtual void OnWindowHidingAnimationCompleted() = 0; protected: virtual ~AnimationHost() {} }; WM_PUBLIC_EXPORT void SetAnimationHost(aura::Window* window, AnimationHost* animation_host); WM_PUBLIC_EXPORT AnimationHost* GetAnimationHost(aura::Window* window); } // namespace wm #endif // UI_WM_PUBLIC_ANIMATION_HOST_H_
Zhao-PengFei35/chromium_src_4
ui/wm/public/animation_host.h
C++
unknown
1,487
// Copyright 2014 The Chromium Authors // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "ui/wm/public/scoped_tooltip_disabler.h" #include "ui/aura/window.h" #include "ui/wm/public/tooltip_client.h" namespace wm { ScopedTooltipDisabler::ScopedTooltipDisabler(aura::Window* window) : root_(window ? window->GetRootWindow() : nullptr) { if (root_) { root_->AddObserver(this); TooltipClient* client = GetTooltipClient(root_); if (client) client->SetTooltipsEnabled(false); } } ScopedTooltipDisabler::~ScopedTooltipDisabler() { EnableTooltips(); } void ScopedTooltipDisabler::EnableTooltips() { if (!root_) return; TooltipClient* client = GetTooltipClient(root_); if (client) client->SetTooltipsEnabled(true); root_->RemoveObserver(this); root_ = nullptr; } void ScopedTooltipDisabler::OnWindowDestroying(aura::Window* window) { EnableTooltips(); } } // namespace wm
Zhao-PengFei35/chromium_src_4
ui/wm/public/scoped_tooltip_disabler.cc
C++
unknown
983
// Copyright 2014 The Chromium Authors // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #ifndef UI_WM_PUBLIC_SCOPED_TOOLTIP_DISABLER_H_ #define UI_WM_PUBLIC_SCOPED_TOOLTIP_DISABLER_H_ #include "base/memory/raw_ptr.h" #include "ui/aura/window_observer.h" #include "ui/wm/public/wm_public_export.h" namespace wm { // Use to temporarily disable tooltips. class WM_PUBLIC_EXPORT ScopedTooltipDisabler : aura::WindowObserver { public: // Disables tooltips on |window| (does nothing if |window| is nullptr). // Tooltips are re-enabled from the destructor when there are no most // outstanding ScopedTooltipDisablers for |window|. explicit ScopedTooltipDisabler(aura::Window* window); ScopedTooltipDisabler(const ScopedTooltipDisabler&) = delete; ScopedTooltipDisabler& operator=(const ScopedTooltipDisabler&) = delete; ~ScopedTooltipDisabler() override; private: // Reenables the tooltips on the TooltipClient. void EnableTooltips(); // aura::WindowObserver: void OnWindowDestroying(aura::Window* window) override; // The RootWindow to disable Tooltips on; nullptr if the Window passed to the // constructor was not in a root or the root has been destroyed. raw_ptr<aura::Window> root_; }; } // namespace wm #endif // UI_WM_PUBLIC_SCOPED_TOOLTIP_DISABLER_H_
Zhao-PengFei35/chromium_src_4
ui/wm/public/scoped_tooltip_disabler.h
C++
unknown
1,350
// Copyright 2012 The Chromium Authors // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "ui/wm/public/tooltip_client.h" #include "ui/aura/window.h" #include "ui/base/class_property.h" DEFINE_EXPORTED_UI_CLASS_PROPERTY_TYPE(WM_PUBLIC_EXPORT, wm::TooltipClient*) DEFINE_EXPORTED_UI_CLASS_PROPERTY_TYPE(WM_PUBLIC_EXPORT, void**) namespace wm { DEFINE_UI_CLASS_PROPERTY_KEY(TooltipClient*, kRootWindowTooltipClientKey, NULL) DEFINE_UI_CLASS_PROPERTY_KEY(std::u16string*, kTooltipTextKey, NULL) DEFINE_UI_CLASS_PROPERTY_KEY(void*, kTooltipIdKey, NULL) void SetTooltipClient(aura::Window* root_window, TooltipClient* client) { DCHECK_EQ(root_window->GetRootWindow(), root_window); root_window->SetProperty(kRootWindowTooltipClientKey, client); } TooltipClient* GetTooltipClient(aura::Window* root_window) { if (root_window) DCHECK_EQ(root_window->GetRootWindow(), root_window); return root_window ? root_window->GetProperty(kRootWindowTooltipClientKey) : NULL; } void SetTooltipText(aura::Window* window, std::u16string* tooltip_text) { window->SetProperty(kTooltipTextKey, tooltip_text); } void SetTooltipId(aura::Window* window, void* id) { if (id != GetTooltipId(window)) window->SetProperty(kTooltipIdKey, id); } const std::u16string GetTooltipText(aura::Window* window) { std::u16string* string_ptr = window->GetProperty(kTooltipTextKey); return string_ptr ? *string_ptr : std::u16string(); } const void* GetTooltipId(aura::Window* window) { return window->GetProperty(kTooltipIdKey); } } // namespace wm
Zhao-PengFei35/chromium_src_4
ui/wm/public/tooltip_client.cc
C++
unknown
1,613
// Copyright 2012 The Chromium Authors // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #ifndef UI_WM_PUBLIC_TOOLTIP_CLIENT_H_ #define UI_WM_PUBLIC_TOOLTIP_CLIENT_H_ #include "ui/aura/window.h" #include "ui/gfx/font.h" #include "ui/wm/public/wm_public_export.h" namespace base { class TimeDelta; } namespace gfx { class Point; } namespace wm { class ScopedTooltipDisabler; class WM_PUBLIC_EXPORT TooltipClient { public: // Returns the max width of the tooltip when shown at the specified location. virtual int GetMaxWidth(const gfx::Point& point) const = 0; // Informs the shell tooltip manager of change in tooltip for window |target|. virtual void UpdateTooltip(aura::Window* target) = 0; // Informs the shell tooltip manager of change in tooltip for window |target|, // triggered by a keyboard and passing the bounds of the newly focused item // within the target. The bounds are relative to the window in which it is // contained. virtual void UpdateTooltipFromKeyboard(const gfx::Rect& bounds, aura::Window* target) = 0; // Returns true if the tooltip was set from a keyboard action. virtual bool IsTooltipSetFromKeyboard(aura::Window* target) = 0; // Sets the time after which the tooltip is hidden for Window |target|. If // |timeout_in_ms| is <= 0, the tooltip is shown indefinitely. virtual void SetHideTooltipTimeout(aura::Window* target, base::TimeDelta timeout) = 0; protected: // Enables/Disables tooltips. This is treated as a reference count. Consumers // must use ScopedTooltipDisabler to enable/disabled tooltips. virtual void SetTooltipsEnabled(bool enable) = 0; private: friend class ScopedTooltipDisabler; }; WM_PUBLIC_EXPORT void SetTooltipClient(aura::Window* root_window, TooltipClient* client); WM_PUBLIC_EXPORT TooltipClient* GetTooltipClient(aura::Window* root_window); // Sets the text for the tooltip. The id is used to determine uniqueness when // the text does not change. For example, if the tooltip text does not change, // but the id does then the position of the tooltip is updated. WM_PUBLIC_EXPORT void SetTooltipText(aura::Window* window, std::u16string* tooltip_text); WM_PUBLIC_EXPORT void SetTooltipId(aura::Window* window, void* id); WM_PUBLIC_EXPORT const std::u16string GetTooltipText(aura::Window* window); WM_PUBLIC_EXPORT const void* GetTooltipId(aura::Window* window); WM_PUBLIC_EXPORT extern const aura::WindowProperty<void*>* const kTooltipIdKey; WM_PUBLIC_EXPORT extern const aura::WindowProperty<std::u16string*>* const kTooltipTextKey; } // namespace wm #endif // UI_WM_PUBLIC_TOOLTIP_CLIENT_H_
Zhao-PengFei35/chromium_src_4
ui/wm/public/tooltip_client.h
C++
unknown
2,819
// Copyright 2022 The Chromium Authors // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #ifndef UI_WM_PUBLIC_TOOLTIP_OBSERVER_H_ #define UI_WM_PUBLIC_TOOLTIP_OBSERVER_H_ #include <string> #include "base/observer_list_types.h" #include "ui/wm/public/wm_public_export.h" namespace aura { class Window; } namespace gfx { class Rect; } namespace wm { class WM_PUBLIC_EXPORT TooltipObserver : public base::CheckedObserver { public: ~TooltipObserver() override = default; // Called when tooltip is shown. // `target` is a target window of show tooltip. This may be null if the target // window is already destroyed, // `bounds` is relative to the target window position. // TODO(crbug.com/1385219): Use tooltip's parent window for `target`. virtual void OnTooltipShown(aura::Window* target, const std::u16string& text, const gfx::Rect& bounds) = 0; // Called when tooltip is hidden. // `target` is a target window of show tooltip. This may be null if the target // window is already destroyed, // TODO(crbug.com/1385219): Use tooltip's parent window for `target`. virtual void OnTooltipHidden(aura::Window* target) = 0; }; } // namespace wm #endif // UI_WM_PUBLIC_TOOLTIP_OBSERVER_H_
Zhao-PengFei35/chromium_src_4
ui/wm/public/tooltip_observer.h
C++
unknown
1,331
// Copyright 2012 The Chromium Authors // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "ui/wm/public/window_move_client.h" #include "ui/aura/window.h" #include "ui/base/class_property.h" DEFINE_UI_CLASS_PROPERTY_TYPE(wm::WindowMoveClient*) namespace wm { // A property key to store a client that handles window moves. DEFINE_UI_CLASS_PROPERTY_KEY(WindowMoveClient*, kWindowMoveClientKey, nullptr) void SetWindowMoveClient(aura::Window* window, WindowMoveClient* client) { window->SetProperty(kWindowMoveClientKey, client); } WindowMoveClient* GetWindowMoveClient(aura::Window* window) { return window->GetProperty(kWindowMoveClientKey); } } // namespace wm
Zhao-PengFei35/chromium_src_4
ui/wm/public/window_move_client.cc
C++
unknown
735
// Copyright 2012 The Chromium Authors // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #ifndef UI_WM_PUBLIC_WINDOW_MOVE_CLIENT_H_ #define UI_WM_PUBLIC_WINDOW_MOVE_CLIENT_H_ #include "ui/gfx/geometry/vector2d.h" #include "ui/wm/public/wm_public_export.h" namespace aura { class Window; } namespace wm { enum WindowMoveResult { MOVE_SUCCESSFUL, // Moving window was successful. MOVE_CANCELED // Moving window was canceled. }; enum WindowMoveSource { WINDOW_MOVE_SOURCE_MOUSE, WINDOW_MOVE_SOURCE_TOUCH, }; // An interface implemented by an object that manages programatically keyed // window moving. class WM_PUBLIC_EXPORT WindowMoveClient { public: // Starts a nested run loop for moving the window. |drag_offset| is the // offset from the window origin to the cursor when the drag was started. // Returns MOVE_SUCCESSFUL if the move has completed successfully, or // MOVE_CANCELED otherwise. virtual WindowMoveResult RunMoveLoop(aura::Window* window, const gfx::Vector2d& drag_offset, WindowMoveSource source) = 0; // Ends a previously started move loop. virtual void EndMoveLoop() = 0; protected: virtual ~WindowMoveClient() {} }; // Sets/Gets the activation client for the specified window. WM_PUBLIC_EXPORT void SetWindowMoveClient(aura::Window* window, WindowMoveClient* client); WM_PUBLIC_EXPORT WindowMoveClient* GetWindowMoveClient(aura::Window* window); } // namespace wm #endif // UI_WM_PUBLIC_WINDOW_MOVE_CLIENT_H_
Zhao-PengFei35/chromium_src_4
ui/wm/public/window_move_client.h
C++
unknown
1,644
// Copyright 2017 The Chromium Authors // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #ifndef UI_WM_PUBLIC_WM_PUBLIC_EXPORT_H_ #define UI_WM_PUBLIC_WM_PUBLIC_EXPORT_H_ // Defines WM_PUBLIC_EXPORT so that functionality implemented by the wm_public // module can be exported to consumers. #if defined(COMPONENT_BUILD) #if defined(WIN32) #if defined(WM_PUBLIC_IMPLEMENTATION) #define WM_PUBLIC_EXPORT __declspec(dllexport) #else #define WM_PUBLIC_EXPORT __declspec(dllimport) #endif // defined(WM_PUBLIC_IMPLEMENTATION) #else // defined(WIN32) #if defined(WM_PUBLIC_IMPLEMENTATION) #define WM_PUBLIC_EXPORT __attribute__((visibility("default"))) #else #define WM_PUBLIC_EXPORT #endif #endif #else // defined(COMPONENT_BUILD) #define WM_PUBLIC_EXPORT #endif #endif // UI_WM_PUBLIC_WM_PUBLIC_EXPORT_H_
Zhao-PengFei35/chromium_src_4
ui/wm/public/wm_public_export.h
C
unknown
865
include_rules = [ "+ui/aura", "+ui/base/resource/resource_bundle.h", "+ui/base/ui_base_paths.h", "+ui/gl", "+ui/platform_window", "+ui/views", ] specific_include_rules = { "run_all_unittests\.cc": [ "+mojo/core/embedder", ] }
Zhao-PengFei35/chromium_src_4
ui/wm/test/DEPS
Python
unknown
247
// Copyright 2014 The Chromium Authors // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include <memory> #include "base/compiler_specific.h" #include "base/files/file_path.h" #include "base/functional/bind.h" #include "base/path_service.h" #include "base/test/launcher/unit_test_launcher.h" #include "base/test/test_discardable_memory_allocator.h" #include "base/test/test_suite.h" #include "mojo/core/embedder/embedder.h" #include "testing/gtest/include/gtest/gtest.h" #include "ui/aura/env.h" #include "ui/base/resource/resource_bundle.h" #include "ui/base/resource/resource_scale_factor.h" #include "ui/base/ui_base_paths.h" #include "ui/gl/test/gl_surface_test_support.h" class WMTestSuite : public base::TestSuite { public: WMTestSuite(int argc, char** argv) : base::TestSuite(argc, argv) {} WMTestSuite(const WMTestSuite&) = delete; WMTestSuite& operator=(const WMTestSuite&) = delete; protected: void Initialize() override { base::TestSuite::Initialize(); gl::GLSurfaceTestSupport::InitializeOneOff(); ui::RegisterPathProvider(); base::FilePath ui_test_pak_path; ASSERT_TRUE(base::PathService::Get(ui::UI_TEST_PAK, &ui_test_pak_path)); ui::ResourceBundle::InitSharedInstanceWithPakPath(ui_test_pak_path); if (ui::ResourceBundle::IsScaleFactorSupported(ui::k200Percent)) { base::FilePath ui_test_resources_200 = ui_test_pak_path.DirName().Append( FILE_PATH_LITERAL("ui_test_200_percent.pak")); ui::ResourceBundle::GetSharedInstance().AddDataPackFromPath( ui_test_resources_200, ui::k200Percent); } env_ = aura::Env::CreateInstance(); base::DiscardableMemoryAllocator::SetInstance( &discardable_memory_allocator_); } void Shutdown() override { env_.reset(); ui::ResourceBundle::CleanupSharedInstance(); base::TestSuite::Shutdown(); } private: std::unique_ptr<aura::Env> env_; base::TestDiscardableMemoryAllocator discardable_memory_allocator_; }; int main(int argc, char** argv) { WMTestSuite test_suite(argc, argv); mojo::core::Init(); return base::LaunchUnitTests( argc, argv, base::BindOnce(&WMTestSuite::Run, base::Unretained(&test_suite))); }
Zhao-PengFei35/chromium_src_4
ui/wm/test/run_all_unittests.cc
C++
unknown
2,254
// Copyright 2016 The Chromium Authors // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "ui/wm/test/testing_cursor_client_observer.h" namespace wm { TestingCursorClientObserver::TestingCursorClientObserver() : cursor_visibility_(false), did_visibility_change_(false), cursor_size_(ui::CursorSize::kNormal), did_cursor_size_change_(false) {} void TestingCursorClientObserver::reset() { cursor_visibility_ = did_visibility_change_ = false; cursor_size_ = ui::CursorSize::kNormal; did_cursor_size_change_ = false; } void TestingCursorClientObserver::OnCursorVisibilityChanged(bool is_visible) { cursor_visibility_ = is_visible; did_visibility_change_ = true; } void TestingCursorClientObserver::OnCursorSizeChanged( ui::CursorSize cursor_size) { cursor_size_ = cursor_size; did_cursor_size_change_ = true; } } // namespace wm
Zhao-PengFei35/chromium_src_4
ui/wm/test/testing_cursor_client_observer.cc
C++
unknown
935
// Copyright 2016 The Chromium Authors // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #ifndef UI_WM_TEST_TESTING_CURSOR_CLIENT_OBSERVER_H_ #define UI_WM_TEST_TESTING_CURSOR_CLIENT_OBSERVER_H_ #include "ui/aura/client/cursor_client_observer.h" #include "ui/base/cursor/cursor_size.h" #include "ui/wm/core/cursor_manager.h" namespace wm { // CursorClientObserver for testing. class TestingCursorClientObserver : public aura::client::CursorClientObserver { public: TestingCursorClientObserver(); TestingCursorClientObserver(const TestingCursorClientObserver&) = delete; TestingCursorClientObserver& operator=(const TestingCursorClientObserver&) = delete; void reset(); bool is_cursor_visible() const { return cursor_visibility_; } bool did_visibility_change() const { return did_visibility_change_; } ui::CursorSize cursor_size() const { return cursor_size_; } bool did_cursor_size_change() const { return did_cursor_size_change_; } // Overridden from aura::client::CursorClientObserver: void OnCursorVisibilityChanged(bool is_visible) override; void OnCursorSizeChanged(ui::CursorSize cursor_size) override; private: bool cursor_visibility_; bool did_visibility_change_; ui::CursorSize cursor_size_; bool did_cursor_size_change_; }; } // namespace wm #endif // UI_WM_TEST_TESTING_CURSOR_CLIENT_OBSERVER_H_
Zhao-PengFei35/chromium_src_4
ui/wm/test/testing_cursor_client_observer.h
C++
unknown
1,412
// Copyright 2013 The Chromium Authors // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "ui/wm/test/wm_test_helper.h" #include <memory> #include <utility> #include "base/memory/ptr_util.h" #include "build/build_config.h" #include "ui/aura/client/default_capture_client.h" #include "ui/aura/test/test_focus_client.h" #include "ui/aura/test/test_screen.h" #include "ui/aura/window.h" #include "ui/platform_window/platform_window_init_properties.h" #include "ui/wm/core/compound_event_filter.h" #include "ui/wm/core/default_activation_client.h" #include "ui/wm/core/wm_state.h" namespace wm { WMTestHelper::WMTestHelper(const gfx::Size& default_window_size) { wm_state_ = std::make_unique<WMState>(); if (!display::Screen::HasScreen()) { test_screen_ = base::WrapUnique(aura::TestScreen::Create(gfx::Size())); display::Screen::SetScreenInstance(test_screen_.get()); } host_ = aura::WindowTreeHost::Create( ui::PlatformWindowInitProperties{gfx::Rect(default_window_size)}); host_->InitHost(); aura::client::SetWindowParentingClient(host_->window(), this); focus_client_ = std::make_unique<aura::test::TestFocusClient>(host_->window()); root_window_event_filter_ = std::make_unique<wm::CompoundEventFilter>(); host_->window()->AddPreTargetHandler(root_window_event_filter_.get()); new wm::DefaultActivationClient(host_->window()); capture_client_ = std::make_unique<aura::client::DefaultCaptureClient>(host_->window()); } WMTestHelper::~WMTestHelper() { host_->window()->RemovePreTargetHandler(root_window_event_filter_.get()); if (test_screen_) display::Screen::SetScreenInstance(nullptr); } aura::Window* WMTestHelper::GetDefaultParent(aura::Window* window, const gfx::Rect& bounds) { return host_->window(); } } // namespace wm
Zhao-PengFei35/chromium_src_4
ui/wm/test/wm_test_helper.cc
C++
unknown
1,908
// Copyright 2013 The Chromium Authors // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #ifndef UI_WM_TEST_WM_TEST_HELPER_H_ #define UI_WM_TEST_WM_TEST_HELPER_H_ #include <memory> #include "base/run_loop.h" #include "ui/aura/client/window_parenting_client.h" #include "ui/aura/window_tree_host.h" namespace aura { class TestScreen; class Window; class WindowTreeHost; namespace client { class DefaultCaptureClient; class FocusClient; } } namespace gfx { class Rect; class Size; } namespace wm { class CompoundEventFilter; class WMState; // Creates a minimal environment for running the shell. We can't pull in all of // ash here, but we can create and attach several of the same things we'd find // in ash. class WMTestHelper : public aura::client::WindowParentingClient { public: explicit WMTestHelper(const gfx::Size& default_window_size); WMTestHelper(const WMTestHelper&) = delete; WMTestHelper& operator=(const WMTestHelper&) = delete; ~WMTestHelper() override; aura::WindowTreeHost* host() { return host_.get(); } // Overridden from client::WindowParentingClient: aura::Window* GetDefaultParent(aura::Window* window, const gfx::Rect& bounds) override; private: std::unique_ptr<WMState> wm_state_; std::unique_ptr<aura::TestScreen> test_screen_; std::unique_ptr<aura::WindowTreeHost> host_; std::unique_ptr<wm::CompoundEventFilter> root_window_event_filter_; std::unique_ptr<aura::client::DefaultCaptureClient> capture_client_; std::unique_ptr<aura::client::FocusClient> focus_client_; }; } // namespace wm #endif // UI_WM_TEST_WM_TEST_HELPER_H_
Zhao-PengFei35/chromium_src_4
ui/wm/test/wm_test_helper.h
C++
unknown
1,684
include_rules = [ # Limit files that can depend on icu. "-base/i18n", "-third_party/icu", ] specific_include_rules = { "gurl_fuzzer.cc": [ "+base/i18n", ], "url_(canon|idna)_icu(\.cc|_unittest\.cc)": [ "+base/i18n", "+third_party/icu", ], "run_all_unittests\.cc": [ "+mojo/core/embedder", ], }
Zhao-PengFei35/chromium_src_4
url/DEPS
Python
unknown
329
// Copyright 2019 The Chromium Authors // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "url/android/gurl_android.h" #include <jni.h> #include <cstdint> #include <string> #include <vector> #include "base/android/jni_android.h" #include "base/android/jni_string.h" #include "base/functional/bind.h" #include "base/functional/callback.h" #include "base/memory/ptr_util.h" #include "url/android/parsed_android.h" #include "url/gurl_jni_headers/GURL_jni.h" #include "url/third_party/mozilla/url_parse.h" using base::android::AttachCurrentThread; using base::android::JavaParamRef; using base::android::JavaRef; using base::android::ScopedJavaLocalRef; namespace url { namespace { static GURL FromJString(JNIEnv* env, const JavaRef<jstring>& uri) { if (!uri) return GURL(); return GURL(base::android::ConvertJavaStringToUTF16(env, uri)); } static std::unique_ptr<GURL> FromJavaGURL(JNIEnv* env, const JavaRef<jstring>& j_spec, bool is_valid, jlong parsed_ptr) { Parsed* parsed = reinterpret_cast<Parsed*>(parsed_ptr); const std::string& spec = ConvertJavaStringToUTF8(env, j_spec); std::unique_ptr<GURL> gurl = std::make_unique<GURL>(spec.data(), parsed->Length(), *parsed, is_valid); delete parsed; return gurl; } static void InitFromGURL(JNIEnv* env, const GURL& gurl, const JavaRef<jobject>& target) { Java_GURL_init( env, target, base::android::ConvertUTF8ToJavaString(env, gurl.possibly_invalid_spec()), gurl.is_valid(), ParsedAndroid::InitFromParsed(env, gurl.parsed_for_possibly_invalid_spec())); } // As |GetArrayLength| makes no guarantees about the returned value (e.g., it // may be -1 if |array| is not a valid Java array), provide a safe wrapper // that always returns a valid, non-negative size. template <typename JavaArrayType> size_t SafeGetArrayLength(JNIEnv* env, const JavaRef<JavaArrayType>& jarray) { DCHECK(jarray); jsize length = env->GetArrayLength(jarray.obj()); DCHECK_GE(length, 0) << "Invalid array length: " << length; return static_cast<size_t>(std::max(0, length)); } } // namespace // static std::unique_ptr<GURL> GURLAndroid::ToNativeGURL( JNIEnv* env, const base::android::JavaRef<jobject>& j_gurl) { return base::WrapUnique<GURL>( reinterpret_cast<GURL*>(Java_GURL_toNativeGURL(env, j_gurl))); } void GURLAndroid::JavaGURLArrayToGURLVector( JNIEnv* env, const base::android::JavaRef<jobjectArray>& array, std::vector<GURL>* out) { DCHECK(out); DCHECK(out->empty()); if (!array) return; size_t len = SafeGetArrayLength(env, array); for (size_t i = 0; i < len; ++i) { ScopedJavaLocalRef<jobject> j_gurl( env, static_cast<jobject>(env->GetObjectArrayElement(array.obj(), i))); out->emplace_back( *reinterpret_cast<GURL*>(Java_GURL_toNativeGURL(env, j_gurl))); } } // static ScopedJavaLocalRef<jobject> GURLAndroid::FromNativeGURL(JNIEnv* env, const GURL& gurl) { ScopedJavaLocalRef<jobject> j_gurl = Java_GURL_Constructor(env); InitFromGURL(env, gurl, j_gurl); return j_gurl; } // static ScopedJavaLocalRef<jobject> GURLAndroid::EmptyGURL(JNIEnv* env) { return Java_GURL_emptyGURL(env); } // static ScopedJavaLocalRef<jobjectArray> GURLAndroid::ToJavaArrayOfGURLs( JNIEnv* env, base::span<ScopedJavaLocalRef<jobject>> v) { jclass clazz = org_chromium_url_GURL_clazz(env); DCHECK(clazz); jobjectArray joa = env->NewObjectArray(v.size(), clazz, nullptr); base::android::CheckException(env); for (size_t i = 0; i < v.size(); ++i) { env->SetObjectArrayElement(joa, i, v[i].obj()); } return ScopedJavaLocalRef<jobjectArray>(env, joa); } static void JNI_GURL_GetOrigin(JNIEnv* env, const JavaParamRef<jstring>& j_spec, jboolean is_valid, jlong parsed_ptr, const JavaParamRef<jobject>& target) { std::unique_ptr<GURL> gurl = FromJavaGURL(env, j_spec, is_valid, parsed_ptr); InitFromGURL(env, gurl->DeprecatedGetOriginAsURL(), target); } static jboolean JNI_GURL_DomainIs(JNIEnv* env, const JavaParamRef<jstring>& j_spec, jboolean is_valid, jlong parsed_ptr, const JavaParamRef<jstring>& j_domain) { std::unique_ptr<GURL> gurl = FromJavaGURL(env, j_spec, is_valid, parsed_ptr); const std::string& domain = ConvertJavaStringToUTF8(env, j_domain); return gurl->DomainIs(domain); } static void JNI_GURL_Init(JNIEnv* env, const base::android::JavaParamRef<jstring>& uri, const base::android::JavaParamRef<jobject>& target) { const GURL& gurl = FromJString(env, uri); InitFromGURL(env, gurl, target); } static jlong JNI_GURL_CreateNative(JNIEnv* env, const JavaParamRef<jstring>& j_spec, jboolean is_valid, jlong parsed_ptr) { return reinterpret_cast<intptr_t>( FromJavaGURL(env, j_spec, is_valid, parsed_ptr).release()); } } // namespace url
Zhao-PengFei35/chromium_src_4
url/android/gurl_android.cc
C++
unknown
5,514
// Copyright 2019 The Chromium Authors // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #ifndef URL_ANDROID_GURL_ANDROID_H_ #define URL_ANDROID_GURL_ANDROID_H_ #include <memory> #include "base/android/scoped_java_ref.h" #include "base/containers/span.h" #include "url/gurl.h" namespace url { class GURLAndroid { public: static std::unique_ptr<GURL> ToNativeGURL( JNIEnv* env, const base::android::JavaRef<jobject>& j_gurl); static base::android::ScopedJavaLocalRef<jobject> FromNativeGURL( JNIEnv* env, const GURL& gurl); static base::android::ScopedJavaLocalRef<jobject> EmptyGURL(JNIEnv* env); static base::android::ScopedJavaLocalRef<jobjectArray> ToJavaArrayOfGURLs( JNIEnv* env, base::span<base::android::ScopedJavaLocalRef<jobject>> v); static void JavaGURLArrayToGURLVector( JNIEnv* env, const base::android::JavaRef<jobjectArray>& gurl_array, std::vector<GURL>* out); }; } // namespace url #endif // URL_ANDROID_GURL_ANDROID_H_
Zhao-PengFei35/chromium_src_4
url/android/gurl_android.h
C++
unknown
1,065
// Copyright 2019 The Chromium Authors // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include <stddef.h> #include "base/android/jni_android.h" #include "base/android/jni_string.h" #include "base/test/icu_test_util.h" #include "url/android/gurl_android.h" #include "url/gurl.h" #include "url/j_test_jni_headers/GURLJavaTestHelper_jni.h" using base::android::AttachCurrentThread; namespace url { static void JNI_GURLJavaTestHelper_InitializeICU(JNIEnv* env) { base::test::InitializeICUForTesting(); } static void JNI_GURLJavaTestHelper_TestGURLEquivalence(JNIEnv* env) { const char* cases[] = { // Common Standard URLs. "https://www.google.com", "https://www.google.com/", "https://www.google.com/maps.htm", "https://www.google.com/maps/", "https://www.google.com/index.html", "https://www.google.com/index.html?q=maps", "https://www.google.com/index.html#maps/", "https://foo:bar@www.google.com/maps.htm", "https://www.google.com/maps/au/index.html", "https://www.google.com/maps/au/north", "https://www.google.com/maps/au/north/", "https://www.google.com/maps/au/index.html?q=maps#fragment/", "http://www.google.com:8000/maps/au/index.html?q=maps#fragment/", "https://www.google.com/maps/au/north/?q=maps#fragment", "https://www.google.com/maps/au/north?q=maps#fragment", // Less common standard URLs. "filesystem:http://www.google.com/temporary/bar.html?baz=22", "file:///temporary/bar.html?baz=22", "ftp://foo/test/index.html", "gopher://foo/test/index.html", "ws://foo/test/index.html", // Non-standard, "chrome://foo/bar.html", "httpa://foo/test/index.html", "blob:https://foo.bar/test/index.html", "about:blank", "data:foobar", "scheme:opaque_data", // Invalid URLs. "foobar", }; for (const char* uri : cases) { GURL gurl(uri); base::android::ScopedJavaLocalRef<jobject> j_gurl = Java_GURLJavaTestHelper_createGURL( env, base::android::ConvertUTF8ToJavaString(env, uri)); std::unique_ptr<GURL> gurl2 = GURLAndroid::ToNativeGURL(env, j_gurl); if (gurl != *gurl2) { std::stringstream ss; ss << "GURL not equivalent: " << gurl << ", " << *gurl2; env->ThrowNew(env->FindClass("java/lang/AssertionError"), ss.str().data()); return; } } } } // namespace url
Zhao-PengFei35/chromium_src_4
url/android/gurl_java_test_helper.cc
C++
unknown
2,503
// Copyright 2019 The Chromium Authors // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. package org.chromium.url; import android.os.SystemClock; import android.text.TextUtils; import androidx.annotation.Nullable; import androidx.annotation.VisibleForTesting; import com.google.errorprone.annotations.DoNotMock; import org.chromium.base.Log; import org.chromium.base.ThreadUtils; import org.chromium.base.annotations.CalledByNative; import org.chromium.base.annotations.JNINamespace; import org.chromium.base.annotations.NativeMethods; import org.chromium.base.library_loader.LibraryLoader; import org.chromium.base.metrics.RecordHistogram; import org.chromium.base.task.PostTask; import org.chromium.base.task.TaskTraits; import org.chromium.build.annotations.MainDex; import org.chromium.url.mojom.Url; import org.chromium.url.mojom.UrlConstants; import java.util.Random; /** * An immutable Java wrapper for GURL, Chromium's URL parsing library. * * This class is safe to use during startup, but will block on the native library being sufficiently * loaded to use native GURL (and will not wait for content initialization). In practice it's very * unlikely that this will actually block startup unless used extremely early, in which case you * should probably seek an alternative solution to using GURL. * * The design of this class avoids destruction/finalization by caching all values necessary to * reconstruct a GURL in Java, allowing it to be much faster in the common case and easier to use. */ @JNINamespace("url") @MainDex @DoNotMock("Create a real instance instead. For Robolectric, see JUnitTestGURLs.java") public class GURL { private static final String TAG = "GURL"; /* package */ static final int SERIALIZER_VERSION = 1; /* package */ static final char SERIALIZER_DELIMITER = '\0'; @FunctionalInterface public interface ReportDebugThrowableCallback { void run(Throwable throwable); } /** * Exception signalling that a GURL failed to parse due to an unexpected version marker in the * serialized input. */ public static class BadSerializerVersionException extends RuntimeException {} // Right now this is only collecting reports on Canary which has a relatively small population. private static final int DEBUG_REPORT_PERCENTAGE = 10; private static ReportDebugThrowableCallback sReportCallback; // TODO(https://crbug.com/1039841): Right now we return a new String with each request for a // GURL component other than the spec itself. Should we cache return Strings (as // WeakReference?) so that callers can share String memory? private String mSpec; private boolean mIsValid; private Parsed mParsed; private static class Holder { private static GURL sEmptyGURL = new GURL(""); } @CalledByNative public static GURL emptyGURL() { return Holder.sEmptyGURL; } /** * Create a new GURL. * * @param uri The string URI representation to parse into a GURL. */ public GURL(String uri) { // Avoid a jni hop (and initializing the native library) for empty GURLs. if (TextUtils.isEmpty(uri)) { mSpec = ""; mParsed = Parsed.createEmpty(); return; } ensureNativeInitializedForGURL(); getNatives().init(uri, this); } @CalledByNative protected GURL() {} /** * Enables debug stack trace gathering for GURL. */ public static void setReportDebugThrowableCallback(ReportDebugThrowableCallback callback) { sReportCallback = callback; } /** * Ensures that the native library is sufficiently loaded for GURL usage. * * This function is public so that GURL-related usage like the UrlFormatter also counts towards * the "Startup.Android.GURLEnsureMainDexInitialized" histogram. */ public static void ensureNativeInitializedForGURL() { if (LibraryLoader.getInstance().isInitialized()) return; long time = SystemClock.elapsedRealtime(); LibraryLoader.getInstance().ensureMainDexInitialized(); // Record metrics only for the UI thread where the delay in loading the library is relevant. if (ThreadUtils.runningOnUiThread()) { // "MainDex" in name of histogram is a dated reference to when we used to have 2 // sections of the native library, main dex and non-main dex. Maintaining name for // consistency in metrics. RecordHistogram.recordTimesHistogram("Startup.Android.GURLEnsureMainDexInitialized", SystemClock.elapsedRealtime() - time); if (sReportCallback != null && new Random().nextInt(100) < DEBUG_REPORT_PERCENTAGE) { final Throwable throwable = new Throwable("This is not a crash, please ignore. See crbug.com/1065377."); // This isn't an assert, because by design this is possible, but we would prefer // this path does not get hit more than necessary and getting stack traces from the // wild will help find issues. PostTask.postTask(TaskTraits.BEST_EFFORT_MAY_BLOCK, () -> { sReportCallback.run(throwable); }); } } } /** @return true if the GURL is null, empty, or invalid. */ public static boolean isEmptyOrInvalid(@Nullable GURL gurl) { return gurl == null || gurl.isEmpty() || !gurl.isValid(); } @CalledByNative private void init(String spec, boolean isValid, Parsed parsed) { mSpec = spec; // Ensure that the spec only contains US-ASCII or the parsed indices will be wrong. assert mSpec.matches("\\A\\p{ASCII}*\\z"); mIsValid = isValid; mParsed = parsed; } @CalledByNative private long toNativeGURL() { return getNatives().createNative(mSpec, mIsValid, mParsed.toNativeParsed()); } /** * See native GURL::is_valid(). */ public boolean isValid() { return mIsValid; } /** * See native GURL::spec(). */ public String getSpec() { if (isValid() || mSpec.isEmpty()) return mSpec; assert false : "Trying to get the spec of an invalid URL!"; return ""; } /** * @return Either a valid Spec (see {@link #getSpec}), or an empty string. */ public String getValidSpecOrEmpty() { if (isValid()) return mSpec; return ""; } /** * See native GURL::possibly_invalid_spec(). */ public String getPossiblyInvalidSpec() { return mSpec; } private String getComponent(int begin, int length) { if (length <= 0) return ""; return mSpec.substring(begin, begin + length); } /** * See native GURL::scheme(). */ public String getScheme() { return getComponent(mParsed.mSchemeBegin, mParsed.mSchemeLength); } /** * See native GURL::username(). */ public String getUsername() { return getComponent(mParsed.mUsernameBegin, mParsed.mUsernameLength); } /** * See native GURL::password(). */ public String getPassword() { return getComponent(mParsed.mPasswordBegin, mParsed.mPasswordLength); } /** * See native GURL::host(). */ public String getHost() { return getComponent(mParsed.mHostBegin, mParsed.mHostLength); } /** * See native GURL::port(). * * Note: Do not convert this to an integer yourself. See native GURL::IntPort(). */ public String getPort() { return getComponent(mParsed.mPortBegin, mParsed.mPortLength); } /** * See native GURL::path(). */ public String getPath() { return getComponent(mParsed.mPathBegin, mParsed.mPathLength); } /** * See native GURL::query(). */ public String getQuery() { return getComponent(mParsed.mQueryBegin, mParsed.mQueryLength); } /** * See native GURL::ref(). */ public String getRef() { return getComponent(mParsed.mRefBegin, mParsed.mRefLength); } /** * @return Whether the GURL is the empty String. */ public boolean isEmpty() { return mSpec.isEmpty(); } /** * See native GURL::GetOrigin(). */ public GURL getOrigin() { GURL target = new GURL(); getOriginInternal(target); return target; } protected void getOriginInternal(GURL target) { getNatives().getOrigin(mSpec, mIsValid, mParsed.toNativeParsed(), target); } /** * See native GURL::DomainIs(). */ public boolean domainIs(String domain) { return getNatives().domainIs(mSpec, mIsValid, mParsed.toNativeParsed(), domain); } @Override public final int hashCode() { return mSpec.hashCode(); } @Override public final boolean equals(Object other) { if (other == this) return true; if (!(other instanceof GURL)) return false; return mSpec.equals(((GURL) other).mSpec); } /** * Serialize a GURL to a String, to be used with {@link GURL#deserialize(String)}. * * Note that a serialized GURL should only be used internally to Chrome, and should *never* be * used if coming from an untrusted source. * * @return A serialzed GURL. */ public final String serialize() { StringBuilder builder = new StringBuilder(); builder.append(SERIALIZER_VERSION).append(SERIALIZER_DELIMITER); builder.append(mIsValid).append(SERIALIZER_DELIMITER); builder.append(mParsed.serialize()).append(SERIALIZER_DELIMITER); builder.append(mSpec); String serialization = builder.toString(); return Integer.toString(serialization.length()) + SERIALIZER_DELIMITER + serialization; } /** * Deserialize a GURL serialized with {@link GURL#serialize()}. This will re-parse in case of * version mismatch, which may trigger undesired native loading. {@see * deserializeLatestVersionOnly} if you want to fail in case of version mismatch. * * This function should *never* be used on a String coming from an untrusted source. * * @return The deserialized GURL (or null if the input is empty). */ public static GURL deserialize(@Nullable String gurl) { try { return deserializeLatestVersionOnly(gurl); } catch (BadSerializerVersionException be) { // Just re-parse the GURL on version changes. String[] tokens = gurl.split(Character.toString(SERIALIZER_DELIMITER)); return new GURL(getSpecFromTokens(gurl, tokens)); } catch (Exception e) { // This is unexpected, maybe the storage got corrupted somehow? Log.w(TAG, "Exception while deserializing a GURL: " + gurl, e); return emptyGURL(); } } /** * Deserialize a GURL serialized with {@link #serialize()}, throwing {@code * BadSerializerException} if the serialized input has a version other than the latest. This * function should never be used on a String coming from an untrusted source. */ public static GURL deserializeLatestVersionOnly(@Nullable String gurl) { if (TextUtils.isEmpty(gurl)) return emptyGURL(); String[] tokens = gurl.split(Character.toString(SERIALIZER_DELIMITER)); // First token MUST always be the length of the serialized data. String length = tokens[0]; if (gurl.length() != Integer.parseInt(length) + length.length() + 1) { throw new IllegalArgumentException("Serialized GURL had the wrong length."); } String spec = getSpecFromTokens(gurl, tokens); // Second token MUST always be the version number. int version = Integer.parseInt(tokens[1]); if (version != SERIALIZER_VERSION) { throw new BadSerializerVersionException(); } boolean isValid = Boolean.parseBoolean(tokens[2]); Parsed parsed = Parsed.deserialize(tokens, 3); GURL result = new GURL(); result.init(spec, isValid, parsed); return result; } private static String getSpecFromTokens(String gurl, String[] tokens) { // Last token MUST always be the original spec. // Special case for empty spec - it won't get its own token. return gurl.endsWith(Character.toString(SERIALIZER_DELIMITER)) ? "" : tokens[tokens.length - 1]; } /** * Returns the instance of {@link Natives}. The Robolectric Shadow intercepts invocations of * this method. * * <p>Unlike {@code GURLJni.TEST_HOOKS.setInstanceForTesting}, shadowing this method doesn't * rely on tests correctly cleaning up global state. */ private static Natives getNatives() { return GURLJni.get(); } /** Inits this GURL with the internal state of another GURL. */ @VisibleForTesting /* package */ void initForTesting(GURL gurl) { init(gurl.mSpec, gurl.mIsValid, gurl.mParsed); } /** @return A Mojom representation of this URL. */ public Url toMojom() { Url url = new Url(); // See url/mojom/url_gurl_mojom_traits.cc. url.url = TextUtils.isEmpty(getPossiblyInvalidSpec()) || getPossiblyInvalidSpec().length() > UrlConstants.MAX_URL_CHARS || !isValid() ? "" : getPossiblyInvalidSpec(); return url; } @NativeMethods interface Natives { /** * Initializes the provided |target| by parsing the provided |uri|. */ void init(String uri, GURL target); /** * Reconstructs the native GURL for this Java GURL and initializes |target| with its Origin. */ void getOrigin(String spec, boolean isValid, long nativeParsed, GURL target); /** * Reconstructs the native GURL for this Java GURL, and calls GURL.DomainIs. */ boolean domainIs(String spec, boolean isValid, long nativeParsed, String domain); /** * Reconstructs the native GURL for this Java GURL, returning its native pointer. */ long createNative(String spec, boolean isValid, long nativeParsed); } }
Zhao-PengFei35/chromium_src_4
url/android/java/src/org/chromium/url/GURL.java
Java
unknown
14,533
// Copyright 2014 The Chromium Authors // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. package org.chromium.url; import org.chromium.base.annotations.CalledByNative; import org.chromium.base.annotations.JNINamespace; import java.net.IDN; /** * This class is used to convert unicode IDN domain names to ASCII, when not * building with ICU. */ @JNINamespace("url::android") public class IDNStringUtil { /** * Attempts to convert a Unicode string to an ASCII string using IDN rules. * As of May 2014, the underlying Java function IDNA2003. * @param src String to convert. * @return: String containing only ASCII characters on success, null on * failure. */ @CalledByNative private static String idnToASCII(String src) { try { return IDN.toASCII(src, IDN.USE_STD3_ASCII_RULES); } catch (Exception e) { return null; } } }
Zhao-PengFei35/chromium_src_4
url/android/java/src/org/chromium/url/IDNStringUtil.java
Java
unknown
989
// Copyright 2019 The Chromium Authors // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. package org.chromium.url; import org.chromium.base.annotations.CalledByNative; import org.chromium.base.annotations.JNINamespace; import org.chromium.base.annotations.NativeMethods; /** An origin is either a (scheme, host, port) tuple or is opaque. */ @JNINamespace("url") public class Origin { private final String mScheme; private final String mHost; private final short mPort; private final boolean mIsOpaque; // Serialization of the Unguessable Token. Do not use directly. private final long mTokenHighBits; private final long mTokenLowBits; /** * Constructs an opaque origin. */ public static Origin createOpaqueOrigin() { return OriginJni.get().createOpaque(); } /** * See origin.h for many warnings about this method. * * Constructs an Origin from a GURL. */ public static Origin create(GURL gurl) { return OriginJni.get().createFromGURL(gurl); } /** * Parses a mojo Origin into a Java analogue of the c++ Origin class. * * `org.chromium.url.internal.mojom.Origin`s, are provided by Mojo-generated code but not * intended for direct use (see crbug.com/1156866). * * @return A Java equivalent of the c++ Origin represented by the provided mojo Origin. */ public Origin(org.chromium.url.internal.mojom.Origin mojoOrigin) { mScheme = mojoOrigin.scheme; mHost = mojoOrigin.host; mPort = mojoOrigin.port; if (mojoOrigin.nonceIfOpaque != null) { mIsOpaque = true; mTokenHighBits = mojoOrigin.nonceIfOpaque.high; mTokenLowBits = mojoOrigin.nonceIfOpaque.low; } else { mIsOpaque = false; mTokenHighBits = 0; mTokenLowBits = 0; } } @CalledByNative private Origin(String scheme, String host, short port, boolean isOpaque, long tokenHighBits, long tokenLowBits) { mScheme = scheme; mHost = host; mPort = port; mIsOpaque = isOpaque; mTokenHighBits = tokenHighBits; mTokenLowBits = tokenLowBits; } /** @return The scheme of the origin. Returns an empty string for an opaque origin. */ public String getScheme() { return !isOpaque() ? mScheme : ""; } /** @return The host of the origin. Returns an empty string for an opaque origin. */ public String getHost() { return !isOpaque() ? mHost : ""; } /** @return The port of the origin. Returns 0 for an opaque origin. */ public int getPort() { return !isOpaque() ? Short.toUnsignedInt(mPort) : 0; } /** @return Whether the origin is opaque. */ public boolean isOpaque() { return mIsOpaque; } @CalledByNative private long toNativeOrigin() { return OriginJni.get().createNative( mScheme, mHost, mPort, mIsOpaque, mTokenHighBits, mTokenLowBits); } @NativeMethods interface Natives { /** Constructs a new Opaque origin. */ Origin createOpaque(); /** Constructs an Origin from a GURL. */ Origin createFromGURL(GURL gurl); /** * Reconstructs the native Origin for this Java Origin, returning its native pointer. */ long createNative(String scheme, String host, short port, boolean isOpaque, long tokenHighBits, long tokenLowBits); } }
Zhao-PengFei35/chromium_src_4
url/android/java/src/org/chromium/url/Origin.java
Java
unknown
3,576
// Copyright 2019 The Chromium Authors // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. package org.chromium.url; import org.chromium.base.annotations.CalledByNative; import org.chromium.base.annotations.JNINamespace; import org.chromium.base.annotations.NativeMethods; import org.chromium.build.annotations.MainDex; /** * A java wrapper for Parsed, GURL's internal parsed URI representation. */ @MainDex @JNINamespace("url") /* package */ class Parsed { /* package */ final int mSchemeBegin; /* package */ final int mSchemeLength; /* package */ final int mUsernameBegin; /* package */ final int mUsernameLength; /* package */ final int mPasswordBegin; /* package */ final int mPasswordLength; /* package */ final int mHostBegin; /* package */ final int mHostLength; /* package */ final int mPortBegin; /* package */ final int mPortLength; /* package */ final int mPathBegin; /* package */ final int mPathLength; /* package */ final int mQueryBegin; /* package */ final int mQueryLength; /* package */ final int mRefBegin; /* package */ final int mRefLength; private final Parsed mInnerUrl; private final boolean mPotentiallyDanglingMarkup; /* package */ static Parsed createEmpty() { return new Parsed(0, -1, 0, -1, 0, -1, 0, -1, 0, -1, 0, -1, 0, -1, 0, -1, false, null); } @CalledByNative private Parsed(int schemeBegin, int schemeLength, int usernameBegin, int usernameLength, int passwordBegin, int passwordLength, int hostBegin, int hostLength, int portBegin, int portLength, int pathBegin, int pathLength, int queryBegin, int queryLength, int refBegin, int refLength, boolean potentiallyDanglingMarkup, Parsed innerUrl) { mSchemeBegin = schemeBegin; mSchemeLength = schemeLength; mUsernameBegin = usernameBegin; mUsernameLength = usernameLength; mPasswordBegin = passwordBegin; mPasswordLength = passwordLength; mHostBegin = hostBegin; mHostLength = hostLength; mPortBegin = portBegin; mPortLength = portLength; mPathBegin = pathBegin; mPathLength = pathLength; mQueryBegin = queryBegin; mQueryLength = queryLength; mRefBegin = refBegin; mRefLength = refLength; mPotentiallyDanglingMarkup = potentiallyDanglingMarkup; mInnerUrl = innerUrl; } /* package */ long toNativeParsed() { long inner = 0; if (mInnerUrl != null) { inner = mInnerUrl.toNativeParsed(); } return ParsedJni.get().createNative(mSchemeBegin, mSchemeLength, mUsernameBegin, mUsernameLength, mPasswordBegin, mPasswordLength, mHostBegin, mHostLength, mPortBegin, mPortLength, mPathBegin, mPathLength, mQueryBegin, mQueryLength, mRefBegin, mRefLength, mPotentiallyDanglingMarkup, inner); } /* package */ String serialize() { StringBuilder builder = new StringBuilder(); builder.append(mSchemeBegin).append(GURL.SERIALIZER_DELIMITER); builder.append(mSchemeLength).append(GURL.SERIALIZER_DELIMITER); builder.append(mUsernameBegin).append(GURL.SERIALIZER_DELIMITER); builder.append(mUsernameLength).append(GURL.SERIALIZER_DELIMITER); builder.append(mPasswordBegin).append(GURL.SERIALIZER_DELIMITER); builder.append(mPasswordLength).append(GURL.SERIALIZER_DELIMITER); builder.append(mHostBegin).append(GURL.SERIALIZER_DELIMITER); builder.append(mHostLength).append(GURL.SERIALIZER_DELIMITER); builder.append(mPortBegin).append(GURL.SERIALIZER_DELIMITER); builder.append(mPortLength).append(GURL.SERIALIZER_DELIMITER); builder.append(mPathBegin).append(GURL.SERIALIZER_DELIMITER); builder.append(mPathLength).append(GURL.SERIALIZER_DELIMITER); builder.append(mQueryBegin).append(GURL.SERIALIZER_DELIMITER); builder.append(mQueryLength).append(GURL.SERIALIZER_DELIMITER); builder.append(mRefBegin).append(GURL.SERIALIZER_DELIMITER); builder.append(mRefLength).append(GURL.SERIALIZER_DELIMITER); builder.append(mPotentiallyDanglingMarkup).append(GURL.SERIALIZER_DELIMITER); builder.append(mInnerUrl != null); if (mInnerUrl != null) { builder.append(GURL.SERIALIZER_DELIMITER).append(mInnerUrl.serialize()); } return builder.toString(); } /* package */ static Parsed deserialize(String[] tokens, int startIndex) { int schemeBegin = Integer.parseInt(tokens[startIndex++]); int schemeLength = Integer.parseInt(tokens[startIndex++]); int usernameBegin = Integer.parseInt(tokens[startIndex++]); int usernameLength = Integer.parseInt(tokens[startIndex++]); int passwordBegin = Integer.parseInt(tokens[startIndex++]); int passwordLength = Integer.parseInt(tokens[startIndex++]); int hostBegin = Integer.parseInt(tokens[startIndex++]); int hostLength = Integer.parseInt(tokens[startIndex++]); int portBegin = Integer.parseInt(tokens[startIndex++]); int portLength = Integer.parseInt(tokens[startIndex++]); int pathBegin = Integer.parseInt(tokens[startIndex++]); int pathLength = Integer.parseInt(tokens[startIndex++]); int queryBegin = Integer.parseInt(tokens[startIndex++]); int queryLength = Integer.parseInt(tokens[startIndex++]); int refBegin = Integer.parseInt(tokens[startIndex++]); int refLength = Integer.parseInt(tokens[startIndex++]); boolean potentiallyDanglingMarkup = Boolean.parseBoolean(tokens[startIndex++]); Parsed innerParsed = null; if (Boolean.parseBoolean(tokens[startIndex++])) { innerParsed = Parsed.deserialize(tokens, startIndex); } return new Parsed(schemeBegin, schemeLength, usernameBegin, usernameLength, passwordBegin, passwordLength, hostBegin, hostLength, portBegin, portLength, pathBegin, pathLength, queryBegin, queryLength, refBegin, refLength, potentiallyDanglingMarkup, innerParsed); } @NativeMethods interface Natives { /** * Create and return the pointer to a native Parsed. */ long createNative(int schemeBegin, int schemeLength, int usernameBegin, int usernameLength, int passwordBegin, int passwordLength, int hostBegin, int hostLength, int portBegin, int portLength, int pathBegin, int pathLength, int queryBegin, int queryLength, int refBegin, int refLength, boolean potentiallyDanglingMarkup, long innerUrl); } }
Zhao-PengFei35/chromium_src_4
url/android/java/src/org/chromium/url/Parsed.java
Java
unknown
6,785
// Copyright 2019 The Chromium Authors // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. package org.chromium.url; import java.net.URISyntaxException; /** * An API shim around GURL that mostly matches the java.net.URI API. * * @deprecated Please use GURL directly in new code. */ @Deprecated public class URI extends GURL { /** * Create a new GURL with a java.net.URI API shim. */ public URI(String uri) throws URISyntaxException { super(uri); if (!isValid()) { throw new URISyntaxException(uri, "Uri could not be parsed as a valid GURL"); } } private URI() {} /** * This function is a convenience wrapper around {@link URI#URI(String)}, that wraps the thrown * thrown URISyntaxException in an IllegalArgumentException and throws that instead. */ public static URI create(String str) { try { return new URI(str); } catch (URISyntaxException e) { throw new IllegalArgumentException(e); } } @Override public URI getOrigin() { URI target = new URI(); getOriginInternal(target); return target; } /** See {@link GURL#getRef()} */ public String getFragment() { return getRef(); } /** See {@link java.net.URI#isAbsolute()} */ public boolean isAbsolute() { return !getScheme().isEmpty(); } @Override public String toString() { return getPossiblyInvalidSpec(); } }
Zhao-PengFei35/chromium_src_4
url/android/java/src/org/chromium/url/URI.java
Java
unknown
1,556
include_rules = [ "+content/public/test/android", ]
Zhao-PengFei35/chromium_src_4
url/android/javatests/DEPS
Python
unknown
54
// Copyright 2019 The Chromium Authors // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. package org.chromium.url; import static org.mockito.ArgumentMatchers.any; import static org.mockito.Mockito.doThrow; import androidx.test.filters.SmallTest; import org.junit.Assert; import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; import org.mockito.Mock; import org.mockito.MockitoAnnotations; import org.chromium.base.test.BaseJUnit4ClassRunner; import org.chromium.base.test.util.Batch; import org.chromium.content_public.browser.test.NativeLibraryTestUtils; import java.net.URISyntaxException; /** * Tests for {@link GURL}. GURL relies heavily on the native implementation, and the lion's share of * the logic is tested there. This test is primarily to make sure everything is plumbed through * correctly. */ @RunWith(BaseJUnit4ClassRunner.class) @Batch(Batch.UNIT_TESTS) public class GURLJavaTest { @Mock GURL.Natives mGURLMocks; @Before public void setUp() { MockitoAnnotations.initMocks(this); NativeLibraryTestUtils.loadNativeLibraryNoBrowserProcess(); GURLJavaTestHelper.nativeInitializeICU(); } /* package */ static void deepAssertEquals(GURL expected, GURL actual) { Assert.assertEquals(expected, actual); Assert.assertEquals(expected.getScheme(), actual.getScheme()); Assert.assertEquals(expected.getUsername(), actual.getUsername()); Assert.assertEquals(expected.getPassword(), actual.getPassword()); Assert.assertEquals(expected.getHost(), actual.getHost()); Assert.assertEquals(expected.getPort(), actual.getPort()); Assert.assertEquals(expected.getPath(), actual.getPath()); Assert.assertEquals(expected.getQuery(), actual.getQuery()); Assert.assertEquals(expected.getRef(), actual.getRef()); } private String prependLengthToSerialization(String serialization) { return Integer.toString(serialization.length()) + GURL.SERIALIZER_DELIMITER + serialization; } @SmallTest @Test public void testGURLEquivalence() { GURLJavaTestHelper.nativeTestGURLEquivalence(); } // Equivalent of GURLTest.Components @SmallTest @Test @SuppressWarnings(value = "AuthLeak") public void testComponents() { GURL empty = new GURL(""); Assert.assertTrue(empty.isEmpty()); Assert.assertFalse(empty.isValid()); GURL url = new GURL("http://user:pass@google.com:99/foo;bar?q=a#ref"); Assert.assertFalse(url.isEmpty()); Assert.assertTrue(url.isValid()); Assert.assertTrue(url.getScheme().equals("http")); Assert.assertEquals("http://user:pass@google.com:99/foo;bar?q=a#ref", url.getSpec()); Assert.assertEquals("http", url.getScheme()); Assert.assertEquals("user", url.getUsername()); Assert.assertEquals("pass", url.getPassword()); Assert.assertEquals("google.com", url.getHost()); Assert.assertEquals("99", url.getPort()); Assert.assertEquals("/foo;bar", url.getPath()); Assert.assertEquals("q=a", url.getQuery()); Assert.assertEquals("ref", url.getRef()); // Test parsing userinfo with special characters. GURL urlSpecialPass = new GURL("http://user:%40!$&'()*+,;=:@google.com:12345"); Assert.assertTrue(urlSpecialPass.isValid()); // GURL canonicalizes some delimiters. Assert.assertEquals("%40!$&%27()*+,%3B%3D%3A", urlSpecialPass.getPassword()); Assert.assertEquals("google.com", urlSpecialPass.getHost()); Assert.assertEquals("12345", urlSpecialPass.getPort()); } // Equivalent of GURLTest.Empty @SmallTest @Test public void testEmpty() { GURLJni.TEST_HOOKS.setInstanceForTesting(mGURLMocks); doThrow(new RuntimeException("Should not need to parse empty URL")) .when(mGURLMocks) .init(any(), any()); GURL url = new GURL(""); Assert.assertFalse(url.isValid()); Assert.assertEquals("", url.getSpec()); Assert.assertEquals("", url.getScheme()); Assert.assertEquals("", url.getUsername()); Assert.assertEquals("", url.getPassword()); Assert.assertEquals("", url.getHost()); Assert.assertEquals("", url.getPort()); Assert.assertEquals("", url.getPath()); Assert.assertEquals("", url.getQuery()); Assert.assertEquals("", url.getRef()); GURLJni.TEST_HOOKS.setInstanceForTesting(null); } // Test that GURL and URI return the correct Origin. @SmallTest @Test @SuppressWarnings(value = "AuthLeak") public void testOrigin() throws URISyntaxException { final String kExpectedOrigin1 = "http://google.com:21/"; final String kExpectedOrigin2 = ""; GURL url1 = new GURL("filesystem:http://user:pass@google.com:21/blah#baz"); GURL url2 = new GURL("javascript:window.alert(\"hello,world\");"); URI uri = new URI("filesystem:http://user:pass@google.com:21/blah#baz"); Assert.assertEquals(kExpectedOrigin1, url1.getOrigin().getSpec()); Assert.assertEquals(kExpectedOrigin2, url2.getOrigin().getSpec()); URI origin = uri.getOrigin(); Assert.assertEquals(kExpectedOrigin1, origin.getSpec()); } @SmallTest @Test public void testWideInput() throws URISyntaxException { final String kExpectedSpec = "http://xn--1xa.com/"; GURL url = new GURL("http://\u03C0.com"); Assert.assertEquals(kExpectedSpec, url.getSpec()); Assert.assertEquals("http", url.getScheme()); Assert.assertEquals("", url.getUsername()); Assert.assertEquals("", url.getPassword()); Assert.assertEquals("xn--1xa.com", url.getHost()); Assert.assertEquals("", url.getPort()); Assert.assertEquals("/", url.getPath()); Assert.assertEquals("", url.getQuery()); Assert.assertEquals("", url.getRef()); } @SmallTest @Test @SuppressWarnings(value = "AuthLeak") public void testSerialization() { GURL cases[] = { // Common Standard URLs. new GURL("https://www.google.com"), new GURL("https://www.google.com/"), new GURL("https://www.google.com/maps.htm"), new GURL("https://www.google.com/maps/"), new GURL("https://www.google.com/index.html"), new GURL("https://www.google.com/index.html?q=maps"), new GURL("https://www.google.com/index.html#maps/"), new GURL("https://foo:bar@www.google.com/maps.htm"), new GURL("https://www.google.com/maps/au/index.html"), new GURL("https://www.google.com/maps/au/north"), new GURL("https://www.google.com/maps/au/north/"), new GURL("https://www.google.com/maps/au/index.html?q=maps#fragment/"), new GURL("http://www.google.com:8000/maps/au/index.html?q=maps#fragment/"), new GURL("https://www.google.com/maps/au/north/?q=maps#fragment"), new GURL("https://www.google.com/maps/au/north?q=maps#fragment"), // Less common standard URLs. new GURL("filesystem:http://www.google.com/temporary/bar.html?baz=22"), new GURL("file:///temporary/bar.html?baz=22"), new GURL("ftp://foo/test/index.html"), new GURL("gopher://foo/test/index.html"), new GURL("ws://foo/test/index.html"), // Non-standard, new GURL("chrome://foo/bar.html"), new GURL("httpa://foo/test/index.html"), new GURL("blob:https://foo.bar/test/index.html"), new GURL("about:blank"), new GURL("data:foobar"), new GURL("scheme:opaque_data"), // Invalid URLs. new GURL("foobar"), // URLs containing the delimiter new GURL("https://www.google.ca/" + GURL.SERIALIZER_DELIMITER + ",foo"), new GURL("https://www.foo" + GURL.SERIALIZER_DELIMITER + "bar.com"), }; GURLJni.TEST_HOOKS.setInstanceForTesting(mGURLMocks); doThrow(new RuntimeException("Should not re-initialize for deserialization when the " + "version hasn't changed.")) .when(mGURLMocks) .init(any(), any()); for (GURL url : cases) { GURL out = GURL.deserialize(url.serialize()); deepAssertEquals(url, out); } GURLJni.TEST_HOOKS.setInstanceForTesting(null); } /** * Tests that we re-parse the URL from the spec, which must always be the last token in the * serialization, if the serialization version differs. */ @SmallTest @Test public void testSerializationWithVersionSkew() { GURL url = new GURL("https://www.google.com"); String serialization = (GURL.SERIALIZER_VERSION + 1) + ",0,0,0,0,foo,https://url.bad,blah,0,".replace(',', GURL.SERIALIZER_DELIMITER) + url.getSpec(); serialization = prependLengthToSerialization(serialization); GURL out = GURL.deserialize(serialization); deepAssertEquals(url, out); } /** * Tests that fields that aren't visible to java code are correctly serialized. */ @SmallTest @Test public void testSerializationOfPrivateFields() { String serialization = GURL.SERIALIZER_VERSION + ",true," // Outer Parsed. + "1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,false,true," // Inner Parsed. + "17,18,19,20,21,22,23,24,25,26,27,28,29,30,31,32,true,false," + "chrome://foo/bar.html"; serialization = serialization.replace(',', GURL.SERIALIZER_DELIMITER); serialization = prependLengthToSerialization(serialization); GURL url = GURL.deserialize(serialization); Assert.assertEquals(url.serialize(), serialization); } /** * Tests serialized GURL truncated by storage. */ @SmallTest @Test public void testTruncatedDeserialization() { String serialization = "123,1,true,1,2,3,4,5,6,7,8,9,10"; serialization = serialization.replace(',', GURL.SERIALIZER_DELIMITER); GURL url = GURL.deserialize(serialization); Assert.assertEquals(url, GURL.emptyGURL()); } /** * Tests serialized GURL truncated by storage. */ @SmallTest @Test public void testCorruptedSerializations() { String serialization = new GURL("https://www.google.ca").serialize(); // Replace the scheme length (5) with an extra delimiter. String corruptedParsed = serialization.replace('5', GURL.SERIALIZER_DELIMITER); GURL url = GURL.deserialize(corruptedParsed); Assert.assertEquals(GURL.emptyGURL(), url); String corruptedVersion = serialization.replaceFirst(Integer.toString(GURL.SERIALIZER_VERSION), "x"); url = GURL.deserialize(corruptedVersion); Assert.assertEquals(GURL.emptyGURL(), url); } // Test that domainIs is hooked up correctly. @SmallTest @Test public void testDomainIs() { GURL url1 = new GURL("https://www.google.com"); GURL url2 = new GURL("https://www.notgoogle.com"); Assert.assertTrue(url1.domainIs("com")); Assert.assertTrue(url2.domainIs("com")); Assert.assertTrue(url1.domainIs("google.com")); Assert.assertFalse(url2.domainIs("google.com")); Assert.assertTrue(url1.domainIs("www.google.com")); Assert.assertFalse(url1.domainIs("images.google.com")); } // Tests Mojom conversion. @SmallTest @Test public void testMojomConvertion() { // Valid: Assert.assertEquals( "https://www.google.com/", new GURL("https://www.google.com/").toMojom().url); // Null: Assert.assertEquals("", new GURL(null).toMojom().url); // Empty: Assert.assertEquals("", new GURL("").toMojom().url); // Invalid: Assert.assertEquals("", new GURL(new String(new byte[] {1, 1, 1})).toMojom().url); // Too long. Assert.assertEquals("", new GURL("https://www.google.com/".concat("a".repeat(2 * 1024 * 1024))) .toMojom() .url); } }
Zhao-PengFei35/chromium_src_4
url/android/javatests/src/org/chromium/url/GURLJavaTest.java
Java
unknown
12,628
// Copyright 2020 The Chromium Authors // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. package org.chromium.url; import org.chromium.base.annotations.CalledByNative; import org.chromium.base.annotations.JNINamespace; import org.chromium.base.annotations.NativeMethods; /** * Helpers for GURLJavaTest that need to call into native code. */ @JNINamespace("url") public class GURLJavaTestHelper { @CalledByNative public static GURL createGURL(String uri) { return new GURL(uri); } public static void nativeInitializeICU() { GURLJavaTestHelperJni.get().initializeICU(); } public static void nativeTestGURLEquivalence() { GURLJavaTestHelperJni.get().testGURLEquivalence(); } @NativeMethods interface Natives { void initializeICU(); void testGURLEquivalence(); } }
Zhao-PengFei35/chromium_src_4
url/android/javatests/src/org/chromium/url/GURLJavaTestHelper.java
Java
unknown
903
// Copyright 2020 The Chromium Authors // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. package org.chromium.url; import static org.mockito.ArgumentMatchers.any; import static org.mockito.Mockito.doThrow; import androidx.test.filters.SmallTest; import org.junit.Assert; import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; import org.mockito.Mock; import org.mockito.MockitoAnnotations; import org.chromium.base.Log; import org.chromium.base.test.BaseJUnit4ClassRunner; import org.chromium.base.test.util.Batch; import java.util.Map; /** * Tests for JUnitTestGURLs. */ @RunWith(BaseJUnit4ClassRunner.class) @Batch(Batch.UNIT_TESTS) public class JUnitTestGURLsTest { private static final String TAG = "JUnitTestGURLs"; @Mock GURL.Natives mGURLMocks; @Before public void setUp() { MockitoAnnotations.initMocks(this); } private RuntimeException getErrorForGURL(GURL gurl) { String serialized = gurl.serialize(); Assert.assertEquals(-1, serialized.indexOf(",")); serialized = serialized.replace(GURL.SERIALIZER_DELIMITER, ','); return new RuntimeException("Please update the serialization in JUnitTestGURLs.java for " + gurl.getPossiblyInvalidSpec() + " to: '" + serialized + "'"); } @SmallTest @Test public void testGURLEquivalence() throws Throwable { doThrow(new RuntimeException("Deserialization required re-initialization.")) .when(mGURLMocks) .init(any(), any()); Throwable exception = null; for (Map.Entry<String, String> entry : JUnitTestGURLs.sGURLMap.entrySet()) { GURL gurl = new GURL(entry.getKey()); try { GURLJni.TEST_HOOKS.setInstanceForTesting(mGURLMocks); GURL deserialized = JUnitTestGURLs.getGURL(entry.getKey()); GURLJni.TEST_HOOKS.setInstanceForTesting(null); GURLJavaTest.deepAssertEquals(deserialized, gurl); } catch (Throwable e) { GURLJni.TEST_HOOKS.setInstanceForTesting(null); exception = getErrorForGURL(gurl); Log.e(TAG, "Error: ", exception); } } if (exception != null) throw exception; } }
Zhao-PengFei35/chromium_src_4
url/android/javatests/src/org/chromium/url/JUnitTestGURLsTest.java
Java
unknown
2,351
// Copyright 2022 The Chromium Authors // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. package org.chromium.url; import androidx.test.filters.SmallTest; import org.junit.Assert; import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; import org.chromium.base.test.BaseJUnit4ClassRunner; import org.chromium.base.test.util.Batch; import org.chromium.content_public.browser.test.NativeLibraryTestUtils; import org.chromium.mojo_base.mojom.UnguessableToken; /** * Tests for {@link Origin}. Origin relies heavily on the native implementation, and the lion's * share of the logic is tested there. This test is primarily to make sure everything is plumbed * through correctly. */ @RunWith(BaseJUnit4ClassRunner.class) @Batch(Batch.UNIT_TESTS) public class OriginJavaTest { @Before public void setUp() { NativeLibraryTestUtils.loadNativeLibraryNoBrowserProcess(); } @SmallTest @Test public void testOriginEquivalence() { OriginJavaTestHelper.testOriginEquivalence(); } @SmallTest @Test public void testCreateOpaqueOrigin() { Origin opaque = Origin.createOpaqueOrigin(); Assert.assertTrue(opaque.isOpaque()); Assert.assertEquals("", opaque.getScheme()); Assert.assertEquals("", opaque.getHost()); Assert.assertEquals(0, opaque.getPort()); } @SmallTest @Test public void testNonOpaqueMojomConstructor() { String scheme = "http"; String host = "host.name"; short port = 42; org.chromium.url.internal.mojom.Origin mojom = new org.chromium.url.internal.mojom.Origin(); mojom.scheme = scheme; mojom.host = host; mojom.port = port; Origin origin = new Origin(mojom); Assert.assertEquals(scheme, origin.getScheme()); Assert.assertEquals(host, origin.getHost()); Assert.assertEquals(port, origin.getPort()); Assert.assertFalse(origin.isOpaque()); } @SmallTest @Test public void testOpaqueMojomConstructor() { String scheme = "http"; String host = "host.name"; short port = 42; org.chromium.url.internal.mojom.Origin mojom = new org.chromium.url.internal.mojom.Origin(); mojom.scheme = scheme; mojom.host = host; mojom.port = port; UnguessableToken token = new UnguessableToken(); token.high = 3; token.low = 4; mojom.nonceIfOpaque = token; Origin origin = new Origin(mojom); Assert.assertEquals("", origin.getScheme()); Assert.assertEquals("", origin.getHost()); Assert.assertEquals(0, origin.getPort()); Assert.assertTrue(origin.isOpaque()); } @SmallTest @Test public void testCreateFromGURL() { GURL gurl = new GURL("https://host.name:61234/path"); Origin opaque = Origin.create(gurl); Assert.assertFalse(opaque.isOpaque()); Assert.assertEquals("https", opaque.getScheme()); Assert.assertEquals("host.name", opaque.getHost()); Assert.assertEquals(61234, opaque.getPort()); } }
Zhao-PengFei35/chromium_src_4
url/android/javatests/src/org/chromium/url/OriginJavaTest.java
Java
unknown
3,181
// Copyright 2022 The Chromium Authors // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. package org.chromium.url; import org.chromium.base.annotations.JNINamespace; import org.chromium.base.annotations.NativeMethods; /** * Helpers for OriginJavaTest that need to call into native code. */ @JNINamespace("url") public class OriginJavaTestHelper { public static void testOriginEquivalence() { OriginJavaTestHelperJni.get().testOriginEquivalence(); } @NativeMethods interface Natives { void testOriginEquivalence(); } }
Zhao-PengFei35/chromium_src_4
url/android/javatests/src/org/chromium/url/OriginJavaTestHelper.java
Java
unknown
614
// Copyright 2021 The Chromium Authors // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. package org.chromium.url; import org.junit.Assert; import org.junit.Test; import org.junit.runner.RunWith; import org.robolectric.annotation.Config; import org.chromium.base.test.BaseRobolectricTestRunner; /** Tests of {@link ShadowGURL}. */ @RunWith(BaseRobolectricTestRunner.class) @Config(shadows = {ShadowGURL.class}) public class ShadowGURLTest { /* package */ static void deepAssertEquals(GURL expected, GURL actual) { Assert.assertEquals(expected, actual); Assert.assertEquals(expected.getScheme(), actual.getScheme()); Assert.assertEquals(expected.getUsername(), actual.getUsername()); Assert.assertEquals(expected.getPassword(), actual.getPassword()); Assert.assertEquals(expected.getHost(), actual.getHost()); Assert.assertEquals(expected.getPort(), actual.getPort()); Assert.assertEquals(expected.getPath(), actual.getPath()); Assert.assertEquals(expected.getQuery(), actual.getQuery()); Assert.assertEquals(expected.getRef(), actual.getRef()); } @Test public void testComponents() { GURL url = new GURL(JUnitTestGURLs.SEARCH_URL); Assert.assertFalse(url.isEmpty()); Assert.assertTrue(url.isValid()); Assert.assertEquals(JUnitTestGURLs.SEARCH_URL, url.getSpec()); Assert.assertEquals("https", url.getScheme()); Assert.assertEquals("", url.getUsername()); Assert.assertEquals("", url.getPassword()); Assert.assertEquals("www.google.com", url.getHost()); Assert.assertEquals("", url.getPort()); Assert.assertEquals("/search", url.getPath()); Assert.assertEquals("q=test", url.getQuery()); Assert.assertEquals("", url.getRef()); } @Test public void testEmpty() { GURL url = new GURL(""); Assert.assertFalse(url.isValid()); Assert.assertEquals("", url.getSpec()); Assert.assertEquals("", url.getScheme()); Assert.assertEquals("", url.getUsername()); Assert.assertEquals("", url.getPassword()); Assert.assertEquals("", url.getHost()); Assert.assertEquals("", url.getPort()); Assert.assertEquals("", url.getPath()); Assert.assertEquals("", url.getQuery()); Assert.assertEquals("", url.getRef()); } @Test public void testSerialization() { GURL gurl = new GURL(JUnitTestGURLs.URL_1_WITH_PATH); GURL deserialized = GURL.deserialize(gurl.serialize()); deepAssertEquals(deserialized, gurl); } }
Zhao-PengFei35/chromium_src_4
url/android/junit/src/org/chromium/url/ShadowGURLTest.java
Java
unknown
2,672
// Copyright 2019 The Chromium Authors // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "url/origin.h" #include <cstdint> #include "base/android/jni_android.h" #include "base/android/jni_string.h" #include "base/android/scoped_java_ref.h" #include "base/memory/ptr_util.h" #include "url/android/gurl_android.h" #include "url/url_jni_headers/Origin_jni.h" namespace url { base::android::ScopedJavaLocalRef<jobject> Origin::CreateJavaObject() const { JNIEnv* env = base::android::AttachCurrentThread(); const base::UnguessableToken* token = Origin::GetNonceForSerialization(); return Java_Origin_Constructor( env, base::android::ConvertUTF8ToJavaString(env, tuple_.scheme()), base::android::ConvertUTF8ToJavaString(env, tuple_.host()), tuple_.port(), opaque(), token ? token->GetHighForSerialization() : 0, token ? token->GetLowForSerialization() : 0); } // static Origin Origin::FromJavaObject( const base::android::JavaRef<jobject>& java_origin) { JNIEnv* env = base::android::AttachCurrentThread(); std::unique_ptr<Origin> origin = base::WrapUnique<Origin>( reinterpret_cast<Origin*>(Java_Origin_toNativeOrigin(env, java_origin))); return std::move(*origin); } // static jlong Origin::CreateNative(JNIEnv* env, const base::android::JavaRef<jstring>& java_scheme, const base::android::JavaRef<jstring>& java_host, uint16_t port, bool is_opaque, uint64_t token_high_bits, uint64_t token_low_bits) { const std::string& scheme = ConvertJavaStringToUTF8(env, java_scheme); const std::string& host = ConvertJavaStringToUTF8(env, java_host); absl::optional<base::UnguessableToken> nonce_token = base::UnguessableToken::Deserialize(token_high_bits, token_low_bits); bool has_nonce = nonce_token.has_value(); CHECK(has_nonce == is_opaque); Origin::Nonce nonce; if (has_nonce) { nonce = Origin::Nonce(nonce_token.value()); } Origin origin = is_opaque ? Origin::CreateOpaqueFromNormalizedPrecursorTuple( scheme, host, port, nonce) : Origin::CreateFromNormalizedTuple(scheme, host, port); return reinterpret_cast<intptr_t>(new Origin(origin)); } static base::android::ScopedJavaLocalRef<jobject> JNI_Origin_CreateOpaque( JNIEnv* env) { return Origin().CreateJavaObject(); } static base::android::ScopedJavaLocalRef<jobject> JNI_Origin_CreateFromGURL( JNIEnv* env, const base::android::JavaParamRef<jobject>& j_gurl) { return Origin::Create(*GURLAndroid::ToNativeGURL(env, j_gurl)) .CreateJavaObject(); } static jlong JNI_Origin_CreateNative( JNIEnv* env, const base::android::JavaParamRef<jstring>& java_scheme, const base::android::JavaParamRef<jstring>& java_host, jshort port, jboolean is_opaque, jlong token_high_bits, jlong token_low_bits) { return Origin::CreateNative(env, java_scheme, java_host, port, is_opaque, token_high_bits, token_low_bits); } } // namespace url
Zhao-PengFei35/chromium_src_4
url/android/origin_android.cc
C++
unknown
3,234
// Copyright 2022 The Chromium Authors // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include <stddef.h> #include "base/android/jni_android.h" #include "base/android/jni_string.h" #include "url/gurl.h" #include "url/j_test_jni_headers/OriginJavaTestHelper_jni.h" #include "url/origin.h" namespace url { static void JNI_OriginJavaTestHelper_TestOriginEquivalence(JNIEnv* env) { Origin cases[] = { Origin(), Origin::Create(GURL("http://a.com")), Origin::Create(GURL("http://a.com:8000")), Origin::Create(GURL("scheme:host")), Origin::Create(GURL("http://a.com:8000")).DeriveNewOpaqueOrigin(), }; for (const Origin& origin : cases) { base::android::ScopedJavaLocalRef<jobject> j_origin = origin.CreateJavaObject(); Origin sameOrigin = Origin::FromJavaObject(j_origin); if (origin != sameOrigin) { std::stringstream ss; ss << "Origin not equivalent: " << origin << ", " << sameOrigin; env->ThrowNew(env->FindClass("java/lang/AssertionError"), ss.str().data()); return; } } } } // namespace url
Zhao-PengFei35/chromium_src_4
url/android/origin_java_test_helper.cc
C++
unknown
1,160
// Copyright 2019 The Chromium Authors // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "url/android/parsed_android.h" #include <jni.h> #include "base/android/jni_android.h" #include "url/gurl_jni_headers/Parsed_jni.h" using base::android::AttachCurrentThread; using base::android::JavaRef; using base::android::ScopedJavaLocalRef; namespace url { namespace { ScopedJavaLocalRef<jobject> CreateJavaParsed(JNIEnv* env, const Parsed& parsed, const JavaRef<jobject>& inner) { static constexpr bool is_signed = std::is_signed<decltype(parsed.scheme.begin)>::value; static constexpr size_t offset_size = sizeof(parsed.scheme.begin); static_assert((is_signed && sizeof(jint) >= offset_size) || (!is_signed && sizeof(jint) > offset_size), "Java size offsets for Parsed Components must be large enough " "to store the full C++ offset."); return Java_Parsed_Constructor( env, parsed.scheme.begin, parsed.scheme.len, parsed.username.begin, parsed.username.len, parsed.password.begin, parsed.password.len, parsed.host.begin, parsed.host.len, parsed.port.begin, parsed.port.len, parsed.path.begin, parsed.path.len, parsed.query.begin, parsed.query.len, parsed.ref.begin, parsed.ref.len, parsed.potentially_dangling_markup, inner); } } // namespace // static ScopedJavaLocalRef<jobject> ParsedAndroid::InitFromParsed( JNIEnv* env, const Parsed& parsed) { ScopedJavaLocalRef<jobject> inner; if (parsed.inner_parsed()) inner = CreateJavaParsed(env, *parsed.inner_parsed(), nullptr); return CreateJavaParsed(env, parsed, inner); } static jlong JNI_Parsed_CreateNative(JNIEnv* env, jint scheme_begin, jint scheme_length, jint username_begin, jint username_length, jint password_begin, jint password_length, jint host_begin, jint host_length, jint port_begin, jint port_length, jint path_begin, jint path_length, jint query_begin, jint query_length, jint ref_begin, jint ref_length, jboolean potentially_dangling_markup, jlong inner_parsed) { Parsed* parsed = new Parsed(); parsed->scheme.begin = scheme_begin; parsed->scheme.len = scheme_length; parsed->username.begin = username_begin; parsed->username.len = username_length; parsed->password.begin = password_begin; parsed->password.len = password_length; parsed->host.begin = host_begin; parsed->host.len = host_length; parsed->port.begin = port_begin; parsed->port.len = port_length; parsed->path.begin = path_begin; parsed->path.len = path_length; parsed->query.begin = query_begin; parsed->query.len = query_length; parsed->ref.begin = ref_begin; parsed->ref.len = ref_length; parsed->potentially_dangling_markup = potentially_dangling_markup; Parsed* inner = reinterpret_cast<Parsed*>(inner_parsed); if (inner) { parsed->set_inner_parsed(*inner); delete inner; } return reinterpret_cast<intptr_t>(parsed); } } // namespace url
Zhao-PengFei35/chromium_src_4
url/android/parsed_android.cc
C++
unknown
3,772
// Copyright 2019 The Chromium Authors // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #ifndef URL_ANDROID_PARSED_ANDROID_H_ #define URL_ANDROID_PARSED_ANDROID_H_ #include "base/android/scoped_java_ref.h" #include "url/third_party/mozilla/url_parse.h" namespace url { class ParsedAndroid { public: static base::android::ScopedJavaLocalRef<jobject> InitFromParsed( JNIEnv* env, const Parsed& parsed); }; } // namespace url #endif // URL_ANDROID_PARSED_ANDROID_H_
Zhao-PengFei35/chromium_src_4
url/android/parsed_android.h
C++
unknown
541
// Copyright 2022 The Chromium Authors // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include <jni.h> #include "base/android/base_jni_onload.h" #include "base/android/jni_android.h" extern "C" JNI_EXPORT jint JNI_OnLoad(JavaVM* vm, void* reserved) { base::android::InitVM(vm); base::android::OnJNIOnLoadInit(); // TODO(1223993): Initialize GURL schemes, like in // content::RegisterContentSchemes(). return JNI_VERSION_1_4; }
Zhao-PengFei35/chromium_src_4
url/android/robolectric_test_main.cc
C++
unknown
500
// Copyright 2020 The Chromium Authors // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. package org.chromium.url; import java.util.Collections; import java.util.HashMap; import java.util.Map; /** * A Helper class for JUnit tests to be able to use GURLs without requiring native initialization. * This should be used sparingly, when converting junit tests to Batched Instrumentation tests is * not feasible. * * If any more complex GURL behaviour is tested, like comparing Origins, the test should be written * as an Instrumentation test instead - you should never mock GURL. */ public class JUnitTestGURLs { // In order to add a test URL: // 1. Add the URL String as a constant here. // 2. Add the constant to the map below, with a placeholder string for the GURL serialization. // 3. Run JUnitTestGURLsTest (eg. './tools/autotest.py -C out/Debug JUnitTestGURLsTest'). // 4. Check logcat output or test exception for the correct serialization String, and place it // in the map. public static final String EXAMPLE_URL = "https://www.example.com/"; public static final String HTTP_URL = "http://www.example.com/"; public static final String URL_1 = "https://www.one.com/"; public static final String URL_1_NUMERAL = "https://www.1.com/"; public static final String URL_1_WITH_PATH = "https://www.one.com/some_path.html"; public static final String URL_2 = "https://www.two.com/"; public static final String URL_3 = "https://www.three.com/"; public static final String MAPS_URL = "https://maps.google.com/"; public static final String SEARCH_URL = "https://www.google.com/search?q=test"; public static final String SEARCH_2_URL = "https://www.google.com/search?q=query"; public static final String INITIAL_URL = "https://initial.com"; public static final String SPECULATED_URL = "https://speculated.com"; public static final String NTP_URL = "chrome://newtab/"; public static final String NTP_NATIVE_URL = "chrome-native://newtab/"; public static final String DOM_DISILLER_URL = "chrome-distiller://url"; public static final String RED_1 = "https://www.red.com/page1"; public static final String RED_2 = "https://www.red.com/page2"; public static final String RED_3 = "https://www.red.com/page3"; public static final String BLUE_1 = "https://www.blue.com/page1"; public static final String BLUE_2 = "https://www.blue.com/page2"; public static final String BLUE_3 = "https://www.blue.com/page3"; public static final String AMP_URL = "https://www.google.com/amp/www.nyt.com/ampthml/blogs.html"; public static final String AMP_CACHE_URL = "https://www.google.com/amp/s/www.nyt.com/ampthml/blogs.html"; public static final String TEXT_FRAGMENT_URL = "https://www.example.com/#:~:text=selector"; public static final String MULTI_TEXT_FRAGMENT_URL = "https://www.example.com/#:~:text=selector1&text=selector2&text=selector3"; public static final String INVALID_URL = "http://0x100.0/"; public static final String GOOGLE_URL = "http://www.google.com/"; public static final String GOOGLE_URL_DOGS = "http://www.google.com/dogs"; public static final String GOOGLE_URL_DOGS_FUN = "http://www.google.com/dogs-are-fun"; public static final String GOOGLE_URL_DOG = "http://www.google.com/dog"; public static final String GOOGLE_URL_CAT = "http://www.google.com/cat"; public static final String GOOGLE_URL_PIG = "http://www.google.com/pig"; public static final String ABOUT_BLANK = "about:blank"; public static final String CHROME_ABOUT = "chrome://about"; // Map of URL string to GURL serialization. /* package */ static final Map<String, String> sGURLMap; static { Map<String, String> map = new HashMap<>(); map.put(EXAMPLE_URL, "82,1,true,0,5,0,-1,0,-1,8,15,0,-1,23,1,0,-1,0,-1," + "false,false,https://www.example.com/"); map.put(HTTP_URL, "81,1,true,0,4,0,-1,0,-1,7,15,0,-1,22,1,0,-1,0,-1," + "false,false,http://www.example.com/"); map.put(URL_1, "78,1,true,0,5,0,-1,0,-1,8,11,0,-1,19,1,0,-1,0,-1," + "false,false,https://www.one.com/"); map.put(URL_1_NUMERAL, "75,1,true,0,5,0,-1,0,-1,8,9,0,-1,17,1,0,-1,0,-1," + "false,false,https://www.1.com/"); map.put(URL_1_WITH_PATH, "93,1,true,0,5,0,-1,0,-1,8,11,0,-1,19,15,0,-1,0,-1," + "false,false,https://www.one.com/some_path.html"); map.put(URL_2, "78,1,true,0,5,0,-1,0,-1,8,11,0,-1,19,1,0,-1,0,-1," + "false,false,https://www.two.com/"); map.put(URL_3, "80,1,true,0,5,0,-1,0,-1,8,13,0,-1,21,1,0,-1,0,-1,false,false,https://www.three.com/"); map.put(RED_1, "83,1,true,0,5,0,-1,0,-1,8,11,0,-1,19,6,0,-1,0,-1," + "false,false,https://www.red.com/page1"); map.put(RED_2, "83,1,true,0,5,0,-1,0,-1,8,11,0,-1,19,6,0,-1,0,-1," + "false,false,https://www.red.com/page2"); map.put(RED_3, "83,1,true,0,5,0,-1,0,-1,8,11,0,-1,19,6,0,-1,0,-1," + "false,false,https://www.red.com/page3"); map.put(BLUE_1, "84,1,true,0,5,0,-1,0,-1,8,12,0,-1,20,6,0,-1,0,-1," + "false,false,https://www.blue.com/page1"); map.put(BLUE_2, "84,1,true,0,5,0,-1,0,-1,8,12,0,-1,20,6,0,-1,0,-1," + "false,false,https://www.blue.com/page2"); map.put(BLUE_3, "84,1,true,0,5,0,-1,0,-1,8,12,0,-1,20,6,0,-1,0,-1," + "false,false,https://www.blue.com/page3"); map.put(SEARCH_URL, "94,1,true,0,5,0,-1,0,-1,8,14,0,-1,22,7,30,6,0,-1," + "false,false,https://www.google.com/search?q=test"); map.put(SEARCH_2_URL, "95,1,true,0,5,0,-1,0,-1,8,14,0,-1,22,7,30,7,0,-1," + "false,false,https://www.google.com/search?q=query"); map.put(INITIAL_URL, "78,1,true,0,5,0,-1,0,-1,8,11,0,-1,19,1,0,-1,0,-1," + "false,false,https://initial.com/"); map.put(SPECULATED_URL, "81,1,true,0,5,0,-1,0,-1,8,14,0,-1,22,1,0,-1,0,-1," + "false,false,https://speculated.com/"); map.put(NTP_URL, "73,1,true,0,6,0,-1,0,-1,9,6,0,-1,15,1,0,-1,0,-1," + "false,false,chrome://newtab/"); map.put(NTP_NATIVE_URL, "82,1,true,0,13,0,-1,0,-1,16,6,0,-1,22,1,0,-1,0,-1,false,false," + "chrome-native://newtab/"); map.put(DOM_DISILLER_URL, "82,1,true,0,16,0,-1,0,-1,19,3,0,-1,22,1,0,-1,0,-1,false,false," + "chrome-distiller://url/"); map.put(MAPS_URL, "82,1,true,0,5,0,-1,0,-1,8,15,0,-1,23,1,0,-1,0,-1,false,false,https://maps.google.com/"); map.put(AMP_URL, "116,1,true,0,5,0,-1,0,-1,8,14,0,-1,22,35,0,-1,0,-1,false,false,https://www.google.com/amp/www.nyt.com/ampthml/blogs.html"); map.put(AMP_CACHE_URL, "118,1,true,0,5,0,-1,0,-1,8,14,0,-1,22,37,0,-1,0,-1,false,false,https://www.google.com/amp/s/www.nyt.com/ampthml/blogs.html"); map.put(TEXT_FRAGMENT_URL, "100,1,true,0,5,0,-1,0,-1,8,15,0,-1,23,1,0,-1,25,16,false,false,https://www.example.com/#:~:text=selector"); map.put(MULTI_TEXT_FRAGMENT_URL, "131,1,true,0,5,0,-1,0,-1,8,15,0,-1,23,1,0,-1,25,47,false,false,https://www.example.com/#:~:text=selector1&text=selector2&text=selector3"); map.put(INVALID_URL, "73,1,false,0,4,0,-1,0,-1,7,7,0,-1,14,1,0,-1,0,-1,false,false,http://0x100.0/"); map.put(GOOGLE_URL, "80,1,true,0,4,0,-1,0,-1,7,14,0,-1,21,1,0,-1,0,-1,false,false,http://www.google.com/"); map.put(GOOGLE_URL_DOGS, "84,1,true,0,4,0,-1,0,-1,7,14,0,-1,21,5,0,-1,0,-1,false,false,http://www.google.com/dogs"); map.put(GOOGLE_URL_DOGS_FUN, "93,1,true,0,4,0,-1,0,-1,7,14,0,-1,21,13,0,-1,0,-1,false,false,http://www.google.com/dogs-are-fun"); map.put(GOOGLE_URL_DOG, "83,1,true,0,4,0,-1,0,-1,7,14,0,-1,21,4,0,-1,0,-1,false,false,http://www.google.com/dog"); map.put(GOOGLE_URL_CAT, "83,1,true,0,4,0,-1,0,-1,7,14,0,-1,21,4,0,-1,0,-1,false,false,http://www.google.com/cat"); map.put(GOOGLE_URL_PIG, "83,1,true,0,4,0,-1,0,-1,7,14,0,-1,21,4,0,-1,0,-1,false,false,http://www.google.com/pig"); map.put(ABOUT_BLANK, "68,1,true,0,5,0,-1,0,-1,0,-1,0,-1,6,5,0,-1,0,-1,false,false,about:blank"); map.put(CHROME_ABOUT, "72,1,true,0,6,0,-1,0,-1,9,5,0,-1,14,1,0,-1,0,-1,false,false,chrome://about/"); sGURLMap = Collections.unmodifiableMap(map); } /** * @return the GURL resulting from parsing the provided url. Must be registered in |sGURLMap|. */ public static GURL getGURL(String url) { String serialized = sGURLMap.get(url); if (serialized == null) { throw new IllegalArgumentException("URL " + url + " not found"); } serialized = serialized.replace(',', GURL.SERIALIZER_DELIMITER); GURL gurl = GURL.deserialize(serialized); // If you're here looking to use an empty GURL, just use GURL.emptyGURL() directly. if (gurl.isEmpty()) { throw new RuntimeException("Could not deserialize: " + serialized); } return gurl; } }
Zhao-PengFei35/chromium_src_4
url/android/test/java/src/org/chromium/url/JUnitTestGURLs.java
Java
unknown
9,900
// Copyright 2021 The Chromium Authors // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. package org.chromium.url; import org.robolectric.annotation.Implementation; import org.robolectric.annotation.Implements; import org.chromium.url.GURL.Natives; /** * Shadow of {@link GURL}. Lets Robolectric tests use {@code GURL} without the native libraries * loaded. * * <p>This shadow can create only GURLs listed in {@link JUnitTestGURLs}. */ @Implements(GURL.class) public class ShadowGURL { /** * The {@link GURL.Natives} implementation used by a shadowed {@link GURL}. */ private static class NativesImpl implements GURL.Natives { @Override public void init(String url, GURL target) { target.initForTesting(JUnitTestGURLs.getGURL(url)); } @Override public void getOrigin(String spec, boolean isValid, long nativeParsed, GURL target) { throw new UnsupportedOperationException( "ShadowGURL.NativesImpl#getOrigin is not implemented"); } @Override public boolean domainIs(String spec, boolean isValid, long nativeParsed, String domain) { throw new UnsupportedOperationException( "ShadowGURL.NativesImpl#domainIs is not implemented"); } @Override public long createNative(String spec, boolean isValid, long nativeParsed) { throw new UnsupportedOperationException( "ShadowGURL.NativesImpl#createNative is not implemented"); } } private static final NativesImpl sNativesInstance = new NativesImpl(); /** * We could instead shadow {@code GURLJni#get}, but that would require tests using this to load * both shadows. */ @Implementation protected static Natives getNatives() { return sNativesInstance; } @Implementation protected static void ensureNativeInitializedForGURL() { // Skip native initialization. } }
Zhao-PengFei35/chromium_src_4
url/android/test/java/src/org/chromium/url/ShadowGURL.java
Java
unknown
2,055
// Copyright 2013 The Chromium Authors // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "url/gurl.h" #include <stddef.h> #include <algorithm> #include <memory> #include <ostream> #include <utility> #include "base/check_op.h" #include "base/no_destructor.h" #include "base/strings/string_piece.h" #include "base/strings/string_util.h" #include "base/trace_event/base_tracing.h" #include "base/trace_event/memory_usage_estimator.h" #include "url/url_canon_stdstring.h" #include "url/url_util.h" GURL::GURL() : is_valid_(false) { } GURL::GURL(const GURL& other) : spec_(other.spec_), is_valid_(other.is_valid_), parsed_(other.parsed_) { if (other.inner_url_) inner_url_ = std::make_unique<GURL>(*other.inner_url_); // Valid filesystem urls should always have an inner_url_. DCHECK(!is_valid_ || !SchemeIsFileSystem() || inner_url_); } GURL::GURL(GURL&& other) noexcept : spec_(std::move(other.spec_)), is_valid_(other.is_valid_), parsed_(other.parsed_), inner_url_(std::move(other.inner_url_)) { other.is_valid_ = false; other.parsed_ = url::Parsed(); } GURL::GURL(base::StringPiece url_string) { InitCanonical(url_string, true); } GURL::GURL(base::StringPiece16 url_string) { InitCanonical(url_string, true); } GURL::GURL(const std::string& url_string, RetainWhiteSpaceSelector) { InitCanonical(url_string, false); } GURL::GURL(const char* canonical_spec, size_t canonical_spec_len, const url::Parsed& parsed, bool is_valid) : spec_(canonical_spec, canonical_spec_len), is_valid_(is_valid), parsed_(parsed) { InitializeFromCanonicalSpec(); } GURL::GURL(std::string canonical_spec, const url::Parsed& parsed, bool is_valid) : spec_(std::move(canonical_spec)), is_valid_(is_valid), parsed_(parsed) { InitializeFromCanonicalSpec(); } template <typename T, typename CharT> void GURL::InitCanonical(T input_spec, bool trim_path_end) { url::StdStringCanonOutput output(&spec_); is_valid_ = url::Canonicalize( input_spec.data(), static_cast<int>(input_spec.length()), trim_path_end, NULL, &output, &parsed_); output.Complete(); // Must be done before using string. if (is_valid_ && SchemeIsFileSystem()) { inner_url_ = std::make_unique<GURL>(spec_.data(), parsed_.Length(), *parsed_.inner_parsed(), true); } // Valid URLs always have non-empty specs. DCHECK(!is_valid_ || !spec_.empty()); } void GURL::InitializeFromCanonicalSpec() { if (is_valid_ && SchemeIsFileSystem()) { inner_url_ = std::make_unique<GURL>(spec_.data(), parsed_.Length(), *parsed_.inner_parsed(), true); } #ifndef NDEBUG // For testing purposes, check that the parsed canonical URL is identical to // what we would have produced. Skip checking for invalid URLs have no meaning // and we can't always canonicalize then reproducibly. if (is_valid_) { DCHECK(!spec_.empty()); url::Component scheme; // We can't do this check on the inner_url of a filesystem URL, as // canonical_spec actually points to the start of the outer URL, so we'd // end up with infinite recursion in this constructor. if (!url::FindAndCompareScheme(spec_.data(), spec_.length(), url::kFileSystemScheme, &scheme) || scheme.begin == parsed_.scheme.begin) { // We need to retain trailing whitespace on path URLs, as the |parsed_| // spec we originally received may legitimately contain trailing white- // space on the path or components e.g. if the #ref has been // removed from a "foo:hello #ref" URL (see http://crbug.com/291747). GURL test_url(spec_, RETAIN_TRAILING_PATH_WHITEPACE); DCHECK_EQ(test_url.is_valid_, is_valid_); DCHECK_EQ(test_url.spec_, spec_); DCHECK_EQ(test_url.parsed_.scheme, parsed_.scheme); DCHECK_EQ(test_url.parsed_.username, parsed_.username); DCHECK_EQ(test_url.parsed_.password, parsed_.password); DCHECK_EQ(test_url.parsed_.host, parsed_.host); DCHECK_EQ(test_url.parsed_.port, parsed_.port); DCHECK_EQ(test_url.parsed_.path, parsed_.path); DCHECK_EQ(test_url.parsed_.query, parsed_.query); DCHECK_EQ(test_url.parsed_.ref, parsed_.ref); } } #endif } GURL::~GURL() = default; GURL& GURL::operator=(const GURL& other) { spec_ = other.spec_; is_valid_ = other.is_valid_; parsed_ = other.parsed_; if (!other.inner_url_) inner_url_.reset(); else if (inner_url_) *inner_url_ = *other.inner_url_; else inner_url_ = std::make_unique<GURL>(*other.inner_url_); return *this; } GURL& GURL::operator=(GURL&& other) noexcept { spec_ = std::move(other.spec_); is_valid_ = other.is_valid_; parsed_ = other.parsed_; inner_url_ = std::move(other.inner_url_); other.is_valid_ = false; other.parsed_ = url::Parsed(); return *this; } const std::string& GURL::spec() const { if (is_valid_ || spec_.empty()) return spec_; DCHECK(false) << "Trying to get the spec of an invalid URL!"; return base::EmptyString(); } bool GURL::operator<(const GURL& other) const { return spec_ < other.spec_; } bool GURL::operator>(const GURL& other) const { return spec_ > other.spec_; } // Note: code duplicated below (it's inconvenient to use a template here). GURL GURL::Resolve(base::StringPiece relative) const { // Not allowed for invalid URLs. if (!is_valid_) return GURL(); GURL result; url::StdStringCanonOutput output(&result.spec_); if (!url::ResolveRelative(spec_.data(), static_cast<int>(spec_.length()), parsed_, relative.data(), static_cast<int>(relative.length()), nullptr, &output, &result.parsed_)) { // Error resolving, return an empty URL. return GURL(); } output.Complete(); result.is_valid_ = true; if (result.SchemeIsFileSystem()) { result.inner_url_ = std::make_unique<GURL>(result.spec_.data(), result.parsed_.Length(), *result.parsed_.inner_parsed(), true); } return result; } // Note: code duplicated above (it's inconvenient to use a template here). GURL GURL::Resolve(base::StringPiece16 relative) const { // Not allowed for invalid URLs. if (!is_valid_) return GURL(); GURL result; url::StdStringCanonOutput output(&result.spec_); if (!url::ResolveRelative(spec_.data(), static_cast<int>(spec_.length()), parsed_, relative.data(), static_cast<int>(relative.length()), nullptr, &output, &result.parsed_)) { // Error resolving, return an empty URL. return GURL(); } output.Complete(); result.is_valid_ = true; if (result.SchemeIsFileSystem()) { result.inner_url_ = std::make_unique<GURL>(result.spec_.data(), result.parsed_.Length(), *result.parsed_.inner_parsed(), true); } return result; } // Note: code duplicated below (it's inconvenient to use a template here). GURL GURL::ReplaceComponents(const Replacements& replacements) const { GURL result; // Not allowed for invalid URLs. if (!is_valid_) return GURL(); url::StdStringCanonOutput output(&result.spec_); result.is_valid_ = url::ReplaceComponents( spec_.data(), static_cast<int>(spec_.length()), parsed_, replacements, NULL, &output, &result.parsed_); output.Complete(); result.ProcessFileSystemURLAfterReplaceComponents(); return result; } // Note: code duplicated above (it's inconvenient to use a template here). GURL GURL::ReplaceComponents(const ReplacementsW& replacements) const { GURL result; // Not allowed for invalid URLs. if (!is_valid_) return GURL(); url::StdStringCanonOutput output(&result.spec_); result.is_valid_ = url::ReplaceComponents( spec_.data(), static_cast<int>(spec_.length()), parsed_, replacements, NULL, &output, &result.parsed_); output.Complete(); result.ProcessFileSystemURLAfterReplaceComponents(); return result; } void GURL::ProcessFileSystemURLAfterReplaceComponents() { if (!is_valid_) return; if (SchemeIsFileSystem()) { inner_url_ = std::make_unique<GURL>(spec_.data(), parsed_.Length(), *parsed_.inner_parsed(), true); } } GURL GURL::DeprecatedGetOriginAsURL() const { // This doesn't make sense for invalid or nonstandard URLs, so return // the empty URL. if (!is_valid_ || !IsStandard()) return GURL(); if (SchemeIsFileSystem()) return inner_url_->DeprecatedGetOriginAsURL(); Replacements replacements; replacements.ClearUsername(); replacements.ClearPassword(); replacements.ClearPath(); replacements.ClearQuery(); replacements.ClearRef(); return ReplaceComponents(replacements); } GURL GURL::GetAsReferrer() const { if (!is_valid() || !IsReferrerScheme(spec_.data(), parsed_.scheme)) return GURL(); if (!has_ref() && !has_username() && !has_password()) return GURL(*this); Replacements replacements; replacements.ClearRef(); replacements.ClearUsername(); replacements.ClearPassword(); return ReplaceComponents(replacements); } GURL GURL::GetWithEmptyPath() const { // This doesn't make sense for invalid or nonstandard URLs, so return // the empty URL. if (!is_valid_ || !IsStandard()) return GURL(); // We could optimize this since we know that the URL is canonical, and we are // appending a canonical path, so avoiding re-parsing. GURL other(*this); if (parsed_.path.len == 0) return other; // Clear everything after the path. other.parsed_.query.reset(); other.parsed_.ref.reset(); // Set the path, since the path is longer than one, we can just set the // first character and resize. other.spec_[other.parsed_.path.begin] = '/'; other.parsed_.path.len = 1; other.spec_.resize(other.parsed_.path.begin + 1); return other; } GURL GURL::GetWithoutFilename() const { return Resolve("."); } GURL GURL::GetWithoutRef() const { if (!has_ref()) return GURL(*this); Replacements replacements; replacements.ClearRef(); return ReplaceComponents(replacements); } bool GURL::IsStandard() const { return url::IsStandard(spec_.data(), parsed_.scheme); } bool GURL::IsAboutBlank() const { return IsAboutUrl(url::kAboutBlankPath); } bool GURL::IsAboutSrcdoc() const { return IsAboutUrl(url::kAboutSrcdocPath); } bool GURL::SchemeIs(base::StringPiece lower_ascii_scheme) const { DCHECK(base::IsStringASCII(lower_ascii_scheme)); DCHECK(base::ToLowerASCII(lower_ascii_scheme) == lower_ascii_scheme); if (!has_scheme()) return lower_ascii_scheme.empty(); return scheme_piece() == lower_ascii_scheme; } bool GURL::SchemeIsHTTPOrHTTPS() const { return SchemeIs(url::kHttpsScheme) || SchemeIs(url::kHttpScheme); } bool GURL::SchemeIsWSOrWSS() const { return SchemeIs(url::kWsScheme) || SchemeIs(url::kWssScheme); } bool GURL::SchemeIsCryptographic() const { if (!has_scheme()) return false; return SchemeIsCryptographic(scheme_piece()); } bool GURL::SchemeIsCryptographic(base::StringPiece lower_ascii_scheme) { DCHECK(base::IsStringASCII(lower_ascii_scheme)); DCHECK(base::ToLowerASCII(lower_ascii_scheme) == lower_ascii_scheme); return lower_ascii_scheme == url::kHttpsScheme || lower_ascii_scheme == url::kWssScheme; } bool GURL::SchemeIsLocal() const { // The `filesystem:` scheme is not in the Fetch spec, but Chromium still // supports it in large part. It should be treated as a local scheme too. return SchemeIs(url::kAboutScheme) || SchemeIs(url::kBlobScheme) || SchemeIs(url::kDataScheme) || SchemeIs(url::kFileSystemScheme); } int GURL::IntPort() const { if (parsed_.port.is_nonempty()) return url::ParsePort(spec_.data(), parsed_.port); return url::PORT_UNSPECIFIED; } int GURL::EffectiveIntPort() const { int int_port = IntPort(); if (int_port == url::PORT_UNSPECIFIED && IsStandard()) return url::DefaultPortForScheme(spec_.data() + parsed_.scheme.begin, parsed_.scheme.len); return int_port; } std::string GURL::ExtractFileName() const { url::Component file_component; url::ExtractFileName(spec_.data(), parsed_.path, &file_component); return ComponentString(file_component); } base::StringPiece GURL::PathForRequestPiece() const { DCHECK(parsed_.path.is_nonempty()) << "Canonical path for requests should be non-empty"; if (parsed_.ref.is_valid()) { // Clip off the reference when it exists. The reference starts after the // #-sign, so we have to subtract one to also remove it. return base::StringPiece(spec_).substr( parsed_.path.begin, parsed_.ref.begin - parsed_.path.begin - 1); } // Compute the actual path length, rather than depending on the spec's // terminator. If we're an inner_url, our spec continues on into our outer // URL's path/query/ref. int path_len = parsed_.path.len; if (parsed_.query.is_valid()) path_len = parsed_.query.end() - parsed_.path.begin; return base::StringPiece(spec_).substr(parsed_.path.begin, path_len); } std::string GURL::PathForRequest() const { return std::string(PathForRequestPiece()); } std::string GURL::HostNoBrackets() const { return std::string(HostNoBracketsPiece()); } base::StringPiece GURL::HostNoBracketsPiece() const { // If host looks like an IPv6 literal, strip the square brackets. url::Component h(parsed_.host); if (h.len >= 2 && spec_[h.begin] == '[' && spec_[h.end() - 1] == ']') { h.begin++; h.len -= 2; } return ComponentStringPiece(h); } std::string GURL::GetContent() const { return std::string(GetContentPiece()); } base::StringPiece GURL::GetContentPiece() const { if (!is_valid_) return base::StringPiece(); url::Component content_component = parsed_.GetContent(); if (!SchemeIs(url::kJavaScriptScheme) && parsed_.ref.is_valid()) content_component.len -= parsed_.ref.len + 1; return ComponentStringPiece(content_component); } bool GURL::HostIsIPAddress() const { return is_valid_ && url::HostIsIPAddress(host_piece()); } const GURL& GURL::EmptyGURL() { static base::NoDestructor<GURL> empty_gurl; return *empty_gurl; } bool GURL::DomainIs(base::StringPiece canonical_domain) const { if (!is_valid_) return false; // FileSystem URLs have empty host_piece, so check this first. if (inner_url_ && SchemeIsFileSystem()) return inner_url_->DomainIs(canonical_domain); return url::DomainIs(host_piece(), canonical_domain); } bool GURL::EqualsIgnoringRef(const GURL& other) const { int ref_position = parsed_.CountCharactersBefore(url::Parsed::REF, true); int ref_position_other = other.parsed_.CountCharactersBefore(url::Parsed::REF, true); return base::StringPiece(spec_).substr(0, ref_position) == base::StringPiece(other.spec_).substr(0, ref_position_other); } void GURL::Swap(GURL* other) { spec_.swap(other->spec_); std::swap(is_valid_, other->is_valid_); std::swap(parsed_, other->parsed_); inner_url_.swap(other->inner_url_); } size_t GURL::EstimateMemoryUsage() const { return base::trace_event::EstimateMemoryUsage(spec_) + base::trace_event::EstimateMemoryUsage(inner_url_) + (parsed_.inner_parsed() ? sizeof(url::Parsed) : 0); } bool GURL::IsAboutUrl(base::StringPiece allowed_path) const { if (!SchemeIs(url::kAboutScheme)) return false; if (has_host() || has_username() || has_password() || has_port()) return false; return IsAboutPath(path_piece(), allowed_path); } // static bool GURL::IsAboutPath(base::StringPiece actual_path, base::StringPiece allowed_path) { if (!base::StartsWith(actual_path, allowed_path)) return false; if (actual_path.size() == allowed_path.size()) { DCHECK_EQ(actual_path, allowed_path); return true; } if ((actual_path.size() == allowed_path.size() + 1) && actual_path.back() == '/') { DCHECK_EQ(actual_path, std::string(allowed_path) + '/'); return true; } return false; } void GURL::WriteIntoTrace(perfetto::TracedValue context) const { std::move(context).WriteString(possibly_invalid_spec()); } #if BUILDFLAG(IS_OHOS) bool GURL::SchemeIsCodeCacheEnabled() const { return url::IsCodeCacheEnabledScheme(scheme()); } #endif std::ostream& operator<<(std::ostream& out, const GURL& url) { return out << url.possibly_invalid_spec(); } bool operator==(const GURL& x, const GURL& y) { return x.possibly_invalid_spec() == y.possibly_invalid_spec(); } bool operator!=(const GURL& x, const GURL& y) { return !(x == y); } bool operator==(const GURL& x, const base::StringPiece& spec) { DCHECK_EQ(GURL(spec).possibly_invalid_spec(), spec) << "Comparisons of GURLs and strings must ensure as a precondition that " "the string is fully canonicalized."; return x.possibly_invalid_spec() == spec; } bool operator==(const base::StringPiece& spec, const GURL& x) { return x == spec; } bool operator!=(const GURL& x, const base::StringPiece& spec) { return !(x == spec); } bool operator!=(const base::StringPiece& spec, const GURL& x) { return !(x == spec); } namespace url::debug { ScopedUrlCrashKey::ScopedUrlCrashKey(base::debug::CrashKeyString* crash_key, const GURL& url) : scoped_string_value_( crash_key, url.is_empty() ? "<empty url>" : url.possibly_invalid_spec()) {} ScopedUrlCrashKey::~ScopedUrlCrashKey() = default; } // namespace url::debug
Zhao-PengFei35/chromium_src_4
url/gurl.cc
C++
unknown
17,725
// Copyright 2013 The Chromium Authors // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #ifndef URL_GURL_H_ #define URL_GURL_H_ #include <stddef.h> #include <iosfwd> #include <memory> #include <string> #include "base/component_export.h" #include "base/debug/alias.h" #include "base/debug/crash_logging.h" #include "base/strings/string_piece.h" #include "base/trace_event/base_tracing_forward.h" #include "url/third_party/mozilla/url_parse.h" #include "url/url_canon.h" #include "url/url_canon_stdstring.h" #include "url/url_constants.h" // Represents a URL. GURL is Google's URL parsing library. // // A parsed canonicalized URL is guaranteed to be UTF-8. Any non-ASCII input // characters are UTF-8 encoded and % escaped to ASCII. // // The string representation of a URL is called the spec(). Getting the // spec will assert if the URL is invalid to help protect against malicious // URLs. If you want the "best effort" canonicalization of an invalid URL, you // can use possibly_invalid_spec(). Test validity with is_valid(). Data and // javascript URLs use GetContent() to extract the data. // // This class has existence checkers and getters for the various components of // a URL. Existence is different than being nonempty. "http://www.google.com/?" // has a query that just happens to be empty, and has_query() will return true // while the query getters will return the empty string. // // Prefer not to modify a URL using string operations (though sometimes this is // unavoidable). Instead, use ReplaceComponents which can replace or delete // multiple parts of a URL in one step, doesn't re-canonicalize unchanged // sections, and avoids some screw-ups. An example is creating a URL with a // path that contains a literal '#'. Using string concatenation will generate a // URL with a truncated path and a reference fragment, while ReplaceComponents // will know to escape this and produce the desired result. class COMPONENT_EXPORT(URL) GURL { public: typedef url::StringPieceReplacements<char> Replacements; typedef url::StringPieceReplacements<char16_t> ReplacementsW; // Creates an empty, invalid URL. GURL(); // Copy construction is relatively inexpensive, with most of the time going // to reallocating the string. It does not re-parse. GURL(const GURL& other); GURL(GURL&& other) noexcept; // The strings to this contructor should be UTF-8 / UTF-16. explicit GURL(base::StringPiece url_string); explicit GURL(base::StringPiece16 url_string); // Constructor for URLs that have already been parsed and canonicalized. This // is used for conversions from KURL, for example. The caller must supply all // information associated with the URL, which must be correct and consistent. GURL(const char* canonical_spec, size_t canonical_spec_len, const url::Parsed& parsed, bool is_valid); // Notice that we take the canonical_spec by value so that we can convert // from WebURL without copying the string. When we call this constructor // we pass in a temporary std::string, which lets the compiler skip the // copy and just move the std::string into the function argument. In the // implementation, we use std::move to move the data into the GURL itself, // which means we end up with zero copies. GURL(std::string canonical_spec, const url::Parsed& parsed, bool is_valid); ~GURL(); GURL& operator=(const GURL& other); GURL& operator=(GURL&& other) noexcept; // Returns true when this object represents a valid parsed URL. When not // valid, other functions will still succeed, but you will not get canonical // data out in the format you may be expecting. Instead, we keep something // "reasonable looking" so that the user can see how it's busted if // displayed to them. bool is_valid() const { return is_valid_; } // Returns true if the URL is zero-length. Note that empty URLs are also // invalid, and is_valid() will return false for them. This is provided // because some users may want to treat the empty case differently. bool is_empty() const { return spec_.empty(); } // Returns the raw spec, i.e., the full text of the URL, in canonical UTF-8, // if the URL is valid. If the URL is not valid, this will assert and return // the empty string (for safety in release builds, to keep them from being // misused which might be a security problem). // // The URL will be ASCII (non-ASCII characters will be %-escaped UTF-8). // // The exception is for empty() URLs (which are !is_valid()) but this will // return the empty string without asserting. // // Use invalid_spec() below to get the unusable spec of an invalid URL. This // separation is designed to prevent errors that may cause security problems // that could result from the mistaken use of an invalid URL. const std::string& spec() const; // Returns the potentially invalid spec for a the URL. This spec MUST NOT be // modified or sent over the network. It is designed to be displayed in error // messages to the user, as the appearance of the spec may explain the error. // If the spec is valid, the valid spec will be returned. // // The returned string is guaranteed to be valid UTF-8. const std::string& possibly_invalid_spec() const { return spec_; } // Getter for the raw parsed structure. This allows callers to locate parts // of the URL within the spec themselves. Most callers should consider using // the individual component getters below. // // The returned parsed structure will reference into the raw spec, which may // or may not be valid. If you are using this to index into the spec, BE // SURE YOU ARE USING possibly_invalid_spec() to get the spec, and that you // don't do anything "important" with invalid specs. const url::Parsed& parsed_for_possibly_invalid_spec() const { return parsed_; } // Allows GURL to used as a key in STL (for example, a std::set or std::map). bool operator<(const GURL& other) const; bool operator>(const GURL& other) const; // Resolves a URL that's possibly relative to this object's URL, and returns // it. Absolute URLs are also handled according to the rules of URLs on web // pages. // // It may be impossible to resolve the URLs properly. If the input is not // "standard" (IsStandard() == false) and the input looks relative, we can't // resolve it. In these cases, the result will be an empty, invalid GURL. // // The result may also be a nonempty, invalid URL if the input has some kind // of encoding error. In these cases, we will try to construct a "good" URL // that may have meaning to the user, but it will be marked invalid. // // It is an error to resolve a URL relative to an invalid URL. The result // will be the empty URL. GURL Resolve(base::StringPiece relative) const; GURL Resolve(base::StringPiece16 relative) const; // Creates a new GURL by replacing the current URL's components with the // supplied versions. See the Replacements class in url_canon.h for more. // // These are not particularly quick, so avoid doing mutations when possible. // Prefer the 8-bit version when possible. // // It is an error to replace components of an invalid URL. The result will // be the empty URL. // // Note that this intentionally disallows direct use of url::Replacements, // which is harder to use correctly. GURL ReplaceComponents(const Replacements& replacements) const; GURL ReplaceComponents(const ReplacementsW& replacements) const; // A helper function that is equivalent to replacing the path with a slash // and clearing out everything after that. We sometimes need to know just the // scheme and the authority. If this URL is not a standard URL (it doesn't // have the regular authority and path sections), then the result will be // an empty, invalid GURL. Note that this *does* work for file: URLs, which // some callers may want to filter out before calling this. // // It is an error to get an empty path on an invalid URL. The result // will be the empty URL. GURL GetWithEmptyPath() const; // A helper function to return a GURL without the filename, query values, and // fragment. For example, // GURL("https://www.foo.com/index.html?q=test").GetWithoutFilename().spec() // will return "https://www.foo.com/". // GURL("https://www.foo.com/bar/").GetWithoutFilename().spec() // will return "https://www.foo.com/bar/". If the GURL is invalid or missing a // scheme, authority or path, it will return an empty, invalid GURL. GURL GetWithoutFilename() const; // A helper function to return a GURL without the Ref (also named Fragment // Identifier). For example, // GURL("https://www.foo.com/index.html#test").GetWithoutRef().spec() // will return "https://www.foo.com/index.html". // If the GURL is invalid or missing a // scheme, authority or path, it will return an empty, invalid GURL. GURL GetWithoutRef() const; // A helper function to return a GURL containing just the scheme, host, // and port from a URL. Equivalent to clearing any username and password, // replacing the path with a slash, and clearing everything after that. If // this URL is not a standard URL, then the result will be an empty, // invalid GURL. If the URL has neither username nor password, this // degenerates to GetWithEmptyPath(). // // It is an error to get the origin of an invalid URL. The result // will be the empty URL. // // WARNING: Please avoid converting urls into origins if at all possible! // //docs/security/origin-vs-url.md is a list of gotchas that can result. Such // conversions will likely return a wrong result for about:blank and/or // in the presence of iframe.sandbox attribute. Prefer to get origins directly // from the source (e.g. RenderFrameHost::GetLastCommittedOrigin). GURL DeprecatedGetOriginAsURL() const; // A helper function to return a GURL stripped from the elements that are not // supposed to be sent as HTTP referrer: username, password and ref fragment. // For invalid URLs or URLs that no valid referrers, an empty URL will be // returned. GURL GetAsReferrer() const; // Returns true if the scheme for the current URL is a known "standard-format" // scheme. A standard-format scheme adheres to what RFC 3986 calls "generic // URI syntax" (https://tools.ietf.org/html/rfc3986#section-3). This includes // file: and filesystem:, which some callers may want to filter out explicitly // by calling SchemeIsFile[System]. bool IsStandard() const; // Returns true when the url is of the form about:blank, about:blank?foo or // about:blank/#foo. bool IsAboutBlank() const; // Returns true when the url is of the form about:srcdoc, about:srcdoc?foo or // about:srcdoc/#foo. bool IsAboutSrcdoc() const; // Returns true if the given parameter (should be lower-case ASCII to match // the canonicalized scheme) is the scheme for this URL. Do not include a // colon. bool SchemeIs(base::StringPiece lower_ascii_scheme) const; // Returns true if the scheme is "http" or "https". bool SchemeIsHTTPOrHTTPS() const; // Returns true is the scheme is "ws" or "wss". bool SchemeIsWSOrWSS() const; // We often need to know if this is a file URL. File URLs are "standard", but // are often treated separately by some programs. bool SchemeIsFile() const { return SchemeIs(url::kFileScheme); } // FileSystem URLs need to be treated differently in some cases. bool SchemeIsFileSystem() const { return SchemeIs(url::kFileSystemScheme); } #if BUILDFLAG(IS_OHOS) // Resource URLs for ohos system bool SchemeIsOhosResource() const { return SchemeIs(url::kResourcesScheme); } // Return true if the js of this scheme supports code cache. bool SchemeIsCodeCacheEnabled() const; #endif // Returns true if the scheme indicates a network connection that uses TLS or // some other cryptographic protocol (e.g. QUIC) for security. // // This function is a not a complete test of whether or not an origin's code // is minimally trustworthy. For that, see Chromium's |IsOriginSecure| for a // higher-level and more complete semantics. See that function's documentation // for more detail. bool SchemeIsCryptographic() const; // As above, but static. Parameter should be lower-case ASCII. static bool SchemeIsCryptographic(base::StringPiece lower_ascii_scheme); // Returns true if the scheme is "blob". bool SchemeIsBlob() const { return SchemeIs(url::kBlobScheme); } // Returns true if the scheme is a local scheme, as defined in Fetch: // https://fetch.spec.whatwg.org/#local-scheme bool SchemeIsLocal() const; // For most URLs, the "content" is everything after the scheme (skipping the // scheme delimiting colon) and before the fragment (skipping the fragment // delimiting octothorpe). For javascript URLs the "content" also includes the // fragment delimiter and fragment. // // It is an error to get the content of an invalid URL: the result will be an // empty string. std::string GetContent() const; base::StringPiece GetContentPiece() const; // Returns true if the hostname is an IP address. Note: this function isn't // as cheap as a simple getter because it re-parses the hostname to verify. bool HostIsIPAddress() const; // Not including the colon. If you are comparing schemes, prefer SchemeIs. bool has_scheme() const { return parsed_.scheme.is_valid(); } std::string scheme() const { return ComponentString(parsed_.scheme); } base::StringPiece scheme_piece() const { return ComponentStringPiece(parsed_.scheme); } bool has_username() const { return parsed_.username.is_valid(); } std::string username() const { return ComponentString(parsed_.username); } base::StringPiece username_piece() const { return ComponentStringPiece(parsed_.username); } bool has_password() const { return parsed_.password.is_valid(); } std::string password() const { return ComponentString(parsed_.password); } base::StringPiece password_piece() const { return ComponentStringPiece(parsed_.password); } // The host may be a hostname, an IPv4 address, or an IPv6 literal surrounded // by square brackets, like "[2001:db8::1]". To exclude these brackets, use // HostNoBrackets() below. bool has_host() const { // Note that hosts are special, absence of host means length 0. return parsed_.host.is_nonempty(); } std::string host() const { return ComponentString(parsed_.host); } base::StringPiece host_piece() const { return ComponentStringPiece(parsed_.host); } // The port if one is explicitly specified. Most callers will want IntPort() // or EffectiveIntPort() instead of these. The getters will not include the // ':'. bool has_port() const { return parsed_.port.is_valid(); } std::string port() const { return ComponentString(parsed_.port); } base::StringPiece port_piece() const { return ComponentStringPiece(parsed_.port); } // Including first slash following host, up to the query. The URL // "http://www.google.com/" has a path of "/". bool has_path() const { return parsed_.path.is_valid(); } std::string path() const { return ComponentString(parsed_.path); } base::StringPiece path_piece() const { return ComponentStringPiece(parsed_.path); } // Stuff following '?' up to the ref. The getters will not include the '?'. bool has_query() const { return parsed_.query.is_valid(); } std::string query() const { return ComponentString(parsed_.query); } base::StringPiece query_piece() const { return ComponentStringPiece(parsed_.query); } // Stuff following '#' to the end of the string. This will be %-escaped UTF-8. // The getters will not include the '#'. bool has_ref() const { return parsed_.ref.is_valid(); } std::string ref() const { return ComponentString(parsed_.ref); } base::StringPiece ref_piece() const { return ComponentStringPiece(parsed_.ref); } // Returns a parsed version of the port. Can also be any of the special // values defined in Parsed for ExtractPort. int IntPort() const; // Returns the port number of the URL, or the default port number. // If the scheme has no concept of port (or unknown default) returns // PORT_UNSPECIFIED. int EffectiveIntPort() const; // Extracts the filename portion of the path and returns it. The filename // is everything after the last slash in the path. This may be empty. std::string ExtractFileName() const; // Returns the path that should be sent to the server. This is the path, // parameter, and query portions of the URL. It is guaranteed to be ASCII. std::string PathForRequest() const; // Returns the same characters as PathForRequest(), avoiding a copy. base::StringPiece PathForRequestPiece() const; // Returns the host, excluding the square brackets surrounding IPv6 address // literals. This can be useful for passing to getaddrinfo(). std::string HostNoBrackets() const; // Returns the same characters as HostNoBrackets(), avoiding a copy. base::StringPiece HostNoBracketsPiece() const; // Returns true if this URL's host matches or is in the same domain as // the given input string. For example, if the hostname of the URL is // "www.google.com", this will return true for "com", "google.com", and // "www.google.com". // // The input domain should match host canonicalization rules. i.e. the input // should be lowercase except for escape chars. // // This call is more efficient than getting the host and checking whether the // host has the specific domain or not because no copies or object // constructions are done. bool DomainIs(base::StringPiece canonical_domain) const; // Checks whether or not two URLs differ only in the ref (the part after // the # character). bool EqualsIgnoringRef(const GURL& other) const; // Swaps the contents of this GURL object with |other|, without doing // any memory allocations. void Swap(GURL* other); // Returns a reference to a singleton empty GURL. This object is for callers // who return references but don't have anything to return in some cases. // If you just want an empty URL for normal use, prefer GURL(). This function // may be called from any thread. static const GURL& EmptyGURL(); // Returns the inner URL of a nested URL (currently only non-null for // filesystem URLs). // // TODO(mmenke): inner_url().spec() currently returns the same value as // caling spec() on the GURL itself. This should be fixed. // See https://crbug.com/619596 const GURL* inner_url() const { return inner_url_.get(); } // Estimates dynamic memory usage. // See base/trace_event/memory_usage_estimator.h for more info. size_t EstimateMemoryUsage() const; // Helper used by GURL::IsAboutUrl and KURL::IsAboutURL. static bool IsAboutPath(base::StringPiece actual_path, base::StringPiece allowed_path); void WriteIntoTrace(perfetto::TracedValue context) const; private: // Variant of the string parsing constructor that allows the caller to elect // retain trailing whitespace, if any, on the passed URL spec, but only if // the scheme is one that allows trailing whitespace. The primary use-case is // for data: URLs. In most cases, you want to use the single parameter // constructor above. enum RetainWhiteSpaceSelector { RETAIN_TRAILING_PATH_WHITEPACE }; GURL(const std::string& url_string, RetainWhiteSpaceSelector); template <typename T, typename CharT = typename T::value_type> void InitCanonical(T input_spec, bool trim_path_end); void InitializeFromCanonicalSpec(); // Helper used by IsAboutBlank and IsAboutSrcdoc. bool IsAboutUrl(base::StringPiece allowed_path) const; // Returns the substring of the input identified by the given component. std::string ComponentString(const url::Component& comp) const { return std::string(ComponentStringPiece(comp)); } base::StringPiece ComponentStringPiece(const url::Component& comp) const { if (comp.is_empty()) return base::StringPiece(); return base::StringPiece(spec_).substr(static_cast<size_t>(comp.begin), static_cast<size_t>(comp.len)); } void ProcessFileSystemURLAfterReplaceComponents(); // The actual text of the URL, in canonical ASCII form. std::string spec_; // Set when the given URL is valid. Otherwise, we may still have a spec and // components, but they may not identify valid resources (for example, an // invalid port number, invalid characters in the scheme, etc.). bool is_valid_; // Identified components of the canonical spec. url::Parsed parsed_; // Used for nested schemes [currently only filesystem:]. std::unique_ptr<GURL> inner_url_; }; // Stream operator so GURL can be used in assertion statements. COMPONENT_EXPORT(URL) std::ostream& operator<<(std::ostream& out, const GURL& url); COMPONENT_EXPORT(URL) bool operator==(const GURL& x, const GURL& y); COMPONENT_EXPORT(URL) bool operator!=(const GURL& x, const GURL& y); // Equality operator for comparing raw spec_. This should be used in place of // url == GURL(spec) where |spec| is known (i.e. constants). This is to prevent // needlessly re-parsing |spec| into a temporary GURL. COMPONENT_EXPORT(URL) bool operator==(const GURL& x, const base::StringPiece& spec); COMPONENT_EXPORT(URL) bool operator==(const base::StringPiece& spec, const GURL& x); COMPONENT_EXPORT(URL) bool operator!=(const GURL& x, const base::StringPiece& spec); COMPONENT_EXPORT(URL) bool operator!=(const base::StringPiece& spec, const GURL& x); // DEBUG_ALIAS_FOR_GURL(var_name, url) copies |url| into a new stack-allocated // variable named |<var_name>|. This helps ensure that the value of |url| gets // preserved in crash dumps. #define DEBUG_ALIAS_FOR_GURL(var_name, url) \ DEBUG_ALIAS_FOR_CSTR(var_name, (url).possibly_invalid_spec().c_str(), 128) namespace url::debug { class COMPONENT_EXPORT(URL) ScopedUrlCrashKey { public: ScopedUrlCrashKey(base::debug::CrashKeyString* crash_key, const GURL& value); ~ScopedUrlCrashKey(); ScopedUrlCrashKey(const ScopedUrlCrashKey&) = delete; ScopedUrlCrashKey& operator=(const ScopedUrlCrashKey&) = delete; private: base::debug::ScopedCrashKeyString scoped_string_value_; }; } // namespace url::debug #endif // URL_GURL_H_
Zhao-PengFei35/chromium_src_4
url/gurl.h
C++
unknown
22,574
// Copyright 2021 The Chromium Authors // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #ifndef URL_GURL_ABSTRACT_TESTS_H_ #define URL_GURL_ABSTRACT_TESTS_H_ // Test suite for tests that cover both url::Url and blink::SecurityUrl. // // AbstractUrlTest below abstracts away differences between GURL and blink::KURL // by parametrizing the tests with a class that has to expose the following // members: // using UrlType = ...; // static UrlType CreateUrlFromString(base::StringPiece s); // static bool IsAboutBlank(const UrlType& url); // static bool IsAboutSrcdoc(const UrlType& url); template <typename TUrlTraits> class AbstractUrlTest : public testing::Test { protected: // Wrappers that help ellide away TUrlTraits. // // Note that calling the wrappers needs to be prefixed with `this->...` to // avoid hitting: explicit qualification required to use member 'IsAboutBlank' // from dependent base class. using UrlType = typename TUrlTraits::UrlType; UrlType CreateUrlFromString(base::StringPiece s) { return TUrlTraits::CreateUrlFromString(s); } bool IsAboutBlank(const UrlType& url) { return TUrlTraits::IsAboutBlank(url); } bool IsAboutSrcdoc(const UrlType& url) { return TUrlTraits::IsAboutSrcdoc(url); } }; TYPED_TEST_SUITE_P(AbstractUrlTest); TYPED_TEST_P(AbstractUrlTest, IsAboutBlankTest) { // See https://tools.ietf.org/html/rfc6694 which explicitly allows // `about-query` and `about-fragment` parts in about: URLs. const std::string kAboutBlankUrls[] = {"about:blank", "about:blank?foo", "about:blank/#foo", "about:blank?foo#foo"}; for (const auto& input : kAboutBlankUrls) { SCOPED_TRACE(testing::Message() << "Test input: " << input); auto url = this->CreateUrlFromString(input); EXPECT_TRUE(this->IsAboutBlank(url)); } const std::string kNotAboutBlankUrls[] = {"", "about", "about:", "about:blanky", "about:blan", "about:about:blank:", "data:blank", "http:blank", "about://blank", "about:blank/foo", "about://:8000/blank", "about://foo:foo@/blank", "foo@about:blank", "foo:bar@about:blank", "about:blank:8000", "about:blANk"}; for (const auto& input : kNotAboutBlankUrls) { SCOPED_TRACE(testing::Message() << "Test input: " << input); auto url = this->CreateUrlFromString(input); EXPECT_FALSE(this->IsAboutBlank(url)); } } TYPED_TEST_P(AbstractUrlTest, IsAboutSrcdocTest) { // See https://tools.ietf.org/html/rfc6694 which explicitly allows // `about-query` and `about-fragment` parts in about: URLs. // // `about:srcdoc` is defined in // https://html.spec.whatwg.org/multipage/urls-and-fetching.html#about:srcdoc // which refers to rfc6694 for details. const std::string kAboutSrcdocUrls[] = { "about:srcdoc", "about:srcdoc/", "about:srcdoc?foo", "about:srcdoc/#foo", "about:srcdoc?foo#foo"}; for (const auto& input : kAboutSrcdocUrls) { SCOPED_TRACE(testing::Message() << "Test input: " << input); auto url = this->CreateUrlFromString(input); EXPECT_TRUE(this->IsAboutSrcdoc(url)); } const std::string kNotAboutSrcdocUrls[] = {"", "about", "about:", "about:srcdocx", "about:srcdo", "about:about:srcdoc:", "data:srcdoc", "http:srcdoc", "about:srcdo", "about://srcdoc", "about://srcdoc\\", "about:srcdoc/foo", "about://:8000/srcdoc", "about://foo:foo@/srcdoc", "foo@about:srcdoc", "foo:bar@about:srcdoc", "about:srcdoc:8000", "about:srCDOc"}; for (const auto& input : kNotAboutSrcdocUrls) { SCOPED_TRACE(testing::Message() << "Test input: " << input); auto url = this->CreateUrlFromString(input); EXPECT_FALSE(this->IsAboutSrcdoc(url)); } } REGISTER_TYPED_TEST_SUITE_P(AbstractUrlTest, IsAboutBlankTest, IsAboutSrcdocTest); #endif // URL_GURL_ABSTRACT_TESTS_H_
Zhao-PengFei35/chromium_src_4
url/gurl_abstract_tests.h
C++
unknown
5,351
// Copyright 2015 The Chromium Authors // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "base/at_exit.h" #include "base/check_op.h" #include "base/i18n/icu_util.h" #include "base/no_destructor.h" #include "url/gurl.h" struct TestCase { TestCase() { CHECK(base::i18n::InitializeICU()); } // used by ICU integration. base::AtExitManager at_exit_manager; }; TestCase* test_case = new TestCase(); // Checks that GURL's canonicalization is idempotent. This can help discover // issues like https://crbug.com/1128999. void CheckIdempotency(const GURL& url) { if (!url.is_valid()) return; const std::string& spec = url.spec(); GURL recanonicalized(spec); CHECK(recanonicalized.is_valid()); CHECK_EQ(spec, recanonicalized.spec()); } // Checks that |url.spec()| is preserved across a call to ReplaceComponents with // zero replacements, which is effectively a copy. This can help discover issues // like https://crbug.com/1075515. void CheckReplaceComponentsPreservesSpec(const GURL& url) { static const base::NoDestructor<GURL::Replacements> no_op; GURL copy = url.ReplaceComponents(*no_op); CHECK_EQ(url.is_valid(), copy.is_valid()); if (url.is_valid()) { CHECK_EQ(url.spec(), copy.spec()); } } // Entry point for LibFuzzer. extern "C" int LLVMFuzzerTestOneInput(const uint8_t* data, size_t size) { if (size < 1) return 0; { base::StringPiece string_piece_input(reinterpret_cast<const char*>(data), size); const GURL url_from_string_piece(string_piece_input); CheckIdempotency(url_from_string_piece); CheckReplaceComponentsPreservesSpec(url_from_string_piece); } // Test for StringPiece16 if size is even. if (size % sizeof(char16_t) == 0) { base::StringPiece16 string_piece_input16( reinterpret_cast<const char16_t*>(data), size / sizeof(char16_t)); const GURL url_from_string_piece16(string_piece_input16); CheckIdempotency(url_from_string_piece16); CheckReplaceComponentsPreservesSpec(url_from_string_piece16); } // Resolve relative url tests. { size_t size_t_bytes = sizeof(size_t); if (size < size_t_bytes + 1) { return 0; } size_t relative_size = *reinterpret_cast<const size_t*>(data) % (size - size_t_bytes); std::string relative_string( reinterpret_cast<const char*>(data + size_t_bytes), relative_size); base::StringPiece string_piece_part_input( reinterpret_cast<const char*>(data + size_t_bytes + relative_size), size - relative_size - size_t_bytes); const GURL url_from_string_piece_part(string_piece_part_input); CheckIdempotency(url_from_string_piece_part); CheckReplaceComponentsPreservesSpec(url_from_string_piece_part); url_from_string_piece_part.Resolve(relative_string); if (relative_size % sizeof(char16_t) == 0) { std::u16string relative_string16( reinterpret_cast<const char16_t*>(data + size_t_bytes), relative_size / sizeof(char16_t)); url_from_string_piece_part.Resolve(relative_string16); } } return 0; }
Zhao-PengFei35/chromium_src_4
url/gurl_fuzzer.cc
C++
unknown
3,155
// Copyright 2013 The Chromium Authors // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "url/gurl.h" #include <stddef.h> #include "base/strings/string_number_conversions.h" #include "base/strings/utf_string_conversions.h" #include "testing/gtest/include/gtest/gtest.h" #include "url/gurl_abstract_tests.h" #include "url/origin.h" #include "url/url_canon.h" #include "url/url_test_utils.h" namespace url { namespace { // Returns the canonicalized string for the given URL string for the // GURLTest.Types test. std::string TypesTestCase(const char* src) { GURL gurl(src); return gurl.possibly_invalid_spec(); } } // namespace // Different types of URLs should be handled differently, and handed off to // different canonicalizers. TEST(GURLTest, Types) { // URLs with unknown schemes should be treated as path URLs, even when they // have things like "://". EXPECT_EQ("something:///HOSTNAME.com/", TypesTestCase("something:///HOSTNAME.com/")); // Conversely, URLs with known schemes should always trigger standard URL // handling. EXPECT_EQ("http://hostname.com/", TypesTestCase("http:HOSTNAME.com")); EXPECT_EQ("http://hostname.com/", TypesTestCase("http:/HOSTNAME.com")); EXPECT_EQ("http://hostname.com/", TypesTestCase("http://HOSTNAME.com")); EXPECT_EQ("http://hostname.com/", TypesTestCase("http:///HOSTNAME.com")); #ifdef WIN32 // URLs that look like Windows absolute path specs. EXPECT_EQ("file:///C:/foo.txt", TypesTestCase("c:\\foo.txt")); EXPECT_EQ("file:///Z:/foo.txt", TypesTestCase("Z|foo.txt")); EXPECT_EQ("file://server/foo.txt", TypesTestCase("\\\\server\\foo.txt")); EXPECT_EQ("file://server/foo.txt", TypesTestCase("//server/foo.txt")); #endif } // Test the basic creation and querying of components in a GURL. We assume that // the parser is already tested and works, so we are mostly interested if the // object does the right thing with the results. TEST(GURLTest, Components) { GURL empty_url(u""); EXPECT_TRUE(empty_url.is_empty()); EXPECT_FALSE(empty_url.is_valid()); GURL url(u"http://user:pass@google.com:99/foo;bar?q=a#ref"); EXPECT_FALSE(url.is_empty()); EXPECT_TRUE(url.is_valid()); EXPECT_TRUE(url.SchemeIs("http")); EXPECT_FALSE(url.SchemeIsFile()); // This is the narrow version of the URL, which should match the wide input. EXPECT_EQ("http://user:pass@google.com:99/foo;bar?q=a#ref", url.spec()); EXPECT_EQ("http", url.scheme()); EXPECT_EQ("user", url.username()); EXPECT_EQ("pass", url.password()); EXPECT_EQ("google.com", url.host()); EXPECT_EQ("99", url.port()); EXPECT_EQ(99, url.IntPort()); EXPECT_EQ("/foo;bar", url.path()); EXPECT_EQ("q=a", url.query()); EXPECT_EQ("ref", url.ref()); // Test parsing userinfo with special characters. GURL url_special_pass("http://user:%40!$&'()*+,;=:@google.com:12345"); EXPECT_TRUE(url_special_pass.is_valid()); // GURL canonicalizes some delimiters. EXPECT_EQ("%40!$&%27()*+,%3B%3D%3A", url_special_pass.password()); EXPECT_EQ("google.com", url_special_pass.host()); EXPECT_EQ("12345", url_special_pass.port()); } TEST(GURLTest, Empty) { GURL url; EXPECT_FALSE(url.is_valid()); EXPECT_EQ("", url.spec()); EXPECT_EQ("", url.scheme()); EXPECT_EQ("", url.username()); EXPECT_EQ("", url.password()); EXPECT_EQ("", url.host()); EXPECT_EQ("", url.port()); EXPECT_EQ(PORT_UNSPECIFIED, url.IntPort()); EXPECT_EQ("", url.path()); EXPECT_EQ("", url.query()); EXPECT_EQ("", url.ref()); } TEST(GURLTest, Copy) { GURL url(u"http://user:pass@google.com:99/foo;bar?q=a#ref"); GURL url2(url); EXPECT_TRUE(url2.is_valid()); EXPECT_EQ("http://user:pass@google.com:99/foo;bar?q=a#ref", url2.spec()); EXPECT_EQ("http", url2.scheme()); EXPECT_EQ("user", url2.username()); EXPECT_EQ("pass", url2.password()); EXPECT_EQ("google.com", url2.host()); EXPECT_EQ("99", url2.port()); EXPECT_EQ(99, url2.IntPort()); EXPECT_EQ("/foo;bar", url2.path()); EXPECT_EQ("q=a", url2.query()); EXPECT_EQ("ref", url2.ref()); // Copying of invalid URL should be invalid GURL invalid; GURL invalid2(invalid); EXPECT_FALSE(invalid2.is_valid()); EXPECT_EQ("", invalid2.spec()); EXPECT_EQ("", invalid2.scheme()); EXPECT_EQ("", invalid2.username()); EXPECT_EQ("", invalid2.password()); EXPECT_EQ("", invalid2.host()); EXPECT_EQ("", invalid2.port()); EXPECT_EQ(PORT_UNSPECIFIED, invalid2.IntPort()); EXPECT_EQ("", invalid2.path()); EXPECT_EQ("", invalid2.query()); EXPECT_EQ("", invalid2.ref()); } TEST(GURLTest, Assign) { GURL url(u"http://user:pass@google.com:99/foo;bar?q=a#ref"); GURL url2; url2 = url; EXPECT_TRUE(url2.is_valid()); EXPECT_EQ("http://user:pass@google.com:99/foo;bar?q=a#ref", url2.spec()); EXPECT_EQ("http", url2.scheme()); EXPECT_EQ("user", url2.username()); EXPECT_EQ("pass", url2.password()); EXPECT_EQ("google.com", url2.host()); EXPECT_EQ("99", url2.port()); EXPECT_EQ(99, url2.IntPort()); EXPECT_EQ("/foo;bar", url2.path()); EXPECT_EQ("q=a", url2.query()); EXPECT_EQ("ref", url2.ref()); // Assignment of invalid URL should be invalid GURL invalid; GURL invalid2; invalid2 = invalid; EXPECT_FALSE(invalid2.is_valid()); EXPECT_EQ("", invalid2.spec()); EXPECT_EQ("", invalid2.scheme()); EXPECT_EQ("", invalid2.username()); EXPECT_EQ("", invalid2.password()); EXPECT_EQ("", invalid2.host()); EXPECT_EQ("", invalid2.port()); EXPECT_EQ(PORT_UNSPECIFIED, invalid2.IntPort()); EXPECT_EQ("", invalid2.path()); EXPECT_EQ("", invalid2.query()); EXPECT_EQ("", invalid2.ref()); } // This is a regression test for http://crbug.com/309975. TEST(GURLTest, SelfAssign) { GURL a("filesystem:http://example.com/temporary/"); // This should not crash. a = *&a; // The *& defeats Clang's -Wself-assign warning. } TEST(GURLTest, CopyFileSystem) { GURL url(u"filesystem:https://user:pass@google.com:99/t/foo;bar?q=a#ref"); GURL url2(url); EXPECT_TRUE(url2.is_valid()); EXPECT_EQ("filesystem:https://google.com:99/t/foo;bar?q=a#ref", url2.spec()); EXPECT_EQ("filesystem", url2.scheme()); EXPECT_EQ("", url2.username()); EXPECT_EQ("", url2.password()); EXPECT_EQ("", url2.host()); EXPECT_EQ("", url2.port()); EXPECT_EQ(PORT_UNSPECIFIED, url2.IntPort()); EXPECT_EQ("/foo;bar", url2.path()); EXPECT_EQ("q=a", url2.query()); EXPECT_EQ("ref", url2.ref()); const GURL* inner = url2.inner_url(); ASSERT_TRUE(inner); EXPECT_EQ("https", inner->scheme()); EXPECT_EQ("", inner->username()); EXPECT_EQ("", inner->password()); EXPECT_EQ("google.com", inner->host()); EXPECT_EQ("99", inner->port()); EXPECT_EQ(99, inner->IntPort()); EXPECT_EQ("/t", inner->path()); EXPECT_EQ("", inner->query()); EXPECT_EQ("", inner->ref()); } TEST(GURLTest, IsValid) { const char* valid_cases[] = { "http://google.com", "unknown://google.com", "http://user:pass@google.com", "http://google.com:12345", "http://google.com:0", // 0 is a valid port "http://google.com/path", "http://google.com//path", "http://google.com?k=v#fragment", "http://user:pass@google.com:12345/path?k=v#fragment", "http:/path", "http:path", }; for (size_t i = 0; i < std::size(valid_cases); i++) { EXPECT_TRUE(GURL(valid_cases[i]).is_valid()) << "Case: " << valid_cases[i]; } const char* invalid_cases[] = { "http://?k=v", "http:://google.com", "http//google.com", "http://google.com:12three45", "file://server:123", // file: URLs cannot have a port "file://server:0", "://google.com", "path", }; for (size_t i = 0; i < std::size(invalid_cases); i++) { EXPECT_FALSE(GURL(invalid_cases[i]).is_valid()) << "Case: " << invalid_cases[i]; } } TEST(GURLTest, ExtraSlashesBeforeAuthority) { // According to RFC3986, the hierarchical part for URI with an authority // must use only two slashes; GURL intentionally just ignores extra slashes // if there are more than 2, and parses the following part as an authority. GURL url("http:///host"); EXPECT_EQ("host", url.host()); EXPECT_EQ("/", url.path()); } // Given invalid URLs, we should still get most of the components. TEST(GURLTest, ComponentGettersWorkEvenForInvalidURL) { constexpr struct InvalidURLTestExpectations { const char* url; const char* spec; const char* scheme; const char* host; const char* port; const char* path; // Extend as needed... } expectations[] = { { "http:google.com:foo", "http://google.com:foo/", "http", "google.com", "foo", "/", }, { "https:google.com:foo", "https://google.com:foo/", "https", "google.com", "foo", "/", }, }; for (const auto& e : expectations) { const GURL url(e.url); EXPECT_FALSE(url.is_valid()); EXPECT_EQ(e.spec, url.possibly_invalid_spec()); EXPECT_EQ(e.scheme, url.scheme()); EXPECT_EQ("", url.username()); EXPECT_EQ("", url.password()); EXPECT_EQ(e.host, url.host()); EXPECT_EQ(e.port, url.port()); EXPECT_EQ(PORT_INVALID, url.IntPort()); EXPECT_EQ(e.path, url.path()); EXPECT_EQ("", url.query()); EXPECT_EQ("", url.ref()); } } TEST(GURLTest, Resolve) { // The tricky cases for relative URL resolving are tested in the // canonicalizer unit test. Here, we just test that the GURL integration // works properly. struct ResolveCase { const char* base; const char* relative; bool expected_valid; const char* expected; } resolve_cases[] = { {"http://www.google.com/", "foo.html", true, "http://www.google.com/foo.html"}, {"http://www.google.com/foo/", "bar", true, "http://www.google.com/foo/bar"}, {"http://www.google.com/foo/", "/bar", true, "http://www.google.com/bar"}, {"http://www.google.com/foo", "bar", true, "http://www.google.com/bar"}, {"http://www.google.com/", "http://images.google.com/foo.html", true, "http://images.google.com/foo.html"}, {"http://www.google.com/", "http://images.\tgoogle.\ncom/\rfoo.html", true, "http://images.google.com/foo.html"}, {"http://www.google.com/blah/bloo?c#d", "../../../hello/./world.html?a#b", true, "http://www.google.com/hello/world.html?a#b"}, {"http://www.google.com/foo#bar", "#com", true, "http://www.google.com/foo#com"}, {"http://www.google.com/", "Https:images.google.com", true, "https://images.google.com/"}, // A non-standard base can be replaced with a standard absolute URL. {"data:blahblah", "http://google.com/", true, "http://google.com/"}, {"data:blahblah", "http:google.com", true, "http://google.com/"}, {"data:blahblah", "https:google.com", true, "https://google.com/"}, // Filesystem URLs have different paths to test. {"filesystem:http://www.google.com/type/", "foo.html", true, "filesystem:http://www.google.com/type/foo.html"}, {"filesystem:http://www.google.com/type/", "../foo.html", true, "filesystem:http://www.google.com/type/foo.html"}, // https://crbug.com/530123 - scheme validation (e.g. are "10.0.0.7:" // or "x1:" valid schemes) when deciding if |relative| is an absolute url. {"file:///some/dir/ip-relative.html", "10.0.0.7:8080/foo.html", true, "file:///some/dir/10.0.0.7:8080/foo.html"}, {"file:///some/dir/", "1://host", true, "file:///some/dir/1://host"}, {"file:///some/dir/", "x1://host", true, "x1://host"}, {"file:///some/dir/", "X1://host", true, "x1://host"}, {"file:///some/dir/", "x.://host", true, "x.://host"}, {"file:///some/dir/", "x+://host", true, "x+://host"}, {"file:///some/dir/", "x-://host", true, "x-://host"}, {"file:///some/dir/", "x!://host", true, "file:///some/dir/x!://host"}, {"file:///some/dir/", "://host", true, "file:///some/dir/://host"}, }; for (size_t i = 0; i < std::size(resolve_cases); i++) { // 8-bit code path. GURL input(resolve_cases[i].base); GURL output = input.Resolve(resolve_cases[i].relative); EXPECT_EQ(resolve_cases[i].expected_valid, output.is_valid()) << i; EXPECT_EQ(resolve_cases[i].expected, output.spec()) << i; EXPECT_EQ(output.SchemeIsFileSystem(), output.inner_url() != NULL); // Wide code path. GURL inputw(base::UTF8ToUTF16(resolve_cases[i].base)); GURL outputw = input.Resolve(base::UTF8ToUTF16(resolve_cases[i].relative)); EXPECT_EQ(resolve_cases[i].expected_valid, outputw.is_valid()) << i; EXPECT_EQ(resolve_cases[i].expected, outputw.spec()) << i; EXPECT_EQ(outputw.SchemeIsFileSystem(), outputw.inner_url() != NULL); } } TEST(GURLTest, GetOrigin) { struct TestCase { const char* input; const char* expected; } cases[] = { {"http://www.google.com", "http://www.google.com/"}, {"javascript:window.alert(\"hello,world\");", ""}, {"http://user:pass@www.google.com:21/blah#baz", "http://www.google.com:21/"}, {"http://user@www.google.com", "http://www.google.com/"}, {"http://:pass@www.google.com", "http://www.google.com/"}, {"http://:@www.google.com", "http://www.google.com/"}, {"filesystem:http://www.google.com/temp/foo?q#b", "http://www.google.com/"}, {"filesystem:http://user:pass@google.com:21/blah#baz", "http://google.com:21/"}, {"blob:null/guid-goes-here", ""}, {"blob:http://origin/guid-goes-here", "" /* should be http://origin/ */}, }; for (size_t i = 0; i < std::size(cases); i++) { GURL url(cases[i].input); GURL origin = url.DeprecatedGetOriginAsURL(); EXPECT_EQ(cases[i].expected, origin.spec()); } } TEST(GURLTest, GetAsReferrer) { struct TestCase { const char* input; const char* expected; } cases[] = { {"http://www.google.com", "http://www.google.com/"}, {"http://user:pass@www.google.com:21/blah#baz", "http://www.google.com:21/blah"}, {"http://user@www.google.com", "http://www.google.com/"}, {"http://:pass@www.google.com", "http://www.google.com/"}, {"http://:@www.google.com", "http://www.google.com/"}, {"http://www.google.com/temp/foo?q#b", "http://www.google.com/temp/foo?q"}, {"not a url", ""}, {"unknown-scheme://foo.html", ""}, {"file:///tmp/test.html", ""}, {"https://www.google.com", "https://www.google.com/"}, }; for (size_t i = 0; i < std::size(cases); i++) { GURL url(cases[i].input); GURL origin = url.GetAsReferrer(); EXPECT_EQ(cases[i].expected, origin.spec()); } } TEST(GURLTest, GetWithEmptyPath) { struct TestCase { const char* input; const char* expected; } cases[] = { {"http://www.google.com", "http://www.google.com/"}, {"javascript:window.alert(\"hello, world\");", ""}, {"http://www.google.com/foo/bar.html?baz=22", "http://www.google.com/"}, {"filesystem:http://www.google.com/temporary/bar.html?baz=22", "filesystem:http://www.google.com/temporary/"}, {"filesystem:file:///temporary/bar.html?baz=22", "filesystem:file:///temporary/"}, }; for (size_t i = 0; i < std::size(cases); i++) { GURL url(cases[i].input); GURL empty_path = url.GetWithEmptyPath(); EXPECT_EQ(cases[i].expected, empty_path.spec()); } } TEST(GURLTest, GetWithoutFilename) { struct TestCase { const char* input; const char* expected; } cases[] = { // Common Standard URLs. {"https://www.google.com", "https://www.google.com/"}, {"https://www.google.com/", "https://www.google.com/"}, {"https://www.google.com/maps.htm", "https://www.google.com/"}, {"https://www.google.com/maps/", "https://www.google.com/maps/"}, {"https://www.google.com/index.html", "https://www.google.com/"}, {"https://www.google.com/index.html?q=maps", "https://www.google.com/"}, {"https://www.google.com/index.html#maps/", "https://www.google.com/"}, {"https://foo:bar@www.google.com/maps.htm", "https://foo:bar@www.google.com/"}, {"https://www.google.com/maps/au/index.html", "https://www.google.com/maps/au/"}, {"https://www.google.com/maps/au/north", "https://www.google.com/maps/au/"}, {"https://www.google.com/maps/au/north/", "https://www.google.com/maps/au/north/"}, {"https://www.google.com/maps/au/index.html?q=maps#fragment/", "https://www.google.com/maps/au/"}, {"http://www.google.com:8000/maps/au/index.html?q=maps#fragment/", "http://www.google.com:8000/maps/au/"}, {"https://www.google.com/maps/au/north/?q=maps#fragment", "https://www.google.com/maps/au/north/"}, {"https://www.google.com/maps/au/north?q=maps#fragment", "https://www.google.com/maps/au/"}, // Less common standard URLs. {"filesystem:http://www.google.com/temporary/bar.html?baz=22", "filesystem:http://www.google.com/temporary/"}, {"file:///temporary/bar.html?baz=22","file:///temporary/"}, {"ftp://foo/test/index.html", "ftp://foo/test/"}, {"gopher://foo/test/index.html", "gopher://foo/test/"}, {"ws://foo/test/index.html", "ws://foo/test/"}, // Non-standard, hierarchical URLs. {"chrome://foo/bar.html", "chrome://foo/"}, {"httpa://foo/test/index.html", "httpa://foo/test/"}, // Non-standard, non-hierarchical URLs. {"blob:https://foo.bar/test/index.html", ""}, {"about:blank", ""}, {"data:foobar", ""}, {"scheme:opaque_data", ""}, // Invalid URLs. {"foobar", ""}, }; for (size_t i = 0; i < std::size(cases); i++) { GURL url(cases[i].input); GURL without_filename = url.GetWithoutFilename(); EXPECT_EQ(cases[i].expected, without_filename.spec()) << i; } } TEST(GURLTest, GetWithoutRef) { struct TestCase { const char* input; const char* expected; } cases[] = { // Common Standard URLs. {"https://www.google.com/index.html", "https://www.google.com/index.html"}, {"https://www.google.com/index.html#maps/", "https://www.google.com/index.html"}, {"https://foo:bar@www.google.com/maps.htm", "https://foo:bar@www.google.com/maps.htm"}, {"https://foo:bar@www.google.com/maps.htm#fragment", "https://foo:bar@www.google.com/maps.htm"}, {"https://www.google.com/maps/au/index.html?q=maps", "https://www.google.com/maps/au/index.html?q=maps"}, {"https://www.google.com/maps/au/index.html?q=maps#fragment/", "https://www.google.com/maps/au/index.html?q=maps"}, {"http://www.google.com:8000/maps/au/index.html?q=maps", "http://www.google.com:8000/maps/au/index.html?q=maps"}, {"http://www.google.com:8000/maps/au/index.html?q=maps#fragment/", "http://www.google.com:8000/maps/au/index.html?q=maps"}, {"https://www.google.com/maps/au/north/?q=maps", "https://www.google.com/maps/au/north/?q=maps"}, {"https://www.google.com/maps/au/north?q=maps#fragment", "https://www.google.com/maps/au/north?q=maps"}, // Less common standard URLs. {"filesystem:http://www.google.com/temporary/bar.html?baz=22", "filesystem:http://www.google.com/temporary/bar.html?baz=22"}, {"file:///temporary/bar.html?baz=22#fragment", "file:///temporary/bar.html?baz=22"}, {"ftp://foo/test/index.html", "ftp://foo/test/index.html"}, {"ftp://foo/test/index.html#fragment", "ftp://foo/test/index.html"}, {"gopher://foo/test/index.html", "gopher://foo/test/index.html"}, {"gopher://foo/test/index.html#fragment", "gopher://foo/test/index.html"}, {"ws://foo/test/index.html", "ws://foo/test/index.html"}, {"ws://foo/test/index.html#fragment", "ws://foo/test/index.html"}, // Non-standard, hierarchical URLs. {"chrome://foo/bar.html", "chrome://foo/bar.html"}, {"chrome://foo/bar.html#fragment", "chrome://foo/bar.html"}, {"httpa://foo/test/index.html", "httpa://foo/test/index.html"}, {"httpa://foo/test/index.html#fragment", "httpa://foo/test/index.html"}, // Non-standard, non-hierarchical URLs. {"blob:https://foo.bar/test/index.html", "blob:https://foo.bar/test/index.html"}, {"blob:https://foo.bar/test/index.html#fragment", "blob:https://foo.bar/test/index.html"}, {"about:blank", "about:blank"}, {"about:blank#ref", "about:blank"}, {"data:foobar", "data:foobar"}, {"scheme:opaque_data", "scheme:opaque_data"}, // Invalid URLs. {"foobar", ""}, }; for (size_t i = 0; i < std::size(cases); i++) { GURL url(cases[i].input); GURL without_ref = url.GetWithoutRef(); EXPECT_EQ(cases[i].expected, without_ref.spec()); } } TEST(GURLTest, Replacements) { // The URL canonicalizer replacement test will handle most of these case. // The most important thing to do here is to check that the proper // canonicalizer gets called based on the scheme of the input. struct ReplaceCase { using ApplyReplacementsFunc = GURL(const GURL&); const char* base; ApplyReplacementsFunc* apply_replacements; const char* expected; } replace_cases[] = { {.base = "http://www.google.com/foo/bar.html?foo#bar", .apply_replacements = +[](const GURL& url) { GURL::Replacements replacements; replacements.SetPathStr("/"); replacements.ClearQuery(); replacements.ClearRef(); return url.ReplaceComponents(replacements); }, .expected = "http://www.google.com/"}, {.base = "http://www.google.com/foo/bar.html?foo#bar", .apply_replacements = +[](const GURL& url) { GURL::Replacements replacements; replacements.SetSchemeStr("javascript"); replacements.ClearUsername(); replacements.ClearPassword(); replacements.ClearHost(); replacements.ClearPort(); replacements.SetPathStr("window.open('foo');"); replacements.ClearQuery(); replacements.ClearRef(); return url.ReplaceComponents(replacements); }, .expected = "javascript:window.open('foo');"}, {.base = "file:///C:/foo/bar.txt", .apply_replacements = +[](const GURL& url) { GURL::Replacements replacements; replacements.SetSchemeStr("http"); replacements.SetHostStr("www.google.com"); replacements.SetPortStr("99"); replacements.SetPathStr("/foo"); replacements.SetQueryStr("search"); replacements.SetRefStr("ref"); return url.ReplaceComponents(replacements); }, .expected = "http://www.google.com:99/foo?search#ref"}, #ifdef WIN32 {.base = "http://www.google.com/foo/bar.html?foo#bar", .apply_replacements = +[](const GURL& url) { GURL::Replacements replacements; replacements.SetSchemeStr("file"); replacements.ClearUsername(); replacements.ClearPassword(); replacements.ClearHost(); replacements.ClearPort(); replacements.SetPathStr("c:\\"); replacements.ClearQuery(); replacements.ClearRef(); return url.ReplaceComponents(replacements); }, .expected = "file:///C:/"}, #endif {.base = "filesystem:http://www.google.com/foo/bar.html?foo#bar", .apply_replacements = +[](const GURL& url) { GURL::Replacements replacements; replacements.SetPathStr("/"); replacements.ClearQuery(); replacements.ClearRef(); return url.ReplaceComponents(replacements); }, .expected = "filesystem:http://www.google.com/foo/"}, // Lengthen the URL instead of shortening it, to test creation of // inner_url. {.base = "filesystem:http://www.google.com/foo/", .apply_replacements = +[](const GURL& url) { GURL::Replacements replacements; replacements.SetPathStr("bar.html"); replacements.SetQueryStr("foo"); replacements.SetRefStr("bar"); return url.ReplaceComponents(replacements); }, .expected = "filesystem:http://www.google.com/foo/bar.html?foo#bar"}, }; for (const ReplaceCase& c : replace_cases) { GURL output = c.apply_replacements(GURL(c.base)); EXPECT_EQ(c.expected, output.spec()); EXPECT_EQ(output.SchemeIsFileSystem(), output.inner_url() != NULL); if (output.SchemeIsFileSystem()) { // TODO(mmenke): inner_url()->spec() is currently the same as the spec() // for the GURL itself. This should be fixed. // See https://crbug.com/619596 EXPECT_EQ(c.expected, output.inner_url()->spec()); } } } TEST(GURLTest, ClearFragmentOnDataUrl) { // http://crbug.com/291747 - a data URL may legitimately have trailing // whitespace in the spec after the ref is cleared. Test this does not trigger // the Parsed importing validation DCHECK in GURL. GURL url(" data: one # two "); EXPECT_TRUE(url.is_valid()); // By default the trailing whitespace will have been stripped. EXPECT_EQ("data: one #%20two", url.spec()); // Clear the URL's ref and observe the trailing whitespace. GURL::Replacements repl; repl.ClearRef(); GURL url_no_ref = url.ReplaceComponents(repl); EXPECT_TRUE(url_no_ref.is_valid()); EXPECT_EQ("data: one ", url_no_ref.spec()); // Importing a parsed URL via this constructor overload will retain trailing // whitespace. GURL import_url(url_no_ref.spec(), url_no_ref.parsed_for_possibly_invalid_spec(), url_no_ref.is_valid()); EXPECT_TRUE(import_url.is_valid()); EXPECT_EQ(url_no_ref, import_url); EXPECT_EQ("data: one ", import_url.spec()); EXPECT_EQ(" one ", import_url.path()); // For completeness, test that re-parsing the same URL rather than importing // it trims the trailing whitespace. GURL reparsed_url(url_no_ref.spec()); EXPECT_TRUE(reparsed_url.is_valid()); EXPECT_EQ("data: one", reparsed_url.spec()); } TEST(GURLTest, PathForRequest) { struct TestCase { const char* input; const char* expected; const char* inner_expected; } cases[] = { {"http://www.google.com", "/", nullptr}, {"http://www.google.com/", "/", nullptr}, {"http://www.google.com/foo/bar.html?baz=22", "/foo/bar.html?baz=22", nullptr}, {"http://www.google.com/foo/bar.html#ref", "/foo/bar.html", nullptr}, {"http://www.google.com/foo/bar.html?query#ref", "/foo/bar.html?query", nullptr}, {"filesystem:http://www.google.com/temporary/foo/bar.html?query#ref", "/foo/bar.html?query", "/temporary"}, {"filesystem:http://www.google.com/temporary/foo/bar.html?query", "/foo/bar.html?query", "/temporary"}, }; for (size_t i = 0; i < std::size(cases); i++) { GURL url(cases[i].input); EXPECT_EQ(cases[i].expected, url.PathForRequest()); EXPECT_EQ(cases[i].expected, url.PathForRequestPiece()); EXPECT_EQ(cases[i].inner_expected == NULL, url.inner_url() == NULL); if (url.inner_url() && cases[i].inner_expected) { EXPECT_EQ(cases[i].inner_expected, url.inner_url()->PathForRequest()); EXPECT_EQ(cases[i].inner_expected, url.inner_url()->PathForRequestPiece()); } } } TEST(GURLTest, EffectiveIntPort) { struct PortTest { const char* spec; int expected_int_port; } port_tests[] = { // http {"http://www.google.com/", 80}, {"http://www.google.com:80/", 80}, {"http://www.google.com:443/", 443}, // https {"https://www.google.com/", 443}, {"https://www.google.com:443/", 443}, {"https://www.google.com:80/", 80}, // ftp {"ftp://www.google.com/", 21}, {"ftp://www.google.com:21/", 21}, {"ftp://www.google.com:80/", 80}, // file - no port {"file://www.google.com/", PORT_UNSPECIFIED}, {"file://www.google.com:443/", PORT_UNSPECIFIED}, // data - no port {"data:www.google.com:90", PORT_UNSPECIFIED}, {"data:www.google.com", PORT_UNSPECIFIED}, // filesystem - no port {"filesystem:http://www.google.com:90/t/foo", PORT_UNSPECIFIED}, {"filesystem:file:///t/foo", PORT_UNSPECIFIED}, }; for (size_t i = 0; i < std::size(port_tests); i++) { GURL url(port_tests[i].spec); EXPECT_EQ(port_tests[i].expected_int_port, url.EffectiveIntPort()); } } TEST(GURLTest, IPAddress) { struct IPTest { const char* spec; bool expected_ip; } ip_tests[] = { {"http://www.google.com/", false}, {"http://192.168.9.1/", true}, {"http://192.168.9.1.2/", false}, {"http://192.168.m.1/", false}, {"http://2001:db8::1/", false}, {"http://[2001:db8::1]/", true}, {"", false}, {"some random input!", false}, }; for (size_t i = 0; i < std::size(ip_tests); i++) { GURL url(ip_tests[i].spec); EXPECT_EQ(ip_tests[i].expected_ip, url.HostIsIPAddress()); } } TEST(GURLTest, HostNoBrackets) { struct TestCase { const char* input; const char* expected_host; const char* expected_plainhost; } cases[] = { {"http://www.google.com", "www.google.com", "www.google.com"}, {"http://[2001:db8::1]/", "[2001:db8::1]", "2001:db8::1"}, {"http://[::]/", "[::]", "::"}, // Don't require a valid URL, but don't crash either. {"http://[]/", "[]", ""}, {"http://[x]/", "[x]", "x"}, {"http://[x/", "[x", "[x"}, {"http://x]/", "x]", "x]"}, {"http://[/", "[", "["}, {"http://]/", "]", "]"}, {"", "", ""}, }; for (size_t i = 0; i < std::size(cases); i++) { GURL url(cases[i].input); EXPECT_EQ(cases[i].expected_host, url.host()); EXPECT_EQ(cases[i].expected_plainhost, url.HostNoBrackets()); EXPECT_EQ(cases[i].expected_plainhost, url.HostNoBracketsPiece()); } } TEST(GURLTest, DomainIs) { GURL url_1("http://google.com/foo"); EXPECT_TRUE(url_1.DomainIs("google.com")); // Subdomain and port are ignored. GURL url_2("http://www.google.com:99/foo"); EXPECT_TRUE(url_2.DomainIs("google.com")); // Different top-level domain. GURL url_3("http://www.google.com.cn/foo"); EXPECT_FALSE(url_3.DomainIs("google.com")); // Different host name. GURL url_4("http://www.iamnotgoogle.com/foo"); EXPECT_FALSE(url_4.DomainIs("google.com")); // The input must be lower-cased otherwise DomainIs returns false. GURL url_5("http://www.google.com/foo"); EXPECT_FALSE(url_5.DomainIs("Google.com")); // If the URL is invalid, DomainIs returns false. GURL invalid_url("google.com"); EXPECT_FALSE(invalid_url.is_valid()); EXPECT_FALSE(invalid_url.DomainIs("google.com")); GURL url_with_escape_chars("https://www.,.test"); EXPECT_TRUE(url_with_escape_chars.is_valid()); EXPECT_EQ(url_with_escape_chars.host(), "www.%2C.test"); EXPECT_TRUE(url_with_escape_chars.DomainIs("%2C.test")); } TEST(GURLTest, DomainIsTerminatingDotBehavior) { // If the host part ends with a dot, it matches input domains // with or without a dot. GURL url_with_dot("http://www.google.com./foo"); EXPECT_TRUE(url_with_dot.DomainIs("google.com")); EXPECT_TRUE(url_with_dot.DomainIs("google.com.")); EXPECT_TRUE(url_with_dot.DomainIs(".com")); EXPECT_TRUE(url_with_dot.DomainIs(".com.")); // But, if the host name doesn't end with a dot and the input // domain does, then it's considered to not match. GURL url_without_dot("http://google.com/foo"); EXPECT_FALSE(url_without_dot.DomainIs("google.com.")); // If the URL ends with two dots, it doesn't match. GURL url_with_two_dots("http://www.google.com../foo"); EXPECT_FALSE(url_with_two_dots.DomainIs("google.com")); } TEST(GURLTest, DomainIsWithFilesystemScheme) { GURL url_1("filesystem:http://www.google.com:99/foo/"); EXPECT_TRUE(url_1.DomainIs("google.com")); GURL url_2("filesystem:http://www.iamnotgoogle.com/foo/"); EXPECT_FALSE(url_2.DomainIs("google.com")); } // Newlines should be stripped from inputs. TEST(GURLTest, Newlines) { // Constructor. GURL url_1(" \t ht\ntp://\twww.goo\rgle.com/as\ndf \n "); EXPECT_EQ("http://www.google.com/asdf", url_1.spec()); EXPECT_FALSE( url_1.parsed_for_possibly_invalid_spec().potentially_dangling_markup); // Relative path resolver. GURL url_2 = url_1.Resolve(" \n /fo\to\r "); EXPECT_EQ("http://www.google.com/foo", url_2.spec()); EXPECT_FALSE( url_2.parsed_for_possibly_invalid_spec().potentially_dangling_markup); // Constructor. GURL url_3(" \t ht\ntp://\twww.goo\rgle.com/as\ndf< \n "); EXPECT_EQ("http://www.google.com/asdf%3C", url_3.spec()); EXPECT_TRUE( url_3.parsed_for_possibly_invalid_spec().potentially_dangling_markup); // Relative path resolver. GURL url_4 = url_1.Resolve(" \n /fo\to<\r "); EXPECT_EQ("http://www.google.com/foo%3C", url_4.spec()); EXPECT_TRUE( url_4.parsed_for_possibly_invalid_spec().potentially_dangling_markup); // Note that newlines are NOT stripped from ReplaceComponents. } TEST(GURLTest, IsStandard) { GURL a("http:foo/bar"); EXPECT_TRUE(a.IsStandard()); GURL b("foo:bar/baz"); EXPECT_FALSE(b.IsStandard()); GURL c("foo://bar/baz"); EXPECT_FALSE(c.IsStandard()); GURL d("cid:bar@baz"); EXPECT_FALSE(d.IsStandard()); } TEST(GURLTest, SchemeIsHTTPOrHTTPS) { EXPECT_TRUE(GURL("http://bar/").SchemeIsHTTPOrHTTPS()); EXPECT_TRUE(GURL("HTTPS://BAR").SchemeIsHTTPOrHTTPS()); EXPECT_FALSE(GURL("ftp://bar/").SchemeIsHTTPOrHTTPS()); } TEST(GURLTest, SchemeIsWSOrWSS) { EXPECT_TRUE(GURL("WS://BAR/").SchemeIsWSOrWSS()); EXPECT_TRUE(GURL("wss://bar/").SchemeIsWSOrWSS()); EXPECT_FALSE(GURL("http://bar/").SchemeIsWSOrWSS()); } TEST(GURLTest, SchemeIsCryptographic) { EXPECT_TRUE(GURL("https://foo.bar.com/").SchemeIsCryptographic()); EXPECT_TRUE(GURL("HTTPS://foo.bar.com/").SchemeIsCryptographic()); EXPECT_TRUE(GURL("HtTpS://foo.bar.com/").SchemeIsCryptographic()); EXPECT_TRUE(GURL("wss://foo.bar.com/").SchemeIsCryptographic()); EXPECT_TRUE(GURL("WSS://foo.bar.com/").SchemeIsCryptographic()); EXPECT_TRUE(GURL("WsS://foo.bar.com/").SchemeIsCryptographic()); EXPECT_FALSE(GURL("http://foo.bar.com/").SchemeIsCryptographic()); EXPECT_FALSE(GURL("ws://foo.bar.com/").SchemeIsCryptographic()); } TEST(GURLTest, SchemeIsCryptographicStatic) { EXPECT_TRUE(GURL::SchemeIsCryptographic("https")); EXPECT_TRUE(GURL::SchemeIsCryptographic("wss")); EXPECT_FALSE(GURL::SchemeIsCryptographic("http")); EXPECT_FALSE(GURL::SchemeIsCryptographic("ws")); EXPECT_FALSE(GURL::SchemeIsCryptographic("ftp")); } #if BUILDFLAG(IS_OHOS) TEST(GURLTest, SchemeIsCodeCacheEnabled) { GURL a("https://foo.bar.com/"); EXPECT_FALSE(a.SchemeIsCodeCacheEnabled()); GURL b("wss://foo.bar.com/"); EXPECT_FALSE(b.SchemeIsCodeCacheEnabled()); GURL c("http://foo.bar.com/"); EXPECT_FALSE(c.SchemeIsCodeCacheEnabled()); GURL d("blob://foo.bar.com/"); EXPECT_FALSE(d.SchemeIsCodeCacheEnabled()); GURL e("abc://foo.bar.com/"); EXPECT_FALSE(e.SchemeIsCodeCacheEnabled()); } #endif TEST(GURLTest, SchemeIsBlob) { EXPECT_TRUE(GURL("BLOB://BAR/").SchemeIsBlob()); EXPECT_TRUE(GURL("blob://bar/").SchemeIsBlob()); EXPECT_FALSE(GURL("http://bar/").SchemeIsBlob()); } TEST(GURLTest, SchemeIsLocal) { EXPECT_TRUE(GURL("BLOB://BAR/").SchemeIsLocal()); EXPECT_TRUE(GURL("blob://bar/").SchemeIsLocal()); EXPECT_TRUE(GURL("DATA:TEXT/HTML,BAR").SchemeIsLocal()); EXPECT_TRUE(GURL("data:text/html,bar").SchemeIsLocal()); EXPECT_TRUE(GURL("ABOUT:BAR").SchemeIsLocal()); EXPECT_TRUE(GURL("about:bar").SchemeIsLocal()); EXPECT_TRUE(GURL("FILESYSTEM:HTTP://FOO.EXAMPLE/BAR").SchemeIsLocal()); EXPECT_TRUE(GURL("filesystem:http://foo.example/bar").SchemeIsLocal()); EXPECT_FALSE(GURL("http://bar/").SchemeIsLocal()); EXPECT_FALSE(GURL("file:///bar").SchemeIsLocal()); } // Tests that the 'content' of the URL is properly extracted. This can be // complex in cases such as multiple schemes (view-source:http:) or for // javascript URLs. See GURL::GetContent for more details. TEST(GURLTest, ContentForNonStandardURLs) { struct TestCase { const char* url; const char* expected; } cases[] = { {"null", ""}, {"not-a-standard-scheme:this is arbitrary content", "this is arbitrary content"}, // When there are multiple schemes, only the first is excluded from the // content. Note also that for e.g. 'http://', the '//' is part of the // content not the scheme. {"view-source:http://example.com/path", "http://example.com/path"}, {"blob:http://example.com/GUID", "http://example.com/GUID"}, {"blob://http://example.com/GUID", "//http://example.com/GUID"}, {"blob:http://user:password@example.com/GUID", "http://user:password@example.com/GUID"}, // The octothorpe character ('#') marks the end of the URL content, and // the start of the fragment. It should not be included in the content. {"http://www.example.com/GUID#ref", "www.example.com/GUID"}, {"http://me:secret@example.com/GUID/#ref", "me:secret@example.com/GUID/"}, {"data:text/html,Question?<div style=\"color: #bad\">idea</div>", "text/html,Question?%3Cdiv%20style=%22color:%20"}, // TODO(mkwst): This seems like a bug. https://crbug.com/513600 {"filesystem:http://example.com/path", "/"}, // Javascript URLs include '#' symbols in their content. {"javascript:#", "#"}, {"javascript:alert('#');", "alert('#');"}, }; for (const auto& test : cases) { GURL url(test.url); EXPECT_EQ(test.expected, url.GetContent()) << test.url; EXPECT_EQ(test.expected, url.GetContentPiece()) << test.url; } } // Tests that the URL path is properly extracted for unusual URLs. This can be // complex in cases such as multiple schemes (view-source:http:) or when // octothorpes ('#') are involved. TEST(GURLTest, PathForNonStandardURLs) { struct TestCase { const char* url; const char* expected; } cases[] = { {"null", ""}, {"not-a-standard-scheme:this is arbitrary content", "this is arbitrary content"}, {"view-source:http://example.com/path", "http://example.com/path"}, {"blob:http://example.com/GUID", "http://example.com/GUID"}, {"blob://http://example.com/GUID", "//http://example.com/GUID"}, {"blob:http://user:password@example.com/GUID", "http://user:password@example.com/GUID"}, {"http://www.example.com/GUID#ref", "/GUID"}, {"http://me:secret@example.com/GUID/#ref", "/GUID/"}, {"data:text/html,Question?<div style=\"color: #bad\">idea</div>", "text/html,Question"}, // TODO(mkwst): This seems like a bug. https://crbug.com/513600 {"filesystem:http://example.com/path", "/"}, }; for (const auto& test : cases) { GURL url(test.url); EXPECT_EQ(test.expected, url.path()) << test.url; } } TEST(GURLTest, EqualsIgnoringRef) { const struct { const char* url_a; const char* url_b; bool are_equals; } kTestCases[] = { // No ref. {"http://a.com", "http://a.com", true}, {"http://a.com", "http://b.com", false}, // Same Ref. {"http://a.com#foo", "http://a.com#foo", true}, {"http://a.com#foo", "http://b.com#foo", false}, // Different Refs. {"http://a.com#foo", "http://a.com#bar", true}, {"http://a.com#foo", "http://b.com#bar", false}, // One has a ref, the other doesn't. {"http://a.com#foo", "http://a.com", true}, {"http://a.com#foo", "http://b.com", false}, // Empty refs. {"http://a.com#", "http://a.com#", true}, {"http://a.com#", "http://a.com", true}, // URLs that differ only by their last character. {"http://aaa", "http://aab", false}, {"http://aaa#foo", "http://aab#foo", false}, // Different size of the part before the ref. {"http://123#a", "http://123456#a", false}, // Blob URLs {"blob:http://a.com#foo", "blob:http://a.com#foo", true}, {"blob:http://a.com#foo", "blob:http://a.com#bar", true}, {"blob:http://a.com#foo", "blob:http://b.com#bar", false}, // Filesystem URLs {"filesystem:http://a.com#foo", "filesystem:http://a.com#foo", true}, {"filesystem:http://a.com#foo", "filesystem:http://a.com#bar", true}, {"filesystem:http://a.com#foo", "filesystem:http://b.com#bar", false}, // Data URLs {"data:text/html,a#foo", "data:text/html,a#bar", true}, {"data:text/html,a#foo", "data:text/html,a#foo", true}, {"data:text/html,a#foo", "data:text/html,b#foo", false}, }; for (const auto& test_case : kTestCases) { SCOPED_TRACE(testing::Message() << std::endl << "url_a = " << test_case.url_a << std::endl << "url_b = " << test_case.url_b << std::endl); // A versus B. EXPECT_EQ(test_case.are_equals, GURL(test_case.url_a).EqualsIgnoringRef(GURL(test_case.url_b))); // B versus A. EXPECT_EQ(test_case.are_equals, GURL(test_case.url_b).EqualsIgnoringRef(GURL(test_case.url_a))); } } TEST(GURLTest, DebugAlias) { GURL url("https://foo.com/bar"); DEBUG_ALIAS_FOR_GURL(url_debug_alias, url); EXPECT_STREQ("https://foo.com/bar", url_debug_alias); } TEST(GURLTest, InvalidHost) { // This contains an invalid percent escape (%T%) and also a valid // percent escape that's not 7-bit ascii (%ae), so that the unescaped // host contains both an invalid percent escape and invalid UTF-8. GURL url("http://%T%Ae"); EXPECT_FALSE(url.is_valid()); EXPECT_TRUE(url.SchemeIs(url::kHttpScheme)); // The invalid percent escape becomes an escaped percent sign (%25), and the // invalid UTF-8 character becomes REPLACEMENT CHARACTER' (U+FFFD) encoded as // UTF-8. EXPECT_EQ(url.host_piece(), "%25t%EF%BF%BD"); } TEST(GURLTest, PortZero) { GURL port_zero_url("http://127.0.0.1:0/blah"); // https://url.spec.whatwg.org/#port-state says that the port 1) consists of // ASCII digits (this excludes negative numbers) and 2) cannot be greater than // 2^16-1. This means that port=0 should be valid. EXPECT_TRUE(port_zero_url.is_valid()); EXPECT_EQ("0", port_zero_url.port()); EXPECT_EQ("127.0.0.1", port_zero_url.host()); EXPECT_EQ("http", port_zero_url.scheme()); // https://crbug.com/1065532: SchemeHostPort would previously incorrectly // consider port=0 to be invalid. SchemeHostPort scheme_host_port(port_zero_url); EXPECT_TRUE(scheme_host_port.IsValid()); EXPECT_EQ(port_zero_url.scheme(), scheme_host_port.scheme()); EXPECT_EQ(port_zero_url.host(), scheme_host_port.host()); EXPECT_EQ(port_zero_url.port(), base::NumberToString(scheme_host_port.port())); // https://crbug.com/1065532: The SchemeHostPort problem above would lead to // bizarre results below - resolved origin would incorrectly be returned as an // opaque origin derived from |another_origin|. url::Origin another_origin = url::Origin::Create(GURL("http://other.com")); url::Origin resolved_origin = url::Origin::Resolve(port_zero_url, another_origin); EXPECT_FALSE(resolved_origin.opaque()); EXPECT_EQ(port_zero_url.scheme(), resolved_origin.scheme()); EXPECT_EQ(port_zero_url.host(), resolved_origin.host()); EXPECT_EQ(port_zero_url.port(), base::NumberToString(resolved_origin.port())); // port=0 and default HTTP port are different. GURL default_port("http://127.0.0.1/foo"); EXPECT_EQ(0, SchemeHostPort(port_zero_url).port()); EXPECT_EQ(80, SchemeHostPort(default_port).port()); url::Origin default_port_origin = url::Origin::Create(default_port); EXPECT_FALSE(default_port_origin.IsSameOriginWith(resolved_origin)); } class GURLTestTraits { public: using UrlType = GURL; static UrlType CreateUrlFromString(base::StringPiece s) { return GURL(s); } static bool IsAboutBlank(const UrlType& url) { return url.IsAboutBlank(); } static bool IsAboutSrcdoc(const UrlType& url) { return url.IsAboutSrcdoc(); } // Only static members. GURLTestTraits() = delete; }; INSTANTIATE_TYPED_TEST_SUITE_P(GURL, AbstractUrlTest, GURLTestTraits); } // namespace url
Zhao-PengFei35/chromium_src_4
url/gurl_unittest.cc
C++
unknown
44,432
// Copyright 2016 The Chromium Authors // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #ifndef URL_IPC_URL_IPC_EXPORT_H_ #define URL_IPC_URL_IPC_EXPORT_H_ #if defined(COMPONENT_BUILD) #if defined(WIN32) #if defined(URL_IPC_IMPLEMENTATION) #define URL_IPC_EXPORT __declspec(dllexport) #else #define URL_IPC_EXPORT __declspec(dllimport) #endif // defined(URL_IPC_IMPLEMENTATION) #else // defined(WIN32) #if defined(URL_IPC_IMPLEMENTATION) #define URL_IPC_EXPORT __attribute__((visibility("default"))) #else #define URL_IPC_EXPORT #endif #endif #else // defined(COMPONENT_BUILD) #define URL_IPC_EXPORT #endif #endif // URL_IPC_URL_IPC_EXPORT_H_
Zhao-PengFei35/chromium_src_4
url/ipc/url_ipc_export.h
C
unknown
708
// Copyright 2016 The Chromium Authors // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "url/ipc/url_param_traits.h" #include <string> #include "base/pickle.h" #include "url/gurl.h" #include "url/url_constants.h" namespace IPC { void ParamTraits<GURL>::Write(base::Pickle* m, const GURL& p) { if (p.possibly_invalid_spec().length() > url::kMaxURLChars) { m->WriteString(std::string()); return; } // Beware of print-parse inconsistency which would change an invalid // URL into a valid one. Ideally, the message would contain this flag // so that the read side could make the check, but performing it here // avoids changing the on-the-wire representation of such a fundamental // type as GURL. See https://crbug.com/166486 for additional work in // this area. if (!p.is_valid()) { m->WriteString(std::string()); return; } m->WriteString(p.possibly_invalid_spec()); // TODO(brettw) bug 684583: Add encoding for query params. } bool ParamTraits<GURL>::Read(const base::Pickle* m, base::PickleIterator* iter, GURL* p) { std::string s; if (!iter->ReadString(&s) || s.length() > url::kMaxURLChars) { *p = GURL(); return false; } *p = GURL(s); if (!s.empty() && !p->is_valid()) { *p = GURL(); return false; } return true; } void ParamTraits<GURL>::Log(const GURL& p, std::string* l) { l->append(p.spec()); } } // namespace IPC
Zhao-PengFei35/chromium_src_4
url/ipc/url_param_traits.cc
C++
unknown
1,526
// Copyright 2016 The Chromium Authors // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #ifndef URL_IPC_URL_PARAM_TRAITS_H_ #define URL_IPC_URL_PARAM_TRAITS_H_ #include <string> #include "ipc/ipc_param_traits.h" #include "url/gurl.h" #include "url/ipc/url_ipc_export.h" namespace base { class Pickle; class PickleIterator; } // namespace base namespace IPC { template <> struct URL_IPC_EXPORT ParamTraits<GURL> { typedef GURL param_type; static void Write(base::Pickle* m, const param_type& p); static bool Read(const base::Pickle* m, base::PickleIterator* iter, param_type* p); static void Log(const param_type& p, std::string* l); }; } // namespace IPC #endif // URL_IPC_URL_PARAM_TRAITS_H_
Zhao-PengFei35/chromium_src_4
url/ipc/url_param_traits.h
C++
unknown
805
// Copyright 2016 The Chromium Authors // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include <string> #include "ipc/ipc_message.h" #include "ipc/ipc_message_utils.h" #include "testing/gtest/include/gtest/gtest.h" #include "url/gurl.h" #include "url/ipc/url_param_traits.h" namespace { GURL BounceUrl(const GURL& input) { IPC::Message msg(1, 2, IPC::Message::PRIORITY_NORMAL); IPC::ParamTraits<GURL>::Write(&msg, input); GURL output; base::PickleIterator iter(msg); EXPECT_TRUE(IPC::ParamTraits<GURL>::Read(&msg, &iter, &output)); return output; } void ExpectSerializationRoundtrips(const GURL& input) { SCOPED_TRACE(testing::Message() << "Input GURL: " << input.possibly_invalid_spec()); GURL output = BounceUrl(input); // We want to test each component individually to make sure its range was // correctly serialized and deserialized, not just the spec. EXPECT_EQ(input.possibly_invalid_spec(), output.possibly_invalid_spec()); EXPECT_EQ(input.is_valid(), output.is_valid()); EXPECT_EQ(input.scheme(), output.scheme()); EXPECT_EQ(input.username(), output.username()); EXPECT_EQ(input.password(), output.password()); EXPECT_EQ(input.host(), output.host()); EXPECT_EQ(input.port(), output.port()); EXPECT_EQ(input.path(), output.path()); EXPECT_EQ(input.query(), output.query()); EXPECT_EQ(input.ref(), output.ref()); } } // namespace // Tests that serialize/deserialize correctly understand each other. TEST(IPCMessageTest, SerializeGurl_Basic) { const char* serialize_cases[] = { "http://www.google.com/", "http://user:pass@host.com:888/foo;bar?baz#nop", }; for (const char* test_input : serialize_cases) { SCOPED_TRACE(testing::Message() << "Test input: " << test_input); GURL input(test_input); ExpectSerializationRoundtrips(input); } } // Test of an excessively long GURL. TEST(IPCMessageTest, SerializeGurl_ExcessivelyLong) { const std::string url = std::string("http://example.org/").append(url::kMaxURLChars + 1, 'a'); GURL input(url.c_str()); GURL output = BounceUrl(input); EXPECT_TRUE(output.is_empty()); } // Test of an invalid GURL. TEST(IPCMessageTest, SerializeGurl_InvalidUrl) { IPC::Message msg; msg.WriteString("#inva://idurl/"); GURL output; base::PickleIterator iter(msg); EXPECT_FALSE(IPC::ParamTraits<GURL>::Read(&msg, &iter, &output)); } // Test of a corrupt deserialization input. TEST(IPCMessageTest, SerializeGurl_CorruptPayload) { IPC::Message msg(1, 2, IPC::Message::PRIORITY_NORMAL); msg.WriteInt(99); GURL output; base::PickleIterator iter(msg); EXPECT_FALSE(IPC::ParamTraits<GURL>::Read(&msg, &iter, &output)); } // Test for the GURL testcase based on https://crbug.com/1214098 (which in turn // was based on ContentSecurityPolicyBrowserTest.FileURLs). TEST(IPCMessageTest, SerializeGurl_WindowsDriveInPathReplacement) { { // #1: Try creating a file URL with a non-empty hostname. GURL url_without_windows_drive_letter("file://hostname/"); EXPECT_EQ("/", url_without_windows_drive_letter.path()); EXPECT_EQ("hostname", url_without_windows_drive_letter.host()); ExpectSerializationRoundtrips(url_without_windows_drive_letter); } { // #2: Use GURL::Replacement to create a GURL with 1) a path that starts // with a Windows drive letter and 2) has a non-empty hostname (inherited // from `url_without_windows_drive_letter` above). This used to not go // through the DoParseUNC path that normally strips the hostname (for more // details, see https://crbug.com/1214098#c4). GURL::Replacements repl; const std::string kNewPath = "/C:/dir/file.txt"; repl.SetPathStr(kNewPath); GURL url_made_with_replace_components = GURL("file://hostname/").ReplaceComponents(repl); EXPECT_EQ(kNewPath, url_made_with_replace_components.path()); EXPECT_EQ("hostname", url_made_with_replace_components.host()); EXPECT_EQ("file://hostname/C:/dir/file.txt", url_made_with_replace_components.spec()); // This is the MAIN VERIFICATION in this test. This used to fail on Windows, // see https://crbug.com/1214098. ExpectSerializationRoundtrips(url_made_with_replace_components); } { // #3: Try to create a URL with a Windows drive letter and a non-empty // hostname directly. GURL url_created_directly("file://hostname/C:/dir/file.txt"); EXPECT_EQ("/C:/dir/file.txt", url_created_directly.path()); EXPECT_EQ("hostname", url_created_directly.host()); EXPECT_EQ("file://hostname/C:/dir/file.txt", url_created_directly.spec()); ExpectSerializationRoundtrips(url_created_directly); // The URL created directly and the URL created through ReplaceComponents // should be the same. GURL::Replacements repl; const std::string kNewPath = "/C:/dir/file.txt"; repl.SetPathStr(kNewPath); GURL url_made_with_replace_components = GURL("file://hostname/").ReplaceComponents(repl); EXPECT_EQ(url_created_directly.spec(), url_made_with_replace_components.spec()); } { // #4: Try to create a URL with a Windows drive letter and "localhost" as // hostname directly. GURL url_created_directly("file://localhost/C:/dir/file.txt"); EXPECT_EQ("/C:/dir/file.txt", url_created_directly.path()); EXPECT_EQ("", url_created_directly.host()); EXPECT_EQ("file:///C:/dir/file.txt", url_created_directly.spec()); ExpectSerializationRoundtrips(url_created_directly); // The URL created directly and the URL created through ReplaceComponents // should be the same. GURL::Replacements repl; const std::string kNewPath = "/C:/dir/file.txt"; repl.SetPathStr(kNewPath); GURL url_made_with_replace_components = GURL("file://localhost/").ReplaceComponents(repl); EXPECT_EQ(url_created_directly.spec(), url_made_with_replace_components.spec()); } }
Zhao-PengFei35/chromium_src_4
url/ipc/url_param_traits_unittest.cc
C++
unknown
5,981
include_rules = [ "+mojo/public/cpp", ]
Zhao-PengFei35/chromium_src_4
url/mojom/DEPS
Python
unknown
42
// Copyright 2020 The Chromium Authors // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "url/mojom/origin_mojom_traits.h" #include "base/strings/string_piece.h" namespace mojo { // static bool StructTraits<url::mojom::OriginDataView, url::Origin>::Read( url::mojom::OriginDataView data, url::Origin* out) { base::StringPiece scheme, host; absl::optional<base::UnguessableToken> nonce_if_opaque; if (!data.ReadScheme(&scheme) || !data.ReadHost(&host) || !data.ReadNonceIfOpaque(&nonce_if_opaque)) return false; absl::optional<url::Origin> creation_result = nonce_if_opaque ? url::Origin::UnsafelyCreateOpaqueOriginWithoutNormalization( scheme, host, data.port(), url::Origin::Nonce(*nonce_if_opaque)) : url::Origin::UnsafelyCreateTupleOriginWithoutNormalization( scheme, host, data.port()); if (!creation_result) return false; *out = std::move(creation_result.value()); return true; } } // namespace mojo
Zhao-PengFei35/chromium_src_4
url/mojom/origin_mojom_traits.cc
C++
unknown
1,070
// Copyright 2016 The Chromium Authors // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #ifndef URL_MOJOM_ORIGIN_MOJOM_TRAITS_H_ #define URL_MOJOM_ORIGIN_MOJOM_TRAITS_H_ #include "base/component_export.h" #include "base/unguessable_token.h" #include "mojo/public/cpp/base/unguessable_token_mojom_traits.h" #include "mojo/public/cpp/bindings/optional_as_pointer.h" #include "third_party/abseil-cpp/absl/types/optional.h" #include "url/mojom/origin.mojom-shared.h" #include "url/origin.h" namespace mojo { template <> struct COMPONENT_EXPORT(URL_MOJOM_TRAITS) StructTraits<url::mojom::OriginDataView, url::Origin> { static const std::string& scheme(const url::Origin& r) { return r.GetTupleOrPrecursorTupleIfOpaque().scheme(); } static const std::string& host(const url::Origin& r) { return r.GetTupleOrPrecursorTupleIfOpaque().host(); } static uint16_t port(const url::Origin& r) { return r.GetTupleOrPrecursorTupleIfOpaque().port(); } static mojo::OptionalAsPointer<const base::UnguessableToken> nonce_if_opaque( const url::Origin& r) { return mojo::MakeOptionalAsPointer(r.GetNonceForSerialization()); } static bool Read(url::mojom::OriginDataView data, url::Origin* out); }; } // namespace mojo #endif // URL_MOJOM_ORIGIN_MOJOM_TRAITS_H_
Zhao-PengFei35/chromium_src_4
url/mojom/origin_mojom_traits.h
C++
unknown
1,347
// Copyright 2021 The Chromium Authors // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "url/mojom/scheme_host_port_mojom_traits.h" #include "base/strings/string_piece.h" #include "url/mojom/scheme_host_port.mojom-shared.h" #include "url/scheme_host_port.h" namespace mojo { // static bool StructTraits<url::mojom::SchemeHostPortDataView, url::SchemeHostPort>:: Read(url::mojom::SchemeHostPortDataView data, url::SchemeHostPort* out) { base::StringPiece scheme, host; if (!data.ReadScheme(&scheme) || !data.ReadHost(&host)) return false; *out = url::SchemeHostPort(scheme, host, data.port()); // Consider it an error if the output SchemeHostPort is not valid, but // non-empty values were received over Mojo. return out->IsValid() || (scheme.empty() && host.empty() && data.port() == 0); } } // namespace mojo
Zhao-PengFei35/chromium_src_4
url/mojom/scheme_host_port_mojom_traits.cc
C++
unknown
902
// Copyright 2021 The Chromium Authors // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #ifndef URL_MOJOM_SCHEME_HOST_PORT_MOJOM_TRAITS_H_ #define URL_MOJOM_SCHEME_HOST_PORT_MOJOM_TRAITS_H_ #include "base/component_export.h" #include "url/mojom/scheme_host_port.mojom-shared.h" #include "url/scheme_host_port.h" namespace mojo { template <> struct COMPONENT_EXPORT(URL_MOJOM_TRAITS) StructTraits<url::mojom::SchemeHostPortDataView, url::SchemeHostPort> { static const std::string& scheme(const url::SchemeHostPort& r) { return r.scheme(); } static const std::string& host(const url::SchemeHostPort& r) { return r.host(); } static uint16_t port(const url::SchemeHostPort& r) { return r.port(); } static bool Read(url::mojom::SchemeHostPortDataView data, url::SchemeHostPort* out); }; } // namespace mojo #endif // URL_MOJOM_SCHEME_HOST_PORT_MOJOM_TRAITS_H_
Zhao-PengFei35/chromium_src_4
url/mojom/scheme_host_port_mojom_traits.h
C++
unknown
962
// Copyright 2021 The Chromium Authors // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "url/mojom/scheme_host_port_mojom_traits.h" #include <string> #include "mojo/public/cpp/test_support/test_utils.h" #include "testing/gtest/include/gtest/gtest.h" #include "url/mojom/scheme_host_port.mojom.h" #include "url/scheme_host_port.h" namespace url { namespace { void TestRoundTrip(const url::SchemeHostPort& in) { url::SchemeHostPort result; ASSERT_TRUE( mojo::test::SerializeAndDeserialize<mojom::SchemeHostPort>(in, result)) << in.Serialize(); EXPECT_EQ(in, result) << "Expected " << in.Serialize() << ", but got " << result.Serialize(); } } // namespace TEST(SchemeHostPortMojomTraitsTest, RoundTrip) { TestRoundTrip(url::SchemeHostPort()); TestRoundTrip(url::SchemeHostPort("http", "test", 80)); TestRoundTrip(url::SchemeHostPort("https", "foo.test", 443)); TestRoundTrip(url::SchemeHostPort("file", "", 0)); } } // namespace url
Zhao-PengFei35/chromium_src_4
url/mojom/scheme_host_port_mojom_traits_unittest.cc
C++
unknown
1,055
// Copyright 2020 The Chromium Authors // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "url/mojom/url_gurl_mojom_traits.h" #include "url/url_constants.h" namespace mojo { // static base::StringPiece StructTraits<url::mojom::UrlDataView, GURL>::url( const GURL& r) { if (r.possibly_invalid_spec().length() > url::kMaxURLChars || !r.is_valid()) { return base::StringPiece(); } return base::StringPiece(r.possibly_invalid_spec().c_str(), r.possibly_invalid_spec().length()); } // static bool StructTraits<url::mojom::UrlDataView, GURL>::Read( url::mojom::UrlDataView data, GURL* out) { base::StringPiece url_string; if (!data.ReadUrl(&url_string)) return false; if (url_string.length() > url::kMaxURLChars) return false; *out = GURL(url_string); if (!url_string.empty() && !out->is_valid()) return false; return true; } } // namespace mojo
Zhao-PengFei35/chromium_src_4
url/mojom/url_gurl_mojom_traits.cc
C++
unknown
986
// Copyright 2016 The Chromium Authors // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #ifndef URL_MOJOM_URL_GURL_MOJOM_TRAITS_H_ #define URL_MOJOM_URL_GURL_MOJOM_TRAITS_H_ #include "base/component_export.h" #include "base/strings/string_piece.h" #include "mojo/public/cpp/bindings/struct_traits.h" #include "url/gurl.h" #include "url/mojom/url.mojom-shared.h" namespace mojo { template <> struct COMPONENT_EXPORT(URL_MOJOM_TRAITS) StructTraits<url::mojom::UrlDataView, GURL> { static base::StringPiece url(const GURL& r); static bool Read(url::mojom::UrlDataView data, GURL* out); }; } // namespace mojo #endif // URL_MOJOM_URL_GURL_MOJOM_TRAITS_H_
Zhao-PengFei35/chromium_src_4
url/mojom/url_gurl_mojom_traits.h
C++
unknown
722
// Copyright 2016 The Chromium Authors // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include <utility> #include "base/test/task_environment.h" #include "mojo/public/cpp/bindings/pending_receiver.h" #include "mojo/public/cpp/bindings/receiver.h" #include "mojo/public/cpp/bindings/remote.h" #include "testing/gtest/include/gtest/gtest.h" #include "url/mojom/url_test.mojom.h" namespace url { class UrlTestImpl : public mojom::UrlTest { public: explicit UrlTestImpl(mojo::PendingReceiver<mojom::UrlTest> receiver) : receiver_(this, std::move(receiver)) {} // UrlTest: void BounceUrl(const GURL& in, BounceUrlCallback callback) override { std::move(callback).Run(in); } void BounceOrigin(const Origin& in, BounceOriginCallback callback) override { std::move(callback).Run(in); } private: mojo::Receiver<UrlTest> receiver_; }; class MojoGURLStructTraitsTest : public ::testing::Test { public: MojoGURLStructTraitsTest() : url_test_impl_(url_test_remote_.BindNewPipeAndPassReceiver()) {} GURL BounceUrl(const GURL& input) { GURL output; EXPECT_TRUE(url_test_remote_->BounceUrl(input, &output)); return output; } void ExpectSerializationRoundtrips(const GURL& input) { SCOPED_TRACE(testing::Message() << "Input GURL: " << input.possibly_invalid_spec()); GURL output = BounceUrl(input); // We want to test each component individually to make sure its range was // correctly serialized and deserialized, not just the spec. EXPECT_EQ(input.possibly_invalid_spec(), output.possibly_invalid_spec()); EXPECT_EQ(input.is_valid(), output.is_valid()); EXPECT_EQ(input.scheme(), output.scheme()); EXPECT_EQ(input.username(), output.username()); EXPECT_EQ(input.password(), output.password()); EXPECT_EQ(input.host(), output.host()); EXPECT_EQ(input.port(), output.port()); EXPECT_EQ(input.path(), output.path()); EXPECT_EQ(input.query(), output.query()); EXPECT_EQ(input.ref(), output.ref()); } Origin BounceOrigin(const Origin& input) { Origin output; EXPECT_TRUE(url_test_remote_->BounceOrigin(input, &output)); return output; } private: base::test::SingleThreadTaskEnvironment task_environment; mojo::Remote<mojom::UrlTest> url_test_remote_; UrlTestImpl url_test_impl_; }; // Mojo version of chrome IPC test in url/ipc/url_param_traits_unittest.cc. TEST_F(MojoGURLStructTraitsTest, Basic) { const char* serialize_cases[] = { "http://www.google.com/", "http://user:pass@host.com:888/foo;bar?baz#nop", }; for (const char* test_input : serialize_cases) { SCOPED_TRACE(testing::Message() << "Test input: " << test_input); GURL input(test_input); ExpectSerializationRoundtrips(input); } } // Test of an excessively long GURL. TEST_F(MojoGURLStructTraitsTest, ExcessivelyLongUrl) { const std::string url = std::string("http://example.org/").append(kMaxURLChars + 1, 'a'); GURL input(url.c_str()); GURL output = BounceUrl(input); EXPECT_TRUE(output.is_empty()); } // Test for the GURL testcase based on https://crbug.com/1214098 (which in turn // was based on ContentSecurityPolicyBrowserTest.FileURLs). TEST_F(MojoGURLStructTraitsTest, WindowsDriveInPathReplacement) { { // #1: Try creating a file URL with a non-empty hostname. GURL url_without_windows_drive_letter("file://hostname/"); EXPECT_EQ("/", url_without_windows_drive_letter.path()); EXPECT_EQ("hostname", url_without_windows_drive_letter.host()); ExpectSerializationRoundtrips(url_without_windows_drive_letter); } { // #2: Use GURL::Replacement to create a GURL with 1) a path that starts // with a Windows drive letter and 2) has a non-empty hostname (inherited // from `url_without_windows_drive_letter` above). This used to not go // through the DoParseUNC path that normally strips the hostname (for more // details, see https://crbug.com/1214098#c4). GURL::Replacements repl; const std::string kNewPath = "/C:/dir/file.txt"; repl.SetPathStr(kNewPath); GURL url_made_with_replace_components = GURL("file://hostname/").ReplaceComponents(repl); EXPECT_EQ(kNewPath, url_made_with_replace_components.path()); EXPECT_EQ("hostname", url_made_with_replace_components.host()); EXPECT_EQ("file://hostname/C:/dir/file.txt", url_made_with_replace_components.spec()); // This is the MAIN VERIFICATION in this test. This used to fail on Windows, // see https://crbug.com/1214098. ExpectSerializationRoundtrips(url_made_with_replace_components); } { // #3: Try to create a URL with a Windows drive letter and a non-empty // hostname directly. GURL url_created_directly("file://hostname/C:/dir/file.txt"); EXPECT_EQ("/C:/dir/file.txt", url_created_directly.path()); EXPECT_EQ("hostname", url_created_directly.host()); EXPECT_EQ("file://hostname/C:/dir/file.txt", url_created_directly.spec()); ExpectSerializationRoundtrips(url_created_directly); // The URL created directly and the URL created through ReplaceComponents // should be the same. GURL::Replacements repl; const std::string kNewPath = "/C:/dir/file.txt"; repl.SetPathStr(kNewPath); GURL url_made_with_replace_components = GURL("file://hostname/").ReplaceComponents(repl); EXPECT_EQ(url_created_directly.spec(), url_made_with_replace_components.spec()); } { // #4: Try to create a URL with a Windows drive letter and "localhost" as // hostname directly. GURL url_created_directly("file://localhost/C:/dir/file.txt"); EXPECT_EQ("/C:/dir/file.txt", url_created_directly.path()); EXPECT_EQ("", url_created_directly.host()); EXPECT_EQ("file:///C:/dir/file.txt", url_created_directly.spec()); ExpectSerializationRoundtrips(url_created_directly); // The URL created directly and the URL created through ReplaceComponents // should be the same. GURL::Replacements repl; const std::string kNewPath = "/C:/dir/file.txt"; repl.SetPathStr(kNewPath); GURL url_made_with_replace_components = GURL("file://localhost/").ReplaceComponents(repl); EXPECT_EQ(url_created_directly.spec(), url_made_with_replace_components.spec()); } } // Test of basic Origin serialization. TEST_F(MojoGURLStructTraitsTest, OriginSerialization) { Origin non_unique = Origin::UnsafelyCreateTupleOriginWithoutNormalization( "http", "www.google.com", 80) .value(); Origin output = BounceOrigin(non_unique); EXPECT_EQ(non_unique, output); EXPECT_FALSE(output.opaque()); Origin unique1; Origin unique2 = non_unique.DeriveNewOpaqueOrigin(); EXPECT_NE(unique1, unique2); EXPECT_NE(unique2, unique1); EXPECT_NE(unique2, non_unique); output = BounceOrigin(unique1); EXPECT_TRUE(output.opaque()); EXPECT_EQ(unique1, output); Origin output2 = BounceOrigin(unique2); EXPECT_EQ(unique2, output2); EXPECT_NE(unique2, output); EXPECT_NE(unique1, output2); Origin normalized = Origin::CreateFromNormalizedTuple("http", "www.google.com", 80); EXPECT_EQ(normalized, non_unique); output = BounceOrigin(normalized); EXPECT_EQ(normalized, output); EXPECT_EQ(non_unique, output); EXPECT_FALSE(output.opaque()); } // Test that the "kMaxURLChars" values are the same in url.mojom and // url_constants.cc. TEST_F(MojoGURLStructTraitsTest, TestMaxURLChars) { EXPECT_EQ(kMaxURLChars, mojom::kMaxURLChars); } } // namespace url
Zhao-PengFei35/chromium_src_4
url/mojom/url_gurl_mojom_traits_unittest.cc
C++
unknown
7,623
// Copyright 2015 The Chromium Authors // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "url/origin.h" #include <stdint.h> #include <algorithm> #include <ostream> #include <string> #include <tuple> #include <utility> #include "base/base64.h" #include "base/check.h" #include "base/check_op.h" #include "base/containers/contains.h" #include "base/containers/span.h" #include "base/debug/crash_logging.h" #include "base/pickle.h" #include "base/strings/strcat.h" #include "base/strings/string_piece.h" #include "base/trace_event/base_tracing.h" #include "base/unguessable_token.h" #include "url/gurl.h" #include "url/scheme_host_port.h" #include "url/url_constants.h" #include "url/url_util.h" namespace url { Origin::Origin() : nonce_(Nonce()) {} Origin Origin::Create(const GURL& url) { if (!url.is_valid()) return Origin(); SchemeHostPort tuple; if (url.SchemeIsFileSystem()) { tuple = SchemeHostPort(*url.inner_url()); } else if (url.SchemeIsBlob()) { // If we're dealing with a 'blob:' URL, https://url.spec.whatwg.org/#origin // defines the origin as the origin of the URL which results from parsing // the "path", which boils down to everything after the scheme. GURL's // 'GetContent()' gives us exactly that. tuple = SchemeHostPort(GURL(url.GetContent())); } else { tuple = SchemeHostPort(url); // It's SchemeHostPort's responsibility to filter out unrecognized schemes; // sanity check that this is happening. DCHECK(!tuple.IsValid() || url.IsStandard() || base::Contains(GetLocalSchemes(), url.scheme_piece()) || AllowNonStandardSchemesForAndroidWebView()); } if (!tuple.IsValid()) return Origin(); return Origin(std::move(tuple)); } Origin Origin::Resolve(const GURL& url, const Origin& base_origin) { if (url.SchemeIs(kAboutScheme) || url.is_empty()) return base_origin; Origin result = Origin::Create(url); if (!result.opaque()) return result; return base_origin.DeriveNewOpaqueOrigin(); } Origin::Origin(const Origin&) = default; Origin& Origin::operator=(const Origin&) = default; Origin::Origin(Origin&&) noexcept = default; Origin& Origin::operator=(Origin&&) noexcept = default; Origin::~Origin() = default; // static absl::optional<Origin> Origin::UnsafelyCreateTupleOriginWithoutNormalization( base::StringPiece scheme, base::StringPiece host, uint16_t port) { SchemeHostPort tuple(std::string(scheme), std::string(host), port, SchemeHostPort::CHECK_CANONICALIZATION); if (!tuple.IsValid()) return absl::nullopt; return Origin(std::move(tuple)); } // static absl::optional<Origin> Origin::UnsafelyCreateOpaqueOriginWithoutNormalization( base::StringPiece precursor_scheme, base::StringPiece precursor_host, uint16_t precursor_port, const Origin::Nonce& nonce) { SchemeHostPort precursor(std::string(precursor_scheme), std::string(precursor_host), precursor_port, SchemeHostPort::CHECK_CANONICALIZATION); // For opaque origins, it is okay for the SchemeHostPort to be invalid; // however, this should only arise when the arguments indicate the // canonical representation of the invalid SchemeHostPort. if (!precursor.IsValid() && !(precursor_scheme.empty() && precursor_host.empty() && precursor_port == 0)) { return absl::nullopt; } return Origin(std::move(nonce), std::move(precursor)); } // static Origin Origin::CreateFromNormalizedTuple(std::string scheme, std::string host, uint16_t port) { SchemeHostPort tuple(std::move(scheme), std::move(host), port, SchemeHostPort::ALREADY_CANONICALIZED); if (!tuple.IsValid()) return Origin(); return Origin(std::move(tuple)); } // static Origin Origin::CreateOpaqueFromNormalizedPrecursorTuple( std::string precursor_scheme, std::string precursor_host, uint16_t precursor_port, const Origin::Nonce& nonce) { SchemeHostPort precursor(std::move(precursor_scheme), std::move(precursor_host), precursor_port, SchemeHostPort::ALREADY_CANONICALIZED); // For opaque origins, it is okay for the SchemeHostPort to be invalid. return Origin(std::move(nonce), std::move(precursor)); } std::string Origin::Serialize() const { if (opaque()) return "null"; if (scheme() == kFileScheme) return "file://"; return tuple_.Serialize(); } GURL Origin::GetURL() const { if (opaque()) return GURL(); if (scheme() == kFileScheme) return GURL("file:///"); return tuple_.GetURL(); } const base::UnguessableToken* Origin::GetNonceForSerialization() const { return nonce_ ? &nonce_->token() : nullptr; } bool Origin::IsSameOriginWith(const Origin& other) const { // scheme/host/port must match, even for opaque origins where |tuple_| holds // the precursor origin. return std::tie(tuple_, nonce_) == std::tie(other.tuple_, other.nonce_); } bool Origin::IsSameOriginWith(const GURL& url) const { if (opaque()) return false; // The `url::Origin::Create` call here preserves how IsSameOriginWith was used // historically, even though in some scenarios it is not clearly correct: // - Origin of about:blank and about:srcdoc cannot be correctly // computed/recovered. // - Ideally passing an invalid `url` would be a caller error (e.g. a DCHECK). // - The caller intent is not always clear wrt handling the outer-vs-inner // origins/URLs in blob: and filesystem: schemes. return IsSameOriginWith(url::Origin::Create(url)); } bool Origin::CanBeDerivedFrom(const GURL& url) const { DCHECK(url.is_valid()); // For "no access" schemes, blink's SecurityOrigin will always create an // opaque unique one. However, about: scheme is also registered as such but // does not behave this way, therefore exclude it from this check. if (base::Contains(url::GetNoAccessSchemes(), url.scheme()) && !url.SchemeIs(kAboutScheme)) { // If |this| is not opaque, definitely return false as the expectation // is for opaque origin. if (!opaque()) return false; // And if it is unique opaque origin, it definitely is fine. But if there // is a precursor stored, we should fall through to compare the tuples. if (!tuple_.IsValid()) return true; } SchemeHostPort url_tuple; // Optimization for the common, success case: Scheme/Host/Port match on the // precursor, and the URL is standard. Opaqueness does not matter as a tuple // origin can always create an opaque tuple origin. if (url.IsStandard()) { // Note: if extra copies of the scheme and host are undesirable, this check // can be implemented using StringPiece comparisons, but it has to account // explicitly checks on port numbers. if (url.SchemeIsFileSystem()) { url_tuple = SchemeHostPort(*url.inner_url()); } else { url_tuple = SchemeHostPort(url); } return url_tuple == tuple_; // Blob URLs still contain an inner origin, however it is not accessible // through inner_url(), therefore it requires specific case to handle it. } else if (url.SchemeIsBlob()) { // If |this| doesn't contain any precursor information, it is an unique // opaque origin. It is valid case, as any browser-initiated navigation // to about:blank or data: URL will result in a document with such // origin and it is valid for it to create blob: URLs. if (!tuple_.IsValid()) return true; url_tuple = SchemeHostPort(GURL(url.GetContent())); return url_tuple == tuple_; } // At this point, the URL has non-standard scheme. DCHECK(!url.IsStandard()); // All about: URLs (about:blank, about:srcdoc) inherit their origin from // the context which navigated them, which means that they can be in any // type of origin. if (url.SchemeIs(kAboutScheme)) return true; // All data: URLs commit in opaque origins, therefore |this| must be opaque // if |url| has data: scheme. if (url.SchemeIs(kDataScheme)) return opaque(); // If |this| does not have valid precursor tuple, it is unique opaque origin, // which is what we expect non-standard schemes to get. if (!tuple_.IsValid()) return true; // However, when there is precursor present, the schemes must match. return url.scheme() == tuple_.scheme(); } bool Origin::DomainIs(base::StringPiece canonical_domain) const { return !opaque() && url::DomainIs(tuple_.host(), canonical_domain); } bool Origin::operator<(const Origin& other) const { return std::tie(tuple_, nonce_) < std::tie(other.tuple_, other.nonce_); } Origin Origin::DeriveNewOpaqueOrigin() const { return Origin(Nonce(), tuple_); } std::string Origin::GetDebugString(bool include_nonce) const { // Handle non-opaque origins first, as they are simpler. if (!opaque()) { std::string out = Serialize(); if (scheme() == kFileScheme) base::StrAppend(&out, {" [internally: ", tuple_.Serialize(), "]"}); return out; } // For opaque origins, log the nonce and precursor as well. Without this, // EXPECT_EQ failures between opaque origins are nearly impossible to // understand. std::string out = base::StrCat({Serialize(), " [internally:"}); if (include_nonce) { out += " ("; if (nonce_->raw_token().is_empty()) out += "nonce TBD"; else out += nonce_->raw_token().ToString(); out += ")"; } if (!tuple_.IsValid()) base::StrAppend(&out, {" anonymous]"}); else base::StrAppend(&out, {" derived from ", tuple_.Serialize(), "]"}); return out; } Origin::Origin(SchemeHostPort tuple) : tuple_(std::move(tuple)) { DCHECK(!opaque()); DCHECK(tuple_.IsValid()); } // Constructs an opaque origin derived from |precursor|. Origin::Origin(const Nonce& nonce, SchemeHostPort precursor) : tuple_(std::move(precursor)), nonce_(std::move(nonce)) { DCHECK(opaque()); // |precursor| is retained, but not accessible via scheme()/host()/port(). DCHECK_EQ("", scheme()); DCHECK_EQ("", host()); DCHECK_EQ(0U, port()); } absl::optional<std::string> Origin::SerializeWithNonce() const { return SerializeWithNonceImpl(); } absl::optional<std::string> Origin::SerializeWithNonceAndInitIfNeeded() { GetNonceForSerialization(); return SerializeWithNonceImpl(); } // The pickle is saved in the following format, in order: // string - tuple_.GetURL().spec(). // uint64_t (if opaque) - high bits of nonce if opaque. 0 if not initialized. // uint64_t (if opaque) - low bits of nonce if opaque. 0 if not initialized. absl::optional<std::string> Origin::SerializeWithNonceImpl() const { if (!opaque() && !tuple_.IsValid()) return absl::nullopt; base::Pickle pickle; pickle.WriteString(tuple_.Serialize()); if (opaque() && !nonce_->raw_token().is_empty()) { pickle.WriteUInt64(nonce_->token().GetHighForSerialization()); pickle.WriteUInt64(nonce_->token().GetLowForSerialization()); } else if (opaque()) { // Nonce hasn't been initialized. pickle.WriteUInt64(0); pickle.WriteUInt64(0); } base::span<const uint8_t> data(static_cast<const uint8_t*>(pickle.data()), pickle.size()); // Base64 encode the data to make it nicer to play with. return base::Base64Encode(data); } // static absl::optional<Origin> Origin::Deserialize(const std::string& value) { std::string data; if (!base::Base64Decode(value, &data)) return absl::nullopt; base::Pickle pickle(reinterpret_cast<char*>(&data[0]), data.size()); base::PickleIterator reader(pickle); std::string pickled_url; if (!reader.ReadString(&pickled_url)) return absl::nullopt; GURL url(pickled_url); // If only a tuple was serialized, then this origin is not opaque. For opaque // origins, we expect two uint64's to be left in the pickle. bool is_opaque = !reader.ReachedEnd(); // Opaque origins without a tuple are ok. if (!is_opaque && !url.is_valid()) return absl::nullopt; SchemeHostPort tuple(url); // Possible successful early return if the pickled Origin was not opaque. if (!is_opaque) { Origin origin(tuple); if (origin.opaque()) return absl::nullopt; // Something went horribly wrong. return origin; } uint64_t nonce_high = 0; if (!reader.ReadUInt64(&nonce_high)) return absl::nullopt; uint64_t nonce_low = 0; if (!reader.ReadUInt64(&nonce_low)) return absl::nullopt; absl::optional<base::UnguessableToken> nonce_token = base::UnguessableToken::Deserialize(nonce_high, nonce_low); Origin::Nonce nonce; if (nonce_token.has_value()) { // The serialized nonce wasn't empty, so copy it here. nonce = Origin::Nonce(nonce_token.value()); } Origin origin; origin.nonce_ = std::move(nonce); origin.tuple_ = tuple; return origin; } void Origin::WriteIntoTrace(perfetto::TracedValue context) const { std::move(context).WriteString(GetDebugString()); } std::ostream& operator<<(std::ostream& out, const url::Origin& origin) { out << origin.GetDebugString(); return out; } std::ostream& operator<<(std::ostream& out, const url::Origin::Nonce& nonce) { // Subtle: don't let logging trigger lazy-generation of the token value. if (nonce.raw_token().is_empty()) return (out << "(nonce TBD)"); else return (out << nonce.raw_token()); } bool IsSameOriginWith(const GURL& a, const GURL& b) { return Origin::Create(a).IsSameOriginWith(Origin::Create(b)); } Origin::Nonce::Nonce() = default; Origin::Nonce::Nonce(const base::UnguessableToken& token) : token_(token) { CHECK(!token_.is_empty()); } const base::UnguessableToken& Origin::Nonce::token() const { // Inspecting the value of a nonce triggers lazy-generation. // TODO(dcheng): UnguessableToken::is_empty should go away -- what sentinel // value to use instead? if (token_.is_empty()) token_ = base::UnguessableToken::Create(); return token_; } const base::UnguessableToken& Origin::Nonce::raw_token() const { return token_; } // Copying a Nonce triggers lazy-generation of the token. Origin::Nonce::Nonce(const Origin::Nonce& other) : token_(other.token()) {} Origin::Nonce& Origin::Nonce::operator=(const Origin::Nonce& other) { // Copying a Nonce triggers lazy-generation of the token. token_ = other.token(); return *this; } // Moving a nonce does NOT trigger lazy-generation of the token. Origin::Nonce::Nonce(Origin::Nonce&& other) noexcept : token_(other.token_) { other.token_ = base::UnguessableToken(); // Reset |other|. } Origin::Nonce& Origin::Nonce::operator=(Origin::Nonce&& other) noexcept { token_ = other.token_; other.token_ = base::UnguessableToken(); // Reset |other|. return *this; } bool Origin::Nonce::operator<(const Origin::Nonce& other) const { // When comparing, lazy-generation is required of both tokens, so that an // ordering is established. return token() < other.token(); } bool Origin::Nonce::operator==(const Origin::Nonce& other) const { // Equality testing doesn't actually require that the tokens be generated. // If the tokens are both zero, equality only holds if they're the same // object. return (other.token_ == token_) && !(token_.is_empty() && (&other != this)); } bool Origin::Nonce::operator!=(const Origin::Nonce& other) const { return !(*this == other); } namespace debug { ScopedOriginCrashKey::ScopedOriginCrashKey( base::debug::CrashKeyString* crash_key, const url::Origin* value) : scoped_string_value_( crash_key, value ? value->GetDebugString(false /* include_nonce */) : "nullptr") {} ScopedOriginCrashKey::~ScopedOriginCrashKey() = default; } // namespace debug } // namespace url
Zhao-PengFei35/chromium_src_4
url/origin.cc
C++
unknown
15,884
// Copyright 2015 The Chromium Authors // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #ifndef URL_ORIGIN_H_ #define URL_ORIGIN_H_ #include <stdint.h> #include <memory> #include <string> #include "base/component_export.h" #include "base/debug/alias.h" #include "base/debug/crash_logging.h" #include "base/gtest_prod_util.h" #include "base/strings/string_piece_forward.h" #include "base/strings/string_util.h" #include "base/trace_event/base_tracing_forward.h" #include "base/unguessable_token.h" #include "build/build_config.h" #include "build/buildflag.h" #include "third_party/abseil-cpp/absl/types/optional.h" #include "url/scheme_host_port.h" #if BUILDFLAG(IS_ANDROID) #include <jni.h> namespace base { namespace android { template <typename> class ScopedJavaLocalRef; template <typename> class JavaRef; } // namespace android } // namespace base #endif // BUILDFLAG(IS_ANDROID) class GURL; namespace blink { class SecurityOrigin; class SecurityOriginTest; class StorageKey; class StorageKeyTest; } // namespace blink namespace IPC { template <class P> struct ParamTraits; } // namespace IPC namespace ipc_fuzzer { template <class T> struct FuzzTraits; } // namespace ipc_fuzzer namespace mojo { template <typename DataViewType, typename T> struct StructTraits; struct UrlOriginAdapter; } // namespace mojo namespace net { class SchemefulSite; } // namespace net namespace url { namespace mojom { class OriginDataView; } // namespace mojom // Per https://html.spec.whatwg.org/multipage/origin.html#origin, an origin is // either: // - a tuple origin of (scheme, host, port) as described in RFC 6454. // - an opaque origin with an internal value, and a memory of the tuple origin // from which it was derived. // // TL;DR: If you need to make a security-relevant decision, use 'url::Origin'. // If you only need to extract the bits of a URL which are relevant for a // network connection, use 'url::SchemeHostPort'. // // STL;SDR: If you aren't making actual network connections, use 'url::Origin'. // // This class ought to be used when code needs to determine if two resources // are "same-origin", and when a canonical serialization of an origin is // required. Note that the canonical serialization of an origin *must not* be // used to determine if two resources are same-origin. // // A tuple origin, like 'SchemeHostPort', is composed of a tuple of (scheme, // host, port), but contains a number of additional concepts which make it // appropriate for use as a security boundary and access control mechanism // between contexts. Two tuple origins are same-origin if the tuples are equal. // A tuple origin may also be re-created from its serialization. // // An opaque origin has an internal globally unique identifier. When creating a // new opaque origin from a URL, a fresh globally unique identifier is // generated. However, if an opaque origin is copied or moved, the internal // globally unique identifier is preserved. Two opaque origins are same-origin // iff the globally unique identifiers match. Unlike tuple origins, an opaque // origin cannot be re-created from its serialization, which is always the // string "null". // // IMPORTANT: Since opaque origins always serialize as the string "null", it is // *never* safe to use the serialization for security checks! // // A tuple origin and an opaque origin are never same-origin. // // There are a few subtleties to note: // // * A default constructed Origin is opaque, with no precursor origin. // // * Invalid and non-standard GURLs are parsed as opaque origins. This includes // non-hierarchical URLs like 'data:text/html,...' and 'javascript:alert(1)'. // // * GURLs with schemes of 'filesystem' or 'blob' parse the origin out of the // internals of the URL. That is, 'filesystem:https://example.com/temporary/f' // is parsed as ('https', 'example.com', 443). // // * GURLs with a 'file' scheme are tricky. They are parsed as ('file', '', 0), // but their behavior may differ from embedder to embedder. // TODO(dcheng): This behavior is not consistent with Blink's notion of file // URLs, which always creates an opaque origin. // // * The host component of an IPv6 address includes brackets, just like the URL // representation. // // * Constructing origins from GURLs (or from SchemeHostPort) is typically a red // flag (this is true for `url::Origin::Create` but also to some extent for // `url::Origin::Resolve`). See docs/security/origin-vs-url.md for more. // // * To answer the question "Are |this| and |that| "same-origin" with each // other?", use |Origin::IsSameOriginWith|: // // if (this.IsSameOriginWith(that)) { // // Amazingness goes here. // } class COMPONENT_EXPORT(URL) Origin { public: // Creates an opaque Origin with a nonce that is different from all previously // existing origins. Origin(); // WARNING: Converting an URL into an Origin is usually a red flag. See // //docs/security/origin-vs-url.md for more details. Some discussion about // deprecating the Create method can be found in https://crbug.com/1270878. // // Creates an Origin from `url`, as described at // https://url.spec.whatwg.org/#origin, with the following additions: // 1. If `url` is invalid or non-standard, an opaque Origin is constructed. // 2. 'filesystem' URLs behave as 'blob' URLs (that is, the origin is parsed // out of everything in the URL which follows the scheme). // 3. 'file' URLs all parse as ("file", "", 0). // // WARNING: `url::Origin::Create(url)` can give unexpected results if: // 1) `url` is "about:blank", or "about:srcdoc" (returning unique, opaque // origin rather than the real origin of the frame) // 2) `url` comes from a sandboxed frame (potentially returning a non-opaque // origin, when an opaque one is needed; see also // https://www.html5rocks.com/en/tutorials/security/sandboxed-iframes/) // 3) Wrong `url` is used - e.g. in some navigations `base_url_for_data_url` // might need to be used instead of relying on // `content::NavigationHandle::GetURL`. // // WARNING: The returned Origin may have a different scheme and host from // `url` (e.g. in case of blob URLs - see OriginTest.ConstructFromGURL). // // WARNING: data: URLs will be correctly be translated into opaque origins, // but the precursor origin will be lost (unlike with `url::Origin::Resolve`). static Origin Create(const GURL& url); // Creates an Origin for the resource `url` as if it were requested // from the context of `base_origin`. If `url` is standard // (in the sense that it embeds a complete origin, like http/https), // this returns the same value as would Create(). // // If `url` is "about:blank" or "about:srcdoc", this returns a copy of // `base_origin`. // // Otherwise, returns a new opaque origin derived from `base_origin`. // In this case, the resulting opaque origin will inherit the tuple // (or precursor tuple) of `base_origin`, but will not be same origin // with `base_origin`, even if `base_origin` is already opaque. static Origin Resolve(const GURL& url, const Origin& base_origin); // Copyable and movable. Origin(const Origin&); Origin& operator=(const Origin&); Origin(Origin&&) noexcept; Origin& operator=(Origin&&) noexcept; // Creates an Origin from a |scheme|, |host|, and |port|. All the parameters // must be valid and canonicalized. Returns nullopt if any parameter is not // canonical, or if all the parameters are empty. // // This constructor should be used in order to pass 'Origin' objects back and // forth over IPC (as transitioning through GURL would risk potentially // dangerous recanonicalization); other potential callers should prefer the // 'GURL'-based constructor. static absl::optional<Origin> UnsafelyCreateTupleOriginWithoutNormalization( base::StringPiece scheme, base::StringPiece host, uint16_t port); // Creates an origin without sanity checking that the host is canonicalized. // This should only be used when converting between already normalized types, // and should NOT be used for IPC. Method takes std::strings for use with move // operators to avoid copies. static Origin CreateFromNormalizedTuple(std::string scheme, std::string host, uint16_t port); ~Origin(); // For opaque origins, these return ("", "", 0). const std::string& scheme() const { return !opaque() ? tuple_.scheme() : base::EmptyString(); } const std::string& host() const { return !opaque() ? tuple_.host() : base::EmptyString(); } uint16_t port() const { return !opaque() ? tuple_.port() : 0; } bool opaque() const { return nonce_.has_value(); } // An ASCII serialization of the Origin as per Section 6.2 of RFC 6454, with // the addition that all Origins with a 'file' scheme serialize to "file://". std::string Serialize() const; // Two non-opaque Origins are "same-origin" if their schemes, hosts, and ports // are exact matches. Two opaque origins are same-origin only if their // internal nonce values match. A non-opaque origin is never same-origin with // an opaque origin. bool IsSameOriginWith(const Origin& other) const; bool operator==(const Origin& other) const { return IsSameOriginWith(other); } bool operator!=(const Origin& other) const { return !IsSameOriginWith(other); } // Non-opaque origin is "same-origin" with `url` if their schemes, hosts, and // ports are exact matches. Opaque origin is never "same-origin" with any // `url`. about:blank, about:srcdoc, and invalid GURLs are never // "same-origin" with any origin. This method is a shorthand for // `origin.IsSameOriginWith(url::Origin::Create(url))`. // // See also CanBeDerivedFrom. bool IsSameOriginWith(const GURL& url) const; // This method returns true for any |url| which if navigated to could result // in an origin compatible with |this|. bool CanBeDerivedFrom(const GURL& url) const; // Get the scheme, host, and port from which this origin derives. For // a tuple Origin, this gives the same values as calling scheme(), host() // and port(). For an opaque Origin that was created by calling // Origin::DeriveNewOpaqueOrigin() on a precursor or Origin::Resolve(), // this returns the tuple inherited from the precursor. // // If this Origin is opaque and was created via the default constructor or // Origin::Create(), the precursor origin is unknown. // // Use with great caution: opaque origins should generally not inherit // privileges from the origins they derive from. However, in some cases // (such as restrictions on process placement, or determining the http lock // icon) this information may be relevant to ensure that entering an // opaque origin does not grant privileges initially denied to the original // non-opaque origin. // // This method has a deliberately obnoxious name to prompt caution in its use. const SchemeHostPort& GetTupleOrPrecursorTupleIfOpaque() const { return tuple_; } // Efficiently returns what GURL(Serialize()) would without re-parsing the // URL. This can be used for the (rare) times a GURL representation is needed // for an Origin. // Note: The returned URL will not necessarily be serialized to the same value // as the Origin would. The GURL will have an added "/" path for Origins with // valid SchemeHostPorts and file Origins. // // Try not to use this method under normal circumstances, as it loses type // information. Downstream consumers can mistake the returned GURL with a full // URL (e.g. with a path component). GURL GetURL() const; // Same as GURL::DomainIs. If |this| origin is opaque, then returns false. bool DomainIs(base::StringPiece canonical_domain) const; // Allows Origin to be used as a key in STL (for example, a std::set or // std::map). bool operator<(const Origin& other) const; // Creates a new opaque origin that is guaranteed to be cross-origin to all // currently existing origins. An origin created by this method retains its // identity across copies. Copies are guaranteed to be same-origin to each // other, e.g. // // url::Origin page = Origin::Create(GURL("http://example.com")) // url::Origin a = page.DeriveNewOpaqueOrigin(); // url::Origin b = page.DeriveNewOpaqueOrigin(); // url::Origin c = a; // url::Origin d = b; // // |a| and |c| are same-origin, since |c| was copied from |a|. |b| and |d| are // same-origin as well, since |d| was copied from |b|. All other combinations // of origins are considered cross-origin, e.g. |a| is cross-origin to |b| and // |d|, |b| is cross-origin to |a| and |c|, |c| is cross-origin to |b| and // |d|, and |d| is cross-origin to |a| and |c|. Origin DeriveNewOpaqueOrigin() const; // Creates a string representation of the object that can be used for logging // and debugging. It serializes the internal state, such as the nonce value // and precursor information. std::string GetDebugString(bool include_nonce = true) const; #if BUILDFLAG(IS_ANDROID) base::android::ScopedJavaLocalRef<jobject> CreateJavaObject() const; static Origin FromJavaObject( const base::android::JavaRef<jobject>& java_origin); static jlong CreateNative(JNIEnv* env, const base::android::JavaRef<jstring>& java_scheme, const base::android::JavaRef<jstring>& java_host, uint16_t port, bool is_opaque, uint64_t tokenHighBits, uint64_t tokenLowBits); #endif // BUILDFLAG(IS_ANDROID) void WriteIntoTrace(perfetto::TracedValue context) const; private: friend class blink::SecurityOrigin; friend class blink::SecurityOriginTest; friend class blink::StorageKey; // SchemefulSite needs access to the serialization/deserialization logic which // includes the nonce. friend class net::SchemefulSite; friend class OriginTest; friend struct mojo::UrlOriginAdapter; friend struct ipc_fuzzer::FuzzTraits<Origin>; friend struct mojo::StructTraits<url::mojom::OriginDataView, url::Origin>; friend IPC::ParamTraits<url::Origin>; friend COMPONENT_EXPORT(URL) std::ostream& operator<<(std::ostream& out, const Origin& origin); friend class blink::StorageKeyTest; // Origin::Nonce is a wrapper around base::UnguessableToken that generates // the random value only when the value is first accessed. The lazy generation // allows Origin to be default-constructed quickly, without spending time // in random number generation. // // TODO(nick): Should this optimization move into UnguessableToken, once it no // longer treats the Null case specially? class COMPONENT_EXPORT(URL) Nonce { public: // Creates a nonce to hold a newly-generated UnguessableToken. The actual // token value will be generated lazily. Nonce(); // Creates a nonce to hold an already-generated UnguessableToken value. This // constructor should only be used for IPC serialization and testing -- // regular code should never need to touch the UnguessableTokens directly, // and the default constructor is faster. explicit Nonce(const base::UnguessableToken& token); // Accessor, which lazily initializes the underlying |token_| member. const base::UnguessableToken& token() const; // Do not use in cases where lazy initialization is expected! This // accessor does not initialize the |token_| member. const base::UnguessableToken& raw_token() const; // Copyable and movable. Copying a Nonce triggers lazy-initialization, // moving it does not. Nonce(const Nonce&); Nonce& operator=(const Nonce&); Nonce(Nonce&&) noexcept; Nonce& operator=(Nonce&&) noexcept; // Note that operator<, used by maps type containers, will trigger |token_| // lazy-initialization. Equality comparisons do not. bool operator<(const Nonce& other) const; bool operator==(const Nonce& other) const; bool operator!=(const Nonce& other) const; private: friend class OriginTest; // mutable to support lazy generation. mutable base::UnguessableToken token_; }; // This needs to be friended within Origin as well, since Nonce is a private // nested class of Origin. friend COMPONENT_EXPORT(URL) std::ostream& operator<<(std::ostream& out, const Nonce& nonce); // Creates an origin without sanity checking that the host is canonicalized. // This should only be used when converting between already normalized types, // and should NOT be used for IPC. Method takes std::strings for use with move // operators to avoid copies. static Origin CreateOpaqueFromNormalizedPrecursorTuple( std::string precursor_scheme, std::string precursor_host, uint16_t precursor_port, const Nonce& nonce); // Creates an opaque Origin with the identity given by |nonce|, and an // optional precursor origin given by |precursor_scheme|, |precursor_host| and // |precursor_port|. Returns nullopt if any parameter is not canonical. When // the precursor is unknown, the precursor parameters should be ("", "", 0). // // This factory method should be used in order to pass opaque Origin objects // back and forth over IPC (as transitioning through GURL would risk // potentially dangerous recanonicalization). static absl::optional<Origin> UnsafelyCreateOpaqueOriginWithoutNormalization( base::StringPiece precursor_scheme, base::StringPiece precursor_host, uint16_t precursor_port, const Nonce& nonce); // Constructs a non-opaque tuple origin. |tuple| must be valid. explicit Origin(SchemeHostPort tuple); // Constructs an opaque origin derived from the |precursor| tuple, with the // given |nonce|. Origin(const Nonce& nonce, SchemeHostPort precursor); // Get the nonce associated with this origin, if it is opaque, or nullptr // otherwise. This should be used only when trying to send an Origin across an // IPC pipe. const base::UnguessableToken* GetNonceForSerialization() const; // Serializes this Origin, including its nonce if it is opaque. If an opaque // origin's |tuple_| is invalid nullopt is returned. If the nonce is not // initialized, a nonce of 0 is used. Use of this method should be limited as // an opaque origin will never be matchable in future browser sessions. absl::optional<std::string> SerializeWithNonce() const; // Like SerializeWithNonce(), but forces |nonce_| to be initialized prior to // serializing. absl::optional<std::string> SerializeWithNonceAndInitIfNeeded(); absl::optional<std::string> SerializeWithNonceImpl() const; // Deserializes an origin from |ToValueWithNonce|. Returns nullopt if the // value was invalid in any way. static absl::optional<Origin> Deserialize(const std::string& value); // The tuple is used for both tuple origins (e.g. https://example.com:80), as // well as for opaque origins, where it tracks the tuple origin from which // the opaque origin was initially derived (we call this the "precursor" // origin). SchemeHostPort tuple_; // The nonce is used for maintaining identity of an opaque origin. This // nonce is preserved when an opaque origin is copied or moved. An Origin // is considered opaque if and only if |nonce_| holds a value. absl::optional<Nonce> nonce_; }; // Pretty-printers for logging. These expose the internal state of the nonce. COMPONENT_EXPORT(URL) std::ostream& operator<<(std::ostream& out, const Origin& origin); COMPONENT_EXPORT(URL) std::ostream& operator<<(std::ostream& out, const Origin::Nonce& origin); COMPONENT_EXPORT(URL) bool IsSameOriginWith(const GURL& a, const GURL& b); // DEBUG_ALIAS_FOR_ORIGIN(var_name, origin) copies `origin` into a new // stack-allocated variable named `<var_name>`. This helps ensure that the // value of `origin` gets preserved in crash dumps. #define DEBUG_ALIAS_FOR_ORIGIN(var_name, origin) \ DEBUG_ALIAS_FOR_CSTR(var_name, (origin).Serialize().c_str(), 128) namespace debug { class COMPONENT_EXPORT(URL) ScopedOriginCrashKey { public: ScopedOriginCrashKey(base::debug::CrashKeyString* crash_key, const url::Origin* value); ~ScopedOriginCrashKey(); ScopedOriginCrashKey(const ScopedOriginCrashKey&) = delete; ScopedOriginCrashKey& operator=(const ScopedOriginCrashKey&) = delete; private: base::debug::ScopedCrashKeyString scoped_string_value_; }; } // namespace debug } // namespace url #endif // URL_ORIGIN_H_
Zhao-PengFei35/chromium_src_4
url/origin.h
C++
unknown
20,880
// Copyright 2021 The Chromium Authors // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "url/origin_abstract_tests.h" namespace url { void ExpectParsedUrlsEqual(const GURL& a, const GURL& b) { EXPECT_EQ(a, b); const Parsed& a_parsed = a.parsed_for_possibly_invalid_spec(); const Parsed& b_parsed = b.parsed_for_possibly_invalid_spec(); EXPECT_EQ(a_parsed.scheme.begin, b_parsed.scheme.begin); EXPECT_EQ(a_parsed.scheme.len, b_parsed.scheme.len); EXPECT_EQ(a_parsed.username.begin, b_parsed.username.begin); EXPECT_EQ(a_parsed.username.len, b_parsed.username.len); EXPECT_EQ(a_parsed.password.begin, b_parsed.password.begin); EXPECT_EQ(a_parsed.password.len, b_parsed.password.len); EXPECT_EQ(a_parsed.host.begin, b_parsed.host.begin); EXPECT_EQ(a_parsed.host.len, b_parsed.host.len); EXPECT_EQ(a_parsed.port.begin, b_parsed.port.begin); EXPECT_EQ(a_parsed.port.len, b_parsed.port.len); EXPECT_EQ(a_parsed.path.begin, b_parsed.path.begin); EXPECT_EQ(a_parsed.path.len, b_parsed.path.len); EXPECT_EQ(a_parsed.query.begin, b_parsed.query.begin); EXPECT_EQ(a_parsed.query.len, b_parsed.query.len); EXPECT_EQ(a_parsed.ref.begin, b_parsed.ref.begin); EXPECT_EQ(a_parsed.ref.len, b_parsed.ref.len); } // static Origin UrlOriginTestTraits::CreateOriginFromString(base::StringPiece s) { return Origin::Create(GURL(s)); } // static Origin UrlOriginTestTraits::CreateUniqueOpaqueOrigin() { return Origin(); } // static Origin UrlOriginTestTraits::CreateWithReferenceOrigin( base::StringPiece url, const Origin& reference_origin) { return Origin::Resolve(GURL(url), reference_origin); } // static Origin UrlOriginTestTraits::DeriveNewOpaqueOrigin( const Origin& reference_origin) { return reference_origin.DeriveNewOpaqueOrigin(); } // static bool UrlOriginTestTraits::IsOpaque(const Origin& origin) { return origin.opaque(); } // static std::string UrlOriginTestTraits::GetScheme(const Origin& origin) { return origin.scheme(); } // static std::string UrlOriginTestTraits::GetHost(const Origin& origin) { return origin.host(); } // static uint16_t UrlOriginTestTraits::GetPort(const Origin& origin) { return origin.port(); } // static SchemeHostPort UrlOriginTestTraits::GetTupleOrPrecursorTupleIfOpaque( const Origin& origin) { return origin.GetTupleOrPrecursorTupleIfOpaque(); } // static bool UrlOriginTestTraits::IsSameOrigin(const Origin& a, const Origin& b) { return a.IsSameOriginWith(b); } // static std::string UrlOriginTestTraits::Serialize(const Origin& origin) { std::string serialized = origin.Serialize(); // Extra test assertion for GetURL (which doesn't have an equivalent in // blink::SecurityOrigin). ExpectParsedUrlsEqual(GURL(serialized), origin.GetURL()); return serialized; } // static bool UrlOriginTestTraits::IsValidUrl(base::StringPiece str) { return GURL(str).is_valid(); } // This is an abstract test suite which is instantiated by each implementation. GTEST_ALLOW_UNINSTANTIATED_PARAMETERIZED_TEST(AbstractOriginTest); } // namespace url
Zhao-PengFei35/chromium_src_4
url/origin_abstract_tests.cc
C++
unknown
3,126
// Copyright 2020 The Chromium Authors // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #ifndef URL_ORIGIN_ABSTRACT_TESTS_H_ #define URL_ORIGIN_ABSTRACT_TESTS_H_ #include <string> #include <type_traits> #include "base/containers/contains.h" #include "base/strings/string_piece.h" #include "testing/gtest/include/gtest/gtest.h" #include "url/gurl.h" #include "url/origin.h" #include "url/scheme_host_port.h" #include "url/url_util.h" namespace url { void ExpectParsedUrlsEqual(const GURL& a, const GURL& b); // AbstractOriginTest below abstracts away differences between url::Origin and // blink::SecurityOrigin by parametrizing the tests with a class that has to // expose the same public members as UrlOriginTestTraits below. class UrlOriginTestTraits { public: using OriginType = Origin; // Constructing an origin. static OriginType CreateOriginFromString(base::StringPiece s); static OriginType CreateUniqueOpaqueOrigin(); static OriginType CreateWithReferenceOrigin( base::StringPiece url, const OriginType& reference_origin); static OriginType DeriveNewOpaqueOrigin(const OriginType& reference_origin); // Accessors for origin properties. static bool IsOpaque(const OriginType& origin); static std::string GetScheme(const OriginType& origin); static std::string GetHost(const OriginType& origin); static uint16_t GetPort(const OriginType& origin); static SchemeHostPort GetTupleOrPrecursorTupleIfOpaque( const OriginType& origin); // Wrappers for other instance methods of OriginType. static bool IsSameOrigin(const OriginType& a, const OriginType& b); static std::string Serialize(const OriginType& origin); // "Accessors" of URL properties. // // TODO(lukasza): Consider merging together OriginTraitsBase here and // UrlTraitsBase in //url/gurl_abstract_tests.h. static bool IsValidUrl(base::StringPiece str); // Only static members = no constructors are needed. UrlOriginTestTraits() = delete; }; // Test suite for tests that cover both url::Origin and blink::SecurityOrigin. template <typename TOriginTraits> class AbstractOriginTest : public testing::Test { public: void SetUp() override { const char* kSchemesToRegister[] = { "noaccess", "std-with-host", "noaccess-std-with-host", "local", "local-noaccess", "local-std-with-host", "local-noaccess-std-with-host", "also-local", "sec", "sec-std-with-host", "sec-noaccess", }; for (const char* kScheme : kSchemesToRegister) { std::string scheme(kScheme); if (base::Contains(scheme, "noaccess")) AddNoAccessScheme(kScheme); if (base::Contains(scheme, "std-with-host")) AddStandardScheme(kScheme, SchemeType::SCHEME_WITH_HOST); if (base::Contains(scheme, "local")) AddLocalScheme(kScheme); if (base::Contains(scheme, "sec")) AddSecureScheme(kScheme); } } protected: // Wrappers that help ellide away TOriginTraits. // // Note that calling the wrappers needs to be prefixed with `this->...` to // avoid hitting: explicit qualification required to use member 'IsOpaque' // from dependent base class. using OriginType = typename TOriginTraits::OriginType; OriginType CreateOriginFromString(base::StringPiece s) { return TOriginTraits::CreateOriginFromString(s); } OriginType CreateUniqueOpaqueOrigin() { return TOriginTraits::CreateUniqueOpaqueOrigin(); } OriginType CreateWithReferenceOrigin(base::StringPiece url, const OriginType& reference_origin) { return TOriginTraits::CreateWithReferenceOrigin(url, reference_origin); } OriginType DeriveNewOpaqueOrigin(const OriginType& reference_origin) { return TOriginTraits::DeriveNewOpaqueOrigin(reference_origin); } bool IsOpaque(const OriginType& origin) { return TOriginTraits::IsOpaque(origin); } std::string GetScheme(const OriginType& origin) { return TOriginTraits::GetScheme(origin); } std::string GetHost(const OriginType& origin) { return TOriginTraits::GetHost(origin); } uint16_t GetPort(const OriginType& origin) { return TOriginTraits::GetPort(origin); } SchemeHostPort GetTupleOrPrecursorTupleIfOpaque(const OriginType& origin) { return TOriginTraits::GetTupleOrPrecursorTupleIfOpaque(origin); } bool IsSameOrigin(const OriginType& a, const OriginType& b) { bool is_a_same_with_b = TOriginTraits::IsSameOrigin(a, b); bool is_b_same_with_a = TOriginTraits::IsSameOrigin(b, a); EXPECT_EQ(is_a_same_with_b, is_b_same_with_a); return is_a_same_with_b; } std::string Serialize(const OriginType& origin) { return TOriginTraits::Serialize(origin); } bool IsValidUrl(base::StringPiece str) { return TOriginTraits::IsValidUrl(str); } #define EXPECT_SAME_ORIGIN(a, b) \ EXPECT_TRUE(this->IsSameOrigin((a), (b))) \ << "When checking if \"" << this->Serialize(a) << "\" is " \ << "same-origin with \"" << this->Serialize(b) << "\"" #define EXPECT_CROSS_ORIGIN(a, b) \ EXPECT_FALSE(this->IsSameOrigin((a), (b))) \ << "When checking if \"" << this->Serialize(a) << "\" is " \ << "cross-origin from \"" << this->Serialize(b) << "\"" void VerifyOriginInvariants(const OriginType& origin) { // An origin is always same-origin with itself. EXPECT_SAME_ORIGIN(origin, origin); // A copy of |origin| should be same-origin as well. auto origin_copy = origin; EXPECT_EQ(this->GetScheme(origin), this->GetScheme(origin_copy)); EXPECT_EQ(this->GetHost(origin), this->GetHost(origin_copy)); EXPECT_EQ(this->GetPort(origin), this->GetPort(origin_copy)); EXPECT_EQ(this->IsOpaque(origin), this->IsOpaque(origin_copy)); EXPECT_SAME_ORIGIN(origin, origin_copy); // An origin is always cross-origin from another, unique, opaque origin. EXPECT_CROSS_ORIGIN(origin, this->CreateUniqueOpaqueOrigin()); // An origin is always cross-origin from another tuple origin. auto different_tuple_origin = this->CreateOriginFromString("https://not-in-the-list.test/"); EXPECT_CROSS_ORIGIN(origin, different_tuple_origin); // Deriving an origin for "about:blank". auto about_blank_origin1 = this->CreateWithReferenceOrigin("about:blank", origin); auto about_blank_origin2 = this->CreateWithReferenceOrigin("about:blank?bar#foo", origin); EXPECT_SAME_ORIGIN(origin, about_blank_origin1); EXPECT_SAME_ORIGIN(origin, about_blank_origin2); // Derived opaque origins. std::vector<OriginType> derived_origins = { this->DeriveNewOpaqueOrigin(origin), this->CreateWithReferenceOrigin("data:text/html,baz", origin), this->DeriveNewOpaqueOrigin(about_blank_origin1), }; for (size_t i = 0; i < derived_origins.size(); i++) { SCOPED_TRACE(testing::Message() << "Derived origin #" << i); const OriginType& derived_origin = derived_origins[i]; EXPECT_TRUE(this->IsOpaque(derived_origin)); EXPECT_SAME_ORIGIN(derived_origin, derived_origin); EXPECT_CROSS_ORIGIN(origin, derived_origin); EXPECT_EQ(this->GetTupleOrPrecursorTupleIfOpaque(origin), this->GetTupleOrPrecursorTupleIfOpaque(derived_origin)); } } void VerifyUniqueOpaqueOriginInvariants(const OriginType& origin) { if (!this->IsOpaque(origin)) { ADD_FAILURE() << "Got unexpectedly non-opaque origin: " << this->Serialize(origin); return; // Skip other test assertions. } // Opaque origins should have an "empty" scheme, host and port. EXPECT_EQ("", this->GetScheme(origin)); EXPECT_EQ("", this->GetHost(origin)); EXPECT_EQ(0, this->GetPort(origin)); // Unique opaque origins should have an empty precursor tuple. EXPECT_EQ(SchemeHostPort(), this->GetTupleOrPrecursorTupleIfOpaque(origin)); // Serialization test. EXPECT_EQ("null", this->Serialize(origin)); // Invariants that should hold for any origin. VerifyOriginInvariants(origin); } void TestUniqueOpaqueOrigin(base::StringPiece test_input) { auto origin = this->CreateOriginFromString(test_input); this->VerifyUniqueOpaqueOriginInvariants(origin); // Re-creating from the URL should be cross-origin. auto origin_recreated_from_same_input = this->CreateOriginFromString(test_input); EXPECT_CROSS_ORIGIN(origin, origin_recreated_from_same_input); } void VerifyTupleOriginInvariants(const OriginType& origin, const SchemeHostPort& expected_tuple) { if (this->IsOpaque(origin)) { ADD_FAILURE() << "Got unexpectedly opaque origin"; return; // Skip other test assertions. } SCOPED_TRACE(testing::Message() << "Actual origin: " << this->Serialize(origin)); // Compare `origin` against the `expected_tuple`. EXPECT_EQ(expected_tuple.scheme(), this->GetScheme(origin)); EXPECT_EQ(expected_tuple.host(), this->GetHost(origin)); EXPECT_EQ(expected_tuple.port(), this->GetPort(origin)); EXPECT_EQ(expected_tuple, this->GetTupleOrPrecursorTupleIfOpaque(origin)); // Serialization test. // // TODO(lukasza): Consider preserving the hostname when serializing file: // URLs. Dropping the hostname seems incompatible with section 6 of // rfc6454. Even though section 4 says that "the implementation MAY // return an implementation-defined value", it seems that Chromium // implementation *does* include the hostname in the origin SchemeHostPort // tuple. if (expected_tuple.scheme() != kFileScheme || expected_tuple.host() == "") { EXPECT_SAME_ORIGIN(origin, this->CreateOriginFromString(this->Serialize(origin))); } // Invariants that should hold for any origin. VerifyOriginInvariants(origin); } private: ScopedSchemeRegistryForTests scoped_scheme_registry_; }; TYPED_TEST_SUITE_P(AbstractOriginTest); TYPED_TEST_P(AbstractOriginTest, NonStandardSchemeWithAndroidWebViewHack) { EnableNonStandardSchemesForAndroidWebView(); // Regression test for https://crbug.com/896059. auto origin = this->CreateOriginFromString("unknown-scheme://"); EXPECT_FALSE(this->IsOpaque(origin)); EXPECT_EQ("unknown-scheme", this->GetScheme(origin)); EXPECT_EQ("", this->GetHost(origin)); EXPECT_EQ(0, this->GetPort(origin)); // about:blank translates into an opaque origin, even in presence of // EnableNonStandardSchemesForAndroidWebView. origin = this->CreateOriginFromString("about:blank"); EXPECT_TRUE(this->IsOpaque(origin)); } TYPED_TEST_P(AbstractOriginTest, OpaqueOriginsFromValidUrls) { const char* kTestCases[] = { // Built-in noaccess schemes. "data:text/html,Hello!", "javascript:alert(1)", "about:blank", // Opaque blob URLs. "blob:null/foo", // blob:null (actually a valid URL) "blob:data:foo", // blob + data (which is nonstandard) "blob:about://blank/", // blob + about (which is nonstandard) "blob:about:blank/", // blob + about (which is nonstandard) "blob:filesystem:ws:b/.", "blob:filesystem:ftp://a/b", #ifndef OHOS_UNITTESTS "blob:blob:http://www.example.com/guid-goes-here", "blob:blob:file://localhost/foo/bar", #endif }; for (const char* test_input : kTestCases) { SCOPED_TRACE(testing::Message() << "Test input: " << test_input); // Verify that `origin` is opaque not just because `test_input` results is // an invalid URL (because of a typo in the scheme name, or because of a // technicality like having no host in a noaccess-std-with-host: scheme). EXPECT_TRUE(this->IsValidUrl(test_input)); this->TestUniqueOpaqueOrigin(test_input); } } TYPED_TEST_P(AbstractOriginTest, OpaqueOriginsFromInvalidUrls) { // TODO(lukasza): Consider moving those to GURL/KURL tests that verify what // inputs are parsed as an invalid URL. const char* kTestCases[] = { // Invalid file: URLs. "file://example.com:443/etc/passwd", // No port expected. // Invalid HTTP URLs. "http", "http:", "http:/", "http://", "http://:", "http://:1", "http::///invalid.example.com/", "http://example.com:65536/", // Port out of range. "http://example.com:-1/", // Port out of range. "http://example.com:18446744073709551616/", // Port = 2^64. "http://example.com:18446744073709551616999/", // Lots of port digits. // Invalid filesystem URLs. "filesystem:http://example.com/", // Missing /type/. "filesystem:local:baz./type/", "filesystem:local://hostname/type/", "filesystem:unknown-scheme://hostname/type/", "filesystem:filesystem:http://example.org:88/foo/bar", // Invalid IP addresses "http://[]/", "http://[2001:0db8:0000:0000:0000:0000:0000:0000:0001]/", // 9 groups. // Unknown scheme without a colon character (":") gives an invalid URL. "unknown-scheme", // Standard schemes require a hostname (and result in an opaque origin if // the hostname is missing). "local-std-with-host:", "noaccess-std-with-host:", }; for (const char* test_input : kTestCases) { SCOPED_TRACE(testing::Message() << "Test input: " << test_input); // All testcases here are expected to represent invalid URLs. // an invalid URL (because of a type in scheme name, or because of a // technicality like having no host in a noaccess-std-with-host: scheme). EXPECT_FALSE(this->IsValidUrl(test_input)); // Invalid URLs should always result in an opaque origin. this->TestUniqueOpaqueOrigin(test_input); } } TYPED_TEST_P(AbstractOriginTest, TupleOrigins) { struct TestCase { const char* input; SchemeHostPort expected_tuple; } kTestCases[] = { // file: URLs {"file:///etc/passwd", {"file", "", 0}}, {"file://example.com/etc/passwd", {"file", "example.com", 0}}, {"file:///", {"file", "", 0}}, {"file://hostname/C:/dir/file.txt", {"file", "hostname", 0}}, // HTTP URLs {"http://example.com/", {"http", "example.com", 80}}, {"http://example.com:80/", {"http", "example.com", 80}}, {"http://example.com:123/", {"http", "example.com", 123}}, {"http://example.com:0/", {"http", "example.com", 0}}, {"http://example.com:65535/", {"http", "example.com", 65535}}, {"https://example.com/", {"https", "example.com", 443}}, {"https://example.com:443/", {"https", "example.com", 443}}, {"https://example.com:123/", {"https", "example.com", 123}}, {"https://example.com:0/", {"https", "example.com", 0}}, {"https://example.com:65535/", {"https", "example.com", 65535}}, {"http://user:pass@example.com/", {"http", "example.com", 80}}, {"http://example.com:123/?query", {"http", "example.com", 123}}, {"https://example.com/#1234", {"https", "example.com", 443}}, {"https://u:p@example.com:123/?query#1234", {"https", "example.com", 123}}, {"http://example/", {"http", "example", 80}}, // Blob URLs. {"blob:http://example.com/guid-goes-here", {"http", "example.com", 80}}, {"blob:http://example.com:123/guid-goes-here", {"http", "example.com", 123}}, {"blob:https://example.com/guid-goes-here", {"https", "example.com", 443}}, {"blob:http://u:p@example.com/guid-goes-here", {"http", "example.com", 80}}, // Filesystem URLs. {"filesystem:http://example.com/type/", {"http", "example.com", 80}}, {"filesystem:http://example.com:123/type/", {"http", "example.com", 123}}, {"filesystem:https://example.com/type/", {"https", "example.com", 443}}, {"filesystem:https://example.com:123/type/", {"https", "example.com", 123}}, {"filesystem:local-std-with-host:baz./type/", {"local-std-with-host", "baz.", 0}}, // IP Addresses {"http://192.168.9.1/", {"http", "192.168.9.1", 80}}, {"http://[2001:db8::1]/", {"http", "[2001:db8::1]", 80}}, {"http://[2001:0db8:0000:0000:0000:0000:0000:0001]/", {"http", "[2001:db8::1]", 80}}, {"http://1/", {"http", "0.0.0.1", 80}}, {"http://1:1/", {"http", "0.0.0.1", 1}}, {"http://3232237825/", {"http", "192.168.9.1", 80}}, // Punycode {"http://☃.net/", {"http", "xn--n3h.net", 80}}, {"blob:http://☃.net/", {"http", "xn--n3h.net", 80}}, {"local-std-with-host:↑↑↓↓←→←→ba.↑↑↓↓←→←→ba.0.bg", {"local-std-with-host", "xn--ba-rzuadaibfa.xn--ba-rzuadaibfa.0.bg", 0}}, // Registered URLs {"ftp://example.com/", {"ftp", "example.com", 21}}, {"ws://example.com/", {"ws", "example.com", 80}}, {"wss://example.com/", {"wss", "example.com", 443}}, {"wss://user:pass@example.com/", {"wss", "example.com", 443}}, }; for (const TestCase& test : kTestCases) { SCOPED_TRACE(testing::Message() << "Test input: " << test.input); // Only valid URLs should translate into valid, non-opaque origins. EXPECT_TRUE(this->IsValidUrl(test.input)); auto origin = this->CreateOriginFromString(test.input); this->VerifyTupleOriginInvariants(origin, test.expected_tuple); } } TYPED_TEST_P(AbstractOriginTest, CustomSchemes_OpaqueOrigins) { const char* kTestCases[] = { #ifndef OHOS_UNITTESTS // Unknown scheme "unknown-scheme:foo", "unknown-scheme://bar", // Unknown scheme that is a prefix or suffix of a registered scheme. "loca:foo", "ocal:foo", "local-suffix:foo", "prefix-local:foo", #endif // Custom no-access schemes translate into an opaque origin (just like the // built-in no-access schemes such as about:blank or data:). "noaccess-std-with-host:foo", "noaccess-std-with-host://bar", "noaccess://host", "local-noaccess://host", "local-noaccess-std-with-host://host", }; for (const char* test_input : kTestCases) { SCOPED_TRACE(testing::Message() << "Test input: " << test_input); // Verify that `origin` is opaque not just because `test_input` results is // an invalid URL (because of a typo in the scheme name, or because of a // technicality like having no host in a noaccess-std-with-host: scheme). EXPECT_TRUE(this->IsValidUrl(test_input)); this->TestUniqueOpaqueOrigin(test_input); } } TYPED_TEST_P(AbstractOriginTest, CustomSchemes_TupleOrigins) { struct TestCase { const char* input; SchemeHostPort expected_tuple; } kTestCases[] = { // Scheme (registered in SetUp()) that's both local and standard. // TODO: Is it really appropriate to do network-host canonicalization of // schemes without ports? {"local-std-with-host:20", {"local-std-with-host", "0.0.0.20", 0}}, {"local-std-with-host:20.", {"local-std-with-host", "0.0.0.20", 0}}, {"local-std-with-host:foo", {"local-std-with-host", "foo", 0}}, {"local-std-with-host://bar:20", {"local-std-with-host", "bar", 0}}, {"local-std-with-host:baz.", {"local-std-with-host", "baz.", 0}}, {"local-std-with-host:baz..", {"local-std-with-host", "baz..", 0}}, {"local-std-with-host:baz..bar", {"local-std-with-host", "baz..bar", 0}}, {"local-std-with-host:baz...", {"local-std-with-host", "baz...", 0}}, // Scheme (registered in SetUp()) that's local but nonstandard. These // always have empty hostnames, but are allowed to be url::Origins. {"local:", {"local", "", 0}}, {"local:foo", {"local", "", 0}}, {"local://bar", {"local", "", 0}}, {"also-local://bar", {"also-local", "", 0}}, {"std-with-host://host", {"std-with-host", "host", 0}}, {"local://host", {"local", "", 0}}, {"local-std-with-host://host", {"local-std-with-host", "host", 0}}, }; for (const TestCase& test : kTestCases) { SCOPED_TRACE(testing::Message() << "Test input: " << test.input); // Only valid URLs should translate into valid, non-opaque origins. EXPECT_TRUE(this->IsValidUrl(test.input)); auto origin = this->CreateOriginFromString(test.input); this->VerifyTupleOriginInvariants(origin, test.expected_tuple); } } REGISTER_TYPED_TEST_SUITE_P(AbstractOriginTest, NonStandardSchemeWithAndroidWebViewHack, OpaqueOriginsFromValidUrls, OpaqueOriginsFromInvalidUrls, TupleOrigins, CustomSchemes_OpaqueOrigins, CustomSchemes_TupleOrigins); } // namespace url #endif // URL_ORIGIN_ABSTRACT_TESTS_H_
Zhao-PengFei35/chromium_src_4
url/origin_abstract_tests.h
C++
unknown
20,948
// Copyright 2015 The Chromium Authors // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include <stddef.h> #include <stdint.h> #include "base/memory/raw_ptr.h" #include "testing/gmock/include/gmock/gmock.h" #include "testing/gtest/include/gtest/gtest.h" #include "url/gurl.h" #include "url/origin.h" #include "url/origin_abstract_tests.h" #include "url/url_util.h" namespace url { class OriginTest : public ::testing::Test { public: void SetUp() override { // Add two schemes which are local but nonstandard. AddLocalScheme("local-but-nonstandard"); AddLocalScheme("also-local-but-nonstandard"); // Add a scheme that's both local and standard. AddStandardScheme("local-and-standard", SchemeType::SCHEME_WITH_HOST); AddLocalScheme("local-and-standard"); // Add a scheme that's standard but no-access. We still want these to // form valid SchemeHostPorts, even though they always commit as opaque // origins, so that they can represent the source of the resource even if // it's not committable as a non-opaque origin. AddStandardScheme("standard-but-noaccess", SchemeType::SCHEME_WITH_HOST); AddNoAccessScheme("standard-but-noaccess"); } ::testing::AssertionResult DoEqualityComparisons(const url::Origin& a, const url::Origin& b, bool should_compare_equal) { ::testing::AssertionResult failure = ::testing::AssertionFailure(); failure << "DoEqualityComparisons failure. Expecting " << (should_compare_equal ? "equality" : "inequality") << " between:\n a\n Which is: " << a << "\n b\n Which is: " << b << "\nThe following check failed: "; if (a.IsSameOriginWith(b) != should_compare_equal) return failure << "a.IsSameOriginWith(b)"; if (b.IsSameOriginWith(a) != should_compare_equal) return failure << "b.IsSameOriginWith(a)"; if ((a == b) != should_compare_equal) return failure << "(a == b)"; if ((b == a) != should_compare_equal) return failure << "(b == a)"; if ((b != a) != !should_compare_equal) return failure << "(b != a)"; if ((a != b) != !should_compare_equal) return failure << "(a != b)"; return ::testing::AssertionSuccess(); } bool HasNonceTokenBeenInitialized(const url::Origin& origin) { EXPECT_TRUE(origin.opaque()); // Avoid calling nonce_.token() here, to not trigger lazy initialization. return !origin.nonce_->token_.is_empty(); } Origin::Nonce CreateNonce() { return Origin::Nonce(); } Origin::Nonce CreateNonce(base::UnguessableToken nonce) { return Origin::Nonce(nonce); } const base::UnguessableToken* GetNonce(const Origin& origin) { return origin.GetNonceForSerialization(); } // Wrappers around url::Origin methods to expose it to tests. absl::optional<Origin> UnsafelyCreateOpaqueOriginWithoutNormalization( base::StringPiece precursor_scheme, base::StringPiece precursor_host, uint16_t precursor_port, const Origin::Nonce& nonce) { return Origin::UnsafelyCreateOpaqueOriginWithoutNormalization( precursor_scheme, precursor_host, precursor_port, nonce); } absl::optional<std::string> SerializeWithNonce(const Origin& origin) { return origin.SerializeWithNonce(); } absl::optional<std::string> SerializeWithNonceAndInitIfNeeded( Origin& origin) { return origin.SerializeWithNonceAndInitIfNeeded(); } absl::optional<Origin> Deserialize(const std::string& value) { return Origin::Deserialize(value); } private: ScopedSchemeRegistryForTests scoped_registry_; }; TEST_F(OriginTest, OpaqueOriginComparison) { // A default-constructed Origin should should be cross origin to everything // but itself. url::Origin opaque_a, opaque_b; EXPECT_TRUE(opaque_a.opaque()); EXPECT_EQ("", opaque_a.scheme()); EXPECT_EQ("", opaque_a.host()); EXPECT_EQ(0, opaque_a.port()); EXPECT_EQ(SchemeHostPort(), opaque_a.GetTupleOrPrecursorTupleIfOpaque()); EXPECT_FALSE(opaque_a.GetTupleOrPrecursorTupleIfOpaque().IsValid()); EXPECT_TRUE(opaque_b.opaque()); EXPECT_EQ("", opaque_b.scheme()); EXPECT_EQ("", opaque_b.host()); EXPECT_EQ(0, opaque_b.port()); EXPECT_EQ(SchemeHostPort(), opaque_b.GetTupleOrPrecursorTupleIfOpaque()); EXPECT_FALSE(opaque_b.GetTupleOrPrecursorTupleIfOpaque().IsValid()); // Two default-constructed Origins should always be cross origin to each // other. EXPECT_TRUE(DoEqualityComparisons(opaque_a, opaque_b, false)); EXPECT_TRUE(DoEqualityComparisons(opaque_b, opaque_b, true)); EXPECT_TRUE(DoEqualityComparisons(opaque_a, opaque_a, true)); // The streaming operator should not trigger lazy initialization to the token. std::ostringstream stream; stream << opaque_a; EXPECT_STREQ("null [internally: (nonce TBD) anonymous]", stream.str().c_str()); EXPECT_FALSE(HasNonceTokenBeenInitialized(opaque_a)); // None of the operations thus far should have triggered lazy-generation of // the UnguessableToken. Copying an origin, however, should trigger this. EXPECT_FALSE(HasNonceTokenBeenInitialized(opaque_a)); EXPECT_FALSE(HasNonceTokenBeenInitialized(opaque_b)); opaque_b = opaque_a; EXPECT_TRUE(HasNonceTokenBeenInitialized(opaque_a)); EXPECT_TRUE(HasNonceTokenBeenInitialized(opaque_b)); EXPECT_TRUE(DoEqualityComparisons(opaque_a, opaque_b, true)); EXPECT_TRUE(DoEqualityComparisons(opaque_b, opaque_b, true)); EXPECT_TRUE(DoEqualityComparisons(opaque_a, opaque_a, true)); // Move-initializing to a fresh Origin should restore the lazy initialization. opaque_a = url::Origin(); EXPECT_FALSE(HasNonceTokenBeenInitialized(opaque_a)); EXPECT_TRUE(HasNonceTokenBeenInitialized(opaque_b)); EXPECT_TRUE(DoEqualityComparisons(opaque_a, opaque_b, false)); EXPECT_TRUE(DoEqualityComparisons(opaque_b, opaque_b, true)); EXPECT_TRUE(DoEqualityComparisons(opaque_a, opaque_a, true)); // Comparing two opaque Origins with matching SchemeHostPorts should trigger // lazy initialization. EXPECT_FALSE(HasNonceTokenBeenInitialized(opaque_a)); EXPECT_TRUE(HasNonceTokenBeenInitialized(opaque_b)); bool should_swap = opaque_b < opaque_a; EXPECT_TRUE(HasNonceTokenBeenInitialized(opaque_a)); EXPECT_TRUE(HasNonceTokenBeenInitialized(opaque_b)); if (should_swap) std::swap(opaque_a, opaque_b); EXPECT_LT(opaque_a, opaque_b); EXPECT_FALSE(opaque_b < opaque_a); EXPECT_TRUE(DoEqualityComparisons(opaque_a, opaque_b, false)); EXPECT_TRUE(DoEqualityComparisons(opaque_b, opaque_b, true)); EXPECT_TRUE(DoEqualityComparisons(opaque_a, opaque_a, true)); EXPECT_LT(opaque_a, url::Origin::Create(GURL("http://www.google.com"))); EXPECT_LT(opaque_b, url::Origin::Create(GURL("http://www.google.com"))); EXPECT_EQ(opaque_b, url::Origin::Resolve(GURL(), opaque_b)); EXPECT_EQ(opaque_b, url::Origin::Resolve(GURL("about:blank"), opaque_b)); EXPECT_EQ(opaque_b, url::Origin::Resolve(GURL("about:srcdoc"), opaque_b)); EXPECT_EQ(opaque_b, url::Origin::Resolve(GURL("about:blank?hello#whee"), opaque_b)); } TEST_F(OriginTest, ConstructFromTuple) { struct TestCases { const char* const scheme; const char* const host; const uint16_t port; } cases[] = { {"http", "example.com", 80}, {"http", "example.com", 123}, {"https", "example.com", 443}, }; for (const auto& test_case : cases) { testing::Message scope_message; scope_message << test_case.scheme << "://" << test_case.host << ":" << test_case.port; SCOPED_TRACE(scope_message); Origin origin = Origin::CreateFromNormalizedTuple( test_case.scheme, test_case.host, test_case.port); EXPECT_EQ(test_case.scheme, origin.scheme()); EXPECT_EQ(test_case.host, origin.host()); EXPECT_EQ(test_case.port, origin.port()); } } TEST_F(OriginTest, Serialization) { struct TestCases { const char* const url; const char* const expected; const char* const expected_log; } cases[] = { {"http://192.168.9.1/", "http://192.168.9.1"}, {"http://[2001:db8::1]/", "http://[2001:db8::1]"}, {"http://☃.net/", "http://xn--n3h.net"}, {"http://example.com/", "http://example.com"}, {"http://example.com:123/", "http://example.com:123"}, {"https://example.com/", "https://example.com"}, {"https://example.com:123/", "https://example.com:123"}, {"file:///etc/passwd", "file://", "file:// [internally: file://]"}, {"file://example.com/etc/passwd", "file://", "file:// [internally: file://example.com]"}, {"data:,", "null", "null [internally: (nonce TBD) anonymous]"}, }; for (const auto& test_case : cases) { SCOPED_TRACE(test_case.url); GURL url(test_case.url); EXPECT_TRUE(url.is_valid()); Origin origin = Origin::Create(url); std::string serialized = origin.Serialize(); ExpectParsedUrlsEqual(GURL(serialized), origin.GetURL()); EXPECT_EQ(test_case.expected, serialized); // The '<<' operator sometimes produces additional information. std::stringstream out; out << origin; if (test_case.expected_log) EXPECT_EQ(test_case.expected_log, out.str()); else EXPECT_EQ(test_case.expected, out.str()); } } TEST_F(OriginTest, Comparison) { // These URLs are arranged in increasing order: const char* const urls[] = { "data:uniqueness", "http://a:80", "http://b:80", "https://a:80", "https://b:80", "http://a:81", "http://b:81", "https://a:81", "https://b:81", }; // Validate the comparison logic still works when creating a canonical origin, // when any created opaque origins contain a nonce. { // Pre-create the origins, as the internal nonce for unique origins changes // with each freshly-constructed Origin (that's not copied). std::vector<Origin> origins; for (const auto* test_url : urls) origins.push_back(Origin::Create(GURL(test_url))); for (size_t i = 0; i < origins.size(); i++) { const Origin& current = origins[i]; for (size_t j = i; j < origins.size(); j++) { const Origin& to_compare = origins[j]; EXPECT_EQ(i < j, current < to_compare) << i << " < " << j; EXPECT_EQ(j < i, to_compare < current) << j << " < " << i; } } } } TEST_F(OriginTest, UnsafelyCreate) { struct TestCase { const char* scheme; const char* host; uint16_t port; } cases[] = { {"http", "example.com", 80}, {"http", "example.com", 123}, {"https", "example.com", 443}, {"https", "example.com", 123}, {"http", "example.com", 0}, // 0 is a valid port for http. {"file", "", 0}, // 0 indicates "no port" for file: scheme. {"file", "example.com", 0}, }; for (const auto& test : cases) { SCOPED_TRACE(testing::Message() << test.scheme << "://" << test.host << ":" << test.port); absl::optional<url::Origin> origin = url::Origin::UnsafelyCreateTupleOriginWithoutNormalization( test.scheme, test.host, test.port); ASSERT_TRUE(origin); EXPECT_EQ(test.scheme, origin->scheme()); EXPECT_EQ(test.host, origin->host()); EXPECT_EQ(test.port, origin->port()); EXPECT_FALSE(origin->opaque()); EXPECT_TRUE(origin->IsSameOriginWith(*origin)); ExpectParsedUrlsEqual(GURL(origin->Serialize()), origin->GetURL()); base::UnguessableToken nonce = base::UnguessableToken::Create(); absl::optional<url::Origin> opaque_origin = UnsafelyCreateOpaqueOriginWithoutNormalization( test.scheme, test.host, test.port, CreateNonce(nonce)); ASSERT_TRUE(opaque_origin); EXPECT_TRUE(opaque_origin->opaque()); EXPECT_FALSE(*opaque_origin == origin); EXPECT_EQ(opaque_origin->GetTupleOrPrecursorTupleIfOpaque(), origin->GetTupleOrPrecursorTupleIfOpaque()); EXPECT_EQ(opaque_origin, UnsafelyCreateOpaqueOriginWithoutNormalization( test.scheme, test.host, test.port, CreateNonce(nonce))); EXPECT_FALSE(*opaque_origin == origin->DeriveNewOpaqueOrigin()); } } TEST_F(OriginTest, UnsafelyCreateUniqueOnInvalidInput) { url::AddStandardScheme("host-only", url::SCHEME_WITH_HOST); url::AddStandardScheme("host-port-only", url::SCHEME_WITH_HOST_AND_PORT); struct TestCases { const char* scheme; const char* host; uint16_t port = 80; } cases[] = {{"", "", 33}, {"data", "", 0}, #ifndef OHOS_UNITTESTS {"blob", "", 0}, {"filesystem", "", 0}, {"data", "example.com"}, {"http", "☃.net"}, {"http\nmore", "example.com"}, {"http\rmore", "example.com"}, {"http\n", "example.com"}, {"http\r", "example.com"}, {"http", "example.com\nnot-example.com"}, {"http", "example.com\rnot-example.com"}, {"http", "example.com\n"}, {"http", "example.com\r"}, {"unknown-scheme", "example.com"}, {"host-only", "\r", 0}, #endif {"host-only", "example.com", 22}, {"file", "", 123}}; // file: shouldn't have a port. for (const auto& test : cases) { SCOPED_TRACE(testing::Message() << test.scheme << "://" << test.host << ":" << test.port); EXPECT_FALSE(UnsafelyCreateOpaqueOriginWithoutNormalization( test.scheme, test.host, test.port, CreateNonce())); EXPECT_FALSE(url::Origin::UnsafelyCreateTupleOriginWithoutNormalization( test.scheme, test.host, test.port)); } // An empty scheme/host/port tuple is not a valid tuple origin. EXPECT_FALSE( url::Origin::UnsafelyCreateTupleOriginWithoutNormalization("", "", 0)); // Opaque origins with unknown precursors are allowed. base::UnguessableToken token = base::UnguessableToken::Create(); absl::optional<url::Origin> anonymous_opaque = UnsafelyCreateOpaqueOriginWithoutNormalization("", "", 0, CreateNonce(token)); ASSERT_TRUE(anonymous_opaque) << "An invalid tuple is a valid input to " << "UnsafelyCreateOpaqueOriginWithoutNormalization, so long as it is " << "the canonical form of the invalid tuple."; EXPECT_TRUE(anonymous_opaque->opaque()); EXPECT_EQ(*GetNonce(anonymous_opaque.value()), token); EXPECT_EQ(anonymous_opaque->GetTupleOrPrecursorTupleIfOpaque(), url::SchemeHostPort()); } TEST_F(OriginTest, UnsafelyCreateUniqueViaEmbeddedNulls) { struct TestCases { base::StringPiece scheme; base::StringPiece host; uint16_t port = 80; } cases[] = { #ifndef OHOS_UNITTESTS {{"http\0more", 9}, {"example.com", 11}}, {{"http\0", 5}, {"example.com", 11}}, {{"\0http", 5}, {"example.com", 11}}, {{"http"}, {"example.com\0not-example.com", 27}}, {{"http"}, {"example.com\0", 12}}, {{"http"}, {"\0example.com", 12}}, {{""}, {"\0", 1}, 0}, {{"\0", 1}, {""}, 0} #endif }; for (const auto& test : cases) { SCOPED_TRACE(testing::Message() << test.scheme << "://" << test.host << ":" << test.port); EXPECT_FALSE(url::Origin::UnsafelyCreateTupleOriginWithoutNormalization( test.scheme, test.host, test.port)); EXPECT_FALSE(UnsafelyCreateOpaqueOriginWithoutNormalization( test.scheme, test.host, test.port, CreateNonce())); } } TEST_F(OriginTest, DomainIs) { const struct { const char* url; const char* lower_ascii_domain; bool expected_domain_is; } kTestCases[] = { {"http://google.com/foo", "google.com", true}, {"http://www.google.com:99/foo", "google.com", true}, {"http://www.google.com.cn/foo", "google.com", false}, {"http://www.google.comm", "google.com", false}, {"http://www.iamnotgoogle.com/foo", "google.com", false}, {"http://www.google.com/foo", "Google.com", false}, // If the host ends with a dot, it matches domains with or without a dot. {"http://www.google.com./foo", "google.com", true}, {"http://www.google.com./foo", "google.com.", true}, {"http://www.google.com./foo", ".com", true}, {"http://www.google.com./foo", ".com.", true}, // But, if the host doesn't end with a dot and the input domain does, then // it's considered to not match. {"http://google.com/foo", "google.com.", false}, // If the host ends with two dots, it doesn't match. {"http://www.google.com../foo", "google.com", false}, // Filesystem scheme. {"filesystem:http://www.google.com:99/foo/", "google.com", true}, {"filesystem:http://www.iamnotgoogle.com/foo/", "google.com", false}, // File scheme. {"file:///home/user/text.txt", "", false}, {"file:///home/user/text.txt", "txt", false}, }; for (const auto& test_case : kTestCases) { SCOPED_TRACE(testing::Message() << "(url, domain): (" << test_case.url << ", " << test_case.lower_ascii_domain << ")"); GURL url(test_case.url); ASSERT_TRUE(url.is_valid()); Origin origin = Origin::Create(url); EXPECT_EQ(test_case.expected_domain_is, origin.DomainIs(test_case.lower_ascii_domain)); EXPECT_FALSE( origin.DeriveNewOpaqueOrigin().DomainIs(test_case.lower_ascii_domain)); } // If the URL is invalid, DomainIs returns false. GURL invalid_url("google.com"); ASSERT_FALSE(invalid_url.is_valid()); EXPECT_FALSE(Origin::Create(invalid_url).DomainIs("google.com")); // Unique origins. EXPECT_FALSE(Origin().DomainIs("")); EXPECT_FALSE(Origin().DomainIs("com")); } TEST_F(OriginTest, DebugAlias) { Origin origin1 = Origin::Create(GURL("https://foo.com/bar")); DEBUG_ALIAS_FOR_ORIGIN(origin1_debug_alias, origin1); EXPECT_STREQ("https://foo.com", origin1_debug_alias); } TEST_F(OriginTest, CanBeDerivedFrom) { AddStandardScheme("new-standard", SchemeType::SCHEME_WITH_HOST); Origin opaque_unique_origin = Origin(); Origin regular_origin = Origin::Create(GURL("https://a.com/")); Origin opaque_precursor_origin = regular_origin.DeriveNewOpaqueOrigin(); Origin file_origin = Origin::Create(GURL("file:///foo/bar")); Origin file_opaque_precursor_origin = file_origin.DeriveNewOpaqueOrigin(); Origin file_host_origin = Origin::Create(GURL("file://a.com/foo/bar")); Origin file_host_opaque_precursor_origin = file_host_origin.DeriveNewOpaqueOrigin(); Origin non_standard_scheme_origin = Origin::Create(GURL("non-standard-scheme:foo")); Origin non_standard_opaque_precursor_origin = non_standard_scheme_origin.DeriveNewOpaqueOrigin(); // Also, add new standard scheme that is local to the test. Origin new_standard_origin = Origin::Create(GURL("new-standard://host/")); Origin new_standard_opaque_precursor_origin = new_standard_origin.DeriveNewOpaqueOrigin(); // No access schemes always get unique opaque origins. Origin no_access_origin = Origin::Create(GURL("standard-but-noaccess://b.com")); Origin no_access_opaque_precursor_origin = no_access_origin.DeriveNewOpaqueOrigin(); Origin local_non_standard_origin = Origin::Create(GURL("local-but-nonstandard://a.com")); Origin local_non_standard_opaque_precursor_origin = local_non_standard_origin.DeriveNewOpaqueOrigin(); // Call origin.CanBeDerivedFrom(url) for each of the following test cases // and ensure that it returns |expected_value| const struct { const char* url; raw_ptr<Origin> origin; bool expected_value; } kTestCases[] = { {"https://a.com", &regular_origin, true}, // Web URL can commit in an opaque origin with precursor information. // Example: iframe sandbox navigated to a.com. {"https://a.com", &opaque_precursor_origin, true}, // URL that comes from the web can never commit in an opaque unique // origin. It must have precursor information. {"https://a.com", &opaque_unique_origin, false}, // Cross-origin URLs should never work. {"https://b.com", &regular_origin, false}, {"https://b.com", &opaque_precursor_origin, false}, // data: URL can never commit in a regular, non-opaque origin. {"data:text/html,foo", &regular_origin, false}, // This is the default case: data: URLs commit in opaque origin carrying // precursor information for the origin that created them. {"data:text/html,foo", &opaque_precursor_origin, true}, // Browser-initiated navigations can result in data: URL committing in // opaque unique origin. {"data:text/html,foo", &opaque_unique_origin, true}, // about:blank can commit in regular origin (default case for iframes). {"about:blank", &regular_origin, true}, // This can happen if data: URL that originated at a.com creates an // about:blank iframe. {"about:blank", &opaque_precursor_origin, true}, // Browser-initiated navigations can result in about:blank URL committing // in opaque unique origin. {"about:blank", &opaque_unique_origin, true}, // Default behavior of srcdoc is to inherit the origin of the parent // document. {"about:srcdoc", &regular_origin, true}, // This happens for sandboxed srcdoc iframe. {"about:srcdoc", &opaque_precursor_origin, true}, // This can happen with browser-initiated navigation to about:blank or // data: URL, which in turn add srcdoc iframe. {"about:srcdoc", &opaque_unique_origin, true}, // Just like srcdoc, blob: URLs can be created in all the cases. {"blob:https://a.com/foo", &regular_origin, true}, {"blob:https://a.com/foo", &opaque_precursor_origin, true}, {"blob:https://a.com/foo", &opaque_unique_origin, true}, {"filesystem:https://a.com/foo", &regular_origin, true}, {"filesystem:https://a.com/foo", &opaque_precursor_origin, true}, // Unlike blob: URLs, filesystem: ones cannot be created in an unique // opaque origin. {"filesystem:https://a.com/foo", &opaque_unique_origin, false}, // file: URLs cannot result in regular web origins, regardless of // opaqueness. {"file:///etc/passwd", &regular_origin, false}, {"file:///etc/passwd", &opaque_precursor_origin, false}, // However, they can result in regular file: origin and an opaque one // containing another file: origin as precursor. {"file:///etc/passwd", &file_origin, true}, {"file:///etc/passwd", &file_opaque_precursor_origin, true}, // It should not be possible to get an opaque unique origin for file: // as it is a standard scheme and will always result in a tuple origin // or will always be derived by other origin. // Note: file:// URLs should become unique opaque origins at some point. {"file:///etc/passwd", &opaque_unique_origin, false}, // The same set as above, but including a host. {"file://a.com/etc/passwd", &regular_origin, false}, {"file://a.com/etc/passwd", &opaque_precursor_origin, false}, {"file://a.com/etc/passwd", &file_host_origin, true}, {"file://a.com/etc/passwd", &file_host_opaque_precursor_origin, true}, {"file://a.com/etc/passwd", &opaque_unique_origin, false}, // Locally registered standard scheme should behave the same way // as built-in standard schemes. {"new-standard://host/foo", &new_standard_origin, true}, {"new-standard://host/foo", &new_standard_opaque_precursor_origin, true}, {"new-standard://host/foo", &opaque_unique_origin, false}, {"new-standard://host2/foo", &new_standard_origin, false}, {"new-standard://host2/foo", &new_standard_opaque_precursor_origin, false}, // A non-standard scheme should never commit in an standard origin or // opaque origin with standard precursor information. {"non-standard-scheme://a.com/foo", &regular_origin, false}, {"non-standard-scheme://a.com/foo", &opaque_precursor_origin, false}, // However, it should be fine to commit in unique opaque origins or in its // own origin. // Note: since non-standard scheme URLs don't parse out anything // but the scheme, using a random different hostname here would work. {"non-standard-scheme://b.com/foo2", &opaque_unique_origin, true}, {"non-standard-scheme://b.com/foo3", &non_standard_scheme_origin, true}, {"non-standard-scheme://b.com/foo4", &non_standard_opaque_precursor_origin, true}, // No access scheme can only commit in opaque origin. {"standard-but-noaccess://a.com/foo", &regular_origin, false}, {"standard-but-noaccess://a.com/foo", &opaque_precursor_origin, false}, {"standard-but-noaccess://a.com/foo", &opaque_unique_origin, true}, {"standard-but-noaccess://a.com/foo", &no_access_origin, true}, {"standard-but-noaccess://a.com/foo", &no_access_opaque_precursor_origin, true}, {"standard-but-noaccess://b.com/foo", &no_access_origin, true}, {"standard-but-noaccess://b.com/foo", &no_access_opaque_precursor_origin, true}, // Local schemes can be non-standard, verify they also work as expected. {"local-but-nonstandard://a.com", &regular_origin, false}, {"local-but-nonstandard://a.com", &opaque_precursor_origin, false}, {"local-but-nonstandard://a.com", &opaque_unique_origin, true}, {"local-but-nonstandard://a.com", &local_non_standard_origin, true}, {"local-but-nonstandard://a.com", &local_non_standard_opaque_precursor_origin, true}, }; for (const auto& test_case : kTestCases) { SCOPED_TRACE(testing::Message() << "(origin, url): (" << *test_case.origin << ", " << test_case.url << ")"); EXPECT_EQ(test_case.expected_value, test_case.origin->CanBeDerivedFrom(GURL(test_case.url))); } } TEST_F(OriginTest, GetDebugString) { Origin http_origin = Origin::Create(GURL("http://192.168.9.1")); EXPECT_STREQ(http_origin.GetDebugString().c_str(), "http://192.168.9.1"); Origin http_opaque_origin = http_origin.DeriveNewOpaqueOrigin(); EXPECT_THAT( http_opaque_origin.GetDebugString().c_str(), ::testing::MatchesRegex( "null \\[internally: \\(\\w*\\) derived from http://192.168.9.1\\]")); EXPECT_THAT( http_opaque_origin.GetDebugString(false /* include_nonce */).c_str(), ::testing::MatchesRegex( "null \\[internally: derived from http://192.168.9.1\\]")); Origin data_origin = Origin::Create(GURL("data:")); EXPECT_STREQ(data_origin.GetDebugString().c_str(), "null [internally: (nonce TBD) anonymous]"); // The nonce of the origin will be initialized if a new opaque origin is // derived. Origin data_derived_origin = data_origin.DeriveNewOpaqueOrigin(); EXPECT_THAT( data_derived_origin.GetDebugString().c_str(), ::testing::MatchesRegex("null \\[internally: \\(\\w*\\) anonymous\\]")); EXPECT_THAT( data_derived_origin.GetDebugString(false /* include_nonce */).c_str(), ::testing::MatchesRegex("null \\[internally: anonymous\\]")); Origin file_origin = Origin::Create(GURL("file:///etc/passwd")); EXPECT_STREQ(file_origin.GetDebugString().c_str(), "file:// [internally: file://]"); Origin file_server_origin = Origin::Create(GURL("file://example.com/etc/passwd")); EXPECT_STREQ(file_server_origin.GetDebugString().c_str(), "file:// [internally: file://example.com]"); } TEST_F(OriginTest, Deserialize) { std::vector<GURL> valid_urls = { GURL("https://a.com"), GURL("http://a"), GURL("http://a:80"), GURL("file://a.com/etc/passwd"), GURL("file:///etc/passwd"), GURL("http://192.168.1.1"), GURL("http://[2001:db8::1]/"), }; for (const GURL& url : valid_urls) { SCOPED_TRACE(url.spec()); Origin origin = Origin::Create(url); absl::optional<std::string> serialized = SerializeWithNonce(origin); ASSERT_TRUE(serialized); absl::optional<Origin> deserialized = Deserialize(std::move(*serialized)); ASSERT_TRUE(deserialized.has_value()); EXPECT_TRUE(DoEqualityComparisons(origin, deserialized.value(), true)); EXPECT_EQ(origin.GetDebugString(), deserialized.value().GetDebugString()); } } TEST_F(OriginTest, DeserializeInvalid) { EXPECT_EQ(absl::nullopt, Deserialize(std::string())); EXPECT_EQ(absl::nullopt, Deserialize("deadbeef")); EXPECT_EQ(absl::nullopt, Deserialize("0123456789")); EXPECT_EQ(absl::nullopt, Deserialize("https://a.com")); EXPECT_EQ(absl::nullopt, Deserialize("https://192.168.1.1")); } TEST_F(OriginTest, SerializeTBDNonce) { std::vector<GURL> invalid_urls = { GURL("data:uniqueness"), GURL("data:,"), GURL("data:text/html,Hello!"), GURL("javascript:alert(1)"), GURL("about:blank"), GURL("google.com"), }; for (const GURL& url : invalid_urls) { SCOPED_TRACE(url.spec()); Origin origin = Origin::Create(url); absl::optional<std::string> serialized = SerializeWithNonce(origin); absl::optional<Origin> deserialized = Deserialize(std::move(*serialized)); ASSERT_TRUE(deserialized.has_value()); // Can't use DoEqualityComparisons here since empty nonces are never == // unless they are the same object. EXPECT_EQ(origin.GetDebugString(), deserialized.value().GetDebugString()); } { // Same basic test as above, but without a GURL to create tuple_. Origin opaque; absl::optional<std::string> serialized = SerializeWithNonce(opaque); ASSERT_TRUE(serialized); absl::optional<Origin> deserialized = Deserialize(std::move(*serialized)); ASSERT_TRUE(deserialized.has_value()); // Can't use DoEqualityComparisons here since empty nonces are never == // unless they are the same object. EXPECT_EQ(opaque.GetDebugString(), deserialized.value().GetDebugString()); } // Now force initialization of the nonce prior to serialization. for (const GURL& url : invalid_urls) { SCOPED_TRACE(url.spec()); Origin origin = Origin::Create(url); absl::optional<std::string> serialized = SerializeWithNonceAndInitIfNeeded(origin); absl::optional<Origin> deserialized = Deserialize(std::move(*serialized)); ASSERT_TRUE(deserialized.has_value()); // The nonce should have been initialized prior to Serialization(). EXPECT_EQ(origin, deserialized.value()); } } TEST_F(OriginTest, DeserializeValidNonce) { Origin opaque; GetNonce(opaque); absl::optional<std::string> serialized = SerializeWithNonce(opaque); ASSERT_TRUE(serialized); absl::optional<Origin> deserialized = Deserialize(std::move(*serialized)); ASSERT_TRUE(deserialized.has_value()); EXPECT_TRUE(DoEqualityComparisons(opaque, deserialized.value(), true)); EXPECT_EQ(opaque.GetDebugString(), deserialized.value().GetDebugString()); } TEST_F(OriginTest, IsSameOriginWith) { url::Origin opaque_origin; GURL foo_url = GURL("https://foo.com/path"); url::Origin foo_origin = url::Origin::Create(foo_url); GURL bar_url = GURL("https://bar.com/path"); url::Origin bar_origin = url::Origin::Create(bar_url); EXPECT_FALSE(opaque_origin.IsSameOriginWith(foo_origin)); EXPECT_FALSE(opaque_origin.IsSameOriginWith(foo_url)); EXPECT_TRUE(foo_origin.IsSameOriginWith(foo_origin)); EXPECT_TRUE(foo_origin.IsSameOriginWith(foo_url)); EXPECT_FALSE(foo_origin.IsSameOriginWith(bar_origin)); EXPECT_FALSE(foo_origin.IsSameOriginWith(bar_url)); // Documenting legacy behavior. This doesn't necessarily mean that the legacy // behavior is correct (or desirable in the long-term). EXPECT_FALSE(foo_origin.IsSameOriginWith(GURL("about:blank"))); EXPECT_FALSE(foo_origin.IsSameOriginWith(GURL())); // Invalid GURL. EXPECT_TRUE(foo_origin.IsSameOriginWith(GURL("blob:https://foo.com/guid"))); } INSTANTIATE_TYPED_TEST_SUITE_P(UrlOrigin, AbstractOriginTest, UrlOriginTestTraits); } // namespace url
Zhao-PengFei35/chromium_src_4
url/origin_unittest.cc
C++
unknown
32,354
// Copyright 2019 The Chromium Authors // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "base/functional/bind.h" #include "base/test/launcher/unit_test_launcher.h" #include "base/test/perf_test_suite.h" int main(int argc, char** argv) { base::PerfTestSuite test_suite(argc, argv); return base::LaunchUnitTestsSerially( argc, argv, base::BindOnce(&base::TestSuite::Run, base::Unretained(&test_suite))); }
Zhao-PengFei35/chromium_src_4
url/run_all_perftests.cc
C++
unknown
486
// Copyright 2016 The Chromium Authors // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include <memory> #include "base/functional/bind.h" #include "base/test/launcher/unit_test_launcher.h" #include "base/test/test_io_thread.h" #include "base/test/test_suite.h" #include "build/build_config.h" #if !BUILDFLAG(IS_IOS) #include "mojo/core/embedder/embedder.h" // nogncheck #endif int main(int argc, char** argv) { base::TestSuite test_suite(argc, argv); #if !BUILDFLAG(IS_IOS) mojo::core::Init(); #endif return base::LaunchUnitTests( argc, argv, base::BindOnce(&base::TestSuite::Run, base::Unretained(&test_suite))); }
Zhao-PengFei35/chromium_src_4
url/run_all_unittests.cc
C++
unknown
698
// Copyright 2015 The Chromium Authors // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "url/scheme_host_port.h" #include <stdint.h> #include <string.h> #include <ostream> #include <tuple> #include "base/check_op.h" #include "base/containers/contains.h" #include "base/notreached.h" #include "base/numerics/safe_conversions.h" #include "base/strings/string_number_conversions.h" #include "base/strings/string_piece.h" #include "url/gurl.h" #include "url/third_party/mozilla/url_parse.h" #include "url/url_canon.h" #include "url/url_canon_stdstring.h" #include "url/url_constants.h" #include "url/url_util.h" namespace url { namespace { bool IsCanonicalHost(const base::StringPiece& host) { std::string canon_host; // Try to canonicalize the host (copy/pasted from net/base. :( ). const Component raw_host_component(0, base::checked_cast<int>(host.length())); StdStringCanonOutput canon_host_output(&canon_host); CanonHostInfo host_info; CanonicalizeHostVerbose(host.data(), raw_host_component, &canon_host_output, &host_info); if (host_info.out_host.is_nonempty() && host_info.family != CanonHostInfo::BROKEN) { // Success! Assert that there's no extra garbage. canon_host_output.Complete(); DCHECK_EQ(host_info.out_host.len, static_cast<int>(canon_host.length())); } else { // Empty host, or canonicalization failed. canon_host.clear(); } return host == canon_host; } // Note: When changing IsValidInput, consider also updating // ShouldTreatAsOpaqueOrigin in Blink (there might be existing differences in // behavior between these 2 layers, but we should avoid introducing new // differences). bool IsValidInput(const base::StringPiece& scheme, const base::StringPiece& host, uint16_t port, SchemeHostPort::ConstructPolicy policy) { // Empty schemes are never valid. if (scheme.empty()) return false; // about:blank and other no-access schemes translate into an opaque origin. // This helps consistency with ShouldTreatAsOpaqueOrigin in Blink. if (base::Contains(GetNoAccessSchemes(), scheme)) return false; SchemeType scheme_type = SCHEME_WITH_HOST_PORT_AND_USER_INFORMATION; bool is_standard = GetStandardSchemeType( scheme.data(), Component(0, base::checked_cast<int>(scheme.length())), &scheme_type); if (!is_standard) { // To be consistent with ShouldTreatAsOpaqueOrigin in Blink, local // non-standard schemes are currently allowed to be tuple origins. // Nonstandard schemes don't have hostnames, so their tuple is just // ("protocol", "", 0). // // TODO: Migrate "content:" and "externalfile:" to be standard schemes, and // remove this local scheme exception. if (base::Contains(GetLocalSchemes(), scheme) && host.empty() && port == 0) return true; // Otherwise, allow non-standard schemes only if the Android WebView // workaround is enabled. return AllowNonStandardSchemesForAndroidWebView(); } switch (scheme_type) { case SCHEME_WITH_HOST_AND_PORT: case SCHEME_WITH_HOST_PORT_AND_USER_INFORMATION: // A URL with |scheme| is required to have the host and port, so return an // invalid instance if host is not given. Note that a valid port is // always provided by SchemeHostPort(const GURL&) constructor (a missing // port is replaced with a default port if needed by // GURL::EffectiveIntPort()). if (host.empty()) return false; // Don't do an expensive canonicalization if the host is already // canonicalized. DCHECK(policy == SchemeHostPort::CHECK_CANONICALIZATION || IsCanonicalHost(host)); if (policy == SchemeHostPort::CHECK_CANONICALIZATION && !IsCanonicalHost(host)) { return false; } return true; case SCHEME_WITH_HOST: if (port != 0) { // Return an invalid object if a URL with the scheme never represents // the port data but the given |port| is non-zero. return false; } // Don't do an expensive canonicalization if the host is already // canonicalized. DCHECK(policy == SchemeHostPort::CHECK_CANONICALIZATION || IsCanonicalHost(host)); if (policy == SchemeHostPort::CHECK_CANONICALIZATION && !IsCanonicalHost(host)) { return false; } return true; case SCHEME_WITHOUT_AUTHORITY: return false; default: NOTREACHED(); return false; } } } // namespace SchemeHostPort::SchemeHostPort() = default; SchemeHostPort::SchemeHostPort(std::string scheme, std::string host, uint16_t port, ConstructPolicy policy) { if (!IsValidInput(scheme, host, port, policy)) { DCHECK(!IsValid()); return; } scheme_ = std::move(scheme); host_ = std::move(host); port_ = port; DCHECK(IsValid()) << "Scheme: " << scheme_ << " Host: " << host_ << " Port: " << port; } SchemeHostPort::SchemeHostPort(base::StringPiece scheme, base::StringPiece host, uint16_t port) : SchemeHostPort(std::string(scheme), std::string(host), port, ConstructPolicy::CHECK_CANONICALIZATION) {} SchemeHostPort::SchemeHostPort(const GURL& url) { if (!url.is_valid()) return; base::StringPiece scheme = url.scheme_piece(); base::StringPiece host = url.host_piece(); // A valid GURL never returns PORT_INVALID. int port = url.EffectiveIntPort(); if (port == PORT_UNSPECIFIED) { port = 0; } else { DCHECK_GE(port, 0); DCHECK_LE(port, 65535); } if (!IsValidInput(scheme, host, port, ALREADY_CANONICALIZED)) return; scheme_ = std::string(scheme); host_ = std::string(host); port_ = port; } SchemeHostPort::~SchemeHostPort() = default; bool SchemeHostPort::IsValid() const { // It suffices to just check |scheme_| for emptiness; the other fields are // never present without it. DCHECK(!scheme_.empty() || host_.empty()); DCHECK(!scheme_.empty() || port_ == 0); return !scheme_.empty(); } std::string SchemeHostPort::Serialize() const { // Null checking for |parsed| in SerializeInternal is probably slower than // just filling it in and discarding it here. url::Parsed parsed; return SerializeInternal(&parsed); } GURL SchemeHostPort::GetURL() const { url::Parsed parsed; std::string serialized = SerializeInternal(&parsed); if (!IsValid()) return GURL(std::move(serialized), parsed, false); // SchemeHostPort does not have enough information to determine if an empty // host is valid or not for the given scheme. Force re-parsing. DCHECK(!scheme_.empty()); if (host_.empty()) return GURL(serialized); // If the serialized string is passed to GURL for parsing, it will append an // empty path "/". Add that here. Note: per RFC 6454 we cannot do this for // normal Origin serialization. DCHECK(!parsed.path.is_valid()); parsed.path = Component(serialized.length(), 1); serialized.append("/"); return GURL(std::move(serialized), parsed, true); } bool SchemeHostPort::operator<(const SchemeHostPort& other) const { return std::tie(port_, scheme_, host_) < std::tie(other.port_, other.scheme_, other.host_); } std::string SchemeHostPort::SerializeInternal(url::Parsed* parsed) const { std::string result; if (!IsValid()) return result; // Reserve enough space for the "normal" case of scheme://host/. result.reserve(scheme_.size() + host_.size() + 4); if (!scheme_.empty()) { parsed->scheme = Component(0, scheme_.length()); result.append(scheme_); } result.append(kStandardSchemeSeparator); if (!host_.empty()) { parsed->host = Component(result.length(), host_.length()); result.append(host_); } // Omit the port component if the port matches with the default port // defined for the scheme, if any. int default_port = DefaultPortForScheme(scheme_.data(), static_cast<int>(scheme_.length())); if (default_port == PORT_UNSPECIFIED) return result; if (port_ != default_port) { result.push_back(':'); std::string port(base::NumberToString(port_)); parsed->port = Component(result.length(), port.length()); result.append(std::move(port)); } return result; } std::ostream& operator<<(std::ostream& out, const SchemeHostPort& scheme_host_port) { return out << scheme_host_port.Serialize(); } } // namespace url
Zhao-PengFei35/chromium_src_4
url/scheme_host_port.cc
C++
unknown
8,811
// Copyright 2015 The Chromium Authors // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #ifndef URL_SCHEME_HOST_PORT_H_ #define URL_SCHEME_HOST_PORT_H_ #include <stdint.h> #include <string> #include "base/component_export.h" #include "base/strings/string_piece.h" class GURL; namespace url { struct Parsed; // This class represents a (scheme, host, port) tuple extracted from a URL. // // The primary purpose of this class is to represent relevant network-authority // information for a URL. It is _not_ an Origin, as described in RFC 6454. In // particular, it is generally NOT the right thing to use for security // decisions. // // Instead, this class is a mechanism for simplifying URLs with standard schemes // (that is, those which follow the generic syntax of RFC 3986) down to the // uniquely identifying information necessary for network fetches. This makes it // suitable as a cache key for a collection of active connections, for instance. // It may, however, be inappropriate to use as a cache key for persistent // storage associated with a host. // // In particular, note that: // // * SchemeHostPort can only represent schemes which follow the RFC 3986 syntax // (e.g. those registered with GURL as "standard schemes"). Non-standard // schemes such as "blob", "filesystem", "data", and "javascript" can only be // represented as invalid SchemeHostPort objects. // // * For example, the "file" scheme follows the standard syntax, but it is // important to note that the authority portion (host, port) is optional. // URLs without an authority portion will be represented with an empty string // for the host, and a port of 0 (e.g. "file:///etc/hosts" => // ("file", "", 0)), and URLs with a host-only authority portion will be // represented with a port of 0 (e.g. "file://example.com/etc/hosts" => // ("file", "example.com", 0)). See Section 3 of RFC 3986 to better understand // these constructs. // // * SchemeHostPort has no notion of the Origin concept (RFC 6454), and in // particular, it has no notion of an opaque Origin. If you need to take // opaque origins into account (and, if you're making security-relevant // decisions then you absolutely do), please use 'url::Origin' instead. // // Usage: // // * SchemeHostPort objects are commonly created from GURL objects: // // GURL url("https://example.com/"); // url::SchemeHostPort tuple(url); // tuple.scheme(); // "https" // tuple.host(); // "example.com" // tuple.port(); // 443 // // * Objects may also be explicitly created and compared: // // url::SchemeHostPort tuple(url::kHttpsScheme, "example.com", 443); // tuple.scheme(); // "https" // tuple.host(); // "example.com" // tuple.port(); // 443 // // GURL url("https://example.com/"); // tuple == url::SchemeHostPort(url); // true class COMPONENT_EXPORT(URL) SchemeHostPort { public: // Creates an invalid (scheme, host, port) tuple, which represents an invalid // or non-standard URL. SchemeHostPort(); // Creates a (scheme, host, port) tuple. |host| must be a canonicalized // A-label (that is, '☃.net' must be provided as 'xn--n3h.net'). |scheme| // must be a standard scheme. |port| must be 0 if |scheme| does not support // ports (e.g. 'file'). // // Copies the data in |scheme| and |host|. SchemeHostPort(base::StringPiece scheme, base::StringPiece host, uint16_t port); // Metadata influencing whether or not the constructor should sanity check // host canonicalization. enum ConstructPolicy { CHECK_CANONICALIZATION, ALREADY_CANONICALIZED }; // Creates a (scheme, host, port) tuple without performing sanity checking // that the host and port are canonicalized. This should only be used when // converting between already normalized types, and should NOT be used for // IPC. SchemeHostPort(std::string scheme, std::string host, uint16_t port, ConstructPolicy policy); // Creates a (scheme, host, port) tuple from |url|, as described at // https://tools.ietf.org/html/rfc6454#section-4 // // If |url| is invalid or non-standard, the result will be an invalid // SchemeHostPort object. explicit SchemeHostPort(const GURL& url); // Copyable and movable. SchemeHostPort(const SchemeHostPort&) = default; SchemeHostPort& operator=(const SchemeHostPort&) = default; SchemeHostPort(SchemeHostPort&&) noexcept = default; SchemeHostPort& operator=(SchemeHostPort&&) noexcept = default; ~SchemeHostPort(); // Returns the host component, in URL form. That is all IDN domain names will // be expressed as A-Labels ('☃.net' will be returned as 'xn--n3h.net'), and // and all IPv6 addresses will be enclosed in brackets ("[2001:db8::1]"). const std::string& host() const { return host_; } const std::string& scheme() const { return scheme_; } uint16_t port() const { return port_; } bool IsValid() const; // Serializes the SchemeHostPort tuple to a canonical form. // // While this string form resembles the Origin serialization specified in // Section 6.2 of RFC 6454, it is important to note that invalid // SchemeHostPort tuples serialize to the empty string, rather than being // serialized as would an opaque Origin. std::string Serialize() const; // Efficiently returns what GURL(Serialize()) would return, without needing to // re-parse the URL. Note: this still performs allocations to copy data into // GURL, so please avoid using this method if you only need to work on // schemes, hosts, or ports individually. // For example, see crrev.com/c/3637099/comments/782360d0_e14757be. GURL GetURL() const; // Two SchemeHostPort objects are "equal" iff their schemes, hosts, and ports // are exact matches. // // Note that this comparison is _not_ the same as an origin-based comparison. // In particular, invalid SchemeHostPort objects match each other (and // themselves). Opaque origins, on the other hand, would not. bool operator==(const SchemeHostPort& other) const { return port_ == other.port() && scheme_ == other.scheme() && host_ == other.host(); } bool operator!=(const SchemeHostPort& other) const { return !(*this == other); } // Allows SchemeHostPort to be used as a key in STL (for example, a std::set // or std::map). bool operator<(const SchemeHostPort& other) const; private: std::string SerializeInternal(url::Parsed* parsed) const; std::string scheme_; std::string host_; uint16_t port_ = 0; }; COMPONENT_EXPORT(URL) std::ostream& operator<<(std::ostream& out, const SchemeHostPort& scheme_host_port); } // namespace url #endif // URL_SCHEME_HOST_PORT_H_
Zhao-PengFei35/chromium_src_4
url/scheme_host_port.h
C++
unknown
6,824
// Copyright 2015 The Chromium Authors // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "url/scheme_host_port.h" #include <stddef.h> #include <stdint.h> #include "testing/gtest/include/gtest/gtest.h" #include "url/gurl.h" #include "url/url_util.h" namespace { class SchemeHostPortTest : public testing::Test { public: SchemeHostPortTest() = default; SchemeHostPortTest(const SchemeHostPortTest&) = delete; SchemeHostPortTest& operator=(const SchemeHostPortTest&) = delete; ~SchemeHostPortTest() override = default; private: url::ScopedSchemeRegistryForTests scoped_registry_; }; void ExpectParsedUrlsEqual(const GURL& a, const GURL& b) { EXPECT_EQ(a, b); const url::Parsed& a_parsed = a.parsed_for_possibly_invalid_spec(); const url::Parsed& b_parsed = b.parsed_for_possibly_invalid_spec(); EXPECT_EQ(a_parsed.scheme.begin, b_parsed.scheme.begin); EXPECT_EQ(a_parsed.scheme.len, b_parsed.scheme.len); EXPECT_EQ(a_parsed.username.begin, b_parsed.username.begin); EXPECT_EQ(a_parsed.username.len, b_parsed.username.len); EXPECT_EQ(a_parsed.password.begin, b_parsed.password.begin); EXPECT_EQ(a_parsed.password.len, b_parsed.password.len); EXPECT_EQ(a_parsed.host.begin, b_parsed.host.begin); EXPECT_EQ(a_parsed.host.len, b_parsed.host.len); EXPECT_EQ(a_parsed.port.begin, b_parsed.port.begin); EXPECT_EQ(a_parsed.port.len, b_parsed.port.len); EXPECT_EQ(a_parsed.path.begin, b_parsed.path.begin); EXPECT_EQ(a_parsed.path.len, b_parsed.path.len); EXPECT_EQ(a_parsed.query.begin, b_parsed.query.begin); EXPECT_EQ(a_parsed.query.len, b_parsed.query.len); EXPECT_EQ(a_parsed.ref.begin, b_parsed.ref.begin); EXPECT_EQ(a_parsed.ref.len, b_parsed.ref.len); } TEST_F(SchemeHostPortTest, Invalid) { url::SchemeHostPort invalid; EXPECT_EQ("", invalid.scheme()); EXPECT_EQ("", invalid.host()); EXPECT_EQ(0, invalid.port()); EXPECT_FALSE(invalid.IsValid()); EXPECT_EQ(invalid, invalid); const char* urls[] = { // about:, data:, javascript: and other no-access schemes translate into // an invalid SchemeHostPort "about:blank", "about:blank#ref", "about:blank?query=123", "about:srcdoc", "about:srcdoc#ref", "about:srcdoc?query=123", "data:text/html,Hello!", "javascript:alert(1)", // GURLs where GURL::is_valid returns false translate into an invalid // SchemeHostPort. "file://example.com:443/etc/passwd", "#!^%!$!&*", // These schemes do not follow the generic URL syntax, so make sure we // treat them as invalid (scheme, host, port) tuples (even though such // URLs' _Origin_ might have a (scheme, host, port) tuple, they themselves // do not). This is only *implicitly* checked in the code, by means of // blob schemes not being standard, and filesystem schemes having type // SCHEME_WITHOUT_AUTHORITY. If conditions change such that the implicit // checks no longer hold, this policy should be made explicit. #ifndef OHOS_UNITTESTS "blob:https://example.com/uuid-goes-here", "filesystem:https://example.com/temporary/yay.png" #endif }; for (auto* test : urls) { SCOPED_TRACE(test); GURL url(test); url::SchemeHostPort tuple(url); EXPECT_EQ("", tuple.scheme()); EXPECT_EQ("", tuple.host()); EXPECT_EQ(0, tuple.port()); EXPECT_FALSE(tuple.IsValid()); EXPECT_EQ(tuple, tuple); EXPECT_EQ(tuple, invalid); EXPECT_EQ(invalid, tuple); ExpectParsedUrlsEqual(GURL(tuple.Serialize()), tuple.GetURL()); } } TEST_F(SchemeHostPortTest, ExplicitConstruction) { struct TestCases { const char* scheme; const char* host; uint16_t port; } cases[] = { {"http", "example.com", 80}, {"http", "example.com", 123}, {"http", "example.com", 0}, // 0 is a valid port for http. {"https", "example.com", 443}, {"https", "example.com", 123}, {"file", "", 0}, // 0 indicates "no port" for file: scheme. {"file", "example.com", 0}, }; for (const auto& test : cases) { SCOPED_TRACE(testing::Message() << test.scheme << "://" << test.host << ":" << test.port); url::SchemeHostPort tuple(test.scheme, test.host, test.port); EXPECT_EQ(test.scheme, tuple.scheme()); EXPECT_EQ(test.host, tuple.host()); EXPECT_EQ(test.port, tuple.port()); EXPECT_TRUE(tuple.IsValid()); EXPECT_EQ(tuple, tuple); ExpectParsedUrlsEqual(GURL(tuple.Serialize()), tuple.GetURL()); } } TEST_F(SchemeHostPortTest, InvalidConstruction) { struct TestCases { const char* scheme; const char* host; uint16_t port; } cases[] = {{"", "", 0}, {"data", "", 0}, #ifndef OHOS_UNITTESTS {"blob", "", 0}, {"filesystem", "", 0}, {"http", "", 80}, {"data", "example.com", 80}, {"http", "☃.net", 80}, {"http\nmore", "example.com", 80}, {"http\rmore", "example.com", 80}, {"http\n", "example.com", 80}, {"http\r", "example.com", 80}, {"http", "example.com\nnot-example.com", 80}, {"http", "example.com\rnot-example.com", 80}, {"http", "example.com\n", 80}, {"http", "example.com\r", 80}, {"file", "", 80} // Can''t have a port for file: scheme. #endif }; for (const auto& test : cases) { SCOPED_TRACE(testing::Message() << test.scheme << "://" << test.host << ":" << test.port); url::SchemeHostPort tuple(test.scheme, test.host, test.port); EXPECT_EQ("", tuple.scheme()); EXPECT_EQ("", tuple.host()); EXPECT_EQ(0, tuple.port()); EXPECT_FALSE(tuple.IsValid()); EXPECT_EQ(tuple, tuple); ExpectParsedUrlsEqual(GURL(tuple.Serialize()), tuple.GetURL()); } } TEST_F(SchemeHostPortTest, InvalidConstructionWithEmbeddedNulls) { struct TestCases { const char* scheme; size_t scheme_length; const char* host; size_t host_length; uint16_t port; } cases[] = { #ifndef OHOS_UNITTESTS {"http\0more", 9, "example.com", 11, 80}, {"http\0", 5, "example.com", 11, 80}, {"\0http", 5, "example.com", 11, 80}, {"http", 4, "example.com\0not-example.com", 27, 80}, {"http", 4, "example.com\0", 12, 80}, {"http", 4, "\0example.com", 12, 80} #endif }; for (const auto& test : cases) { SCOPED_TRACE(testing::Message() << test.scheme << "://" << test.host << ":" << test.port); url::SchemeHostPort tuple(std::string(test.scheme, test.scheme_length), std::string(test.host, test.host_length), test.port); EXPECT_EQ("", tuple.scheme()); EXPECT_EQ("", tuple.host()); EXPECT_EQ(0, tuple.port()); EXPECT_FALSE(tuple.IsValid()); ExpectParsedUrlsEqual(GURL(tuple.Serialize()), tuple.GetURL()); } } TEST_F(SchemeHostPortTest, GURLConstruction) { struct TestCases { const char* url; const char* scheme; const char* host; uint16_t port; } cases[] = { {"http://192.168.9.1/", "http", "192.168.9.1", 80}, {"http://[2001:db8::1]/", "http", "[2001:db8::1]", 80}, {"http://☃.net/", "http", "xn--n3h.net", 80}, {"http://example.com/", "http", "example.com", 80}, {"http://example.com:123/", "http", "example.com", 123}, {"https://example.com/", "https", "example.com", 443}, {"https://example.com:123/", "https", "example.com", 123}, {"file:///etc/passwd", "file", "", 0}, {"file://example.com/etc/passwd", "file", "example.com", 0}, {"http://u:p@example.com/", "http", "example.com", 80}, {"http://u:p@example.com/path", "http", "example.com", 80}, {"http://u:p@example.com/path?123", "http", "example.com", 80}, {"http://u:p@example.com/path?123#hash", "http", "example.com", 80}, }; for (const auto& test : cases) { SCOPED_TRACE(test.url); GURL url(test.url); EXPECT_TRUE(url.is_valid()); url::SchemeHostPort tuple(url); EXPECT_EQ(test.scheme, tuple.scheme()); EXPECT_EQ(test.host, tuple.host()); EXPECT_EQ(test.port, tuple.port()); EXPECT_TRUE(tuple.IsValid()); EXPECT_EQ(tuple, tuple); ExpectParsedUrlsEqual(GURL(tuple.Serialize()), tuple.GetURL()); } } TEST_F(SchemeHostPortTest, Serialization) { struct TestCases { const char* url; const char* expected; } cases[] = { {"http://192.168.9.1/", "http://192.168.9.1"}, {"http://[2001:db8::1]/", "http://[2001:db8::1]"}, {"http://☃.net/", "http://xn--n3h.net"}, {"http://example.com/", "http://example.com"}, {"http://example.com:123/", "http://example.com:123"}, {"https://example.com/", "https://example.com"}, {"https://example.com:123/", "https://example.com:123"}, {"file:///etc/passwd", "file://"}, {"file://example.com/etc/passwd", "file://example.com"}, {"https://example.com:0/", "https://example.com:0"}, }; for (const auto& test : cases) { SCOPED_TRACE(test.url); GURL url(test.url); url::SchemeHostPort tuple(url); EXPECT_EQ(test.expected, tuple.Serialize()); ExpectParsedUrlsEqual(GURL(tuple.Serialize()), tuple.GetURL()); } } TEST_F(SchemeHostPortTest, Comparison) { // These tuples are arranged in increasing order: struct SchemeHostPorts { const char* scheme; const char* host; uint16_t port; } tuples[] = { {"http", "a", 80}, {"http", "b", 80}, {"https", "a", 80}, {"https", "b", 80}, {"http", "a", 81}, {"http", "b", 81}, {"https", "a", 81}, {"https", "b", 81}, }; for (size_t i = 0; i < std::size(tuples); i++) { url::SchemeHostPort current(tuples[i].scheme, tuples[i].host, tuples[i].port); for (size_t j = i; j < std::size(tuples); j++) { url::SchemeHostPort to_compare(tuples[j].scheme, tuples[j].host, tuples[j].port); EXPECT_EQ(i < j, current < to_compare) << i << " < " << j; EXPECT_EQ(j < i, to_compare < current) << j << " < " << i; } } } // Some schemes have optional authority. Make sure that GURL conversion from // SchemeHostPort is not opinionated in that regard. For more info, See // crbug.com/820194, where we considered all SchemeHostPorts with // SCHEME_WITH_HOST (i.e., without ports) as valid with empty hosts, even though // most are not (e.g. chrome URLs). TEST_F(SchemeHostPortTest, EmptyHostGurlConversion) { url::AddStandardScheme("chrome", url::SCHEME_WITH_HOST); GURL chrome_url("chrome:"); EXPECT_FALSE(chrome_url.is_valid()); url::SchemeHostPort chrome_tuple("chrome", "", 0); EXPECT_FALSE(chrome_tuple.GetURL().is_valid()); ExpectParsedUrlsEqual(GURL(chrome_tuple.Serialize()), chrome_tuple.GetURL()); ExpectParsedUrlsEqual(chrome_url, chrome_tuple.GetURL()); } } // namespace url
Zhao-PengFei35/chromium_src_4
url/scheme_host_port_unittest.cc
C++
unknown
11,119
// Copyright 2017 The Chromium Authors // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "url/url_canon.h" #include "base/component_export.h" namespace url { template class EXPORT_TEMPLATE_DEFINE(COMPONENT_EXPORT(URL)) CanonOutputT<char>; template class EXPORT_TEMPLATE_DEFINE(COMPONENT_EXPORT(URL)) CanonOutputT<char16_t>; } // namespace url
Zhao-PengFei35/chromium_src_4
url/url_canon.cc
C++
unknown
416
// Copyright 2013 The Chromium Authors // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #ifndef URL_URL_CANON_H_ #define URL_URL_CANON_H_ #include <stdlib.h> #include <string.h> #include "base/component_export.h" #include "base/export_template.h" #include "base/memory/raw_ptr_exclusion.h" #include "base/numerics/clamped_math.h" #include "url/third_party/mozilla/url_parse.h" namespace url { // Canonicalizer output ------------------------------------------------------- // Base class for the canonicalizer output, this maintains a buffer and // supports simple resizing and append operations on it. // // It is VERY IMPORTANT that no virtual function calls be made on the common // code path. We only have two virtual function calls, the destructor and a // resize function that is called when the existing buffer is not big enough. // The derived class is then in charge of setting up our buffer which we will // manage. template <typename T> class CanonOutputT { public: CanonOutputT() = default; virtual ~CanonOutputT() = default; // Implemented to resize the buffer. This function should update the buffer // pointer to point to the new buffer, and any old data up to |cur_len_| in // the buffer must be copied over. // // The new size |sz| must be larger than buffer_len_. virtual void Resize(size_t sz) = 0; // Accessor for returning a character at a given position. The input offset // must be in the valid range. inline T at(size_t offset) const { return buffer_[offset]; } // Sets the character at the given position. The given position MUST be less // than the length(). inline void set(size_t offset, T ch) { buffer_[offset] = ch; } // Returns the number of characters currently in the buffer. inline size_t length() const { return cur_len_; } // Returns the current capacity of the buffer. The length() is the number of // characters that have been declared to be written, but the capacity() is // the number that can be written without reallocation. If the caller must // write many characters at once, it can make sure there is enough capacity, // write the data, then use set_size() to declare the new length(). size_t capacity() const { return buffer_len_; } // Called by the user of this class to get the output. The output will NOT // be NULL-terminated. Call length() to get the // length. const T* data() const { return buffer_; } T* data() { return buffer_; } // Shortens the URL to the new length. Used for "backing up" when processing // relative paths. This can also be used if an external function writes a lot // of data to the buffer (when using the "Raw" version below) beyond the end, // to declare the new length. // // This MUST NOT be used to expand the size of the buffer beyond capacity(). void set_length(size_t new_len) { cur_len_ = new_len; } // This is the most performance critical function, since it is called for // every character. void push_back(T ch) { // In VC2005, putting this common case first speeds up execution // dramatically because this branch is predicted as taken. if (cur_len_ < buffer_len_) { buffer_[cur_len_] = ch; cur_len_++; return; } // Grow the buffer to hold at least one more item. Hopefully we won't have // to do this very often. if (!Grow(1)) return; // Actually do the insertion. buffer_[cur_len_] = ch; cur_len_++; } // Appends the given string to the output. void Append(const T* str, size_t str_len) { if (str_len > buffer_len_ - cur_len_) { if (!Grow(str_len - (buffer_len_ - cur_len_))) return; } memcpy(buffer_ + cur_len_, str, str_len * sizeof(T)); cur_len_ += str_len; } void ReserveSizeIfNeeded(size_t estimated_size) { // Reserve a bit extra to account for escaped chars. if (estimated_size > buffer_len_) Resize((base::ClampedNumeric<size_t>(estimated_size) + 8).RawValue()); } protected: // Grows the given buffer so that it can fit at least |min_additional| // characters. Returns true if the buffer could be resized, false on OOM. bool Grow(size_t min_additional) { static const size_t kMinBufferLen = 16; size_t new_len = (buffer_len_ == 0) ? kMinBufferLen : buffer_len_; do { if (new_len >= (1 << 30)) // Prevent overflow below. return false; new_len *= 2; } while (new_len < buffer_len_ + min_additional); Resize(new_len); return true; } // `buffer_` is not a raw_ptr<...> for performance reasons (based on analysis // of sampling profiler data). RAW_PTR_EXCLUSION T* buffer_ = nullptr; size_t buffer_len_ = 0; // Used characters in the buffer. size_t cur_len_ = 0; }; // Simple implementation of the CanonOutput using new[]. This class // also supports a static buffer so if it is allocated on the stack, most // URLs can be canonicalized with no heap allocations. template <typename T, int fixed_capacity = 1024> class RawCanonOutputT : public CanonOutputT<T> { public: RawCanonOutputT() : CanonOutputT<T>() { this->buffer_ = fixed_buffer_; this->buffer_len_ = fixed_capacity; } ~RawCanonOutputT() override { if (this->buffer_ != fixed_buffer_) delete[] this->buffer_; } void Resize(size_t sz) override { T* new_buf = new T[sz]; memcpy(new_buf, this->buffer_, sizeof(T) * (this->cur_len_ < sz ? this->cur_len_ : sz)); if (this->buffer_ != fixed_buffer_) delete[] this->buffer_; this->buffer_ = new_buf; this->buffer_len_ = sz; } protected: T fixed_buffer_[fixed_capacity]; }; // Explicitely instantiate commonly used instatiations. extern template class EXPORT_TEMPLATE_DECLARE(COMPONENT_EXPORT(URL)) CanonOutputT<char>; extern template class EXPORT_TEMPLATE_DECLARE(COMPONENT_EXPORT(URL)) CanonOutputT<char16_t>; // Normally, all canonicalization output is in narrow characters. We support // the templates so it can also be used internally if a wide buffer is // required. typedef CanonOutputT<char> CanonOutput; typedef CanonOutputT<char16_t> CanonOutputW; template <int fixed_capacity> class RawCanonOutput : public RawCanonOutputT<char, fixed_capacity> {}; template <int fixed_capacity> class RawCanonOutputW : public RawCanonOutputT<char16_t, fixed_capacity> {}; // Character set converter ---------------------------------------------------- // // Converts query strings into a custom encoding. The embedder can supply an // implementation of this class to interface with their own character set // conversion libraries. // // Embedders will want to see the unit test for the ICU version. class COMPONENT_EXPORT(URL) CharsetConverter { public: CharsetConverter() {} virtual ~CharsetConverter() {} // Converts the given input string from UTF-16 to whatever output format the // converter supports. This is used only for the query encoding conversion, // which does not fail. Instead, the converter should insert "invalid // character" characters in the output for invalid sequences, and do the // best it can. // // If the input contains a character not representable in the output // character set, the converter should append the HTML entity sequence in // decimal, (such as "&#20320;") with escaping of the ampersand, number // sign, and semicolon (in the previous example it would be // "%26%2320320%3B"). This rule is based on what IE does in this situation. virtual void ConvertFromUTF16(const char16_t* input, int input_len, CanonOutput* output) = 0; }; // Schemes -------------------------------------------------------------------- // Types of a scheme representing the requirements on the data represented by // the authority component of a URL with the scheme. enum SchemeType { // The authority component of a URL with the scheme has the form // "username:password@host:port". The username and password entries are // optional; the host may not be empty. The default value of the port can be // omitted in serialization. This type occurs with network schemes like http, // https, and ftp. SCHEME_WITH_HOST_PORT_AND_USER_INFORMATION, // The authority component of a URL with the scheme has the form "host:port", // and does not include username or password. The default value of the port // can be omitted in serialization. Used by inner URLs of filesystem URLs of // origins with network hosts, from which the username and password are // stripped. SCHEME_WITH_HOST_AND_PORT, // The authority component of an URL with the scheme has the form "host", and // does not include port, username, or password. Used when the hosts are not // network addresses; for example, schemes used internally by the browser. SCHEME_WITH_HOST, // A URL with the scheme doesn't have the authority component. SCHEME_WITHOUT_AUTHORITY, }; // Whitespace ----------------------------------------------------------------- // Searches for whitespace that should be removed from the middle of URLs, and // removes it. Removed whitespace are tabs and newlines, but NOT spaces. Spaces // are preserved, which is what most browsers do. A pointer to the output will // be returned, and the length of that output will be in |output_len|. // // This should be called before parsing if whitespace removal is desired (which // it normally is when you are canonicalizing). // // If no whitespace is removed, this function will not use the buffer and will // return a pointer to the input, to avoid the extra copy. If modification is // required, the given |buffer| will be used and the returned pointer will // point to the beginning of the buffer. // // Therefore, callers should not use the buffer, since it may actually be empty, // use the computed pointer and |*output_len| instead. // // If |input| contained both removable whitespace and a raw `<` character, // |potentially_dangling_markup| will be set to `true`. Otherwise, it will be // left untouched. COMPONENT_EXPORT(URL) const char* RemoveURLWhitespace(const char* input, int input_len, CanonOutputT<char>* buffer, int* output_len, bool* potentially_dangling_markup); COMPONENT_EXPORT(URL) const char16_t* RemoveURLWhitespace(const char16_t* input, int input_len, CanonOutputT<char16_t>* buffer, int* output_len, bool* potentially_dangling_markup); // IDN ------------------------------------------------------------------------ // Converts the Unicode input representing a hostname to ASCII using IDN rules. // The output must fall in the ASCII range, but will be encoded in UTF-16. // // On success, the output will be filled with the ASCII host name and it will // return true. Unlike most other canonicalization functions, this assumes that // the output is empty. The beginning of the host will be at offset 0, and // the length of the output will be set to the length of the new host name. // // On error, returns false. The output in this case is undefined. COMPONENT_EXPORT(URL) bool IDNToASCII(const char16_t* src, int src_len, CanonOutputW* output); // Piece-by-piece canonicalizers ---------------------------------------------- // // These individual canonicalizers append the canonicalized versions of the // corresponding URL component to the given CanonOutput. The spec and the // previously-identified range of that component are the input. The range of // the canonicalized component will be written to the output component. // // These functions all append to the output so they can be chained. Make sure // the output is empty when you start. // // These functions returns boolean values indicating success. On failure, they // will attempt to write something reasonable to the output so that, if // displayed to the user, they will recognise it as something that's messed up. // Nothing more should ever be done with these invalid URLs, however. // Scheme: Appends the scheme and colon to the URL. The output component will // indicate the range of characters up to but not including the colon. // // Canonical URLs always have a scheme. If the scheme is not present in the // input, this will just write the colon to indicate an empty scheme. Does not // append slashes which will be needed before any authority components for most // URLs. // // The 8-bit version requires UTF-8 encoding. COMPONENT_EXPORT(URL) bool CanonicalizeScheme(const char* spec, const Component& scheme, CanonOutput* output, Component* out_scheme); COMPONENT_EXPORT(URL) bool CanonicalizeScheme(const char16_t* spec, const Component& scheme, CanonOutput* output, Component* out_scheme); // User info: username/password. If present, this will add the delimiters so // the output will be "<username>:<password>@" or "<username>@". Empty // username/password pairs, or empty passwords, will get converted to // nonexistent in the canonical version. // // The components for the username and password refer to ranges in the // respective source strings. Usually, these will be the same string, which // is legal as long as the two components don't overlap. // // The 8-bit version requires UTF-8 encoding. COMPONENT_EXPORT(URL) bool CanonicalizeUserInfo(const char* username_source, const Component& username, const char* password_source, const Component& password, CanonOutput* output, Component* out_username, Component* out_password); COMPONENT_EXPORT(URL) bool CanonicalizeUserInfo(const char16_t* username_source, const Component& username, const char16_t* password_source, const Component& password, CanonOutput* output, Component* out_username, Component* out_password); // This structure holds detailed state exported from the IP/Host canonicalizers. // Additional fields may be added as callers require them. struct CanonHostInfo { CanonHostInfo() : family(NEUTRAL), num_ipv4_components(0), out_host() {} // Convenience function to test if family is an IP address. bool IsIPAddress() const { return family == IPV4 || family == IPV6; } // This field summarizes how the input was classified by the canonicalizer. enum Family { NEUTRAL, // - Doesn't resemble an IP address. As far as the IP // canonicalizer is concerned, it should be treated as a // hostname. BROKEN, // - Almost an IP, but was not canonicalized. This could be an // IPv4 address where truncation occurred, or something // containing the special characters :[] which did not parse // as an IPv6 address. Never attempt to connect to this // address, because it might actually succeed! IPV4, // - Successfully canonicalized as an IPv4 address. IPV6, // - Successfully canonicalized as an IPv6 address. }; Family family; // If |family| is IPV4, then this is the number of nonempty dot-separated // components in the input text, from 1 to 4. If |family| is not IPV4, // this value is undefined. int num_ipv4_components; // Location of host within the canonicalized output. // CanonicalizeIPAddress() only sets this field if |family| is IPV4 or IPV6. // CanonicalizeHostVerbose() always sets it. Component out_host; // |address| contains the parsed IP Address (if any) in its first // AddressLength() bytes, in network order. If IsIPAddress() is false // AddressLength() will return zero and the content of |address| is undefined. unsigned char address[16]; // Convenience function to calculate the length of an IP address corresponding // to the current IP version in |family|, if any. For use with |address|. int AddressLength() const { return family == IPV4 ? 4 : (family == IPV6 ? 16 : 0); } }; // Host. // // The 8-bit version requires UTF-8 encoding. Use this version when you only // need to know whether canonicalization succeeded. COMPONENT_EXPORT(URL) bool CanonicalizeHost(const char* spec, const Component& host, CanonOutput* output, Component* out_host); COMPONENT_EXPORT(URL) bool CanonicalizeHost(const char16_t* spec, const Component& host, CanonOutput* output, Component* out_host); // Extended version of CanonicalizeHost, which returns additional information. // Use this when you need to know whether the hostname was an IP address. // A successful return is indicated by host_info->family != BROKEN. See the // definition of CanonHostInfo above for details. COMPONENT_EXPORT(URL) void CanonicalizeHostVerbose(const char* spec, const Component& host, CanonOutput* output, CanonHostInfo* host_info); COMPONENT_EXPORT(URL) void CanonicalizeHostVerbose(const char16_t* spec, const Component& host, CanonOutput* output, CanonHostInfo* host_info); // Canonicalizes a string according to the host canonicalization rules. Unlike // CanonicalizeHost, this will not check for IP addresses which can change the // meaning (and canonicalization) of the components. This means it is possible // to call this for sub-components of a host name without corruption. // // As an example, "01.02.03.04.com" is a canonical hostname. If you called // CanonicalizeHost on the substring "01.02.03.04" it will get "fixed" to // "1.2.3.4" which will produce an invalid host name when reassembled. This // can happen more than one might think because all numbers by themselves are // considered IP addresses; so "5" canonicalizes to "0.0.0.5". // // Be careful: Because Punycode works on each dot-separated substring as a // unit, you should only pass this function substrings that represent complete // dot-separated subcomponents of the original host. Even if you have ASCII // input, percent-escaped characters will have different meanings if split in // the middle. // // Returns true if the host was valid. This function will treat a 0-length // host as valid (because it's designed to be used for substrings) while the // full version above will mark empty hosts as broken. COMPONENT_EXPORT(URL) bool CanonicalizeHostSubstring(const char* spec, const Component& host, CanonOutput* output); COMPONENT_EXPORT(URL) bool CanonicalizeHostSubstring(const char16_t* spec, const Component& host, CanonOutput* output); // IP addresses. // // Tries to interpret the given host name as an IPv4 or IPv6 address. If it is // an IP address, it will canonicalize it as such, appending it to |output|. // Additional status information is returned via the |*host_info| parameter. // See the definition of CanonHostInfo above for details. // // This is called AUTOMATICALLY from the host canonicalizer, which ensures that // the input is unescaped and name-prepped, etc. It should not normally be // necessary or wise to call this directly. COMPONENT_EXPORT(URL) void CanonicalizeIPAddress(const char* spec, const Component& host, CanonOutput* output, CanonHostInfo* host_info); COMPONENT_EXPORT(URL) void CanonicalizeIPAddress(const char16_t* spec, const Component& host, CanonOutput* output, CanonHostInfo* host_info); // Port: this function will add the colon for the port if a port is present. // The caller can pass PORT_UNSPECIFIED as the // default_port_for_scheme argument if there is no default port. // // The 8-bit version requires UTF-8 encoding. COMPONENT_EXPORT(URL) bool CanonicalizePort(const char* spec, const Component& port, int default_port_for_scheme, CanonOutput* output, Component* out_port); COMPONENT_EXPORT(URL) bool CanonicalizePort(const char16_t* spec, const Component& port, int default_port_for_scheme, CanonOutput* output, Component* out_port); // Returns the default port for the given canonical scheme, or PORT_UNSPECIFIED // if the scheme is unknown. Based on https://url.spec.whatwg.org/#default-port COMPONENT_EXPORT(URL) int DefaultPortForScheme(const char* scheme, int scheme_len); // Path. If the input does not begin in a slash (including if the input is // empty), we'll prepend a slash to the path to make it canonical. // // The 8-bit version assumes UTF-8 encoding, but does not verify the validity // of the UTF-8 (i.e., you can have invalid UTF-8 sequences, invalid // characters, etc.). Normally, URLs will come in as UTF-16, so this isn't // an issue. Somebody giving us an 8-bit path is responsible for generating // the path that the server expects (we'll escape high-bit characters), so // if something is invalid, it's their problem. COMPONENT_EXPORT(URL) bool CanonicalizePath(const char* spec, const Component& path, CanonOutput* output, Component* out_path); COMPONENT_EXPORT(URL) bool CanonicalizePath(const char16_t* spec, const Component& path, CanonOutput* output, Component* out_path); // Like CanonicalizePath(), but does not assume that its operating on the // entire path. It therefore does not prepend a slash, etc. COMPONENT_EXPORT(URL) bool CanonicalizePartialPath(const char* spec, const Component& path, CanonOutput* output, Component* out_path); COMPONENT_EXPORT(URL) bool CanonicalizePartialPath(const char16_t* spec, const Component& path, CanonOutput* output, Component* out_path); // Canonicalizes the input as a file path. This is like CanonicalizePath except // that it also handles Windows drive specs. For example, the path can begin // with "c|\" and it will get properly canonicalized to "C:/". // The string will be appended to |*output| and |*out_path| will be updated. // // The 8-bit version requires UTF-8 encoding. COMPONENT_EXPORT(URL) bool FileCanonicalizePath(const char* spec, const Component& path, CanonOutput* output, Component* out_path); COMPONENT_EXPORT(URL) bool FileCanonicalizePath(const char16_t* spec, const Component& path, CanonOutput* output, Component* out_path); // Query: Prepends the ? if needed. // // The 8-bit version requires the input to be UTF-8 encoding. Incorrectly // encoded characters (in UTF-8 or UTF-16) will be replaced with the Unicode // "invalid character." This function can not fail, we always just try to do // our best for crazy input here since web pages can set it themselves. // // This will convert the given input into the output encoding that the given // character set converter object provides. The converter will only be called // if necessary, for ASCII input, no conversions are necessary. // // The converter can be NULL. In this case, the output encoding will be UTF-8. COMPONENT_EXPORT(URL) void CanonicalizeQuery(const char* spec, const Component& query, CharsetConverter* converter, CanonOutput* output, Component* out_query); COMPONENT_EXPORT(URL) void CanonicalizeQuery(const char16_t* spec, const Component& query, CharsetConverter* converter, CanonOutput* output, Component* out_query); // Ref: Prepends the # if needed. The output will be UTF-8 (this is the only // canonicalizer that does not produce ASCII output). The output is // guaranteed to be valid UTF-8. // // This function will not fail. If the input is invalid UTF-8/UTF-16, we'll use // the "Unicode replacement character" for the confusing bits and copy the rest. COMPONENT_EXPORT(URL) void CanonicalizeRef(const char* spec, const Component& path, CanonOutput* output, Component* out_path); COMPONENT_EXPORT(URL) void CanonicalizeRef(const char16_t* spec, const Component& path, CanonOutput* output, Component* out_path); // Full canonicalizer --------------------------------------------------------- // // These functions replace any string contents, rather than append as above. // See the above piece-by-piece functions for information specific to // canonicalizing individual components. // // The output will be ASCII except the reference fragment, which may be UTF-8. // // The 8-bit versions require UTF-8 encoding. // Use for standard URLs with authorities and paths. COMPONENT_EXPORT(URL) bool CanonicalizeStandardURL(const char* spec, int spec_len, const Parsed& parsed, SchemeType scheme_type, CharsetConverter* query_converter, CanonOutput* output, Parsed* new_parsed); COMPONENT_EXPORT(URL) bool CanonicalizeStandardURL(const char16_t* spec, int spec_len, const Parsed& parsed, SchemeType scheme_type, CharsetConverter* query_converter, CanonOutput* output, Parsed* new_parsed); // Use for file URLs. COMPONENT_EXPORT(URL) bool CanonicalizeFileURL(const char* spec, int spec_len, const Parsed& parsed, CharsetConverter* query_converter, CanonOutput* output, Parsed* new_parsed); COMPONENT_EXPORT(URL) bool CanonicalizeFileURL(const char16_t* spec, int spec_len, const Parsed& parsed, CharsetConverter* query_converter, CanonOutput* output, Parsed* new_parsed); // Use for filesystem URLs. COMPONENT_EXPORT(URL) bool CanonicalizeFileSystemURL(const char* spec, int spec_len, const Parsed& parsed, CharsetConverter* query_converter, CanonOutput* output, Parsed* new_parsed); COMPONENT_EXPORT(URL) bool CanonicalizeFileSystemURL(const char16_t* spec, int spec_len, const Parsed& parsed, CharsetConverter* query_converter, CanonOutput* output, Parsed* new_parsed); // Use for path URLs such as javascript. This does not modify the path in any // way, for example, by escaping it. COMPONENT_EXPORT(URL) bool CanonicalizePathURL(const char* spec, int spec_len, const Parsed& parsed, CanonOutput* output, Parsed* new_parsed); COMPONENT_EXPORT(URL) bool CanonicalizePathURL(const char16_t* spec, int spec_len, const Parsed& parsed, CanonOutput* output, Parsed* new_parsed); // Use to canonicalize just the path component of a "path" URL; e.g. the // path of a javascript URL. COMPONENT_EXPORT(URL) void CanonicalizePathURLPath(const char* source, const Component& component, CanonOutput* output, Component* new_component); COMPONENT_EXPORT(URL) void CanonicalizePathURLPath(const char16_t* source, const Component& component, CanonOutput* output, Component* new_component); // Use for mailto URLs. This "canonicalizes" the URL into a path and query // component. It does not attempt to merge "to" fields. It uses UTF-8 for // the query encoding if there is a query. This is because a mailto URL is // really intended for an external mail program, and the encoding of a page, // etc. which would influence a query encoding normally are irrelevant. COMPONENT_EXPORT(URL) bool CanonicalizeMailtoURL(const char* spec, int spec_len, const Parsed& parsed, CanonOutput* output, Parsed* new_parsed); COMPONENT_EXPORT(URL) bool CanonicalizeMailtoURL(const char16_t* spec, int spec_len, const Parsed& parsed, CanonOutput* output, Parsed* new_parsed); // Part replacer -------------------------------------------------------------- // Internal structure used for storing separate strings for each component. // The basic canonicalization functions use this structure internally so that // component replacement (different strings for different components) can be // treated on the same code path as regular canonicalization (the same string // for each component). // // A Parsed structure usually goes along with this. Those components identify // offsets within these strings, so that they can all be in the same string, // or spread arbitrarily across different ones. // // This structures does not own any data. It is the caller's responsibility to // ensure that the data the pointers point to stays in scope and is not // modified. template <typename CHAR> struct URLComponentSource { // Constructor normally used by callers wishing to replace components. This // will make them all NULL, which is no replacement. The caller would then // override the components they want to replace. URLComponentSource() : scheme(nullptr), username(nullptr), password(nullptr), host(nullptr), port(nullptr), path(nullptr), query(nullptr), ref(nullptr) {} // Constructor normally used internally to initialize all the components to // point to the same spec. explicit URLComponentSource(const CHAR* default_value) : scheme(default_value), username(default_value), password(default_value), host(default_value), port(default_value), path(default_value), query(default_value), ref(default_value) {} // This field is not a raw_ptr<> because it was filtered by the rewriter for: // #addr-of RAW_PTR_EXCLUSION const CHAR* scheme; // This field is not a raw_ptr<> because it was filtered by the rewriter for: // #addr-of RAW_PTR_EXCLUSION const CHAR* username; // This field is not a raw_ptr<> because it was filtered by the rewriter for: // #addr-of RAW_PTR_EXCLUSION const CHAR* password; // This field is not a raw_ptr<> because it was filtered by the rewriter for: // #addr-of RAW_PTR_EXCLUSION const CHAR* host; // This field is not a raw_ptr<> because it was filtered by the rewriter for: // #addr-of RAW_PTR_EXCLUSION const CHAR* port; // This field is not a raw_ptr<> because it was filtered by the rewriter for: // #addr-of RAW_PTR_EXCLUSION const CHAR* path; // This field is not a raw_ptr<> because it was filtered by the rewriter for: // #addr-of RAW_PTR_EXCLUSION const CHAR* query; // This field is not a raw_ptr<> because it was filtered by the rewriter for: // #addr-of RAW_PTR_EXCLUSION const CHAR* ref; }; // This structure encapsulates information on modifying a URL. Each component // may either be left unchanged, replaced, or deleted. // // By default, each component is unchanged. For those components that should be // modified, call either Set* or Clear* to modify it. // // The string passed to Set* functions DOES NOT GET COPIED AND MUST BE KEPT // IN SCOPE BY THE CALLER for as long as this object exists! // // Prefer the 8-bit replacement version if possible since it is more efficient. template <typename CHAR> class Replacements { public: Replacements() {} // Scheme void SetScheme(const CHAR* s, const Component& comp) { sources_.scheme = s; components_.scheme = comp; } // Note: we don't have a ClearScheme since this doesn't make any sense. bool IsSchemeOverridden() const { return sources_.scheme != NULL; } // Username void SetUsername(const CHAR* s, const Component& comp) { sources_.username = s; components_.username = comp; } void ClearUsername() { sources_.username = Placeholder(); components_.username = Component(); } bool IsUsernameOverridden() const { return sources_.username != NULL; } // Password void SetPassword(const CHAR* s, const Component& comp) { sources_.password = s; components_.password = comp; } void ClearPassword() { sources_.password = Placeholder(); components_.password = Component(); } bool IsPasswordOverridden() const { return sources_.password != NULL; } // Host void SetHost(const CHAR* s, const Component& comp) { sources_.host = s; components_.host = comp; } void ClearHost() { sources_.host = Placeholder(); components_.host = Component(); } bool IsHostOverridden() const { return sources_.host != NULL; } // Port void SetPort(const CHAR* s, const Component& comp) { sources_.port = s; components_.port = comp; } void ClearPort() { sources_.port = Placeholder(); components_.port = Component(); } bool IsPortOverridden() const { return sources_.port != NULL; } // Path void SetPath(const CHAR* s, const Component& comp) { sources_.path = s; components_.path = comp; } void ClearPath() { sources_.path = Placeholder(); components_.path = Component(); } bool IsPathOverridden() const { return sources_.path != NULL; } // Query void SetQuery(const CHAR* s, const Component& comp) { sources_.query = s; components_.query = comp; } void ClearQuery() { sources_.query = Placeholder(); components_.query = Component(); } bool IsQueryOverridden() const { return sources_.query != NULL; } // Ref void SetRef(const CHAR* s, const Component& comp) { sources_.ref = s; components_.ref = comp; } void ClearRef() { sources_.ref = Placeholder(); components_.ref = Component(); } bool IsRefOverridden() const { return sources_.ref != NULL; } // Getters for the internal data. See the variables below for how the // information is encoded. const URLComponentSource<CHAR>& sources() const { return sources_; } const Parsed& components() const { return components_; } private: // Returns a pointer to a static empty string that is used as a placeholder // to indicate a component should be deleted (see below). const CHAR* Placeholder() { static const CHAR empty_cstr = 0; return &empty_cstr; } // We support three states: // // Action | Source Component // -----------------------+-------------------------------------------------- // Don't change component | NULL (unused) // Replace component | (replacement string) (replacement component) // Delete component | (non-NULL) (invalid component: (0,-1)) // // We use a pointer to the empty string for the source when the component // should be deleted. URLComponentSource<CHAR> sources_; Parsed components_; }; // The base must be an 8-bit canonical URL. COMPONENT_EXPORT(URL) bool ReplaceStandardURL(const char* base, const Parsed& base_parsed, const Replacements<char>& replacements, SchemeType scheme_type, CharsetConverter* query_converter, CanonOutput* output, Parsed* new_parsed); COMPONENT_EXPORT(URL) bool ReplaceStandardURL(const char* base, const Parsed& base_parsed, const Replacements<char16_t>& replacements, SchemeType scheme_type, CharsetConverter* query_converter, CanonOutput* output, Parsed* new_parsed); // Filesystem URLs can only have the path, query, or ref replaced. // All other components will be ignored. COMPONENT_EXPORT(URL) bool ReplaceFileSystemURL(const char* base, const Parsed& base_parsed, const Replacements<char>& replacements, CharsetConverter* query_converter, CanonOutput* output, Parsed* new_parsed); COMPONENT_EXPORT(URL) bool ReplaceFileSystemURL(const char* base, const Parsed& base_parsed, const Replacements<char16_t>& replacements, CharsetConverter* query_converter, CanonOutput* output, Parsed* new_parsed); // Replacing some parts of a file URL is not permitted. Everything except // the host, path, query, and ref will be ignored. COMPONENT_EXPORT(URL) bool ReplaceFileURL(const char* base, const Parsed& base_parsed, const Replacements<char>& replacements, CharsetConverter* query_converter, CanonOutput* output, Parsed* new_parsed); COMPONENT_EXPORT(URL) bool ReplaceFileURL(const char* base, const Parsed& base_parsed, const Replacements<char16_t>& replacements, CharsetConverter* query_converter, CanonOutput* output, Parsed* new_parsed); // Path URLs can only have the scheme and path replaced. All other components // will be ignored. COMPONENT_EXPORT(URL) bool ReplacePathURL(const char* base, const Parsed& base_parsed, const Replacements<char>& replacements, CanonOutput* output, Parsed* new_parsed); COMPONENT_EXPORT(URL) bool ReplacePathURL(const char* base, const Parsed& base_parsed, const Replacements<char16_t>& replacements, CanonOutput* output, Parsed* new_parsed); // Mailto URLs can only have the scheme, path, and query replaced. // All other components will be ignored. COMPONENT_EXPORT(URL) bool ReplaceMailtoURL(const char* base, const Parsed& base_parsed, const Replacements<char>& replacements, CanonOutput* output, Parsed* new_parsed); COMPONENT_EXPORT(URL) bool ReplaceMailtoURL(const char* base, const Parsed& base_parsed, const Replacements<char16_t>& replacements, CanonOutput* output, Parsed* new_parsed); // Relative URL --------------------------------------------------------------- // Given an input URL or URL fragment |fragment|, determines if it is a // relative or absolute URL and places the result into |*is_relative|. If it is // relative, the relevant portion of the URL will be placed into // |*relative_component| (there may have been trimmed whitespace, for example). // This value is passed to ResolveRelativeURL. If the input is not relative, // this value is UNDEFINED (it may be changed by the function). // // Returns true on success (we successfully determined the URL is relative or // not). Failure means that the combination of URLs doesn't make any sense. // // The base URL should always be canonical, therefore is ASCII. COMPONENT_EXPORT(URL) bool IsRelativeURL(const char* base, const Parsed& base_parsed, const char* fragment, int fragment_len, bool is_base_hierarchical, bool* is_relative, Component* relative_component); COMPONENT_EXPORT(URL) bool IsRelativeURL(const char* base, const Parsed& base_parsed, const char16_t* fragment, int fragment_len, bool is_base_hierarchical, bool* is_relative, Component* relative_component); // Given a canonical parsed source URL, a URL fragment known to be relative, // and the identified relevant portion of the relative URL (computed by // IsRelativeURL), this produces a new parsed canonical URL in |output| and // |out_parsed|. // // It also requires a flag indicating whether the base URL is a file: URL // which triggers additional logic. // // The base URL should be canonical and have a host (may be empty for file // URLs) and a path. If it doesn't have these, we can't resolve relative // URLs off of it and will return the base as the output with an error flag. // Because it is canonical is should also be ASCII. // // The query charset converter follows the same rules as CanonicalizeQuery. // // Returns true on success. On failure, the output will be "something // reasonable" that will be consistent and valid, just probably not what // was intended by the web page author or caller. COMPONENT_EXPORT(URL) bool ResolveRelativeURL(const char* base_url, const Parsed& base_parsed, bool base_is_file, const char* relative_url, const Component& relative_component, CharsetConverter* query_converter, CanonOutput* output, Parsed* out_parsed); COMPONENT_EXPORT(URL) bool ResolveRelativeURL(const char* base_url, const Parsed& base_parsed, bool base_is_file, const char16_t* relative_url, const Component& relative_component, CharsetConverter* query_converter, CanonOutput* output, Parsed* out_parsed); } // namespace url #endif // URL_URL_CANON_H_
Zhao-PengFei35/chromium_src_4
url/url_canon.h
C++
unknown
43,514
// Copyright 2013 The Chromium Authors // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. // Canonicalizers for random bits that aren't big enough for their own files. #include <string.h> #include "url/url_canon.h" #include "url/url_canon_internal.h" namespace url { namespace { // Returns true if the given character should be removed from the middle of a // URL. inline bool IsRemovableURLWhitespace(int ch) { return ch == '\r' || ch == '\n' || ch == '\t'; } // Backend for RemoveURLWhitespace (see declaration in url_canon.h). // It sucks that we have to do this, since this takes about 13% of the total URL // canonicalization time. template <typename CHAR> const CHAR* DoRemoveURLWhitespace(const CHAR* input, int input_len, CanonOutputT<CHAR>* buffer, int* output_len, bool* potentially_dangling_markup) { // Fast verification that there's nothing that needs removal. This is the 99% // case, so we want it to be fast and don't care about impacting the speed // when we do find whitespace. bool found_whitespace = false; if (sizeof(*input) == 1 && input_len >= kMinimumLengthForSIMD) { // For large strings, memchr is much faster than any scalar code we can // write, even if we need to run it three times. (If this turns out to still // be a bottleneck, we could write our own vector code, but given that // memchr is so fast, it's unlikely to be relevant.) found_whitespace = memchr(input, '\n', input_len) != nullptr || memchr(input, '\r', input_len) != nullptr || memchr(input, '\t', input_len) != nullptr; } else { for (int i = 0; i < input_len; i++) { if (!IsRemovableURLWhitespace(input[i])) continue; found_whitespace = true; break; } } if (!found_whitespace) { // Didn't find any whitespace, we don't need to do anything. We can just // return the input as the output. *output_len = input_len; return input; } // Skip whitespace removal for `data:` URLs. // // TODO(mkwst): Ideally, this would use something like `base::StartsWith`, but // that turns out to be difficult to do correctly given this function's // character type templating. if (input_len > 5 && input[0] == 'd' && input[1] == 'a' && input[2] == 't' && input[3] == 'a' && input[4] == ':') { *output_len = input_len; return input; } // Remove the whitespace into the new buffer and return it. for (int i = 0; i < input_len; i++) { if (!IsRemovableURLWhitespace(input[i])) { if (potentially_dangling_markup && input[i] == 0x3C) *potentially_dangling_markup = true; buffer->push_back(input[i]); } } *output_len = buffer->length(); return buffer->data(); } // Contains the canonical version of each possible input letter in the scheme // (basically, lower-cased). The corresponding entry will be 0 if the letter // is not allowed in a scheme. // clang-format off const char kSchemeCanonical[0x80] = { // 00-1f: all are invalid 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, 0, 0, 0, 0, 0, 0, // ' ' ! " # $ % & ' ( ) * + , - . / 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, '+', 0, '-', '.', 0, // 0 1 2 3 4 5 6 7 8 9 : ; < = > ? '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 0 , 0 , 0 , 0 , 0 , 0 , // @ A B C D E F G H I J K L M N O 0 , 'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', // P Q R S T U V W X Y Z [ \ ] ^ _ 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z', 0, 0 , 0, 0 , 0, // ` a b c d e f g h i j k l m n o 0 , 'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', // p q r s t u v w x y z { | } ~ 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z', 0 , 0 , 0 , 0 , 0 }; // clang-format on // This could be a table lookup as well by setting the high bit for each // valid character, but it's only called once per URL, and it makes the lookup // table easier to read not having extra stuff in it. inline bool IsSchemeFirstChar(unsigned char c) { return (c >= 'a' && c <= 'z') || (c >= 'A' && c <= 'Z'); } template <typename CHAR, typename UCHAR> bool DoScheme(const CHAR* spec, const Component& scheme, CanonOutput* output, Component* out_scheme) { if (scheme.is_empty()) { // Scheme is unspecified or empty, convert to empty by appending a colon. *out_scheme = Component(output->length(), 0); output->push_back(':'); return false; } // The output scheme starts from the current position. out_scheme->begin = output->length(); // Danger: it's important that this code does not strip any characters; // it only emits the canonical version (be it valid or escaped) for each // of the input characters. Stripping would put it out of sync with // FindAndCompareScheme, which could cause some security checks on // schemes to be incorrect. bool success = true; size_t begin = static_cast<size_t>(scheme.begin); size_t end = static_cast<size_t>(scheme.end()); for (size_t i = begin; i < end; i++) { UCHAR ch = static_cast<UCHAR>(spec[i]); char replacement = 0; if (ch < 0x80) { if (i == begin) { // Need to do a special check for the first letter of the scheme. if (IsSchemeFirstChar(static_cast<unsigned char>(ch))) replacement = kSchemeCanonical[ch]; } else { replacement = kSchemeCanonical[ch]; } } if (replacement) { output->push_back(replacement); } else if (ch == '%') { // Canonicalizing the scheme multiple times should lead to the same // result. Since invalid characters will be escaped, we need to preserve // the percent to avoid multiple escaping. The scheme will be invalid. success = false; output->push_back('%'); } else { // Invalid character, store it but mark this scheme as invalid. success = false; // This will escape the output and also handle encoding issues. // Ignore the return value since we already failed. AppendUTF8EscapedChar(spec, &i, end, output); } } // The output scheme ends with the the current position, before appending // the colon. out_scheme->len = output->length() - out_scheme->begin; output->push_back(':'); return success; } // The username and password components reference ranges in the corresponding // *_spec strings. Typically, these specs will be the same (we're // canonicalizing a single source string), but may be different when // replacing components. template <typename CHAR, typename UCHAR> bool DoUserInfo(const CHAR* username_spec, const Component& username, const CHAR* password_spec, const Component& password, CanonOutput* output, Component* out_username, Component* out_password) { if (username.is_empty() && password.is_empty()) { // Common case: no user info. We strip empty username/passwords. *out_username = Component(); *out_password = Component(); return true; } // Write the username. out_username->begin = output->length(); if (username.is_nonempty()) { // This will escape characters not valid for the username. AppendStringOfType(&username_spec[username.begin], static_cast<size_t>(username.len), CHAR_USERINFO, output); } out_username->len = output->length() - out_username->begin; // When there is a password, we need the separator. Note that we strip // empty but specified passwords. if (password.is_nonempty()) { output->push_back(':'); out_password->begin = output->length(); AppendStringOfType(&password_spec[password.begin], static_cast<size_t>(password.len), CHAR_USERINFO, output); out_password->len = output->length() - out_password->begin; } else { *out_password = Component(); } output->push_back('@'); return true; } // Helper functions for converting port integers to strings. inline void WritePortInt(char* output, int output_len, int port) { _itoa_s(port, output, output_len, 10); } // This function will prepend the colon if there will be a port. template <typename CHAR, typename UCHAR> bool DoPort(const CHAR* spec, const Component& port, int default_port_for_scheme, CanonOutput* output, Component* out_port) { int port_num = ParsePort(spec, port); if (port_num == PORT_UNSPECIFIED || port_num == default_port_for_scheme) { *out_port = Component(); return true; // Leave port empty. } if (port_num == PORT_INVALID) { // Invalid port: We'll copy the text from the input so the user can see // what the error was, and mark the URL as invalid by returning false. output->push_back(':'); out_port->begin = output->length(); AppendInvalidNarrowString(spec, static_cast<size_t>(port.begin), static_cast<size_t>(port.end()), output); out_port->len = output->length() - out_port->begin; return false; } // Convert port number back to an integer. Max port value is 5 digits, and // the Parsed::ExtractPort will have made sure the integer is in range. const int buf_size = 6; char buf[buf_size]; WritePortInt(buf, buf_size, port_num); // Append the port number to the output, preceded by a colon. output->push_back(':'); out_port->begin = output->length(); for (int i = 0; i < buf_size && buf[i]; i++) output->push_back(buf[i]); out_port->len = output->length() - out_port->begin; return true; } // clang-format off // Percent-escape all characters from the fragment percent-encode set // https://url.spec.whatwg.org/#fragment-percent-encode-set const bool kShouldEscapeCharInFragment[0x80] = { // Control characters (0x00-0x1F) true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, // ' ' ! " # $ % & ' true, false, true, false, false, false, false, false, // ( ) * + , - . / false, false, false, false, false, false, false, false, // 0 1 2 3 4 5 6 7 false, false, false, false, false, false, false, false, // 8 9 : ; < = > ? false, false, false, false, true, false, true, false, // @ A B C D E F G false, false, false, false, false, false, false, false, // H I J K L M N O false, false, false, false, false, false, false, false, // P Q R S T U V W false, false, false, false, false, false, false, false, // X Y Z [ \ ] ^ _ false, false, false, false, false, false, false, false, // ` a b c d e f g true, false, false, false, false, false, false, false, // h i j k l m n o false, false, false, false, false, false, false, false, // p q r s t u v w false, false, false, false, false, false, false, false, // x y z { | } ~ DELETE false, false, false, false, false, false, false, true }; // clang-format on template <typename CHAR, typename UCHAR> void DoCanonicalizeRef(const CHAR* spec, const Component& ref, CanonOutput* output, Component* out_ref) { if (!ref.is_valid()) { // Common case of no ref. *out_ref = Component(); return; } // Append the ref separator. Note that we need to do this even when the ref // is empty but present. output->push_back('#'); out_ref->begin = output->length(); // Now iterate through all the characters, converting to UTF-8 and validating. size_t end = static_cast<size_t>(ref.end()); for (size_t i = static_cast<size_t>(ref.begin); i < end; i++) { UCHAR current_char = static_cast<UCHAR>(spec[i]); if (current_char < 0x80) { if (kShouldEscapeCharInFragment[current_char]) AppendEscapedChar(static_cast<unsigned char>(spec[i]), output); else output->push_back(static_cast<char>(spec[i])); } else { AppendUTF8EscapedChar(spec, &i, end, output); } } out_ref->len = output->length() - out_ref->begin; } } // namespace const char* RemoveURLWhitespace(const char* input, int input_len, CanonOutputT<char>* buffer, int* output_len, bool* potentially_dangling_markup) { return DoRemoveURLWhitespace(input, input_len, buffer, output_len, potentially_dangling_markup); } const char16_t* RemoveURLWhitespace(const char16_t* input, int input_len, CanonOutputT<char16_t>* buffer, int* output_len, bool* potentially_dangling_markup) { return DoRemoveURLWhitespace(input, input_len, buffer, output_len, potentially_dangling_markup); } char CanonicalSchemeChar(char16_t ch) { if (ch >= 0x80) return 0; // Non-ASCII is not supported by schemes. return kSchemeCanonical[ch]; } bool CanonicalizeScheme(const char* spec, const Component& scheme, CanonOutput* output, Component* out_scheme) { return DoScheme<char, unsigned char>(spec, scheme, output, out_scheme); } bool CanonicalizeScheme(const char16_t* spec, const Component& scheme, CanonOutput* output, Component* out_scheme) { return DoScheme<char16_t, char16_t>(spec, scheme, output, out_scheme); } bool CanonicalizeUserInfo(const char* username_source, const Component& username, const char* password_source, const Component& password, CanonOutput* output, Component* out_username, Component* out_password) { return DoUserInfo<char, unsigned char>(username_source, username, password_source, password, output, out_username, out_password); } bool CanonicalizeUserInfo(const char16_t* username_source, const Component& username, const char16_t* password_source, const Component& password, CanonOutput* output, Component* out_username, Component* out_password) { return DoUserInfo<char16_t, char16_t>(username_source, username, password_source, password, output, out_username, out_password); } bool CanonicalizePort(const char* spec, const Component& port, int default_port_for_scheme, CanonOutput* output, Component* out_port) { return DoPort<char, unsigned char>(spec, port, default_port_for_scheme, output, out_port); } bool CanonicalizePort(const char16_t* spec, const Component& port, int default_port_for_scheme, CanonOutput* output, Component* out_port) { return DoPort<char16_t, char16_t>(spec, port, default_port_for_scheme, output, out_port); } void CanonicalizeRef(const char* spec, const Component& ref, CanonOutput* output, Component* out_ref) { DoCanonicalizeRef<char, unsigned char>(spec, ref, output, out_ref); } void CanonicalizeRef(const char16_t* spec, const Component& ref, CanonOutput* output, Component* out_ref) { DoCanonicalizeRef<char16_t, char16_t>(spec, ref, output, out_ref); } } // namespace url
Zhao-PengFei35/chromium_src_4
url/url_canon_etc.cc
C++
unknown
17,142
// Copyright 2013 The Chromium Authors // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. // Functions for canonicalizing "filesystem:file:" URLs. #include "url/url_canon.h" #include "url/url_canon_internal.h" #include "url/url_file.h" #include "url/url_parse_internal.h" #include "url/url_util.h" #include "url/url_util_internal.h" namespace url { namespace { // We use the URLComponentSource for the outer URL, as it can have replacements, // whereas the inner_url can't, so it uses spec. template<typename CHAR, typename UCHAR> bool DoCanonicalizeFileSystemURL(const CHAR* spec, const URLComponentSource<CHAR>& source, const Parsed& parsed, CharsetConverter* charset_converter, CanonOutput* output, Parsed* new_parsed) { // filesystem only uses {scheme, path, query, ref} -- clear the rest. new_parsed->username.reset(); new_parsed->password.reset(); new_parsed->host.reset(); new_parsed->port.reset(); const Parsed* inner_parsed = parsed.inner_parsed(); Parsed new_inner_parsed; // Scheme (known, so we don't bother running it through the more // complicated scheme canonicalizer). new_parsed->scheme.begin = output->length(); output->Append("filesystem:", 11); new_parsed->scheme.len = 10; if (!inner_parsed || !inner_parsed->scheme.is_valid()) return false; bool success = true; SchemeType inner_scheme_type = SCHEME_WITH_HOST_PORT_AND_USER_INFORMATION; if (CompareSchemeComponent(spec, inner_parsed->scheme, url::kFileScheme)) { new_inner_parsed.scheme.begin = output->length(); output->Append("file://", 7); new_inner_parsed.scheme.len = 4; success &= CanonicalizePath(spec, inner_parsed->path, output, &new_inner_parsed.path); } else if (GetStandardSchemeType(spec, inner_parsed->scheme, &inner_scheme_type)) { if (inner_scheme_type == SCHEME_WITH_HOST_PORT_AND_USER_INFORMATION) { // Strip out the user information from the inner URL, if any. inner_scheme_type = SCHEME_WITH_HOST_AND_PORT; } success = CanonicalizeStandardURL( spec, inner_parsed->Length(), *inner_parsed, inner_scheme_type, charset_converter, output, &new_inner_parsed); } else { // TODO(ericu): The URL is wrong, but should we try to output more of what // we were given? Echoing back filesystem:mailto etc. doesn't seem all that // useful. return false; } // The filesystem type must be more than just a leading slash for validity. success &= new_inner_parsed.path.len > 1; success &= CanonicalizePath(source.path, parsed.path, output, &new_parsed->path); // Ignore failures for query/ref since the URL can probably still be loaded. CanonicalizeQuery(source.query, parsed.query, charset_converter, output, &new_parsed->query); CanonicalizeRef(source.ref, parsed.ref, output, &new_parsed->ref); if (success) new_parsed->set_inner_parsed(new_inner_parsed); return success; } } // namespace bool CanonicalizeFileSystemURL(const char* spec, int spec_len, const Parsed& parsed, CharsetConverter* charset_converter, CanonOutput* output, Parsed* new_parsed) { return DoCanonicalizeFileSystemURL<char, unsigned char>( spec, URLComponentSource<char>(spec), parsed, charset_converter, output, new_parsed); } bool CanonicalizeFileSystemURL(const char16_t* spec, int spec_len, const Parsed& parsed, CharsetConverter* charset_converter, CanonOutput* output, Parsed* new_parsed) { return DoCanonicalizeFileSystemURL<char16_t, char16_t>( spec, URLComponentSource<char16_t>(spec), parsed, charset_converter, output, new_parsed); } bool ReplaceFileSystemURL(const char* base, const Parsed& base_parsed, const Replacements<char>& replacements, CharsetConverter* charset_converter, CanonOutput* output, Parsed* new_parsed) { URLComponentSource<char> source(base); Parsed parsed(base_parsed); SetupOverrideComponents(base, replacements, &source, &parsed); return DoCanonicalizeFileSystemURL<char, unsigned char>( base, source, parsed, charset_converter, output, new_parsed); } bool ReplaceFileSystemURL(const char* base, const Parsed& base_parsed, const Replacements<char16_t>& replacements, CharsetConverter* charset_converter, CanonOutput* output, Parsed* new_parsed) { RawCanonOutput<1024> utf8; URLComponentSource<char> source(base); Parsed parsed(base_parsed); SetupUTF16OverrideComponents(base, replacements, &utf8, &source, &parsed); return DoCanonicalizeFileSystemURL<char, unsigned char>( base, source, parsed, charset_converter, output, new_parsed); } } // namespace url
Zhao-PengFei35/chromium_src_4
url/url_canon_filesystemurl.cc
C++
unknown
5,458
// Copyright 2013 The Chromium Authors // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. // Functions for canonicalizing "file:" URLs. #include "base/strings/string_piece.h" #include "base/strings/string_util.h" #include "url/url_canon.h" #include "url/url_canon_internal.h" #include "url/url_file.h" #include "url/url_parse_internal.h" namespace url { namespace { bool IsLocalhost(const char* spec, int begin, int end) { if (begin > end) return false; return base::StringPiece(&spec[begin], end - begin) == "localhost"; } bool IsLocalhost(const char16_t* spec, int begin, int end) { if (begin > end) return false; return base::StringPiece16(&spec[begin], end - begin) == u"localhost"; } template <typename CHAR> int DoFindWindowsDriveLetter(const CHAR* spec, int begin, int end) { if (begin > end) return -1; // First guess the beginning of the drive letter. // If there is something that looks like a drive letter in the spec between // begin and end, store its position in drive_letter_pos. int drive_letter_pos = DoesContainWindowsDriveSpecUntil(spec, begin, end, end); if (drive_letter_pos < begin) return -1; // Check if the path up to the drive letter candidate can be canonicalized as // "/". Component sub_path = MakeRange(begin, drive_letter_pos); RawCanonOutput<1024> output; Component output_path; bool success = CanonicalizePath(spec, sub_path, &output, &output_path); if (!success || output_path.len != 1 || output.at(output_path.begin) != '/') { return -1; } return drive_letter_pos; } #ifdef WIN32 // Given a pointer into the spec, this copies and canonicalizes the drive // letter and colon to the output, if one is found. If there is not a drive // spec, it won't do anything. The index of the next character in the input // spec is returned (after the colon when a drive spec is found, the begin // offset if one is not). template <typename CHAR> int FileDoDriveSpec(const CHAR* spec, int begin, int end, CanonOutput* output) { int drive_letter_pos = FindWindowsDriveLetter(spec, begin, end); if (drive_letter_pos < begin) return begin; // By now, a valid drive letter is confirmed at position drive_letter_pos, // followed by a valid drive letter separator (a colon or a pipe). output->push_back('/'); // Normalize Windows drive letters to uppercase. if (base::IsAsciiLower(spec[drive_letter_pos])) output->push_back(static_cast<char>(spec[drive_letter_pos] - 'a' + 'A')); else output->push_back(static_cast<char>(spec[drive_letter_pos])); // Normalize the character following it to a colon rather than pipe. output->push_back(':'); return drive_letter_pos + 2; } #endif // WIN32 template<typename CHAR, typename UCHAR> bool DoFileCanonicalizePath(const CHAR* spec, const Component& path, CanonOutput* output, Component* out_path) { // Copies and normalizes the "c:" at the beginning, if present. out_path->begin = output->length(); int after_drive; #ifdef WIN32 after_drive = FileDoDriveSpec(spec, path.begin, path.end(), output); #else after_drive = path.begin; #endif // Copies the rest of the path, starting from the slash following the // drive colon (if any, Windows only), or the first slash of the path. bool success = true; if (after_drive < path.end()) { // Use the regular path canonicalizer to canonicalize the rest of the path // after the drive. // // Give it a fake output component to write into, since we will be // calculating the out_path ourselves (consisting of both the drive and the // path we canonicalize here). Component sub_path = MakeRange(after_drive, path.end()); Component fake_output_path; success = CanonicalizePath(spec, sub_path, output, &fake_output_path); } else if (after_drive == path.begin) { // No input path and no drive spec, canonicalize to a slash. output->push_back('/'); } out_path->len = output->length() - out_path->begin; return success; } template<typename CHAR, typename UCHAR> bool DoCanonicalizeFileURL(const URLComponentSource<CHAR>& source, const Parsed& parsed, CharsetConverter* query_converter, CanonOutput* output, Parsed* new_parsed) { // Things we don't set in file: URLs. new_parsed->username = Component(); new_parsed->password = Component(); new_parsed->port = Component(); // Scheme (known, so we don't bother running it through the more // complicated scheme canonicalizer). new_parsed->scheme.begin = output->length(); output->Append("file://", 7); new_parsed->scheme.len = 4; // If the host is localhost, and the path starts with a Windows drive letter, // remove the host component. This does the following transformation: // file://localhost/C:/hello.txt -> file:///C:/hello.txt // // Note: we do this on every platform per URL Standard, not just Windows. // // TODO(https://crbug.com/688961): According to the latest URL spec, this // transformation should be done regardless of the path. Component host_range = parsed.host; if (IsLocalhost(source.host, host_range.begin, host_range.end()) && FindWindowsDriveLetter(source.path, parsed.path.begin, parsed.path.end()) >= parsed.path.begin) { host_range.reset(); } // Append the host. For many file URLs, this will be empty. For UNC, this // will be present. // TODO(brettw) This doesn't do any checking for host name validity. We // should probably handle validity checking of UNC hosts differently than // for regular IP hosts. bool success = CanonicalizeHost(source.host, host_range, output, &new_parsed->host); success &= DoFileCanonicalizePath<CHAR, UCHAR>(source.path, parsed.path, output, &new_parsed->path); CanonicalizeQuery(source.query, parsed.query, query_converter, output, &new_parsed->query); CanonicalizeRef(source.ref, parsed.ref, output, &new_parsed->ref); return success; } } // namespace int FindWindowsDriveLetter(const char* spec, int begin, int end) { return DoFindWindowsDriveLetter(spec, begin, end); } int FindWindowsDriveLetter(const char16_t* spec, int begin, int end) { return DoFindWindowsDriveLetter(spec, begin, end); } bool CanonicalizeFileURL(const char* spec, int spec_len, const Parsed& parsed, CharsetConverter* query_converter, CanonOutput* output, Parsed* new_parsed) { return DoCanonicalizeFileURL<char, unsigned char>( URLComponentSource<char>(spec), parsed, query_converter, output, new_parsed); } bool CanonicalizeFileURL(const char16_t* spec, int spec_len, const Parsed& parsed, CharsetConverter* query_converter, CanonOutput* output, Parsed* new_parsed) { return DoCanonicalizeFileURL<char16_t, char16_t>( URLComponentSource<char16_t>(spec), parsed, query_converter, output, new_parsed); } bool FileCanonicalizePath(const char* spec, const Component& path, CanonOutput* output, Component* out_path) { return DoFileCanonicalizePath<char, unsigned char>(spec, path, output, out_path); } bool FileCanonicalizePath(const char16_t* spec, const Component& path, CanonOutput* output, Component* out_path) { return DoFileCanonicalizePath<char16_t, char16_t>(spec, path, output, out_path); } bool ReplaceFileURL(const char* base, const Parsed& base_parsed, const Replacements<char>& replacements, CharsetConverter* query_converter, CanonOutput* output, Parsed* new_parsed) { URLComponentSource<char> source(base); Parsed parsed(base_parsed); SetupOverrideComponents(base, replacements, &source, &parsed); return DoCanonicalizeFileURL<char, unsigned char>( source, parsed, query_converter, output, new_parsed); } bool ReplaceFileURL(const char* base, const Parsed& base_parsed, const Replacements<char16_t>& replacements, CharsetConverter* query_converter, CanonOutput* output, Parsed* new_parsed) { RawCanonOutput<1024> utf8; URLComponentSource<char> source(base); Parsed parsed(base_parsed); SetupUTF16OverrideComponents(base, replacements, &utf8, &source, &parsed); return DoCanonicalizeFileURL<char, unsigned char>( source, parsed, query_converter, output, new_parsed); } } // namespace url
Zhao-PengFei35/chromium_src_4
url/url_canon_fileurl.cc
C++
unknown
9,164
// Copyright 2013 The Chromium Authors // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "base/check.h" #include "base/cpu_reduction_experiment.h" #include "url/url_canon.h" #include "url/url_canon_internal.h" namespace url { namespace { // For reference, here's what IE supports: // Key: 0 (disallowed: failure if present in the input) // + (allowed either escaped or unescaped, and unmodified) // U (allowed escaped or unescaped but always unescaped if present in // escaped form) // E (allowed escaped or unescaped but always escaped if present in // unescaped form) // % (only allowed escaped in the input, will be unmodified). // I left blank alpha numeric characters. // // 00 01 02 03 04 05 06 07 08 09 0a 0b 0c 0d 0e 0f // ----------------------------------------------- // 0 0 E E E E E E E E E E E E E E E // 1 E E E E E E E E E E E E E E E E // 2 E + E E + E + + + + + + + U U 0 // 3 % % E + E 0 <-- Those are : ; < = > ? // 4 % // 5 U 0 U U U <-- Those are [ \ ] ^ _ // 6 E <-- That's ` // 7 E E E U E <-- Those are { | } ~ (UNPRINTABLE) // // NOTE: I didn't actually test all the control characters. Some may be // disallowed in the input, but they are all accepted escaped except for 0. // I also didn't test if characters affecting HTML parsing are allowed // unescaped, e.g. (") or (#), which would indicate the beginning of the path. // Surprisingly, space is accepted in the input and always escaped. // This table lists the canonical version of all characters we allow in the // input, with 0 indicating it is disallowed. We use the magic kEscapedHostChar // value to indicate that this character should be escaped. We are a little more // restrictive than IE, but less restrictive than Firefox. // // Note that we disallow the % character. We will allow it when part of an // escape sequence, of course, but this disallows "%25". Even though IE allows // it, allowing it would put us in a funny state. If there was an invalid // escape sequence like "%zz", we'll add "%25zz" to the output and fail. // Allowing percents means we'll succeed a second time, so validity would change // based on how many times you run the canonicalizer. We prefer to always report // the same vailidity, so reject this. const unsigned char kEsc = 0xff; const unsigned char kHostCharLookup[0x80] = { // 00-1f: all are invalid 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, 0, 0, 0, 0, 0, 0, // ' ' ! " # $ % & ' ( ) * + , - . / kEsc,kEsc,kEsc,kEsc,kEsc, 0, kEsc,kEsc,kEsc,kEsc,kEsc, '+',kEsc, '-', '.', 0, // 0 1 2 3 4 5 6 7 8 9 : ; < = > ? '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', ':', 0 ,kEsc,kEsc,kEsc, 0 , // @ A B C D E F G H I J K L M N O kEsc, 'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', // P Q R S T U V W X Y Z [ \ ] ^ _ 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z', '[', 0 , ']', 0 , '_', // ` a b c d e f g h i j k l m n o kEsc, 'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', // p q r s t u v w x y z { | } ~ 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z',kEsc,kEsc,kEsc, 0 , 0 }; // RFC1034 maximum FQDN length. constexpr size_t kMaxHostLength = 253; // Generous padding to account for the fact that UTS#46 normalization can cause // a long string to actually shrink and fit within the 253 character RFC1034 // FQDN length limit. Note that this can still be too short for pathological // cases: An arbitrary number of characters (e.g. U+00AD SOFT HYPHEN) can be // removed from the input by UTS#46 processing. However, this should be // sufficient for all normally-encountered, non-abusive hostname strings. constexpr size_t kMaxHostBufferLength = kMaxHostLength * 5; constexpr size_t kTempHostBufferLen = 1024; using StackBuffer = RawCanonOutputT<char, kTempHostBufferLen>; using StackBufferW = RawCanonOutputT<char16_t, kTempHostBufferLen>; // Scans a host name and fills in the output flags according to what we find. // |has_non_ascii| will be true if there are any non-7-bit characters, and // |has_escaped| will be true if there is a percent sign. template<typename CHAR, typename UCHAR> void ScanHostname(const CHAR* spec, const Component& host, bool* has_non_ascii, bool* has_escaped) { int end = host.end(); *has_non_ascii = false; *has_escaped = false; for (int i = host.begin; i < end; i++) { if (static_cast<UCHAR>(spec[i]) >= 0x80) *has_non_ascii = true; else if (spec[i] == '%') *has_escaped = true; } } // Canonicalizes a host name that is entirely 8-bit characters (even though // the type holding them may be 16 bits. Escaped characters will be unescaped. // Non-7-bit characters (for example, UTF-8) will be passed unchanged. // // The |*has_non_ascii| flag will be true if there are non-7-bit characters in // the output. // // This function is used in two situations: // // * When the caller knows there is no non-ASCII or percent escaped // characters. This is what DoHost does. The result will be a completely // canonicalized host since we know nothing weird can happen (escaped // characters could be unescaped to non-7-bit, so they have to be treated // with suspicion at this point). It does not use the |has_non_ascii| flag. // // * When the caller has an 8-bit string that may need unescaping. // DoComplexHost calls us this situation to do unescaping and validation. // After this, it may do other IDN operations depending on the value of the // |*has_non_ascii| flag. // // The return value indicates if the output is a potentially valid host name. template <typename INCHAR, typename OUTCHAR> bool DoSimpleHost(const INCHAR* host, size_t host_len, CanonOutputT<OUTCHAR>* output, bool* has_non_ascii) { *has_non_ascii = false; bool success = true; for (size_t i = 0; i < host_len; ++i) { unsigned int source = host[i]; if (source == '%') { // Unescape first, if possible. // Source will be used only if decode operation was successful. if (!DecodeEscaped(host, &i, host_len, reinterpret_cast<unsigned char*>(&source))) { // Invalid escaped character. There is nothing that can make this // host valid. We append an escaped percent so the URL looks reasonable // and mark as failed. AppendEscapedChar('%', output); success = false; continue; } } if (source < 0x80) { // We have ASCII input, we can use our lookup table. unsigned char replacement = kHostCharLookup[source]; if (!replacement) { // Invalid character, add it as percent-escaped and mark as failed. AppendEscapedChar(source, output); success = false; } else if (replacement == kEsc) { // This character is valid but should be escaped. AppendEscapedChar(source, output); } else { // Common case, the given character is valid in a hostname, the lookup // table tells us the canonical representation of that character (lower // cased). output->push_back(replacement); } } else { // It's a non-ascii char. Just push it to the output. // In case where we have char16 input, and char output it's safe to // cast char16->char only if input string was converted to ASCII. output->push_back(static_cast<OUTCHAR>(source)); *has_non_ascii = true; } } return success; } // Canonicalizes a host that requires IDN conversion. Returns true on success bool DoIDNHost(const char16_t* src, size_t src_len, CanonOutput* output) { int original_output_len = output->length(); // So we can rewind below. // We need to escape URL before doing IDN conversion, since punicode strings // cannot be escaped after they are created. RawCanonOutputW<kTempHostBufferLen> url_escaped_host; bool has_non_ascii; DoSimpleHost(src, src_len, &url_escaped_host, &has_non_ascii); if (url_escaped_host.length() > kMaxHostBufferLength) { AppendInvalidNarrowString(src, 0, src_len, output); return false; } StackBufferW wide_output; if (!IDNToASCII(url_escaped_host.data(), url_escaped_host.length(), &wide_output)) { // Some error, give up. This will write some reasonable looking // representation of the string to the output. AppendInvalidNarrowString(src, 0, src_len, output); return false; } // Now we check the ASCII output like a normal host. It will also handle // unescaping. Although we unescaped everything before this function call, if // somebody does %00 as fullwidth, ICU will convert this to ASCII. bool success = DoSimpleHost(wide_output.data(), wide_output.length(), output, &has_non_ascii); if (has_non_ascii) { // ICU generated something that DoSimpleHost didn't think looked like // ASCII. This is quite rare, but ICU might convert some characters to // percent signs which might generate new escape sequences which might in // turn be invalid. An example is U+FE6A "small percent" which ICU will // name prep into an ASCII percent and then we can interpret the following // characters as escaped characters. // // If DoSimpleHost didn't think the output was ASCII, just escape the // thing we gave ICU and give up. DoSimpleHost will have handled a further // level of escaping from ICU for simple ASCII cases (i.e. if ICU generates // a new escaped ASCII sequence like "%41" we'll unescape it) but it won't // do more (like handle escaped non-ASCII sequences). Handling the escaped // ASCII isn't strictly necessary, but DoSimpleHost handles this case // anyway so we handle it/ output->set_length(original_output_len); AppendInvalidNarrowString(wide_output.data(), 0, wide_output.length(), output); return false; } return success; } // 8-bit convert host to its ASCII version: this converts the UTF-8 input to // UTF-16. The has_escaped flag should be set if the input string requires // unescaping. bool DoComplexHost(const char* host, size_t host_len, bool has_non_ascii, bool has_escaped, CanonOutput* output) { // Save the current position in the output. We may write stuff and rewind it // below, so we need to know where to rewind to. size_t begin_length = output->length(); // Points to the UTF-8 data we want to convert. This will either be the // input or the unescaped version written to |*output| if necessary. const char* utf8_source; size_t utf8_source_len; bool are_all_escaped_valid = true; if (has_escaped) { // Unescape before converting to UTF-16 for IDN. We write this into the // output because it most likely does not require IDNization, and we can // save another huge stack buffer. It will be replaced below if it requires // IDN. This will also update our non-ASCII flag so we know whether the // unescaped input requires IDN. if (!DoSimpleHost(host, host_len, output, &has_non_ascii)) { // Error with some escape sequence. We'll call the current output // complete. DoSimpleHost will have written some "reasonable" output // for the invalid escapes, but the output could be non-ASCII and // needs to go through re-encoding below. are_all_escaped_valid = false; } // Unescaping may have left us with ASCII input, in which case the // unescaped version we wrote to output is complete. if (!has_non_ascii) { return are_all_escaped_valid; } // Save the pointer into the data was just converted (it may be appended to // other data in the output buffer). utf8_source = &output->data()[begin_length]; utf8_source_len = output->length() - begin_length; } else { // We don't need to unescape, use input for IDNization later. (We know the // input has non-ASCII, or the simple version would have been called // instead of us.) utf8_source = host; utf8_source_len = host_len; } // Non-ASCII input requires IDN, convert to UTF-16 and do the IDN conversion. // Above, we may have used the output to write the unescaped values to, so // we have to rewind it to where we started after we convert it to UTF-16. StackBufferW utf16; if (!ConvertUTF8ToUTF16(utf8_source, utf8_source_len, &utf16)) { // In this error case, the input may or may not be the output. StackBuffer utf8; for (size_t i = 0; i < utf8_source_len; i++) utf8.push_back(utf8_source[i]); output->set_length(begin_length); AppendInvalidNarrowString(utf8.data(), 0, utf8.length(), output); return false; } output->set_length(begin_length); // This will call DoSimpleHost which will do normal ASCII canonicalization // and also check for IP addresses in the outpt. return DoIDNHost(utf16.data(), utf16.length(), output) && are_all_escaped_valid; } // UTF-16 convert host to its ASCII version. The set up is already ready for // the backend, so we just pass through. The has_escaped flag should be set if // the input string requires unescaping. bool DoComplexHost(const char16_t* host, size_t host_len, bool has_non_ascii, bool has_escaped, CanonOutput* output) { if (has_escaped) { // Yikes, we have escaped characters with wide input. The escaped // characters should be interpreted as UTF-8. To solve this problem, // we convert to UTF-8, unescape, then convert back to UTF-16 for IDN. // // We don't bother to optimize the conversion in the ASCII case (which // *could* just be a copy) and use the UTF-8 path, because it should be // very rare that host names have escaped characters, and it is relatively // fast to do the conversion anyway. StackBuffer utf8; if (!ConvertUTF16ToUTF8(host, host_len, &utf8)) { AppendInvalidNarrowString(host, 0, host_len, output); return false; } // Once we convert to UTF-8, we can use the 8-bit version of the complex // host handling code above. return DoComplexHost(utf8.data(), utf8.length(), has_non_ascii, has_escaped, output); } // No unescaping necessary, we can safely pass the input to ICU. This // function will only get called if we either have escaped or non-ascii // input, so it's safe to just use ICU now. Even if the input is ASCII, // this function will do the right thing (just slower than we could). return DoIDNHost(host, host_len, output); } template <typename CHAR, typename UCHAR> bool DoHostSubstring(const CHAR* spec, const Component& host, CanonOutput* output) { DCHECK(host.is_valid()); bool has_non_ascii, has_escaped; ScanHostname<CHAR, UCHAR>(spec, host, &has_non_ascii, &has_escaped); if (has_non_ascii || has_escaped) { return DoComplexHost(&spec[host.begin], static_cast<size_t>(host.len), has_non_ascii, has_escaped, output); } const bool success = DoSimpleHost( &spec[host.begin], static_cast<size_t>(host.len), output, &has_non_ascii); DCHECK(!has_non_ascii); return success; } template <typename CHAR, typename UCHAR> void DoHost(const CHAR* spec, const Component& host, CanonOutput* output, CanonHostInfo* host_info) { if (host.is_empty()) { // Empty hosts don't need anything. host_info->family = CanonHostInfo::NEUTRAL; host_info->out_host = Component(); return; } // Keep track of output's initial length, so we can rewind later. const int output_begin = output->length(); if (DoHostSubstring<CHAR, UCHAR>(spec, host, output)) { // After all the other canonicalization, check if we ended up with an IP // address. IP addresses are small, so writing into this temporary buffer // should not cause an allocation. RawCanonOutput<64> canon_ip; CanonicalizeIPAddress(output->data(), MakeRange(output_begin, output->length()), &canon_ip, host_info); // If we got an IPv4/IPv6 address, copy the canonical form back to the // real buffer. Otherwise, it's a hostname or broken IP, in which case // we just leave it in place. if (host_info->IsIPAddress()) { output->set_length(output_begin); output->Append(canon_ip.data(), canon_ip.length()); } } else { // Canonicalization failed. Set BROKEN to notify the caller. host_info->family = CanonHostInfo::BROKEN; } host_info->out_host = MakeRange(output_begin, output->length()); } } // namespace bool CanonicalizeHost(const char* spec, const Component& host, CanonOutput* output, Component* out_host) { CanonHostInfo host_info; DoHost<char, unsigned char>(spec, host, output, &host_info); *out_host = host_info.out_host; return (host_info.family != CanonHostInfo::BROKEN); } bool CanonicalizeHost(const char16_t* spec, const Component& host, CanonOutput* output, Component* out_host) { CanonHostInfo host_info; DoHost<char16_t, char16_t>(spec, host, output, &host_info); *out_host = host_info.out_host; return (host_info.family != CanonHostInfo::BROKEN); } void CanonicalizeHostVerbose(const char* spec, const Component& host, CanonOutput* output, CanonHostInfo* host_info) { DoHost<char, unsigned char>(spec, host, output, host_info); } void CanonicalizeHostVerbose(const char16_t* spec, const Component& host, CanonOutput* output, CanonHostInfo* host_info) { DoHost<char16_t, char16_t>(spec, host, output, host_info); } bool CanonicalizeHostSubstring(const char* spec, const Component& host, CanonOutput* output) { return DoHostSubstring<char, unsigned char>(spec, host, output); } bool CanonicalizeHostSubstring(const char16_t* spec, const Component& host, CanonOutput* output) { return DoHostSubstring<char16_t, char16_t>(spec, host, output); } } // namespace url
Zhao-PengFei35/chromium_src_4
url/url_canon_host.cc
C++
unknown
19,247
// Copyright 2013 The Chromium Authors // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. // ICU-based character set converter. #include <stdint.h> #include <stdlib.h> #include <string.h> #include "base/check.h" #include "base/memory/raw_ptr.h" #include "base/memory/raw_ptr_exclusion.h" #include "third_party/icu/source/common/unicode/ucnv.h" #include "third_party/icu/source/common/unicode/ucnv_cb.h" #include "third_party/icu/source/common/unicode/utypes.h" #include "url/url_canon_icu.h" #include "url/url_canon_internal.h" // for _itoa_s namespace url { namespace { // Called when converting a character that can not be represented, this will // append an escaped version of the numerical character reference for that code // point. It is of the form "&#1234;" and we will escape the non-digits to // "%26%231234%3B". Why? This is what Netscape did back in the olden days. void appendURLEscapedChar(const void* context, UConverterFromUnicodeArgs* from_args, const UChar* code_units, int32_t length, UChar32 code_point, UConverterCallbackReason reason, UErrorCode* err) { if (reason == UCNV_UNASSIGNED) { *err = U_ZERO_ERROR; const static int prefix_len = 6; const static char prefix[prefix_len + 1] = "%26%23"; // "&#" percent-escaped ucnv_cbFromUWriteBytes(from_args, prefix, prefix_len, 0, err); DCHECK(code_point < 0x110000); char number[8]; // Max Unicode code point is 7 digits. _itoa_s(code_point, number, 10); int number_len = static_cast<int>(strlen(number)); ucnv_cbFromUWriteBytes(from_args, number, number_len, 0, err); const static int postfix_len = 3; const static char postfix[postfix_len + 1] = "%3B"; // ";" percent-escaped ucnv_cbFromUWriteBytes(from_args, postfix, postfix_len, 0, err); } } // A class for scoping the installation of the invalid character callback. class AppendHandlerInstaller { public: // The owner of this object must ensure that the converter is alive for the // duration of this object's lifetime. AppendHandlerInstaller(UConverter* converter) : converter_(converter) { UErrorCode err = U_ZERO_ERROR; ucnv_setFromUCallBack(converter_, appendURLEscapedChar, 0, &old_callback_, &old_context_, &err); } ~AppendHandlerInstaller() { UErrorCode err = U_ZERO_ERROR; ucnv_setFromUCallBack(converter_, old_callback_, old_context_, 0, 0, &err); } private: raw_ptr<UConverter> converter_; UConverterFromUCallback old_callback_; // This field is not a raw_ptr<> because it was filtered by the rewriter for: // #addr-of RAW_PTR_EXCLUSION const void* old_context_; }; } // namespace ICUCharsetConverter::ICUCharsetConverter(UConverter* converter) : converter_(converter) { } ICUCharsetConverter::~ICUCharsetConverter() = default; void ICUCharsetConverter::ConvertFromUTF16(const char16_t* input, int input_len, CanonOutput* output) { // Install our error handler. It will be called for character that can not // be represented in the destination character set. AppendHandlerInstaller handler(converter_); int begin_offset = output->length(); int dest_capacity = output->capacity() - begin_offset; output->set_length(output->length()); do { UErrorCode err = U_ZERO_ERROR; char* dest = &output->data()[begin_offset]; int required_capacity = ucnv_fromUChars(converter_, dest, dest_capacity, input, input_len, &err); if (err != U_BUFFER_OVERFLOW_ERROR) { output->set_length(begin_offset + required_capacity); return; } // Output didn't fit, expand dest_capacity = required_capacity; output->Resize(begin_offset + dest_capacity); } while (true); } } // namespace url
Zhao-PengFei35/chromium_src_4
url/url_canon_icu.cc
C++
unknown
4,042
// Copyright 2013 The Chromium Authors // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #ifndef URL_URL_CANON_ICU_H_ #define URL_URL_CANON_ICU_H_ // ICU integration functions. #include "base/compiler_specific.h" #include "base/component_export.h" #include "base/memory/raw_ptr.h" #include "url/url_canon.h" typedef struct UConverter UConverter; namespace url { // An implementation of CharsetConverter that implementations can use to // interface the canonicalizer with ICU's conversion routines. class COMPONENT_EXPORT(URL) ICUCharsetConverter : public CharsetConverter { public: // Constructs a converter using an already-existing ICU character set // converter. This converter is NOT owned by this object; the lifetime must // be managed by the creator such that it is alive as long as this is. ICUCharsetConverter(UConverter* converter); ~ICUCharsetConverter() override; void ConvertFromUTF16(const char16_t* input, int input_len, CanonOutput* output) override; private: // The ICU converter, not owned by this class. raw_ptr<UConverter> converter_; }; } // namespace url #endif // URL_URL_CANON_ICU_H_
Zhao-PengFei35/chromium_src_4
url/url_canon_icu.h
C++
unknown
1,241
// Copyright 2014 The Chromium Authors // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "url/url_canon_icu.h" #include <stddef.h> #include "base/logging.h" #include "base/memory/raw_ptr.h" #include "testing/gtest/include/gtest/gtest.h" #include "third_party/icu/source/common/unicode/ucnv.h" #include "url/url_canon.h" #include "url/url_canon_stdstring.h" #include "url/url_test_utils.h" namespace url { namespace { // Wrapper around a UConverter object that managers creation and destruction. class UConvScoper { public: explicit UConvScoper(const char* charset_name) { UErrorCode err = U_ZERO_ERROR; converter_ = ucnv_open(charset_name, &err); if (!converter_) { LOG(ERROR) << "Failed to open charset " << charset_name << ": " << u_errorName(err); } } ~UConvScoper() { if (converter_) ucnv_close(converter_.ExtractAsDangling()); } // Returns the converter object, may be NULL. UConverter* converter() const { return converter_; } private: raw_ptr<UConverter> converter_; }; TEST(URLCanonIcuTest, ICUCharsetConverter) { struct ICUCase { const wchar_t* input; const char* encoding; const char* expected; } icu_cases[] = { // UTF-8. {L"Hello, world", "utf-8", "Hello, world"}, {L"\x4f60\x597d", "utf-8", "\xe4\xbd\xa0\xe5\xa5\xbd"}, // Non-BMP UTF-8. {L"!\xd800\xdf00!", "utf-8", "!\xf0\x90\x8c\x80!"}, // Big5 {L"\x4f60\x597d", "big5", "\xa7\x41\xa6\x6e"}, // Unrepresentable character in the destination set. {L"hello\x4f60\x06de\x597dworld", "big5", "hello\xa7\x41%26%231758%3B\xa6\x6eworld"}, }; for (size_t i = 0; i < std::size(icu_cases); i++) { UConvScoper conv(icu_cases[i].encoding); ASSERT_TRUE(conv.converter() != NULL); ICUCharsetConverter converter(conv.converter()); std::string str; StdStringCanonOutput output(&str); std::u16string input_str( test_utils::TruncateWStringToUTF16(icu_cases[i].input)); int input_len = static_cast<int>(input_str.length()); converter.ConvertFromUTF16(input_str.c_str(), input_len, &output); output.Complete(); EXPECT_STREQ(icu_cases[i].expected, str.c_str()); } // Test string sizes around the resize boundary for the output to make sure // the converter resizes as needed. const int static_size = 16; UConvScoper conv("utf-8"); ASSERT_TRUE(conv.converter()); ICUCharsetConverter converter(conv.converter()); for (int i = static_size - 2; i <= static_size + 2; i++) { // Make a string with the appropriate length. std::u16string input; for (int ch = 0; ch < i; ch++) input.push_back('a'); RawCanonOutput<static_size> output; converter.ConvertFromUTF16(input.c_str(), static_cast<int>(input.length()), &output); EXPECT_EQ(input.length(), output.length()); } } TEST(URLCanonIcuTest, QueryWithConverter) { struct QueryCase { const char* input8; const wchar_t* input16; const char* encoding; const char* expected; } query_cases[] = { // Regular ASCII case in some different encodings. {"foo=bar", L"foo=bar", "utf-8", "?foo=bar"}, {"foo=bar", L"foo=bar", "shift_jis", "?foo=bar"}, {"foo=bar", L"foo=bar", "gb2312", "?foo=bar"}, // Chinese input/output {"q=\xe4\xbd\xa0\xe5\xa5\xbd", L"q=\x4f60\x597d", "gb2312", "?q=%C4%E3%BA%C3"}, {"q=\xe4\xbd\xa0\xe5\xa5\xbd", L"q=\x4f60\x597d", "big5", "?q=%A7A%A6n"}, // Unencodable character in the destination character set should be // escaped. The escape sequence unescapes to be the entity name: // "?q=&#20320;" {"q=Chinese\xef\xbc\xa7", L"q=Chinese\xff27", "iso-8859-1", "?q=Chinese%26%2365319%3B"}, }; for (size_t i = 0; i < std::size(query_cases); i++) { Component out_comp; UConvScoper conv(query_cases[i].encoding); ASSERT_TRUE(!query_cases[i].encoding || conv.converter()); ICUCharsetConverter converter(conv.converter()); if (query_cases[i].input8) { int len = static_cast<int>(strlen(query_cases[i].input8)); Component in_comp(0, len); std::string out_str; StdStringCanonOutput output(&out_str); CanonicalizeQuery(query_cases[i].input8, in_comp, &converter, &output, &out_comp); output.Complete(); EXPECT_EQ(query_cases[i].expected, out_str); } if (query_cases[i].input16) { std::u16string input16( test_utils::TruncateWStringToUTF16(query_cases[i].input16)); int len = static_cast<int>(input16.length()); Component in_comp(0, len); std::string out_str; StdStringCanonOutput output(&out_str); CanonicalizeQuery(input16.c_str(), in_comp, &converter, &output, &out_comp); output.Complete(); EXPECT_EQ(query_cases[i].expected, out_str); } } // Extra test for input with embedded NULL; std::string out_str; StdStringCanonOutput output(&out_str); Component out_comp; CanonicalizeQuery("a \x00z\x01", Component(0, 5), NULL, &output, &out_comp); output.Complete(); EXPECT_EQ("?a%20%00z%01", out_str); } } // namespace } // namespace url
Zhao-PengFei35/chromium_src_4
url/url_canon_icu_unittest.cc
C++
unknown
5,265
// Copyright 2013 The Chromium Authors // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "url/url_canon_internal.h" #include <errno.h> #include <stddef.h> #include <stdlib.h> #ifdef __SSE2__ #include <immintrin.h> #elif defined(__aarch64__) #include <arm_neon.h> #endif #include <cstdio> #include <string> #include "base/bits.h" #include "base/numerics/safe_conversions.h" #include "base/strings/utf_string_conversion_utils.h" namespace url { namespace { // Find the initial segment of the given string that consists solely // of characters valid for CHAR_QUERY. (We can have false negatives in // one specific case, namely the exclamation mark 0x21, but false negatives // are fine, and it's not worth adding a separate test for.) This is // a fast path to speed up checking of very long query strings that are // already valid, which happen on some web pages. // // This has some startup cost to load the constants and such, so it's // usually not worth it for short strings. size_t FindInitialQuerySafeString(const char* source, size_t length) { #if defined(__SSE2__) || defined(__aarch64__) constexpr size_t kChunkSize = 16; size_t i; for (i = 0; i < base::bits::AlignDown(length, kChunkSize); i += kChunkSize) { char b __attribute__((vector_size(16))); memcpy(&b, source + i, sizeof(b)); // Compare each element with the ranges for CHAR_QUERY // (see kSharedCharTypeTable), vectorized so that it creates // a mask of which elements match. For completeness, we could // have had (...) | b == 0x21 here, but exclamation marks are // rare and the extra test costs us some time. auto mask = b >= 0x24 && b <= 0x7e && b != 0x27 && b != 0x3c && b != 0x3e; #ifdef __SSE2__ if (_mm_movemask_epi8(reinterpret_cast<__m128i>(mask)) != 0xffff) { return i; } #else if (vminvq_u8(reinterpret_cast<uint8x16_t>(mask)) == 0) { return i; } #endif } return i; #else // Need SIMD support (with fast reductions) for this to be efficient. return 0; #endif } template <typename CHAR, typename UCHAR> void DoAppendStringOfType(const CHAR* source, size_t length, SharedCharTypes type, CanonOutput* output) { size_t i = 0; // We only instantiate this for char, to avoid a Clang crash // (and because Append() does not support converting). if constexpr (sizeof(CHAR) == 1) { if (type == CHAR_QUERY && length >= kMinimumLengthForSIMD) { i = FindInitialQuerySafeString(source, length); output->Append(source, i); } } for (; i < length; i++) { if (static_cast<UCHAR>(source[i]) >= 0x80) { // ReadChar will fill the code point with kUnicodeReplacementCharacter // when the input is invalid, which is what we want. base_icu::UChar32 code_point; ReadUTFChar(source, &i, length, &code_point); AppendUTF8EscapedValue(code_point, output); } else { // Just append the 7-bit character, possibly escaping it. unsigned char uch = static_cast<unsigned char>(source[i]); if (!IsCharOfType(uch, type)) AppendEscapedChar(uch, output); else output->push_back(uch); } } } // This function assumes the input values are all contained in 8-bit, // although it allows any type. Returns true if input is valid, false if not. template <typename CHAR, typename UCHAR> void DoAppendInvalidNarrowString(const CHAR* spec, size_t begin, size_t end, CanonOutput* output) { for (size_t i = begin; i < end; i++) { UCHAR uch = static_cast<UCHAR>(spec[i]); if (uch >= 0x80) { // Handle UTF-8/16 encodings. This call will correctly handle the error // case by appending the invalid character. AppendUTF8EscapedChar(spec, &i, end, output); } else if (uch <= ' ' || uch == 0x7f) { // This function is for error handling, so we escape all control // characters and spaces, but not anything else since we lack // context to do something more specific. AppendEscapedChar(static_cast<unsigned char>(uch), output); } else { output->push_back(static_cast<char>(uch)); } } } // Overrides one component, see the Replacements structure for // what the various combionations of source pointer and component mean. void DoOverrideComponent(const char* override_source, const Component& override_component, const char** dest, Component* dest_component) { if (override_source) { *dest = override_source; *dest_component = override_component; } } // Similar to DoOverrideComponent except that it takes a UTF-16 input and does // not actually set the output character pointer. // // The input is converted to UTF-8 at the end of the given buffer as a temporary // holding place. The component identifying the portion of the buffer used in // the |utf8_buffer| will be specified in |*dest_component|. // // This will not actually set any |dest| pointer like DoOverrideComponent // does because all of the pointers will point into the |utf8_buffer|, which // may get resized while we're overriding a subsequent component. Instead, the // caller should use the beginning of the |utf8_buffer| as the string pointer // for all components once all overrides have been prepared. bool PrepareUTF16OverrideComponent(const char16_t* override_source, const Component& override_component, CanonOutput* utf8_buffer, Component* dest_component) { bool success = true; if (override_source) { if (!override_component.is_valid()) { // Non-"valid" component (means delete), so we need to preserve that. *dest_component = Component(); } else { // Convert to UTF-8. dest_component->begin = utf8_buffer->length(); success = ConvertUTF16ToUTF8(&override_source[override_component.begin], static_cast<size_t>(override_component.len), utf8_buffer); dest_component->len = utf8_buffer->length() - dest_component->begin; } } return success; } } // namespace // See the header file for this array's declaration. // clang-format off const unsigned char kSharedCharTypeTable[0x100] = { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, // 0x00 - 0x0f 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, // 0x10 - 0x1f 0, // 0x20 ' ' (escape spaces in queries) CHAR_QUERY | CHAR_USERINFO | CHAR_COMPONENT, // 0x21 ! 0, // 0x22 " 0, // 0x23 # (invalid in query since it marks the ref) CHAR_QUERY | CHAR_USERINFO, // 0x24 $ CHAR_QUERY | CHAR_USERINFO, // 0x25 % CHAR_QUERY | CHAR_USERINFO, // 0x26 & 0, // 0x27 ' (Try to prevent XSS.) CHAR_QUERY | CHAR_USERINFO | CHAR_COMPONENT, // 0x28 ( CHAR_QUERY | CHAR_USERINFO | CHAR_COMPONENT, // 0x29 ) CHAR_QUERY | CHAR_USERINFO | CHAR_COMPONENT, // 0x2a * CHAR_QUERY | CHAR_USERINFO, // 0x2b + CHAR_QUERY | CHAR_USERINFO, // 0x2c , CHAR_QUERY | CHAR_USERINFO | CHAR_COMPONENT, // 0x2d - CHAR_QUERY | CHAR_USERINFO | CHAR_IPV4 | CHAR_COMPONENT, // 0x2e . CHAR_QUERY, // 0x2f / CHAR_QUERY | CHAR_USERINFO | CHAR_IPV4 | CHAR_HEX | CHAR_DEC | CHAR_OCT | CHAR_COMPONENT, // 0x30 0 CHAR_QUERY | CHAR_USERINFO | CHAR_IPV4 | CHAR_HEX | CHAR_DEC | CHAR_OCT | CHAR_COMPONENT, // 0x31 1 CHAR_QUERY | CHAR_USERINFO | CHAR_IPV4 | CHAR_HEX | CHAR_DEC | CHAR_OCT | CHAR_COMPONENT, // 0x32 2 CHAR_QUERY | CHAR_USERINFO | CHAR_IPV4 | CHAR_HEX | CHAR_DEC | CHAR_OCT | CHAR_COMPONENT, // 0x33 3 CHAR_QUERY | CHAR_USERINFO | CHAR_IPV4 | CHAR_HEX | CHAR_DEC | CHAR_OCT | CHAR_COMPONENT, // 0x34 4 CHAR_QUERY | CHAR_USERINFO | CHAR_IPV4 | CHAR_HEX | CHAR_DEC | CHAR_OCT | CHAR_COMPONENT, // 0x35 5 CHAR_QUERY | CHAR_USERINFO | CHAR_IPV4 | CHAR_HEX | CHAR_DEC | CHAR_OCT | CHAR_COMPONENT, // 0x36 6 CHAR_QUERY | CHAR_USERINFO | CHAR_IPV4 | CHAR_HEX | CHAR_DEC | CHAR_OCT | CHAR_COMPONENT, // 0x37 7 CHAR_QUERY | CHAR_USERINFO | CHAR_IPV4 | CHAR_HEX | CHAR_DEC | CHAR_COMPONENT, // 0x38 8 CHAR_QUERY | CHAR_USERINFO | CHAR_IPV4 | CHAR_HEX | CHAR_DEC | CHAR_COMPONENT, // 0x39 9 CHAR_QUERY, // 0x3a : CHAR_QUERY, // 0x3b ; 0, // 0x3c < (Try to prevent certain types of XSS.) CHAR_QUERY, // 0x3d = 0, // 0x3e > (Try to prevent certain types of XSS.) CHAR_QUERY, // 0x3f ? CHAR_QUERY, // 0x40 @ CHAR_QUERY | CHAR_USERINFO | CHAR_IPV4 | CHAR_HEX | CHAR_COMPONENT, // 0x41 A CHAR_QUERY | CHAR_USERINFO | CHAR_IPV4 | CHAR_HEX | CHAR_COMPONENT, // 0x42 B CHAR_QUERY | CHAR_USERINFO | CHAR_IPV4 | CHAR_HEX | CHAR_COMPONENT, // 0x43 C CHAR_QUERY | CHAR_USERINFO | CHAR_IPV4 | CHAR_HEX | CHAR_COMPONENT, // 0x44 D CHAR_QUERY | CHAR_USERINFO | CHAR_IPV4 | CHAR_HEX | CHAR_COMPONENT, // 0x45 E CHAR_QUERY | CHAR_USERINFO | CHAR_IPV4 | CHAR_HEX | CHAR_COMPONENT, // 0x46 F CHAR_QUERY | CHAR_USERINFO | CHAR_COMPONENT, // 0x47 G CHAR_QUERY | CHAR_USERINFO | CHAR_COMPONENT, // 0x48 H CHAR_QUERY | CHAR_USERINFO | CHAR_COMPONENT, // 0x49 I CHAR_QUERY | CHAR_USERINFO | CHAR_COMPONENT, // 0x4a J CHAR_QUERY | CHAR_USERINFO | CHAR_COMPONENT, // 0x4b K CHAR_QUERY | CHAR_USERINFO | CHAR_COMPONENT, // 0x4c L CHAR_QUERY | CHAR_USERINFO | CHAR_COMPONENT, // 0x4d M CHAR_QUERY | CHAR_USERINFO | CHAR_COMPONENT, // 0x4e N CHAR_QUERY | CHAR_USERINFO | CHAR_COMPONENT, // 0x4f O CHAR_QUERY | CHAR_USERINFO | CHAR_COMPONENT, // 0x50 P CHAR_QUERY | CHAR_USERINFO | CHAR_COMPONENT, // 0x51 Q CHAR_QUERY | CHAR_USERINFO | CHAR_COMPONENT, // 0x52 R CHAR_QUERY | CHAR_USERINFO | CHAR_COMPONENT, // 0x53 S CHAR_QUERY | CHAR_USERINFO | CHAR_COMPONENT, // 0x54 T CHAR_QUERY | CHAR_USERINFO | CHAR_COMPONENT, // 0x55 U CHAR_QUERY | CHAR_USERINFO | CHAR_COMPONENT, // 0x56 V CHAR_QUERY | CHAR_USERINFO | CHAR_COMPONENT, // 0x57 W CHAR_QUERY | CHAR_USERINFO | CHAR_IPV4 | CHAR_COMPONENT, // 0x58 X CHAR_QUERY | CHAR_USERINFO | CHAR_COMPONENT, // 0x59 Y CHAR_QUERY | CHAR_USERINFO | CHAR_COMPONENT, // 0x5a Z CHAR_QUERY, // 0x5b [ CHAR_QUERY, // 0x5c '\' CHAR_QUERY, // 0x5d ] CHAR_QUERY, // 0x5e ^ CHAR_QUERY | CHAR_USERINFO | CHAR_COMPONENT, // 0x5f _ CHAR_QUERY, // 0x60 ` CHAR_QUERY | CHAR_USERINFO | CHAR_IPV4 | CHAR_HEX | CHAR_COMPONENT, // 0x61 a CHAR_QUERY | CHAR_USERINFO | CHAR_IPV4 | CHAR_HEX | CHAR_COMPONENT, // 0x62 b CHAR_QUERY | CHAR_USERINFO | CHAR_IPV4 | CHAR_HEX | CHAR_COMPONENT, // 0x63 c CHAR_QUERY | CHAR_USERINFO | CHAR_IPV4 | CHAR_HEX | CHAR_COMPONENT, // 0x64 d CHAR_QUERY | CHAR_USERINFO | CHAR_IPV4 | CHAR_HEX | CHAR_COMPONENT, // 0x65 e CHAR_QUERY | CHAR_USERINFO | CHAR_IPV4 | CHAR_HEX | CHAR_COMPONENT, // 0x66 f CHAR_QUERY | CHAR_USERINFO | CHAR_COMPONENT, // 0x67 g CHAR_QUERY | CHAR_USERINFO | CHAR_COMPONENT, // 0x68 h CHAR_QUERY | CHAR_USERINFO | CHAR_COMPONENT, // 0x69 i CHAR_QUERY | CHAR_USERINFO | CHAR_COMPONENT, // 0x6a j CHAR_QUERY | CHAR_USERINFO | CHAR_COMPONENT, // 0x6b k CHAR_QUERY | CHAR_USERINFO | CHAR_COMPONENT, // 0x6c l CHAR_QUERY | CHAR_USERINFO | CHAR_COMPONENT, // 0x6d m CHAR_QUERY | CHAR_USERINFO | CHAR_COMPONENT, // 0x6e n CHAR_QUERY | CHAR_USERINFO | CHAR_COMPONENT, // 0x6f o CHAR_QUERY | CHAR_USERINFO | CHAR_COMPONENT, // 0x70 p CHAR_QUERY | CHAR_USERINFO | CHAR_COMPONENT, // 0x71 q CHAR_QUERY | CHAR_USERINFO | CHAR_COMPONENT, // 0x72 r CHAR_QUERY | CHAR_USERINFO | CHAR_COMPONENT, // 0x73 s CHAR_QUERY | CHAR_USERINFO | CHAR_COMPONENT, // 0x74 t CHAR_QUERY | CHAR_USERINFO | CHAR_COMPONENT, // 0x75 u CHAR_QUERY | CHAR_USERINFO | CHAR_COMPONENT, // 0x76 v CHAR_QUERY | CHAR_USERINFO | CHAR_COMPONENT, // 0x77 w CHAR_QUERY | CHAR_USERINFO | CHAR_IPV4 | CHAR_COMPONENT, // 0x78 x CHAR_QUERY | CHAR_USERINFO | CHAR_COMPONENT, // 0x79 y CHAR_QUERY | CHAR_USERINFO | CHAR_COMPONENT, // 0x7a z CHAR_QUERY, // 0x7b { CHAR_QUERY, // 0x7c | CHAR_QUERY, // 0x7d } CHAR_QUERY | CHAR_USERINFO | CHAR_COMPONENT, // 0x7e ~ 0, // 0x7f 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, // 0x80 - 0x8f 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, // 0x90 - 0x9f 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, // 0xa0 - 0xaf 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, // 0xb0 - 0xbf 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, // 0xc0 - 0xcf 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, // 0xd0 - 0xdf 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, // 0xe0 - 0xef 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, // 0xf0 - 0xff }; // clang-format on const char kHexCharLookup[0x10] = { '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'A', 'B', 'C', 'D', 'E', 'F', }; const char kCharToHexLookup[8] = { 0, // 0x00 - 0x1f '0', // 0x20 - 0x3f: digits 0 - 9 are 0x30 - 0x39 'A' - 10, // 0x40 - 0x5f: letters A - F are 0x41 - 0x46 'a' - 10, // 0x60 - 0x7f: letters a - f are 0x61 - 0x66 0, // 0x80 - 0x9F 0, // 0xA0 - 0xBF 0, // 0xC0 - 0xDF 0, // 0xE0 - 0xFF }; const base_icu::UChar32 kUnicodeReplacementCharacter = 0xfffd; void AppendStringOfType(const char* source, size_t length, SharedCharTypes type, CanonOutput* output) { DoAppendStringOfType<char, unsigned char>(source, length, type, output); } void AppendStringOfType(const char16_t* source, size_t length, SharedCharTypes type, CanonOutput* output) { DoAppendStringOfType<char16_t, char16_t>(source, length, type, output); } bool ReadUTFChar(const char* str, size_t* begin, size_t length, base_icu::UChar32* code_point_out) { if (!base::ReadUnicodeCharacter(str, length, begin, code_point_out) || !base::IsValidCharacter(*code_point_out)) { *code_point_out = kUnicodeReplacementCharacter; return false; } return true; } bool ReadUTFChar(const char16_t* str, size_t* begin, size_t length, base_icu::UChar32* code_point_out) { if (!base::ReadUnicodeCharacter(str, length, begin, code_point_out) || !base::IsValidCharacter(*code_point_out)) { *code_point_out = kUnicodeReplacementCharacter; return false; } return true; } void AppendInvalidNarrowString(const char* spec, size_t begin, size_t end, CanonOutput* output) { DoAppendInvalidNarrowString<char, unsigned char>(spec, begin, end, output); } void AppendInvalidNarrowString(const char16_t* spec, size_t begin, size_t end, CanonOutput* output) { DoAppendInvalidNarrowString<char16_t, char16_t>(spec, begin, end, output); } bool ConvertUTF16ToUTF8(const char16_t* input, size_t input_len, CanonOutput* output) { bool success = true; for (size_t i = 0; i < input_len; i++) { base_icu::UChar32 code_point; success &= ReadUTFChar(input, &i, input_len, &code_point); AppendUTF8Value(code_point, output); } return success; } bool ConvertUTF8ToUTF16(const char* input, size_t input_len, CanonOutputT<char16_t>* output) { bool success = true; for (size_t i = 0; i < input_len; i++) { base_icu::UChar32 code_point; success &= ReadUTFChar(input, &i, input_len, &code_point); AppendUTF16Value(code_point, output); } return success; } void SetupOverrideComponents(const char* base, const Replacements<char>& repl, URLComponentSource<char>* source, Parsed* parsed) { // Get the source and parsed structures of the things we are replacing. const URLComponentSource<char>& repl_source = repl.sources(); const Parsed& repl_parsed = repl.components(); DoOverrideComponent(repl_source.scheme, repl_parsed.scheme, &source->scheme, &parsed->scheme); DoOverrideComponent(repl_source.username, repl_parsed.username, &source->username, &parsed->username); DoOverrideComponent(repl_source.password, repl_parsed.password, &source->password, &parsed->password); // Our host should be empty if not present, so override the default setup. DoOverrideComponent(repl_source.host, repl_parsed.host, &source->host, &parsed->host); if (parsed->host.len == -1) parsed->host.len = 0; DoOverrideComponent(repl_source.port, repl_parsed.port, &source->port, &parsed->port); DoOverrideComponent(repl_source.path, repl_parsed.path, &source->path, &parsed->path); DoOverrideComponent(repl_source.query, repl_parsed.query, &source->query, &parsed->query); DoOverrideComponent(repl_source.ref, repl_parsed.ref, &source->ref, &parsed->ref); } bool SetupUTF16OverrideComponents(const char* base, const Replacements<char16_t>& repl, CanonOutput* utf8_buffer, URLComponentSource<char>* source, Parsed* parsed) { bool success = true; // Get the source and parsed structures of the things we are replacing. const URLComponentSource<char16_t>& repl_source = repl.sources(); const Parsed& repl_parsed = repl.components(); success &= PrepareUTF16OverrideComponent( repl_source.scheme, repl_parsed.scheme, utf8_buffer, &parsed->scheme); success &= PrepareUTF16OverrideComponent(repl_source.username, repl_parsed.username, utf8_buffer, &parsed->username); success &= PrepareUTF16OverrideComponent(repl_source.password, repl_parsed.password, utf8_buffer, &parsed->password); success &= PrepareUTF16OverrideComponent(repl_source.host, repl_parsed.host, utf8_buffer, &parsed->host); success &= PrepareUTF16OverrideComponent(repl_source.port, repl_parsed.port, utf8_buffer, &parsed->port); success &= PrepareUTF16OverrideComponent(repl_source.path, repl_parsed.path, utf8_buffer, &parsed->path); success &= PrepareUTF16OverrideComponent(repl_source.query, repl_parsed.query, utf8_buffer, &parsed->query); success &= PrepareUTF16OverrideComponent(repl_source.ref, repl_parsed.ref, utf8_buffer, &parsed->ref); // PrepareUTF16OverrideComponent will not have set the data pointer since the // buffer could be resized, invalidating the pointers. We set the data // pointers for affected components now that the buffer is finalized. if (repl_source.scheme) source->scheme = utf8_buffer->data(); if (repl_source.username) source->username = utf8_buffer->data(); if (repl_source.password) source->password = utf8_buffer->data(); if (repl_source.host) source->host = utf8_buffer->data(); if (repl_source.port) source->port = utf8_buffer->data(); if (repl_source.path) source->path = utf8_buffer->data(); if (repl_source.query) source->query = utf8_buffer->data(); if (repl_source.ref) source->ref = utf8_buffer->data(); return success; } #ifndef WIN32 int _itoa_s(int value, char* buffer, size_t size_in_chars, int radix) { const char* format_str; if (radix == 10) format_str = "%d"; else if (radix == 16) format_str = "%x"; else return EINVAL; int written = snprintf(buffer, size_in_chars, format_str, value); if (static_cast<size_t>(written) >= size_in_chars) { // Output was truncated, or written was negative. return EINVAL; } return 0; } int _itow_s(int value, char16_t* buffer, size_t size_in_chars, int radix) { if (radix != 10) return EINVAL; // No more than 12 characters will be required for a 32-bit integer. // Add an extra byte for the terminating null. char temp[13]; int written = snprintf(temp, sizeof(temp), "%d", value); if (static_cast<size_t>(written) >= size_in_chars) { // Output was truncated, or written was negative. return EINVAL; } for (int i = 0; i < written; ++i) { buffer[i] = static_cast<char16_t>(temp[i]); } buffer[written] = '\0'; return 0; } #endif // !WIN32 } // namespace url
Zhao-PengFei35/chromium_src_4
url/url_canon_internal.cc
C++
unknown
21,436
// Copyright 2013 The Chromium Authors // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #ifndef URL_URL_CANON_INTERNAL_H_ #define URL_URL_CANON_INTERNAL_H_ // This file is intended to be included in another C++ file where the character // types are defined. This allows us to write mostly generic code, but not have // template bloat because everything is inlined when anybody calls any of our // functions. #include <stddef.h> #include <stdlib.h> #include "base/component_export.h" #include "base/notreached.h" #include "base/third_party/icu/icu_utf.h" #include "url/url_canon.h" namespace url { // Character type handling ----------------------------------------------------- // Bits that identify different character types. These types identify different // bits that are set for each 8-bit character in the kSharedCharTypeTable. enum SharedCharTypes { // Characters that do not require escaping in queries. Characters that do // not have this flag will be escaped; see url_canon_query.cc CHAR_QUERY = 1, // Valid in the username/password field. CHAR_USERINFO = 2, // Valid in a IPv4 address (digits plus dot and 'x' for hex). CHAR_IPV4 = 4, // Valid in an ASCII-representation of a hex digit (as in %-escaped). CHAR_HEX = 8, // Valid in an ASCII-representation of a decimal digit. CHAR_DEC = 16, // Valid in an ASCII-representation of an octal digit. CHAR_OCT = 32, // Characters that do not require escaping in encodeURIComponent. Characters // that do not have this flag will be escaped; see url_util.cc. CHAR_COMPONENT = 64, }; // This table contains the flags in SharedCharTypes for each 8-bit character. // Some canonicalization functions have their own specialized lookup table. // For those with simple requirements, we have collected the flags in one // place so there are fewer lookup tables to load into the CPU cache. // // Using an unsigned char type has a small but measurable performance benefit // over using a 32-bit number. extern const unsigned char kSharedCharTypeTable[0x100]; // More readable wrappers around the character type lookup table. inline bool IsCharOfType(unsigned char c, SharedCharTypes type) { return !!(kSharedCharTypeTable[c] & type); } inline bool IsQueryChar(unsigned char c) { return IsCharOfType(c, CHAR_QUERY); } inline bool IsIPv4Char(unsigned char c) { return IsCharOfType(c, CHAR_IPV4); } inline bool IsHexChar(unsigned char c) { return IsCharOfType(c, CHAR_HEX); } inline bool IsComponentChar(unsigned char c) { return IsCharOfType(c, CHAR_COMPONENT); } // Appends the given string to the output, escaping characters that do not // match the given |type| in SharedCharTypes. void AppendStringOfType(const char* source, size_t length, SharedCharTypes type, CanonOutput* output); void AppendStringOfType(const char16_t* source, size_t length, SharedCharTypes type, CanonOutput* output); // Maps the hex numerical values 0x0 to 0xf to the corresponding ASCII digit // that will be used to represent it. COMPONENT_EXPORT(URL) extern const char kHexCharLookup[0x10]; // This lookup table allows fast conversion between ASCII hex letters and their // corresponding numerical value. The 8-bit range is divided up into 8 // regions of 0x20 characters each. Each of the three character types (numbers, // uppercase, lowercase) falls into different regions of this range. The table // contains the amount to subtract from characters in that range to get at // the corresponding numerical value. // // See HexDigitToValue for the lookup. extern const char kCharToHexLookup[8]; // Assumes the input is a valid hex digit! Call IsHexChar before using this. inline int HexCharToValue(unsigned char c) { return c - kCharToHexLookup[c / 0x20]; } // Indicates if the given character is a dot or dot equivalent, returning the // number of characters taken by it. This will be one for a literal dot, 3 for // an escaped dot. If the character is not a dot, this will return 0. template <typename CHAR> inline size_t IsDot(const CHAR* spec, size_t offset, size_t end) { if (spec[offset] == '.') { return 1; } else if (spec[offset] == '%' && offset + 3 <= end && spec[offset + 1] == '2' && (spec[offset + 2] == 'e' || spec[offset + 2] == 'E')) { // Found "%2e" return 3; } return 0; } // Returns the canonicalized version of the input character according to scheme // rules. This is implemented alongside the scheme canonicalizer, and is // required for relative URL resolving to test for scheme equality. // // Returns 0 if the input character is not a valid scheme character. char CanonicalSchemeChar(char16_t ch); // Write a single character, escaped, to the output. This always escapes: it // does no checking that thee character requires escaping. // Escaping makes sense only 8 bit chars, so code works in all cases of // input parameters (8/16bit). template <typename UINCHAR, typename OUTCHAR> inline void AppendEscapedChar(UINCHAR ch, CanonOutputT<OUTCHAR>* output) { output->push_back('%'); output->push_back(static_cast<OUTCHAR>(kHexCharLookup[(ch >> 4) & 0xf])); output->push_back(static_cast<OUTCHAR>(kHexCharLookup[ch & 0xf])); } // The character we'll substitute for undecodable or invalid characters. extern const base_icu::UChar32 kUnicodeReplacementCharacter; // UTF-8 functions ------------------------------------------------------------ // Reads one character in UTF-8 starting at |*begin| in |str| and places // the decoded value into |*code_point|. If the character is valid, we will // return true. If invalid, we'll return false and put the // kUnicodeReplacementCharacter into |*code_point|. // // |*begin| will be updated to point to the last character consumed so it // can be incremented in a loop and will be ready for the next character. // (for a single-byte ASCII character, it will not be changed). COMPONENT_EXPORT(URL) bool ReadUTFChar(const char* str, size_t* begin, size_t length, base_icu::UChar32* code_point_out); // Generic To-UTF-8 converter. This will call the given append method for each // character that should be appended, with the given output method. Wrappers // are provided below for escaped and non-escaped versions of this. // // The char_value must have already been checked that it's a valid Unicode // character. template <class Output, void Appender(unsigned char, Output*)> inline void DoAppendUTF8(base_icu::UChar32 char_value, Output* output) { DCHECK(char_value >= 0); DCHECK(char_value <= 0x10FFFF); if (char_value <= 0x7f) { Appender(static_cast<unsigned char>(char_value), output); } else if (char_value <= 0x7ff) { // 110xxxxx 10xxxxxx Appender(static_cast<unsigned char>(0xC0 | (char_value >> 6)), output); Appender(static_cast<unsigned char>(0x80 | (char_value & 0x3f)), output); } else if (char_value <= 0xffff) { // 1110xxxx 10xxxxxx 10xxxxxx Appender(static_cast<unsigned char>(0xe0 | (char_value >> 12)), output); Appender(static_cast<unsigned char>(0x80 | ((char_value >> 6) & 0x3f)), output); Appender(static_cast<unsigned char>(0x80 | (char_value & 0x3f)), output); } else { // 11110xxx 10xxxxxx 10xxxxxx 10xxxxxx Appender(static_cast<unsigned char>(0xf0 | (char_value >> 18)), output); Appender(static_cast<unsigned char>(0x80 | ((char_value >> 12) & 0x3f)), output); Appender(static_cast<unsigned char>(0x80 | ((char_value >> 6) & 0x3f)), output); Appender(static_cast<unsigned char>(0x80 | (char_value & 0x3f)), output); } } // Helper used by AppendUTF8Value below. We use an unsigned parameter so there // are no funny sign problems with the input, but then have to convert it to // a regular char for appending. inline void AppendCharToOutput(unsigned char ch, CanonOutput* output) { output->push_back(static_cast<char>(ch)); } // Writes the given character to the output as UTF-8. This does NO checking // of the validity of the Unicode characters; the caller should ensure that // the value it is appending is valid to append. inline void AppendUTF8Value(base_icu::UChar32 char_value, CanonOutput* output) { DoAppendUTF8<CanonOutput, AppendCharToOutput>(char_value, output); } // Writes the given character to the output as UTF-8, escaping ALL // characters (even when they are ASCII). This does NO checking of the // validity of the Unicode characters; the caller should ensure that the value // it is appending is valid to append. inline void AppendUTF8EscapedValue(base_icu::UChar32 char_value, CanonOutput* output) { DoAppendUTF8<CanonOutput, AppendEscapedChar>(char_value, output); } // UTF-16 functions ----------------------------------------------------------- // Reads one character in UTF-16 starting at |*begin| in |str| and places // the decoded value into |*code_point|. If the character is valid, we will // return true. If invalid, we'll return false and put the // kUnicodeReplacementCharacter into |*code_point|. // // |*begin| will be updated to point to the last character consumed so it // can be incremented in a loop and will be ready for the next character. // (for a single-16-bit-word character, it will not be changed). COMPONENT_EXPORT(URL) bool ReadUTFChar(const char16_t* str, size_t* begin, size_t length, base_icu::UChar32* code_point_out); // Equivalent to U16_APPEND_UNSAFE in ICU but uses our output method. inline void AppendUTF16Value(base_icu::UChar32 code_point, CanonOutputT<char16_t>* output) { if (code_point > 0xffff) { output->push_back(static_cast<char16_t>((code_point >> 10) + 0xd7c0)); output->push_back(static_cast<char16_t>((code_point & 0x3ff) | 0xdc00)); } else { output->push_back(static_cast<char16_t>(code_point)); } } // Escaping functions --------------------------------------------------------- // Writes the given character to the output as UTF-8, escaped. Call this // function only when the input is wide. Returns true on success. Failure // means there was some problem with the encoding, we'll still try to // update the |*begin| pointer and add a placeholder character to the // output so processing can continue. // // We will append the character starting at ch[begin] with the buffer ch // being |length|. |*begin| will be updated to point to the last character // consumed (we may consume more than one for UTF-16) so that if called in // a loop, incrementing the pointer will move to the next character. // // Every single output character will be escaped. This means that if you // give it an ASCII character as input, it will be escaped. Some code uses // this when it knows that a character is invalid according to its rules // for validity. If you don't want escaping for ASCII characters, you will // have to filter them out prior to calling this function. // // Assumes that ch[begin] is within range in the array, but does not assume // that any following characters are. inline bool AppendUTF8EscapedChar(const char16_t* str, size_t* begin, size_t length, CanonOutput* output) { // UTF-16 input. ReadUTFChar will handle invalid characters for us and give // us the kUnicodeReplacementCharacter, so we don't have to do special // checking after failure, just pass through the failure to the caller. base_icu::UChar32 char_value; bool success = ReadUTFChar(str, begin, length, &char_value); AppendUTF8EscapedValue(char_value, output); return success; } // Handles UTF-8 input. See the wide version above for usage. inline bool AppendUTF8EscapedChar(const char* str, size_t* begin, size_t length, CanonOutput* output) { // ReadUTF8Char will handle invalid characters for us and give us the // kUnicodeReplacementCharacter, so we don't have to do special checking // after failure, just pass through the failure to the caller. base_icu::UChar32 ch; bool success = ReadUTFChar(str, begin, length, &ch); AppendUTF8EscapedValue(ch, output); return success; } // Given a '%' character at |*begin| in the string |spec|, this will decode // the escaped value and put it into |*unescaped_value| on success (returns // true). On failure, this will return false, and will not write into // |*unescaped_value|. // // |*begin| will be updated to point to the last character of the escape // sequence so that when called with the index of a for loop, the next time // through it will point to the next character to be considered. On failure, // |*begin| will be unchanged. inline bool Is8BitChar(char c) { return true; // this case is specialized to avoid a warning } inline bool Is8BitChar(char16_t c) { return c <= 255; } template <typename CHAR> inline bool DecodeEscaped(const CHAR* spec, size_t* begin, size_t end, unsigned char* unescaped_value) { if (*begin + 3 > end || !Is8BitChar(spec[*begin + 1]) || !Is8BitChar(spec[*begin + 2])) { // Invalid escape sequence because there's not enough room, or the // digits are not ASCII. return false; } unsigned char first = static_cast<unsigned char>(spec[*begin + 1]); unsigned char second = static_cast<unsigned char>(spec[*begin + 2]); if (!IsHexChar(first) || !IsHexChar(second)) { // Invalid hex digits, fail. return false; } // Valid escape sequence. *unescaped_value = static_cast<unsigned char>((HexCharToValue(first) << 4) + HexCharToValue(second)); *begin += 2; return true; } // Appends the given substring to the output, escaping "some" characters that // it feels may not be safe. It assumes the input values are all contained in // 8-bit although it allows any type. // // This is used in error cases to append invalid output so that it looks // approximately correct. Non-error cases should not call this function since // the escaping rules are not guaranteed! void AppendInvalidNarrowString(const char* spec, size_t begin, size_t end, CanonOutput* output); void AppendInvalidNarrowString(const char16_t* spec, size_t begin, size_t end, CanonOutput* output); // Misc canonicalization helpers ---------------------------------------------- // Converts between UTF-8 and UTF-16, returning true on successful conversion. // The output will be appended to the given canonicalizer output (so make sure // it's empty if you want to replace). // // On invalid input, this will still write as much output as possible, // replacing the invalid characters with the "invalid character". It will // return false in the failure case, and the caller should not continue as // normal. COMPONENT_EXPORT(URL) bool ConvertUTF16ToUTF8(const char16_t* input, size_t input_len, CanonOutput* output); COMPONENT_EXPORT(URL) bool ConvertUTF8ToUTF16(const char* input, size_t input_len, CanonOutputT<char16_t>* output); // Converts from UTF-16 to 8-bit using the character set converter. If the // converter is NULL, this will use UTF-8. void ConvertUTF16ToQueryEncoding(const char16_t* input, const Component& query, CharsetConverter* converter, CanonOutput* output); // Applies the replacements to the given component source. The component source // should be pre-initialized to the "old" base. That is, all pointers will // point to the spec of the old URL, and all of the Parsed components will // be indices into that string. // // The pointers and components in the |source| for all non-NULL strings in the // |repl| (replacements) will be updated to reference those strings. // Canonicalizing with the new |source| and |parsed| can then combine URL // components from many different strings. void SetupOverrideComponents(const char* base, const Replacements<char>& repl, URLComponentSource<char>* source, Parsed* parsed); // Like the above 8-bit version, except that it additionally converts the // UTF-16 input to UTF-8 before doing the overrides. // // The given utf8_buffer is used to store the converted components. They will // be appended one after another, with the parsed structure identifying the // appropriate substrings. This buffer is a parameter because the source has // no storage, so the buffer must have the same lifetime as the source // parameter owned by the caller. // // THE CALLER MUST NOT ADD TO THE |utf8_buffer| AFTER THIS CALL. Members of // |source| will point into this buffer, which could be invalidated if // additional data is added and the CanonOutput resizes its buffer. // // Returns true on success. False means that the input was not valid UTF-16, // although we will have still done the override with "invalid characters" in // place of errors. bool SetupUTF16OverrideComponents(const char* base, const Replacements<char16_t>& repl, CanonOutput* utf8_buffer, URLComponentSource<char>* source, Parsed* parsed); // Implemented in url_canon_path.cc, these are required by the relative URL // resolver as well, so we declare them here. bool CanonicalizePartialPathInternal(const char* spec, const Component& path, size_t path_begin_in_output, CanonOutput* output); bool CanonicalizePartialPathInternal(const char16_t* spec, const Component& path, size_t path_begin_in_output, CanonOutput* output); // Find the position of a bona fide Windows drive letter in the given path. If // no leading drive letter is found, -1 is returned. This function correctly // treats /c:/foo and /./c:/foo as having drive letters, and /def/c:/foo as not // having a drive letter. // // Exported for tests. COMPONENT_EXPORT(URL) int FindWindowsDriveLetter(const char* spec, int begin, int end); COMPONENT_EXPORT(URL) int FindWindowsDriveLetter(const char16_t* spec, int begin, int end); #ifndef WIN32 // Implementations of Windows' int-to-string conversions COMPONENT_EXPORT(URL) int _itoa_s(int value, char* buffer, size_t size_in_chars, int radix); COMPONENT_EXPORT(URL) int _itow_s(int value, char16_t* buffer, size_t size_in_chars, int radix); // Secure template overloads for these functions template <size_t N> inline int _itoa_s(int value, char (&buffer)[N], int radix) { return _itoa_s(value, buffer, N, radix); } template <size_t N> inline int _itow_s(int value, char16_t (&buffer)[N], int radix) { return _itow_s(value, buffer, N, radix); } // _strtoui64 and strtoull behave the same inline unsigned long long _strtoui64(const char* nptr, char** endptr, int base) { return strtoull(nptr, endptr, base); } #endif // WIN32 // The threshold we set to consider SIMD processing, in bytes; there is // no deep theory here, it's just set empirically to a value that seems // to be good. (We don't really know why there's a slowdown for zero; // but a guess would be that there's no need in going into a complex loop // with a lot of setup for a five-byte string.) static constexpr int kMinimumLengthForSIMD = 50; } // namespace url #endif // URL_URL_CANON_INTERNAL_H_
Zhao-PengFei35/chromium_src_4
url/url_canon_internal.h
C++
unknown
20,268
// Copyright 2013 The Chromium Authors // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #ifndef URL_URL_CANON_INTERNAL_FILE_H_ #define URL_URL_CANON_INTERNAL_FILE_H_ // As with url_canon_internal.h, this file is intended to be included in // another C++ file where the template types are defined. This allows the // programmer to use this to use these functions for their own strings // types, without bloating the code by having inline templates used in // every call site. // // *** This file must be included after url_canon_internal as we depend on some // functions in it. *** #include "base/strings/string_util.h" #include "url/url_file.h" #include "url/url_parse_internal.h" namespace url { // Given a pointer into the spec, this copies and canonicalizes the drive // letter and colon to the output, if one is found. If there is not a drive // spec, it won't do anything. The index of the next character in the input // spec is returned (after the colon when a drive spec is found, the begin // offset if one is not). template<typename CHAR> static int FileDoDriveSpec(const CHAR* spec, int begin, int end, CanonOutput* output) { // The path could be one of several things: /foo/bar, c:/foo/bar, /c:/foo, // (with backslashes instead of slashes as well). int num_slashes = CountConsecutiveSlashes(spec, begin, end); int after_slashes = begin + num_slashes; if (!DoesBeginWindowsDriveSpec(spec, after_slashes, end)) return begin; // Haven't consumed any characters // DoesBeginWindowsDriveSpec will ensure that the drive letter is valid // and that it is followed by a colon/pipe. // Normalize Windows drive letters to uppercase if (base::IsAsciiLower(spec[after_slashes])) output->push_back(spec[after_slashes] - 'a' + 'A'); else output->push_back(static_cast<char>(spec[after_slashes])); // Normalize the character following it to a colon rather than pipe. output->push_back(':'); output->push_back('/'); return after_slashes + 2; } // FileDoDriveSpec will have already added the first backslash, so we need to // write everything following the slashes using the path canonicalizer. template<typename CHAR, typename UCHAR> static void FileDoPath(const CHAR* spec, int begin, int end, CanonOutput* output) { // Normalize the number of slashes after the drive letter. The path // canonicalizer expects the input to begin in a slash already so // doesn't check. We want to handle no-slashes int num_slashes = CountConsecutiveSlashes(spec, begin, end); int after_slashes = begin + num_slashes; // Now use the regular path canonicalizer to canonicalize the rest of the // path. We supply it with the path following the slashes. It won't prepend // a slash because it assumes any nonempty path already starts with one. // We explicitly filter out calls with no path here to prevent that case. ParsedComponent sub_path(after_slashes, end - after_slashes); if (sub_path.len > 0) { // Give it a fake output component to write into. DoCanonicalizeFile will // compute the full path component. ParsedComponent fake_output_path; URLCanonInternal<CHAR, UCHAR>::DoPath( spec, sub_path, output, &fake_output_path); } } template<typename CHAR, typename UCHAR> static bool DoCanonicalizeFileURL(const URLComponentSource<CHAR>& source, const ParsedURL& parsed, CanonOutput* output, ParsedURL* new_parsed) { // Things we don't set in file: URLs. new_parsed->username = ParsedComponent(0, -1); new_parsed->password = ParsedComponent(0, -1); new_parsed->port = ParsedComponent(0, -1); // Scheme (known, so we don't bother running it through the more // complicated scheme canonicalizer). new_parsed->scheme.begin = output->length(); output->push_back('f'); output->push_back('i'); output->push_back('l'); output->push_back('e'); new_parsed->scheme.len = output->length() - new_parsed->scheme.begin; output->push_back(':'); // Write the separator for the host. output->push_back('/'); output->push_back('/'); // Append the host. For many file URLs, this will be empty. For UNC, this // will be present. // TODO(brettw) This doesn't do any checking for host name validity. We // should probably handle validity checking of UNC hosts differently than // for regular IP hosts. bool success = URLCanonInternal<CHAR, UCHAR>::DoHost( source.host, parsed.host, output, &new_parsed->host); // Write a separator for the start of the path. We'll ignore any slashes // already at the beginning of the path. new_parsed->path.begin = output->length(); output->push_back('/'); // Copy and normalize the "c:" at the beginning, if present. int after_drive = FileDoDriveSpec(source.path, parsed.path.begin, parsed.path.end(), output); // Copy the rest of the path. FileDoPath<CHAR, UCHAR>(source.path, after_drive, parsed.path.end(), output); new_parsed->path.len = output->length() - new_parsed->path.begin; // For things following the path, we can use the standard canonicalizers. success &= URLCanonInternal<CHAR, UCHAR>::DoQuery( source.query, parsed.query, output, &new_parsed->query); success &= URLCanonInternal<CHAR, UCHAR>::DoRef( source.ref, parsed.ref, output, &new_parsed->ref); return success; } } // namespace url #endif // URL_URL_CANON_INTERNAL_FILE_H_
Zhao-PengFei35/chromium_src_4
url/url_canon_internal_file.h
C++
unknown
5,582