<commit_before>// Copyright (c) 2011 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

#include "base/utf_string_conversions.h"
#include "chrome/browser/automation/automation_util.h"
#include "chrome/browser/extensions/extension_apitest.h"
#include "chrome/browser/extensions/extension_host.h"
#include "chrome/browser/extensions/extension_service.h"
#include "chrome/browser/profiles/profile.h"
#include "chrome/browser/ui/browser.h"
#include "chrome/browser/ui/tab_contents/tab_contents_wrapper.h"
#include "chrome/common/chrome_switches.h"
#include "chrome/test/base/ui_test_utils.h"
#include "content/browser/renderer_host/browser_render_process_host.h"
#include "content/browser/renderer_host/render_view_host.h"
#include "content/browser/tab_contents/tab_contents.h"
#include "net/base/mock_host_resolver.h"

namespace {

class IsolatedAppApiTest : public ExtensionApiTest {
 public:
  // Returns whether the given tab's current URL has the given cookie.
  bool WARN_UNUSED_RESULT HasCookie(TabContents* contents, std::string cookie) {
    int value_size;
    std::string actual_cookie;
    automation_util::GetCookies(contents->GetURL(), contents, &value_size,
                                &actual_cookie);
    return actual_cookie.find(cookie) != std::string::npos;
  }

  const Extension* GetInstalledApp(TabContents* contents) {
    const Extension* installed_app = NULL;
    Profile* profile = Profile::FromBrowserContext(contents->browser_context());
    ExtensionService* service = profile->GetExtensionService();
    if (service) {
      installed_app = service->GetInstalledAppForRenderer(
          contents->render_view_host()->process()->id());
    }
    return installed_app;
  }
};

}  // namespace

// Tests that cookies set within an isolated app are not visible to normal
// pages or other apps.
//
// Flaky on Mac/Win.  http://crbug.com/86562
#if defined(OS_WIN) || defined(OS_MACOSX)
#define MAYBE_CookieIsolation DISABLED_CookieIsolation
#else
#define MAYBE_CookieIsolation CookieIsolation
#endif
IN_PROC_BROWSER_TEST_F(IsolatedAppApiTest, MAYBE_CookieIsolation) {
  CommandLine::ForCurrentProcess()->AppendSwitch(
      switches::kDisablePopupBlocking);
  CommandLine::ForCurrentProcess()->AppendSwitch(
      switches::kEnableExperimentalExtensionApis);

  host_resolver()->AddRule("*", "127.0.0.1");
  ASSERT_TRUE(test_server()->Start());

  ASSERT_TRUE(LoadExtension(test_data_dir_.AppendASCII("isolated_apps/app1")));
  ASSERT_TRUE(LoadExtension(test_data_dir_.AppendASCII("isolated_apps/app2")));

  // The app under test acts on URLs whose host is "localhost",
  // so the URLs we navigate to must have host "localhost".
  GURL base_url = test_server()->GetURL(
      "files/extensions/api_test/isolated_apps/");
  GURL::Replacements replace_host;
  std::string host_str("localhost");  // Must stay in scope with replace_host.
  replace_host.SetHostStr(host_str);
  base_url = base_url.ReplaceComponents(replace_host);

  browser()->NewTab();
  ui_test_utils::NavigateToURL(browser(), base_url.Resolve("app1/main.html"));
  browser()->NewTab();
  ui_test_utils::NavigateToURL(browser(), base_url.Resolve("app2/main.html"));
  browser()->NewTab();
  ui_test_utils::NavigateToURL(browser(),
                               base_url.Resolve("non_app/main.html"));

  // Ensure first two tabs have installed apps.
  TabContents* tab1 = browser()->GetTabContentsAt(1);
  TabContents* tab2 = browser()->GetTabContentsAt(2);
  TabContents* tab3 = browser()->GetTabContentsAt(3);
  ASSERT_TRUE(GetInstalledApp(tab1));
  ASSERT_TRUE(GetInstalledApp(tab2));
  ASSERT_TRUE(!GetInstalledApp(tab3));

  // Check that each tab sees its own cookie.
  EXPECT_TRUE(HasCookie(tab1, "app1=3"));
  EXPECT_TRUE(HasCookie(tab2, "app2=4"));
  EXPECT_TRUE(HasCookie(tab3, "normalPage=5"));

  // Check that app1 tab cannot see the other cookies.
  EXPECT_FALSE(HasCookie(tab1, "app2"));
  EXPECT_FALSE(HasCookie(tab1, "normalPage"));

  // Check that app2 tab cannot see the other cookies.
  EXPECT_FALSE(HasCookie(tab2, "app1"));
  EXPECT_FALSE(HasCookie(tab2, "normalPage"));

  // Check that normal tab cannot see the other cookies.
  EXPECT_FALSE(HasCookie(tab3, "app1"));
  EXPECT_FALSE(HasCookie(tab3, "app2"));

  // Check that the non_app iframe cookie is associated with app1 and not the
  // normal tab.  (For now, iframes are always rendered in their parent
  // process, even if they aren't in the app manifest.)
  EXPECT_TRUE(HasCookie(tab1, "nonAppFrame=6"));
  EXPECT_FALSE(HasCookie(tab3, "nonAppFrame"));

  // Check that isolation persists even if the tab crashes and is reloaded.
  browser()->SelectNumberedTab(1);
  ui_test_utils::CrashTab(tab1);
  ui_test_utils::WindowedNotificationObserver observer(
      content::NOTIFICATION_LOAD_STOP,
      Source<NavigationController>(
          &browser()->GetSelectedTabContentsWrapper()->controller()));
  browser()->Reload(CURRENT_TAB);
  observer.Wait();
  EXPECT_TRUE(HasCookie(tab1, "app1=3"));
  EXPECT_FALSE(HasCookie(tab1, "app2"));
  EXPECT_FALSE(HasCookie(tab1, "normalPage"));
}

// Ensure that cookies are not isolated if the isolated apps are not installed.
#if defined(OS_WIN)
// Disabled due to http://crbug.com/89090.
#define MAYBE_NoCookieIsolationWithoutApp DISABLED_NoCookieIsolationWithoutApp
#else
#define MAYBE_NoCookieIsolationWithoutApp NoCookieIsolationWithoutApp
#endif
IN_PROC_BROWSER_TEST_F(IsolatedAppApiTest, NoCookieIsolationWithoutApp) {
  CommandLine::ForCurrentProcess()->AppendSwitch(
      switches::kDisablePopupBlocking);

  host_resolver()->AddRule("*", "127.0.0.1");
  ASSERT_TRUE(test_server()->Start());

  // The app under test acts on URLs whose host is "localhost",
  // so the URLs we navigate to must have host "localhost".
  GURL base_url = test_server()->GetURL(
      "files/extensions/api_test/isolated_apps/");
  GURL::Replacements replace_host;
  std::string host_str("localhost");  // Must stay in scope with replace_host.
  replace_host.SetHostStr(host_str);
  base_url = base_url.ReplaceComponents(replace_host);

  browser()->NewTab();
  ui_test_utils::NavigateToURL(browser(), base_url.Resolve("app1/main.html"));
  browser()->NewTab();
  ui_test_utils::NavigateToURL(browser(), base_url.Resolve("app2/main.html"));
  browser()->NewTab();
  ui_test_utils::NavigateToURL(browser(),
                               base_url.Resolve("non_app/main.html"));

  // Check that tabs see each others' cookies.
  ASSERT_TRUE(HasCookie(browser()->GetTabContentsAt(1), "app2=4"));
  ASSERT_TRUE(HasCookie(browser()->GetTabContentsAt(1), "normalPage=5"));
  ASSERT_TRUE(HasCookie(browser()->GetTabContentsAt(1), "nonAppFrame=6"));
  ASSERT_TRUE(HasCookie(browser()->GetTabContentsAt(2), "app1=3"));
  ASSERT_TRUE(HasCookie(browser()->GetTabContentsAt(2), "normalPage=5"));
  ASSERT_TRUE(HasCookie(browser()->GetTabContentsAt(2), "nonAppFrame=6"));
  ASSERT_TRUE(HasCookie(browser()->GetTabContentsAt(3), "app1=3"));
  ASSERT_TRUE(HasCookie(browser()->GetTabContentsAt(3), "app2=4"));
  ASSERT_TRUE(HasCookie(browser()->GetTabContentsAt(3), "nonAppFrame=6"));
}
<commit_msg>Actually disable the flakey test on Windows.<commit_after>// Copyright (c) 2011 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

#include "base/utf_string_conversions.h"
#include "chrome/browser/automation/automation_util.h"
#include "chrome/browser/extensions/extension_apitest.h"
#include "chrome/browser/extensions/extension_host.h"
#include "chrome/browser/extensions/extension_service.h"
#include "chrome/browser/profiles/profile.h"
#include "chrome/browser/ui/browser.h"
#include "chrome/browser/ui/tab_contents/tab_contents_wrapper.h"
#include "chrome/common/chrome_switches.h"
#include "chrome/test/base/ui_test_utils.h"
#include "content/browser/renderer_host/browser_render_process_host.h"
#include "content/browser/renderer_host/render_view_host.h"
#include "content/browser/tab_contents/tab_contents.h"
#include "net/base/mock_host_resolver.h"

namespace {

class IsolatedAppApiTest : public ExtensionApiTest {
 public:
  // Returns whether the given tab's current URL has the given cookie.
  bool WARN_UNUSED_RESULT HasCookie(TabContents* contents, std::string cookie) {
    int value_size;
    std::string actual_cookie;
    automation_util::GetCookies(contents->GetURL(), contents, &value_size,
                                &actual_cookie);
    return actual_cookie.find(cookie) != std::string::npos;
  }

  const Extension* GetInstalledApp(TabContents* contents) {
    const Extension* installed_app = NULL;
    Profile* profile = Profile::FromBrowserContext(contents->browser_context());
    ExtensionService* service = profile->GetExtensionService();
    if (service) {
      installed_app = service->GetInstalledAppForRenderer(
          contents->render_view_host()->process()->id());
    }
    return installed_app;
  }
};

}  // namespace

// Tests that cookies set within an isolated app are not visible to normal
// pages or other apps.
//
// Flaky on Mac/Win.  http://crbug.com/86562
#if defined(OS_WIN) || defined(OS_MACOSX)
#define MAYBE_CookieIsolation DISABLED_CookieIsolation
#else
#define MAYBE_CookieIsolation CookieIsolation
#endif
IN_PROC_BROWSER_TEST_F(IsolatedAppApiTest, MAYBE_CookieIsolation) {
  CommandLine::ForCurrentProcess()->AppendSwitch(
      switches::kDisablePopupBlocking);
  CommandLine::ForCurrentProcess()->AppendSwitch(
      switches::kEnableExperimentalExtensionApis);

  host_resolver()->AddRule("*", "127.0.0.1");
  ASSERT_TRUE(test_server()->Start());

  ASSERT_TRUE(LoadExtension(test_data_dir_.AppendASCII("isolated_apps/app1")));
  ASSERT_TRUE(LoadExtension(test_data_dir_.AppendASCII("isolated_apps/app2")));

  // The app under test acts on URLs whose host is "localhost",
  // so the URLs we navigate to must have host "localhost".
  GURL base_url = test_server()->GetURL(
      "files/extensions/api_test/isolated_apps/");
  GURL::Replacements replace_host;
  std::string host_str("localhost");  // Must stay in scope with replace_host.
  replace_host.SetHostStr(host_str);
  base_url = base_url.ReplaceComponents(replace_host);

  browser()->NewTab();
  ui_test_utils::NavigateToURL(browser(), base_url.Resolve("app1/main.html"));
  browser()->NewTab();
  ui_test_utils::NavigateToURL(browser(), base_url.Resolve("app2/main.html"));
  browser()->NewTab();
  ui_test_utils::NavigateToURL(browser(),
                               base_url.Resolve("non_app/main.html"));

  // Ensure first two tabs have installed apps.
  TabContents* tab1 = browser()->GetTabContentsAt(1);
  TabContents* tab2 = browser()->GetTabContentsAt(2);
  TabContents* tab3 = browser()->GetTabContentsAt(3);
  ASSERT_TRUE(GetInstalledApp(tab1));
  ASSERT_TRUE(GetInstalledApp(tab2));
  ASSERT_TRUE(!GetInstalledApp(tab3));

  // Check that each tab sees its own cookie.
  EXPECT_TRUE(HasCookie(tab1, "app1=3"));
  EXPECT_TRUE(HasCookie(tab2, "app2=4"));
  EXPECT_TRUE(HasCookie(tab3, "normalPage=5"));

  // Check that app1 tab cannot see the other cookies.
  EXPECT_FALSE(HasCookie(tab1, "app2"));
  EXPECT_FALSE(HasCookie(tab1, "normalPage"));

  // Check that app2 tab cannot see the other cookies.
  EXPECT_FALSE(HasCookie(tab2, "app1"));
  EXPECT_FALSE(HasCookie(tab2, "normalPage"));

  // Check that normal tab cannot see the other cookies.
  EXPECT_FALSE(HasCookie(tab3, "app1"));
  EXPECT_FALSE(HasCookie(tab3, "app2"));

  // Check that the non_app iframe cookie is associated with app1 and not the
  // normal tab.  (For now, iframes are always rendered in their parent
  // process, even if they aren't in the app manifest.)
  EXPECT_TRUE(HasCookie(tab1, "nonAppFrame=6"));
  EXPECT_FALSE(HasCookie(tab3, "nonAppFrame"));

  // Check that isolation persists even if the tab crashes and is reloaded.
  browser()->SelectNumberedTab(1);
  ui_test_utils::CrashTab(tab1);
  ui_test_utils::WindowedNotificationObserver observer(
      content::NOTIFICATION_LOAD_STOP,
      Source<NavigationController>(
          &browser()->GetSelectedTabContentsWrapper()->controller()));
  browser()->Reload(CURRENT_TAB);
  observer.Wait();
  EXPECT_TRUE(HasCookie(tab1, "app1=3"));
  EXPECT_FALSE(HasCookie(tab1, "app2"));
  EXPECT_FALSE(HasCookie(tab1, "normalPage"));
}

// Ensure that cookies are not isolated if the isolated apps are not installed.
#if defined(OS_WIN)
// Disabled due to http://crbug.com/89090.
#define MAYBE_NoCookieIsolationWithoutApp DISABLED_NoCookieIsolationWithoutApp
#else
#define MAYBE_NoCookieIsolationWithoutApp NoCookieIsolationWithoutApp
#endif
IN_PROC_BROWSER_TEST_F(IsolatedAppApiTest, MAYBE_NoCookieIsolationWithoutApp) {
  CommandLine::ForCurrentProcess()->AppendSwitch(
      switches::kDisablePopupBlocking);

  host_resolver()->AddRule("*", "127.0.0.1");
  ASSERT_TRUE(test_server()->Start());

  // The app under test acts on URLs whose host is "localhost",
  // so the URLs we navigate to must have host "localhost".
  GURL base_url = test_server()->GetURL(
      "files/extensions/api_test/isolated_apps/");
  GURL::Replacements replace_host;
  std::string host_str("localhost");  // Must stay in scope with replace_host.
  replace_host.SetHostStr(host_str);
  base_url = base_url.ReplaceComponents(replace_host);

  browser()->NewTab();
  ui_test_utils::NavigateToURL(browser(), base_url.Resolve("app1/main.html"));
  browser()->NewTab();
  ui_test_utils::NavigateToURL(browser(), base_url.Resolve("app2/main.html"));
  browser()->NewTab();
  ui_test_utils::NavigateToURL(browser(),
                               base_url.Resolve("non_app/main.html"));

  // Check that tabs see each others' cookies.
  ASSERT_TRUE(HasCookie(browser()->GetTabContentsAt(1), "app2=4"));
  ASSERT_TRUE(HasCookie(browser()->GetTabContentsAt(1), "normalPage=5"));
  ASSERT_TRUE(HasCookie(browser()->GetTabContentsAt(1), "nonAppFrame=6"));
  ASSERT_TRUE(HasCookie(browser()->GetTabContentsAt(2), "app1=3"));
  ASSERT_TRUE(HasCookie(browser()->GetTabContentsAt(2), "normalPage=5"));
  ASSERT_TRUE(HasCookie(browser()->GetTabContentsAt(2), "nonAppFrame=6"));
  ASSERT_TRUE(HasCookie(browser()->GetTabContentsAt(3), "app1=3"));
  ASSERT_TRUE(HasCookie(browser()->GetTabContentsAt(3), "app2=4"));
  ASSERT_TRUE(HasCookie(browser()->GetTabContentsAt(3), "nonAppFrame=6"));
}
<|endoftext|>


<commit_before>// Copyright (c) 2011 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

#include "base/command_line.h"
#include "base/path_service.h"
#include "chrome/browser/prerender/prerender_contents.h"
#include "chrome/browser/prerender/prerender_manager.h"
#include "chrome/browser/profiles/profile.h"
#include "chrome/browser/tab_contents/tab_contents.h"
#include "chrome/browser/ui/browser.h"
#include "chrome/common/chrome_paths.h"
#include "chrome/common/chrome_switches.h"
#include "chrome/common/net/url_request_context_getter.h"
#include "chrome/test/in_process_browser_test.h"
#include "chrome/test/ui_test_utils.h"
#include "net/url_request/url_request_context.h"

// Prerender tests work as follows:
//
// A page with a prefetch link to the test page is loaded.  Once prerendered,
// its Javascript function DidPrerenderPass() is called, which returns true if
// the page behaves as expected when prerendered.
//
// The prerendered page is then displayed on a tab.  The Javascript function
// DidDisplayPass() is called, and returns true if the page behaved as it
// should while being displayed.

namespace prerender {

namespace {

// PrerenderContents that stops the UI message loop on DidStopLoading().
class TestPrerenderContents : public PrerenderContents {
 public:
  TestPrerenderContents(
      PrerenderManager* prerender_manager, Profile* profile, const GURL& url,
      const std::vector<GURL>& alias_urls,
      const GURL& referrer,
      FinalStatus expected_final_status)
      : PrerenderContents(prerender_manager, profile, url, alias_urls,
                          referrer),
        did_finish_loading_(false),
        expected_final_status_(expected_final_status) {
  }

  virtual ~TestPrerenderContents() {
    EXPECT_EQ(expected_final_status_, final_status());
    // In the event we are destroyed, say if the prerender was canceled, quit
    // the UI message loop.
    if (!did_finish_loading_)
      MessageLoopForUI::current()->Quit();
  }

  virtual void DidStopLoading() {
    PrerenderContents::DidStopLoading();
    did_finish_loading_ = true;
    MessageLoopForUI::current()->Quit();
  }

  bool did_finish_loading() const { return did_finish_loading_; }
  void set_did_finish_loading(bool did_finish_loading) {
    did_finish_loading_ = did_finish_loading;
  }

 private:
  bool did_finish_loading_;
  FinalStatus expected_final_status_;
};

// PrerenderManager that uses TestPrerenderContents.
class WaitForLoadPrerenderContentsFactory : public PrerenderContents::Factory {
 public:
  explicit WaitForLoadPrerenderContentsFactory(
      FinalStatus expected_final_status)
      : expected_final_status_(expected_final_status) {
  }

  virtual PrerenderContents* CreatePrerenderContents(
      PrerenderManager* prerender_manager, Profile* profile, const GURL& url,
      const std::vector<GURL>& alias_urls, const GURL& referrer) {
    return new TestPrerenderContents(prerender_manager, profile, url,
                                     alias_urls, referrer,
                                     expected_final_status_);
  }

 private:
  FinalStatus expected_final_status_;
};

}  // namespace

class PrerenderBrowserTest : public InProcessBrowserTest {
 public:
  PrerenderBrowserTest() {
    EnableDOMAutomation();
  }

  virtual void SetUpCommandLine(CommandLine* command_line) {
    command_line->AppendSwitchASCII(switches::kPrerender,
                                    switches::kPrerenderSwitchValueEnabled);
#if defined(OS_MACOSX)
    // The plugins directory isn't read by default on the Mac, so it needs to be
    // explicitly registered.
    FilePath app_dir;
    PathService::Get(chrome::DIR_APP, &app_dir);
    command_line->AppendSwitchPath(
        switches::kExtraPluginDir,
        app_dir.Append(FILE_PATH_LITERAL("plugins")));
#endif
  }

  void PrerenderTestURL(const std::string& html_file,
                        FinalStatus expected_final_status,
                        int total_navigations) {
    ASSERT_TRUE(test_server()->Start());
    std::string dest_path = "files/prerender/";
    dest_path.append(html_file);
    dest_url_ = test_server()->GetURL(dest_path);

    std::vector<net::TestServer::StringPair> replacement_text;
    replacement_text.push_back(
        make_pair("REPLACE_WITH_PREFETCH_URL", dest_url_.spec()));
    std::string replacement_path;
    ASSERT_TRUE(net::TestServer::GetFilePathWithReplacements(
        "files/prerender/prerender_loader.html",
        replacement_text,
        &replacement_path));
    GURL src_url = test_server()->GetURL(replacement_path);

    Profile* profile = browser()->GetSelectedTabContents()->profile();
    PrerenderManager* prerender_manager = profile->GetPrerenderManager();
    ASSERT_TRUE(prerender_manager);

    // This is needed to exit the event loop once the prerendered page has
    // stopped loading or was cancelled.
    prerender_manager->SetPrerenderContentsFactory(
        new WaitForLoadPrerenderContentsFactory(expected_final_status));

    // ui_test_utils::NavigateToURL uses its own observer and message loop.
    // Since the test needs to wait until the prerendered page has stopped
    // loading, rathather than the page directly navigated to, need to
    // handle browser navigation directly.
    browser()->OpenURL(src_url, GURL(), CURRENT_TAB, PageTransition::TYPED);

    TestPrerenderContents* prerender_contents = NULL;
    int navigations = 0;
    while (true) {
      ui_test_utils::RunMessageLoop();
      ++navigations;

      prerender_contents =
          static_cast<TestPrerenderContents*>(
              prerender_manager->FindEntry(dest_url_));
      if (prerender_contents == NULL ||
          !prerender_contents->did_finish_loading() ||
          navigations >= total_navigations) {
        EXPECT_EQ(navigations, total_navigations);
        break;
      }
      prerender_contents->set_did_finish_loading(false);
    }

    switch (expected_final_status) {
      case FINAL_STATUS_USED: {
        ASSERT_TRUE(prerender_contents != NULL);
        ASSERT_TRUE(prerender_contents->did_finish_loading());

        // Check if page behaves as expected while in prerendered state.
        bool prerender_test_result = false;
        ASSERT_TRUE(ui_test_utils::ExecuteJavaScriptAndExtractBool(
            prerender_contents->render_view_host(), L"",
            L"window.domAutomationController.send(DidPrerenderPass())",
            &prerender_test_result));
        EXPECT_TRUE(prerender_test_result);
        break;
      }
      default:
        // In the failure case, we should have removed dest_url_ from the
        // prerender_manager.
        EXPECT_TRUE(prerender_contents == NULL);
        break;
    }
  }

  void NavigateToDestURL() const {
    ui_test_utils::NavigateToURL(browser(), dest_url_);

    Profile* profile = browser()->GetSelectedTabContents()->profile();
    PrerenderManager* prerender_manager = profile->GetPrerenderManager();
    ASSERT_TRUE(prerender_manager);

    // Make sure the PrerenderContents found earlier was used or removed
    EXPECT_TRUE(prerender_manager->FindEntry(dest_url_) == NULL);

    // Check if page behaved as expected when actually displayed.
    bool display_test_result = false;
    ASSERT_TRUE(ui_test_utils::ExecuteJavaScriptAndExtractBool(
        browser()->GetSelectedTabContents()->render_view_host(), L"",
        L"window.domAutomationController.send(DidDisplayPass())",
        &display_test_result));
    EXPECT_TRUE(display_test_result);
  }

 private:
  GURL dest_url_;
};

// Checks that a page is correctly prerendered in the case of a
// <link rel=prefetch> tag and then loaded into a tab in response to a
// navigation.
IN_PROC_BROWSER_TEST_F(PrerenderBrowserTest, PrerenderPage) {
  PrerenderTestURL("prerender_page.html",
                   FINAL_STATUS_USED, 1);
  NavigateToDestURL();
}

// Checks that the prerendering of a page is canceled correctly when a
// Javascript alert is called.
IN_PROC_BROWSER_TEST_F(PrerenderBrowserTest, PrerenderAlertBeforeOnload) {
  PrerenderTestURL(
      "prerender_alert_before_onload.html",
      FINAL_STATUS_JAVASCRIPT_ALERT, 1);
}

// Checks that the prerendering of a page is canceled correctly when a
// Javascript alert is called.
IN_PROC_BROWSER_TEST_F(PrerenderBrowserTest, PrerenderAlertAfterOnload) {
  PrerenderTestURL(
      "prerender_alert_after_onload.html",
      FINAL_STATUS_JAVASCRIPT_ALERT, 1);
}

// Checks that plugins are not loaded while a page is being preloaded, but
// are loaded when the page is displayed.
IN_PROC_BROWSER_TEST_F(PrerenderBrowserTest, PrerenderDelayLoadPlugin) {
  PrerenderTestURL("plugin_delay_load.html",
                   FINAL_STATUS_USED, 1);
  NavigateToDestURL();
}

// Checks that plugins in an iframe are not loaded while a page is
// being preloaded, but are loaded when the page is displayed.
IN_PROC_BROWSER_TEST_F(PrerenderBrowserTest, PrerenderIframeDelayLoadPlugin) {
  PrerenderTestURL("prerender_iframe_plugin_delay_load.html",
                   FINAL_STATUS_USED, 1);
  NavigateToDestURL();
}

// Renders a page that contains a prerender link to a page that contains an
// iframe with a source that requires http authentication. This should not
// prerender successfully.
IN_PROC_BROWSER_TEST_F(PrerenderBrowserTest, PrerenderHttpAuthentication) {
  PrerenderTestURL("prerender_http_auth_container.html",
                   FINAL_STATUS_AUTH_NEEDED, 1);
}

// Checks that redirects work with prerendering.
IN_PROC_BROWSER_TEST_F(PrerenderBrowserTest, PrerenderRedirect) {
  PrerenderTestURL("prerender_redirect.html",
                   FINAL_STATUS_USED, 2);
  NavigateToDestURL();
}

// Prerenders a page that contains an automatic download triggered through an
// iframe. This should not prerender successfully.
IN_PROC_BROWSER_TEST_F(PrerenderBrowserTest, PrerenderDownloadIFrame) {
  PrerenderTestURL("prerender_download_iframe.html",
                   FINAL_STATUS_DOWNLOAD, 1);
}

// Prerenders a page that contains an automatic download triggered through
// Javascript changing the window.location. This should not prerender
// successfully.
IN_PROC_BROWSER_TEST_F(PrerenderBrowserTest, PrerenderDownloadLocation) {
  PrerenderTestURL("prerender_download_location.html",
                   FINAL_STATUS_DOWNLOAD, 2);
}

// Prerenders a page that contains an automatic download triggered through a
// <meta http-equiv="refresh"> tag. This should not prerender successfully.
IN_PROC_BROWSER_TEST_F(PrerenderBrowserTest, PrerenderDownloadRefresh) {
  PrerenderTestURL("prerender_download_refresh.html",
                   FINAL_STATUS_DOWNLOAD, 2);
}

// Checks that the referrer is set when prerendering.
IN_PROC_BROWSER_TEST_F(PrerenderBrowserTest, PrerenderReferrer) {
  PrerenderTestURL("prerender_referrer.html",
                   FINAL_STATUS_USED, 1);
  NavigateToDestURL();
}

// Checks that popups on a prerendered page cause cancellation.
IN_PROC_BROWSER_TEST_F(PrerenderBrowserTest, PrerenderPopup) {
  PrerenderTestURL("prerender_popup.html",
                   FINAL_STATUS_CREATE_NEW_WINDOW, 1);
}

// Test that page-based redirects to https will cancel prerenders.
IN_PROC_BROWSER_TEST_F(PrerenderBrowserTest, PrerenderRedirectToHttps) {
  net::TestServer https_server(net::TestServer::TYPE_HTTPS,
                               FilePath(FILE_PATH_LITERAL("chrome/test/data")));
  ASSERT_TRUE(https_server.Start());
  GURL https_url = https_server.GetURL("files/prerender/prerender_page.html");
  std::vector<net::TestServer::StringPair> replacement_text;
  replacement_text.push_back(
      make_pair("REPLACE_WITH_HTTPS_URL", https_url.spec()));
  std::string redirect_path;
  ASSERT_TRUE(net::TestServer::GetFilePathWithReplacements(
      "prerender_redirect_to_https.html",
      replacement_text,
      &redirect_path));
  PrerenderTestURL(redirect_path,
                   FINAL_STATUS_HTTPS,
                   2);
}

}  // namespace prerender
<commit_msg>Mark PrenderBrowserTest.PrerenderRedirectToHttps flaky.<commit_after>// Copyright (c) 2011 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

#include "base/command_line.h"
#include "base/path_service.h"
#include "chrome/browser/prerender/prerender_contents.h"
#include "chrome/browser/prerender/prerender_manager.h"
#include "chrome/browser/profiles/profile.h"
#include "chrome/browser/tab_contents/tab_contents.h"
#include "chrome/browser/ui/browser.h"
#include "chrome/common/chrome_paths.h"
#include "chrome/common/chrome_switches.h"
#include "chrome/common/net/url_request_context_getter.h"
#include "chrome/test/in_process_browser_test.h"
#include "chrome/test/ui_test_utils.h"
#include "net/url_request/url_request_context.h"

// Prerender tests work as follows:
//
// A page with a prefetch link to the test page is loaded.  Once prerendered,
// its Javascript function DidPrerenderPass() is called, which returns true if
// the page behaves as expected when prerendered.
//
// The prerendered page is then displayed on a tab.  The Javascript function
// DidDisplayPass() is called, and returns true if the page behaved as it
// should while being displayed.

namespace prerender {

namespace {

// PrerenderContents that stops the UI message loop on DidStopLoading().
class TestPrerenderContents : public PrerenderContents {
 public:
  TestPrerenderContents(
      PrerenderManager* prerender_manager, Profile* profile, const GURL& url,
      const std::vector<GURL>& alias_urls,
      const GURL& referrer,
      FinalStatus expected_final_status)
      : PrerenderContents(prerender_manager, profile, url, alias_urls,
                          referrer),
        did_finish_loading_(false),
        expected_final_status_(expected_final_status) {
  }

  virtual ~TestPrerenderContents() {
    EXPECT_EQ(expected_final_status_, final_status());
    // In the event we are destroyed, say if the prerender was canceled, quit
    // the UI message loop.
    if (!did_finish_loading_)
      MessageLoopForUI::current()->Quit();
  }

  virtual void DidStopLoading() {
    PrerenderContents::DidStopLoading();
    did_finish_loading_ = true;
    MessageLoopForUI::current()->Quit();
  }

  bool did_finish_loading() const { return did_finish_loading_; }
  void set_did_finish_loading(bool did_finish_loading) {
    did_finish_loading_ = did_finish_loading;
  }

 private:
  bool did_finish_loading_;
  FinalStatus expected_final_status_;
};

// PrerenderManager that uses TestPrerenderContents.
class WaitForLoadPrerenderContentsFactory : public PrerenderContents::Factory {
 public:
  explicit WaitForLoadPrerenderContentsFactory(
      FinalStatus expected_final_status)
      : expected_final_status_(expected_final_status) {
  }

  virtual PrerenderContents* CreatePrerenderContents(
      PrerenderManager* prerender_manager, Profile* profile, const GURL& url,
      const std::vector<GURL>& alias_urls, const GURL& referrer) {
    return new TestPrerenderContents(prerender_manager, profile, url,
                                     alias_urls, referrer,
                                     expected_final_status_);
  }

 private:
  FinalStatus expected_final_status_;
};

}  // namespace

class PrerenderBrowserTest : public InProcessBrowserTest {
 public:
  PrerenderBrowserTest() {
    EnableDOMAutomation();
  }

  virtual void SetUpCommandLine(CommandLine* command_line) {
    command_line->AppendSwitchASCII(switches::kPrerender,
                                    switches::kPrerenderSwitchValueEnabled);
#if defined(OS_MACOSX)
    // The plugins directory isn't read by default on the Mac, so it needs to be
    // explicitly registered.
    FilePath app_dir;
    PathService::Get(chrome::DIR_APP, &app_dir);
    command_line->AppendSwitchPath(
        switches::kExtraPluginDir,
        app_dir.Append(FILE_PATH_LITERAL("plugins")));
#endif
  }

  void PrerenderTestURL(const std::string& html_file,
                        FinalStatus expected_final_status,
                        int total_navigations) {
    ASSERT_TRUE(test_server()->Start());
    std::string dest_path = "files/prerender/";
    dest_path.append(html_file);
    dest_url_ = test_server()->GetURL(dest_path);

    std::vector<net::TestServer::StringPair> replacement_text;
    replacement_text.push_back(
        make_pair("REPLACE_WITH_PREFETCH_URL", dest_url_.spec()));
    std::string replacement_path;
    ASSERT_TRUE(net::TestServer::GetFilePathWithReplacements(
        "files/prerender/prerender_loader.html",
        replacement_text,
        &replacement_path));
    GURL src_url = test_server()->GetURL(replacement_path);

    Profile* profile = browser()->GetSelectedTabContents()->profile();
    PrerenderManager* prerender_manager = profile->GetPrerenderManager();
    ASSERT_TRUE(prerender_manager);

    // This is needed to exit the event loop once the prerendered page has
    // stopped loading or was cancelled.
    prerender_manager->SetPrerenderContentsFactory(
        new WaitForLoadPrerenderContentsFactory(expected_final_status));

    // ui_test_utils::NavigateToURL uses its own observer and message loop.
    // Since the test needs to wait until the prerendered page has stopped
    // loading, rathather than the page directly navigated to, need to
    // handle browser navigation directly.
    browser()->OpenURL(src_url, GURL(), CURRENT_TAB, PageTransition::TYPED);

    TestPrerenderContents* prerender_contents = NULL;
    int navigations = 0;
    while (true) {
      ui_test_utils::RunMessageLoop();
      ++navigations;

      prerender_contents =
          static_cast<TestPrerenderContents*>(
              prerender_manager->FindEntry(dest_url_));
      if (prerender_contents == NULL ||
          !prerender_contents->did_finish_loading() ||
          navigations >= total_navigations) {
        EXPECT_EQ(navigations, total_navigations);
        break;
      }
      prerender_contents->set_did_finish_loading(false);
    }

    switch (expected_final_status) {
      case FINAL_STATUS_USED: {
        ASSERT_TRUE(prerender_contents != NULL);
        ASSERT_TRUE(prerender_contents->did_finish_loading());

        // Check if page behaves as expected while in prerendered state.
        bool prerender_test_result = false;
        ASSERT_TRUE(ui_test_utils::ExecuteJavaScriptAndExtractBool(
            prerender_contents->render_view_host(), L"",
            L"window.domAutomationController.send(DidPrerenderPass())",
            &prerender_test_result));
        EXPECT_TRUE(prerender_test_result);
        break;
      }
      default:
        // In the failure case, we should have removed dest_url_ from the
        // prerender_manager.
        EXPECT_TRUE(prerender_contents == NULL);
        break;
    }
  }

  void NavigateToDestURL() const {
    ui_test_utils::NavigateToURL(browser(), dest_url_);

    Profile* profile = browser()->GetSelectedTabContents()->profile();
    PrerenderManager* prerender_manager = profile->GetPrerenderManager();
    ASSERT_TRUE(prerender_manager);

    // Make sure the PrerenderContents found earlier was used or removed
    EXPECT_TRUE(prerender_manager->FindEntry(dest_url_) == NULL);

    // Check if page behaved as expected when actually displayed.
    bool display_test_result = false;
    ASSERT_TRUE(ui_test_utils::ExecuteJavaScriptAndExtractBool(
        browser()->GetSelectedTabContents()->render_view_host(), L"",
        L"window.domAutomationController.send(DidDisplayPass())",
        &display_test_result));
    EXPECT_TRUE(display_test_result);
  }

 private:
  GURL dest_url_;
};

// Checks that a page is correctly prerendered in the case of a
// <link rel=prefetch> tag and then loaded into a tab in response to a
// navigation.
IN_PROC_BROWSER_TEST_F(PrerenderBrowserTest, PrerenderPage) {
  PrerenderTestURL("prerender_page.html",
                   FINAL_STATUS_USED, 1);
  NavigateToDestURL();
}

// Checks that the prerendering of a page is canceled correctly when a
// Javascript alert is called.
IN_PROC_BROWSER_TEST_F(PrerenderBrowserTest, PrerenderAlertBeforeOnload) {
  PrerenderTestURL(
      "prerender_alert_before_onload.html",
      FINAL_STATUS_JAVASCRIPT_ALERT, 1);
}

// Checks that the prerendering of a page is canceled correctly when a
// Javascript alert is called.
IN_PROC_BROWSER_TEST_F(PrerenderBrowserTest, PrerenderAlertAfterOnload) {
  PrerenderTestURL(
      "prerender_alert_after_onload.html",
      FINAL_STATUS_JAVASCRIPT_ALERT, 1);
}

// Checks that plugins are not loaded while a page is being preloaded, but
// are loaded when the page is displayed.
IN_PROC_BROWSER_TEST_F(PrerenderBrowserTest, PrerenderDelayLoadPlugin) {
  PrerenderTestURL("plugin_delay_load.html",
                   FINAL_STATUS_USED, 1);
  NavigateToDestURL();
}

// Checks that plugins in an iframe are not loaded while a page is
// being preloaded, but are loaded when the page is displayed.
IN_PROC_BROWSER_TEST_F(PrerenderBrowserTest, PrerenderIframeDelayLoadPlugin) {
  PrerenderTestURL("prerender_iframe_plugin_delay_load.html",
                   FINAL_STATUS_USED, 1);
  NavigateToDestURL();
}

// Renders a page that contains a prerender link to a page that contains an
// iframe with a source that requires http authentication. This should not
// prerender successfully.
IN_PROC_BROWSER_TEST_F(PrerenderBrowserTest, PrerenderHttpAuthentication) {
  PrerenderTestURL("prerender_http_auth_container.html",
                   FINAL_STATUS_AUTH_NEEDED, 1);
}

// Checks that redirects work with prerendering.
IN_PROC_BROWSER_TEST_F(PrerenderBrowserTest, PrerenderRedirect) {
  PrerenderTestURL("prerender_redirect.html",
                   FINAL_STATUS_USED, 2);
  NavigateToDestURL();
}

// Prerenders a page that contains an automatic download triggered through an
// iframe. This should not prerender successfully.
IN_PROC_BROWSER_TEST_F(PrerenderBrowserTest, PrerenderDownloadIFrame) {
  PrerenderTestURL("prerender_download_iframe.html",
                   FINAL_STATUS_DOWNLOAD, 1);
}

// Prerenders a page that contains an automatic download triggered through
// Javascript changing the window.location. This should not prerender
// successfully.
IN_PROC_BROWSER_TEST_F(PrerenderBrowserTest, PrerenderDownloadLocation) {
  PrerenderTestURL("prerender_download_location.html",
                   FINAL_STATUS_DOWNLOAD, 2);
}

// Prerenders a page that contains an automatic download triggered through a
// <meta http-equiv="refresh"> tag. This should not prerender successfully.
IN_PROC_BROWSER_TEST_F(PrerenderBrowserTest, PrerenderDownloadRefresh) {
  PrerenderTestURL("prerender_download_refresh.html",
                   FINAL_STATUS_DOWNLOAD, 2);
}

// Checks that the referrer is set when prerendering.
IN_PROC_BROWSER_TEST_F(PrerenderBrowserTest, PrerenderReferrer) {
  PrerenderTestURL("prerender_referrer.html",
                   FINAL_STATUS_USED, 1);
  NavigateToDestURL();
}

// Checks that popups on a prerendered page cause cancellation.
IN_PROC_BROWSER_TEST_F(PrerenderBrowserTest, PrerenderPopup) {
  PrerenderTestURL("prerender_popup.html",
                   FINAL_STATUS_CREATE_NEW_WINDOW, 1);
}

// Test that page-based redirects to https will cancel prerenders.
// Flaky, http://crbug.com/73580
IN_PROC_BROWSER_TEST_F(PrerenderBrowserTest, FLAKY_PrerenderRedirectToHttps) {
  net::TestServer https_server(net::TestServer::TYPE_HTTPS,
                               FilePath(FILE_PATH_LITERAL("chrome/test/data")));
  ASSERT_TRUE(https_server.Start());
  GURL https_url = https_server.GetURL("files/prerender/prerender_page.html");
  std::vector<net::TestServer::StringPair> replacement_text;
  replacement_text.push_back(
      make_pair("REPLACE_WITH_HTTPS_URL", https_url.spec()));
  std::string redirect_path;
  ASSERT_TRUE(net::TestServer::GetFilePathWithReplacements(
      "prerender_redirect_to_https.html",
      replacement_text,
      &redirect_path));
  PrerenderTestURL(redirect_path,
                   FINAL_STATUS_HTTPS,
                   2);
}

}  // namespace prerender
<|endoftext|>


<commit_before>/* $Id$ */

/*
 * Copyright (c) 2010 .SE (The Internet Infrastructure Foundation).
 * All rights reserved.
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions
 * are met:
 * 1. Redistributions of source code must retain the above copyright
 *    notice, this list of conditions and the following disclaimer.
 * 2. Redistributions in binary form must reproduce the above copyright
 *    notice, this list of conditions and the following disclaimer in the
 *    documentation and/or other materials provided with the distribution.
 *
 * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR
 * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
 * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
 * ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY
 * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE
 * GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
 * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER
 * IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR
 * OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN
 * IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
 */

/************************************************************
*
* softhsm-keyconv
*
* This program is for converting from BIND .private-key
* format to PKCS#8 key file format. So that keys can be
* imported from BIND to SoftHSM.
*
* Some of the design/code is from keyconv.c written by
* Hakan Olsson and Jakob Schlyter in 2000 and 2001.
*
************************************************************/

#include <config.h>
#include "softhsm-keyconv.h"

#include <stdio.h>
#include <stdlib.h>
#include <getopt.h>
#include <string.h>
#include <unistd.h>
#include <iostream>
#include <fstream>
#include <stdint.h>

void usage()
{
	printf("Converting from BIND .private-key format to PKCS#8 key file format.\n");
	printf("Usage: softhsm-keyconv [OPTIONS]\n");
	printf("Options:\n");
	printf("  -h                  Shows this help screen.\n");
	printf("  --help              Shows this help screen.\n");
	printf("  --in <path>         The path to the input file.\n");
	printf("  --out <path>        The path to the output file.\n");
	printf("  --pin <PIN>         To encrypt PKCS#8 file. Optional.\n");
	printf("  -v                  Show version info.\n");
	printf("  --version           Show version info.\n");
}

// Give a number to each option
enum {
	OPT_HELP = 0x100,
	OPT_IN,
	OPT_OUT,
	OPT_PIN,
	OPT_VERSION
};

// Define the options
static const struct option long_options[] = {
	{ "help",    0, NULL, OPT_HELP },
	{ "in",      1, NULL, OPT_IN },
	{ "out",     1, NULL, OPT_OUT },
	{ "pin",     1, NULL, OPT_PIN },
	{ "version", 0, NULL, OPT_VERSION },
	{ NULL,      0, NULL, 0 }
};

int main(int argc, char *argv[])
{
	int option_index = 0;
	int opt, result;

	char *in_path = NULL;
	char *out_path = NULL;
	char *file_pin = NULL;

	while ((opt = getopt_long(argc, argv, "hv", long_options, &option_index)) != -1)
	{
		switch (opt)
		{
			case OPT_IN:
				in_path = optarg;
				break;
			case OPT_OUT:
				out_path = optarg;
				break;
			case OPT_PIN:
				file_pin = optarg;
				break;
			case OPT_VERSION:
			case 'v':
				printf("%s\n", PACKAGE_VERSION);
				exit(0);
				break;
			case OPT_HELP:
			case 'h':
			default:
				usage();
				exit(0);
				break;
		}
	}

	// We should convert to PKCS#8
	result = to_pkcs8(in_path, out_path, file_pin);

	return result;
}

// Convert from BIND to PKCS#8
int to_pkcs8(char *in_path, char *out_path, char *file_pin)
{
	FILE *file_pointer = NULL;
	char line[MAX_LINE], data[MAX_LINE], *value_pointer;
	int lineno = 0, m, n, error = 0, found, algorithm = DNS_KEYALG_ERROR, data_length;
	uint32_t bitfield = 0;
	key_material_t pkey[TAG_MAX];

	if (in_path == NULL)
	{
		fprintf(stderr, "ERROR: A path to the input file must be supplied. Use --in <path>\n");
		return 1;
	}

	if (out_path == NULL)
	{
		fprintf(stderr, "ERROR: A path to the output file must be supplied. Use --out <path>\n");
		return 1;
	}

	file_pointer = fopen(in_path, "r");
	if (!file_pointer)
	{
		fprintf(stderr, "ERROR: Could not open input file %.100s for reading.\n", in_path);
		return 1;
	}

	// Loop over all of the lines
	while (fgets(line, MAX_LINE, file_pointer) != NULL)
	{
		lineno++;

		// Find the current text field in the BIND file.
		for (m = 0, found = -1; found == -1 && file_tags[m]; m++)
		{
			if (strncasecmp(line, file_tags[m], strlen(file_tags[m])) == 0)
			{
				found = m;
			}
		}

		// The text files is not recognized.
		if (found == -1)
		{
			fprintf(stderr, "ERROR: Unrecognized input line %i\n", lineno);
			fprintf(stderr, "ERROR: --> %s", line);
			continue;
		}

		// Point to the data for this text field.
		value_pointer = line + strlen(file_tags[found]) + 1;

		// Continue if we are at the end of the string
		if (*value_pointer == 0)
		{
			continue;
		}

		// Check that we do not get duplicates.
		if (bitfield & (1 << found))
		{
			fprintf(stderr, "ERROR: Duplicate \"%s\" field, line %i - ignored\n",
					file_tags[found], lineno);
			continue;
		}
		bitfield |= (1 << found);

		// Handle the data for this text field.
		switch (found)
		{
			case TAG_VERSION:
				if (sscanf(value_pointer, "v%i.%i", &m, &n) != 2)
				{
					fprintf(stderr, "ERROR: Invalid/unknown version string "
							"(%.100s).\n", value_pointer);
					error = 1;
					break;
				}
				if (m > FILE_MAJOR_VERSION || n > FILE_MINOR_VERSION)
				{
					fprintf(stderr, "ERROR: Cannot parse this version of file format, "
							"v%i.%i.\n", m, n);
					error = 1;
				}
				break;
			case TAG_ALGORITHM:
				algorithm = strtol(value_pointer, NULL, 10);
				break;
			// RSA
			case TAG_MODULUS:
			case TAG_PUBEXP:
			case TAG_PRIVEXP:
			case TAG_PRIME1:
			case TAG_PRIME2:
			case TAG_EXP1:
			case TAG_EXP2:
			case TAG_COEFF:
			// DSA
			case TAG_PRIME:
			case TAG_SUBPRIME:
			case TAG_BASE:
			case TAG_PRIVVAL:
			case TAG_PUBVAL:
				data_length = b64_pton(value_pointer, (unsigned char*)data, MAX_LINE);
				if (data_length == -1)
				{
					error = 1;
					fprintf(stderr, "ERROR: Could not parse the base64 string on line %i.\n", lineno);
				}
				else
				{
					pkey[found].big = malloc(data_length);
					if (!pkey[found].big)
					{
						fprintf(stderr, "ERROR: Could not allocate memory.\n");
						error = 1;
						break;
					}
					memcpy(pkey[found].big, data, data_length);
					pkey[found].size = data_length;
				}
				break;
			// Do not need these
			case TAG_CREATED:
			case TAG_PUBLISH:
			case TAG_ACTIVATE:
			default:
				break;
		}
	}

	fclose(file_pointer);

	// Something went wrong. Clean up and quit.
	if (error)
	{
		free_key_material(pkey);
		return error;
	}

	crypto_init();

	// Save the the key to the disk
	switch (algorithm)
	{
		case DNS_KEYALG_ERROR:
			fprintf(stderr, "ERROR: The algorithm was not given in the file.\n",
					algorithm);
			error = 1;
			break;
		case DNS_KEYALG_RSAMD5:
		case DNS_KEYALG_RSASHA1:
		case DNS_KEYALG_RSASHA1_NSEC3_SHA1:
		case DNS_KEYALG_RSASHA256:
		case DNS_KEYALG_RSASHA512:
			error = save_rsa_pkcs8(out_path, file_pin, pkey);
			break;
		case DNS_KEYALG_DSA:
		case DNS_KEYALG_DSA_NSEC3_SHA1:
			error = save_dsa_pkcs8(out_path, file_pin, pkey);
			break;
		case DNS_KEYALG_ECC:
		case DNS_KEYALG_ECC_GOST:
		default:
			fprintf(stderr, "ERROR: The algorithm %i is not supported.\n",
					algorithm);
			error = 1;
			break;
	}

	crypto_final();
	free_key_material(pkey);

	return error;
}

// Free allocated memory
void free_key_material(key_material_t *pkey)
{
	int i;

	if (!pkey)
	{
		return;
	}

	for (i = 0; i < TAG_MAX; i++)
	{
		if (pkey[i].big)
		{
			free(pkey[i].big);
		}
	}
}
<commit_msg>Fix version check<commit_after>/* $Id$ */

/*
 * Copyright (c) 2010 .SE (The Internet Infrastructure Foundation).
 * All rights reserved.
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions
 * are met:
 * 1. Redistributions of source code must retain the above copyright
 *    notice, this list of conditions and the following disclaimer.
 * 2. Redistributions in binary form must reproduce the above copyright
 *    notice, this list of conditions and the following disclaimer in the
 *    documentation and/or other materials provided with the distribution.
 *
 * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR
 * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
 * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
 * ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY
 * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE
 * GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
 * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER
 * IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR
 * OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN
 * IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
 */

/************************************************************
*
* softhsm-keyconv
*
* This program is for converting from BIND .private-key
* format to PKCS#8 key file format. So that keys can be
* imported from BIND to SoftHSM.
*
* Some of the design/code is from keyconv.c written by
* Hakan Olsson and Jakob Schlyter in 2000 and 2001.
*
************************************************************/

#include <config.h>
#include "softhsm-keyconv.h"

#include <stdio.h>
#include <stdlib.h>
#include <getopt.h>
#include <string.h>
#include <unistd.h>
#include <iostream>
#include <fstream>
#include <stdint.h>

void usage()
{
	printf("Converting from BIND .private-key format to PKCS#8 key file format.\n");
	printf("Usage: softhsm-keyconv [OPTIONS]\n");
	printf("Options:\n");
	printf("  -h                  Shows this help screen.\n");
	printf("  --help              Shows this help screen.\n");
	printf("  --in <path>         The path to the input file.\n");
	printf("  --out <path>        The path to the output file.\n");
	printf("  --pin <PIN>         To encrypt PKCS#8 file. Optional.\n");
	printf("  -v                  Show version info.\n");
	printf("  --version           Show version info.\n");
}

// Give a number to each option
enum {
	OPT_HELP = 0x100,
	OPT_IN,
	OPT_OUT,
	OPT_PIN,
	OPT_VERSION
};

// Define the options
static const struct option long_options[] = {
	{ "help",    0, NULL, OPT_HELP },
	{ "in",      1, NULL, OPT_IN },
	{ "out",     1, NULL, OPT_OUT },
	{ "pin",     1, NULL, OPT_PIN },
	{ "version", 0, NULL, OPT_VERSION },
	{ NULL,      0, NULL, 0 }
};

int main(int argc, char *argv[])
{
	int option_index = 0;
	int opt, result;

	char *in_path = NULL;
	char *out_path = NULL;
	char *file_pin = NULL;

	while ((opt = getopt_long(argc, argv, "hv", long_options, &option_index)) != -1)
	{
		switch (opt)
		{
			case OPT_IN:
				in_path = optarg;
				break;
			case OPT_OUT:
				out_path = optarg;
				break;
			case OPT_PIN:
				file_pin = optarg;
				break;
			case OPT_VERSION:
			case 'v':
				printf("%s\n", PACKAGE_VERSION);
				exit(0);
				break;
			case OPT_HELP:
			case 'h':
			default:
				usage();
				exit(0);
				break;
		}
	}

	// We should convert to PKCS#8
	result = to_pkcs8(in_path, out_path, file_pin);

	return result;
}

// Convert from BIND to PKCS#8
int to_pkcs8(char *in_path, char *out_path, char *file_pin)
{
	FILE *file_pointer = NULL;
	char line[MAX_LINE], data[MAX_LINE], *value_pointer;
	int lineno = 0, m, n, error = 0, found, algorithm = DNS_KEYALG_ERROR, data_length;
	uint32_t bitfield = 0;
	key_material_t pkey[TAG_MAX];

	if (in_path == NULL)
	{
		fprintf(stderr, "ERROR: A path to the input file must be supplied. Use --in <path>\n");
		return 1;
	}

	if (out_path == NULL)
	{
		fprintf(stderr, "ERROR: A path to the output file must be supplied. Use --out <path>\n");
		return 1;
	}

	file_pointer = fopen(in_path, "r");
	if (!file_pointer)
	{
		fprintf(stderr, "ERROR: Could not open input file %.100s for reading.\n", in_path);
		return 1;
	}

	// Loop over all of the lines
	while (fgets(line, MAX_LINE, file_pointer) != NULL)
	{
		lineno++;

		// Find the current text field in the BIND file.
		for (m = 0, found = -1; found == -1 && file_tags[m]; m++)
		{
			if (strncasecmp(line, file_tags[m], strlen(file_tags[m])) == 0)
			{
				found = m;
			}
		}

		// The text files is not recognized.
		if (found == -1)
		{
			fprintf(stderr, "ERROR: Unrecognized input line %i\n", lineno);
			fprintf(stderr, "ERROR: --> %s", line);
			continue;
		}

		// Point to the data for this text field.
		value_pointer = line + strlen(file_tags[found]) + 1;

		// Continue if we are at the end of the string
		if (*value_pointer == 0)
		{
			continue;
		}

		// Check that we do not get duplicates.
		if (bitfield & (1 << found))
		{
			fprintf(stderr, "ERROR: Duplicate \"%s\" field, line %i - ignored\n",
					file_tags[found], lineno);
			continue;
		}
		bitfield |= (1 << found);

		// Handle the data for this text field.
		switch (found)
		{
			case TAG_VERSION:
				if (sscanf(value_pointer, "v%i.%i", &m, &n) != 2)
				{
					fprintf(stderr, "ERROR: Invalid/unknown version string "
							"(%.100s).\n", value_pointer);
					error = 1;
					break;
				}
				if (m > FILE_MAJOR_VERSION || (m == FILE_MAJOR_VERSION && n > FILE_MINOR_VERSION))
				{
					fprintf(stderr, "ERROR: Cannot parse this version of file format, "
							"v%i.%i.\n", m, n);
					error = 1;
				}
				break;
			case TAG_ALGORITHM:
				algorithm = strtol(value_pointer, NULL, 10);
				break;
			// RSA
			case TAG_MODULUS:
			case TAG_PUBEXP:
			case TAG_PRIVEXP:
			case TAG_PRIME1:
			case TAG_PRIME2:
			case TAG_EXP1:
			case TAG_EXP2:
			case TAG_COEFF:
			// DSA
			case TAG_PRIME:
			case TAG_SUBPRIME:
			case TAG_BASE:
			case TAG_PRIVVAL:
			case TAG_PUBVAL:
				data_length = b64_pton(value_pointer, (unsigned char*)data, MAX_LINE);
				if (data_length == -1)
				{
					error = 1;
					fprintf(stderr, "ERROR: Could not parse the base64 string on line %i.\n", lineno);
				}
				else
				{
					pkey[found].big = malloc(data_length);
					if (!pkey[found].big)
					{
						fprintf(stderr, "ERROR: Could not allocate memory.\n");
						error = 1;
						break;
					}
					memcpy(pkey[found].big, data, data_length);
					pkey[found].size = data_length;
				}
				break;
			// Do not need these
			case TAG_CREATED:
			case TAG_PUBLISH:
			case TAG_ACTIVATE:
			default:
				break;
		}
	}

	fclose(file_pointer);

	// Something went wrong. Clean up and quit.
	if (error)
	{
		free_key_material(pkey);
		return error;
	}

	crypto_init();

	// Save the the key to the disk
	switch (algorithm)
	{
		case DNS_KEYALG_ERROR:
			fprintf(stderr, "ERROR: The algorithm was not given in the file.\n",
					algorithm);
			error = 1;
			break;
		case DNS_KEYALG_RSAMD5:
		case DNS_KEYALG_RSASHA1:
		case DNS_KEYALG_RSASHA1_NSEC3_SHA1:
		case DNS_KEYALG_RSASHA256:
		case DNS_KEYALG_RSASHA512:
			error = save_rsa_pkcs8(out_path, file_pin, pkey);
			break;
		case DNS_KEYALG_DSA:
		case DNS_KEYALG_DSA_NSEC3_SHA1:
			error = save_dsa_pkcs8(out_path, file_pin, pkey);
			break;
		case DNS_KEYALG_ECC:
		case DNS_KEYALG_ECC_GOST:
		default:
			fprintf(stderr, "ERROR: The algorithm %i is not supported.\n",
					algorithm);
			error = 1;
			break;
	}

	crypto_final();
	free_key_material(pkey);

	return error;
}

// Free allocated memory
void free_key_material(key_material_t *pkey)
{
	int i;

	if (!pkey)
	{
		return;
	}

	for (i = 0; i < TAG_MAX; i++)
	{
		if (pkey[i].big)
		{
			free(pkey[i].big);
		}
	}
}
<|endoftext|>


<commit_before>// Copyright (c) 2011 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

#include "chrome/service/net/service_url_request_context.h"

#if defined(OS_POSIX) && !defined(OS_MACOSX)
#include <sys/utsname.h>
#endif

#include "base/message_loop_proxy.h"
#include "base/string_util.h"
#include "base/sys_info.h"
#include "chrome/common/chrome_version_info.h"
#include "chrome/service/service_process.h"
#include "net/base/cert_verifier.h"
#include "net/base/cookie_monster.h"
#include "net/base/cookie_policy.h"
#include "net/base/dnsrr_resolver.h"
#include "net/base/host_resolver.h"
#include "net/base/ssl_config_service_defaults.h"
#include "net/ftp/ftp_network_layer.h"
#include "net/http/http_auth_handler_factory.h"
#include "net/http/http_cache.h"
#include "net/http/http_network_session.h"
#include "net/proxy/proxy_service.h"

namespace {
// Copied from webkit/glue/user_agent.cc. We don't want to pull in a dependency
// on webkit/glue which also pulls in the renderer. Also our user-agent is
// totally different from the user-agent used by the browser, just the
// OS-specific parts are common.
std::string BuildOSCpuInfo() {
  std::string os_cpu;

#if defined(OS_WIN) || defined(OS_MACOSX) || defined(OS_CHROMEOS)
  int32 os_major_version = 0;
  int32 os_minor_version = 0;
  int32 os_bugfix_version = 0;
  base::SysInfo::OperatingSystemVersionNumbers(&os_major_version,
                                               &os_minor_version,
                                               &os_bugfix_version);
#endif
#if defined(OS_POSIX) && !defined(OS_MACOSX)
  // Should work on any Posix system.
  struct utsname unixinfo;
  uname(&unixinfo);

  std::string cputype;
  // special case for biarch systems
  if (strcmp(unixinfo.machine, "x86_64") == 0 &&
      sizeof(void*) == sizeof(int32)) {  // NOLINT
    cputype.assign("i686 (x86_64)");
  } else {
    cputype.assign(unixinfo.machine);
  }
#endif

  base::StringAppendF(
      &os_cpu,
#if defined(OS_WIN)
      "Windows NT %d.%d",
      os_major_version,
      os_minor_version
#elif defined(OS_MACOSX)
      "Intel Mac OS X %d_%d_%d",
      os_major_version,
      os_minor_version,
      os_bugfix_version
#elif defined(OS_CHROMEOS)
      "CrOS %s %d.%d.%d",
      cputype.c_str(),  // e.g. i686
      os_major_version,
      os_minor_version,
      os_bugfix_version
#else
      "%s %s",
      unixinfo.sysname,  // e.g. Linux
      cputype.c_str()    // e.g. i686
#endif
  );  // NOLINT

  return os_cpu;
}

std::string MakeUserAgentForServiceProcess() {
  std::string user_agent;
  chrome::VersionInfo version_info;
  if (!version_info.is_valid()) {
    DLOG(ERROR) << "Unable to create chrome::VersionInfo object";
  }
  std::string extra_version_info;
  if (!version_info.IsOfficialBuild())
    extra_version_info = "-devel";
  base::StringAppendF(&user_agent,
                      "Chrome Service %s(%s)%s %s ",
                      version_info.Version().c_str(),
                      version_info.LastChange().c_str(),
                      extra_version_info.c_str(),
                      BuildOSCpuInfo().c_str());
  return user_agent;
}

}  // namespace

ServiceURLRequestContext::ServiceURLRequestContext(
    const std::string& user_agent,
    net::ProxyService* net_proxy_service) : user_agent_(user_agent) {
  set_host_resolver(
      net::CreateSystemHostResolver(net::HostResolver::kDefaultParallelism,
                                    NULL, NULL));
  set_proxy_service(net_proxy_service);
  set_cert_verifier(new net::CertVerifier);
  set_dnsrr_resolver(new net::DnsRRResolver);
  set_ftp_transaction_factory(new net::FtpNetworkLayer(host_resolver()));
  set_ssl_config_service(new net::SSLConfigServiceDefaults);
  set_http_auth_handler_factory(net::HttpAuthHandlerFactory::CreateDefault(
      host_resolver()));
  net::HttpNetworkSession::Params session_params;
  session_params.host_resolver = host_resolver();
  session_params.cert_verifier = cert_verifier();
  session_params.dnsrr_resolver = dnsrr_resolver();
  session_params.proxy_service = proxy_service();
  session_params.ssl_config_service = ssl_config_service();
  scoped_refptr<net::HttpNetworkSession> network_session(
      new net::HttpNetworkSession(session_params));
  set_http_transaction_factory(
      new net::HttpCache(
          network_session,
          net::HttpCache::DefaultBackend::InMemory(0)));
  // In-memory cookie store.
  set_cookie_store(new net::CookieMonster(NULL, NULL));
  set_accept_language("en-us,fr");
  set_accept_charset("iso-8859-1,*,utf-8");
}

const std::string& ServiceURLRequestContext::GetUserAgent(
    const GURL& url) const {
  // If the user agent is set explicitly return that, otherwise call the
  // base class method to return default value.
  return user_agent_.empty() ?
      net::URLRequestContext::GetUserAgent(url) : user_agent_;
}

ServiceURLRequestContext::~ServiceURLRequestContext() {
  delete ftp_transaction_factory();
  delete http_transaction_factory();
  delete http_auth_handler_factory();
  delete cert_verifier();
  delete dnsrr_resolver();
  delete host_resolver();
}

ServiceURLRequestContextGetter::ServiceURLRequestContextGetter()
    : io_message_loop_proxy_(
          g_service_process->io_thread()->message_loop_proxy()) {
  // Build the default user agent.
  user_agent_ = MakeUserAgentForServiceProcess();

#if defined(OS_LINUX)
  // Create the proxy service now, at initialization time, on the main thread,
  // only for Linux, which requires that.
  CreateProxyService();
#endif
}

net::URLRequestContext*
ServiceURLRequestContextGetter::GetURLRequestContext() {
#if !defined(OS_LINUX)
  if (!proxy_service_)
    CreateProxyService();
#endif
  if (!url_request_context_)
    url_request_context_ = new ServiceURLRequestContext(user_agent_,
                                                        proxy_service_);
  return url_request_context_;
}

scoped_refptr<base::MessageLoopProxy>
ServiceURLRequestContextGetter::GetIOMessageLoopProxy() const {
  return io_message_loop_proxy_;
}

ServiceURLRequestContextGetter::~ServiceURLRequestContextGetter() {}

void ServiceURLRequestContextGetter::CreateProxyService() {
  // TODO(sanjeevr): Change CreateSystemProxyConfigService to accept a
  // MessageLoopProxy* instead of MessageLoop*.
  DCHECK(g_service_process);
  net::ProxyConfigService * proxy_config_service =
      net::ProxyService::CreateSystemProxyConfigService(
          g_service_process->io_thread()->message_loop(),
          g_service_process->file_thread()->message_loop());
  proxy_service_ = net::ProxyService::CreateUsingSystemProxyResolver(
      proxy_config_service, 0u, NULL);
}
<commit_msg>Added the HttpAuthHandlerFactory pointer to the net::HttpNetworkSession::Params structure. This fixes the service process crash as seen here: http://crash/reportdetail?reportid=2e6994509abbee7b<commit_after>// Copyright (c) 2011 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

#include "chrome/service/net/service_url_request_context.h"

#if defined(OS_POSIX) && !defined(OS_MACOSX)
#include <sys/utsname.h>
#endif

#include "base/message_loop_proxy.h"
#include "base/string_util.h"
#include "base/sys_info.h"
#include "chrome/common/chrome_version_info.h"
#include "chrome/service/service_process.h"
#include "net/base/cert_verifier.h"
#include "net/base/cookie_monster.h"
#include "net/base/cookie_policy.h"
#include "net/base/dnsrr_resolver.h"
#include "net/base/host_resolver.h"
#include "net/base/ssl_config_service_defaults.h"
#include "net/ftp/ftp_network_layer.h"
#include "net/http/http_auth_handler_factory.h"
#include "net/http/http_cache.h"
#include "net/http/http_network_session.h"
#include "net/proxy/proxy_service.h"

namespace {
// Copied from webkit/glue/user_agent.cc. We don't want to pull in a dependency
// on webkit/glue which also pulls in the renderer. Also our user-agent is
// totally different from the user-agent used by the browser, just the
// OS-specific parts are common.
std::string BuildOSCpuInfo() {
  std::string os_cpu;

#if defined(OS_WIN) || defined(OS_MACOSX) || defined(OS_CHROMEOS)
  int32 os_major_version = 0;
  int32 os_minor_version = 0;
  int32 os_bugfix_version = 0;
  base::SysInfo::OperatingSystemVersionNumbers(&os_major_version,
                                               &os_minor_version,
                                               &os_bugfix_version);
#endif
#if defined(OS_POSIX) && !defined(OS_MACOSX)
  // Should work on any Posix system.
  struct utsname unixinfo;
  uname(&unixinfo);

  std::string cputype;
  // special case for biarch systems
  if (strcmp(unixinfo.machine, "x86_64") == 0 &&
      sizeof(void*) == sizeof(int32)) {  // NOLINT
    cputype.assign("i686 (x86_64)");
  } else {
    cputype.assign(unixinfo.machine);
  }
#endif

  base::StringAppendF(
      &os_cpu,
#if defined(OS_WIN)
      "Windows NT %d.%d",
      os_major_version,
      os_minor_version
#elif defined(OS_MACOSX)
      "Intel Mac OS X %d_%d_%d",
      os_major_version,
      os_minor_version,
      os_bugfix_version
#elif defined(OS_CHROMEOS)
      "CrOS %s %d.%d.%d",
      cputype.c_str(),  // e.g. i686
      os_major_version,
      os_minor_version,
      os_bugfix_version
#else
      "%s %s",
      unixinfo.sysname,  // e.g. Linux
      cputype.c_str()    // e.g. i686
#endif
  );  // NOLINT

  return os_cpu;
}

std::string MakeUserAgentForServiceProcess() {
  std::string user_agent;
  chrome::VersionInfo version_info;
  if (!version_info.is_valid()) {
    DLOG(ERROR) << "Unable to create chrome::VersionInfo object";
  }
  std::string extra_version_info;
  if (!version_info.IsOfficialBuild())
    extra_version_info = "-devel";
  base::StringAppendF(&user_agent,
                      "Chrome Service %s(%s)%s %s ",
                      version_info.Version().c_str(),
                      version_info.LastChange().c_str(),
                      extra_version_info.c_str(),
                      BuildOSCpuInfo().c_str());
  return user_agent;
}

}  // namespace

ServiceURLRequestContext::ServiceURLRequestContext(
    const std::string& user_agent,
    net::ProxyService* net_proxy_service) : user_agent_(user_agent) {
  set_host_resolver(
      net::CreateSystemHostResolver(net::HostResolver::kDefaultParallelism,
                                    NULL, NULL));
  set_proxy_service(net_proxy_service);
  set_cert_verifier(new net::CertVerifier);
  set_dnsrr_resolver(new net::DnsRRResolver);
  set_ftp_transaction_factory(new net::FtpNetworkLayer(host_resolver()));
  set_ssl_config_service(new net::SSLConfigServiceDefaults);
  set_http_auth_handler_factory(net::HttpAuthHandlerFactory::CreateDefault(
      host_resolver()));

  net::HttpNetworkSession::Params session_params;
  session_params.host_resolver = host_resolver();
  session_params.cert_verifier = cert_verifier();
  session_params.dnsrr_resolver = dnsrr_resolver();
  session_params.proxy_service = proxy_service();
  session_params.ssl_config_service = ssl_config_service();
  session_params.http_auth_handler_factory = http_auth_handler_factory();
  scoped_refptr<net::HttpNetworkSession> network_session(
      new net::HttpNetworkSession(session_params));
  set_http_transaction_factory(
      new net::HttpCache(
          network_session,
          net::HttpCache::DefaultBackend::InMemory(0)));
  // In-memory cookie store.
  set_cookie_store(new net::CookieMonster(NULL, NULL));
  set_accept_language("en-us,fr");
  set_accept_charset("iso-8859-1,*,utf-8");
}

const std::string& ServiceURLRequestContext::GetUserAgent(
    const GURL& url) const {
  // If the user agent is set explicitly return that, otherwise call the
  // base class method to return default value.
  return user_agent_.empty() ?
      net::URLRequestContext::GetUserAgent(url) : user_agent_;
}

ServiceURLRequestContext::~ServiceURLRequestContext() {
  delete ftp_transaction_factory();
  delete http_transaction_factory();
  delete http_auth_handler_factory();
  delete cert_verifier();
  delete dnsrr_resolver();
  delete host_resolver();
}

ServiceURLRequestContextGetter::ServiceURLRequestContextGetter()
    : io_message_loop_proxy_(
          g_service_process->io_thread()->message_loop_proxy()) {
  // Build the default user agent.
  user_agent_ = MakeUserAgentForServiceProcess();

#if defined(OS_LINUX)
  // Create the proxy service now, at initialization time, on the main thread,
  // only for Linux, which requires that.
  CreateProxyService();
#endif
}

net::URLRequestContext*
ServiceURLRequestContextGetter::GetURLRequestContext() {
#if !defined(OS_LINUX)
  if (!proxy_service_)
    CreateProxyService();
#endif
  if (!url_request_context_)
    url_request_context_ = new ServiceURLRequestContext(user_agent_,
                                                        proxy_service_);
  return url_request_context_;
}

scoped_refptr<base::MessageLoopProxy>
ServiceURLRequestContextGetter::GetIOMessageLoopProxy() const {
  return io_message_loop_proxy_;
}

ServiceURLRequestContextGetter::~ServiceURLRequestContextGetter() {}

void ServiceURLRequestContextGetter::CreateProxyService() {
  // TODO(sanjeevr): Change CreateSystemProxyConfigService to accept a
  // MessageLoopProxy* instead of MessageLoop*.
  DCHECK(g_service_process);
  net::ProxyConfigService * proxy_config_service =
      net::ProxyService::CreateSystemProxyConfigService(
          g_service_process->io_thread()->message_loop(),
          g_service_process->file_thread()->message_loop());
  proxy_service_ = net::ProxyService::CreateUsingSystemProxyResolver(
      proxy_config_service, 0u, NULL);
}
<|endoftext|>


<commit_before>/*
	Copyright 2014 Justin White
	See included LICENSE file for details.
*/

#include <iostream>
#include <fstream>

#include <cstdio>
#include <cmath>

using std::string;

#include <SFML/Config.hpp>
#include <SFML/Graphics.hpp>

#include "log4cpp/Category.hh"
#include "log4cpp/Appender.hh"
#include "log4cpp/FileAppender.hh"
#include "log4cpp/OstreamAppender.hh"
#include "log4cpp/Layout.hh"
#include "log4cpp/BasicLayout.hh"
#include "log4cpp/PatternLayout.hh"
#include "log4cpp/Priority.hh"

#include "GameSprite.h"

// short names for log4cpp Priorities;
const int DEBUG = log4cpp::Priority::DEBUG;
const int INFO = log4cpp::Priority::INFO;
const int WARN = log4cpp::Priority::WARN;
const int ERROR = log4cpp::Priority::ERROR;

//system data
const int version = 0;
const int revision = 1;
const int width = 1280;
const int height = 720;
const string title = "SpaceFight";
sf::RenderWindow* window;
string fileLogName = title + ".log";
log4cpp::Category& alog = log4cpp::Category::getRoot();
log4cpp::Category& clog = log4cpp::Category::getInstance("cons");
log4cpp::Category& flog = log4cpp::Category::getInstance("file");

// game data
const float deadZone = 15;
const float keySpeed = 75;
GameSprite* player;

// system functions
void initializeSystem();
void processEvents();
void updateControls();
void updateWorld(sf::Time);
void renderWorld();

void initializeSystem()
{
	window = new sf::RenderWindow(sf::VideoMode(width, height), title, sf::Style::Titlebar | sf::Style::Close);
	if(window->isOpen()) {
		sf::ContextSettings settings = window->getSettings();
		alog.info("Using OpenGL v%d.%d", settings.majorVersion, settings.minorVersion);
		alog.info("Created the main window %dx%d", width, height);
		window->setVerticalSyncEnabled(true);
		alog.info("Enabled VSync");
	} else {
		alog.error("Could not create main window");
		exit(EXIT_FAILURE);
	}
	window->setPosition(sf::Vector2i(100,100));

	player = new GameSprite(sf::Color::Blue);
	player->setPosition(width / 2, height / 2);
	alog.info("Loaded sprite");
}

void processEvents()
{
	static sf::Event event;

	while(window->pollEvent(event)) {
		switch(event.type) {
		case sf::Event::Closed:
			alog.info("Window closed");
			window->close();
			break;
		case sf::Event::KeyPressed:
			switch(event.key.code) {
			case sf::Keyboard::Escape:
				alog.info("Player exited");
				window->close();
				break;
			default:
				break;
			}
			break;
		case sf::Event::KeyReleased:
			switch(event.key.code) {
			default:
				break;
			}
			break;
		default:
			break;
		}
	}
}

void updateControls()
{
	float x, y = 0;

	float joy0_X = sf::Joystick::getAxisPosition(0, sf::Joystick::X);
	float joy0_y = sf::Joystick::getAxisPosition(0, sf::Joystick::Y);
	x = abs(joy0_X) < deadZone ? 0 : joy0_X;
	y = abs(joy0_y) < deadZone ? 0 : joy0_y;

	if(sf::Keyboard::isKeyPressed(sf::Keyboard::Up)) {
		y += -keySpeed;
	}
	if(sf::Keyboard::isKeyPressed(sf::Keyboard::Right)) {
		x += keySpeed;
	}
	if(sf::Keyboard::isKeyPressed(sf::Keyboard::Down)) {
		y += keySpeed;
	}
	if(sf::Keyboard::isKeyPressed(sf::Keyboard::Left)) {
		x += -keySpeed;
	}
	player->moveBy(x, y);
}

void updateWorld(sf::Time elapsed)
{
	const int millis = elapsed.asMilliseconds();
	player->update(millis);
}

void renderWorld()
{
	window->clear(sf::Color::Black);
	window->draw(*player);
	window->display();
}

int main()
{
	log4cpp::Category::setRootPriority(DEBUG);

	// console log: 'time priority message'
	log4cpp::PatternLayout* consLogLayout = new log4cpp::PatternLayout();
	consLogLayout->setConversionPattern("%d{%H:%M:%S,%l} %p %m%n");
	log4cpp::Appender* consLog = new log4cpp::OstreamAppender("cons", &std::clog);
	consLog->setLayout(consLogLayout);
	// show debug priority & above when debugging
#ifdef DO_DEBUG
	consLog->setThreshold(DEBUG);
#else
	// show only info priority & above normally
	consLog->setThreshold(INFO);
#endif

	// file log: 'date time priority message'
	log4cpp::PatternLayout* fileLogLayout = new log4cpp::PatternLayout();
	fileLogLayout->setConversionPattern("%d{%Y-%m-%d %H:%M:%S,%l} %p %m%n");
	log4cpp::Appender* fileLog = new log4cpp::FileAppender("file", fileLogName, false);
	fileLog->setLayout(fileLogLayout);
	// always show debug priority & above
	fileLog->setThreshold(DEBUG);

	alog.addAppender(consLog);
	alog.addAppender(fileLog);

	clog.addAppender(consLog);
	clog.setAdditivity(false);
	flog.addAppender(fileLog);
	flog.setAdditivity(false);

	flog << DEBUG << "Opened logFile " << fileLogName;

	alog.info("Spacefight v%d.%d", version, revision);
	alog.info("Built %s %s", __DATE__, __TIME__);
	alog.info("GCC %s", __VERSION__);
	alog.info("SFML %d.%d", SFML_VERSION_MAJOR, SFML_VERSION_MINOR);
	initializeSystem();
	sf::Clock gameClock;
	sf::Time elapsed;
	alog.info("Running...");
	while(window->isOpen()) {
		elapsed = gameClock.restart();
		processEvents();
		updateControls();
		updateWorld(elapsed);
		renderWorld();
	}
	alog.info("Stopped");

	flog << DEBUG << "Closed logFile " << fileLogName;
	fileLog->close();

	return EXIT_SUCCESS;
}
<commit_msg>Center the window, approximately.<commit_after>/*
	Copyright 2014 Justin White
	See included LICENSE file for details.
*/

#include <iostream>
#include <fstream>

#include <cstdio>
#include <cmath>

using std::string;

#include <SFML/Config.hpp>
#include <SFML/Graphics.hpp>

#include "log4cpp/Category.hh"
#include "log4cpp/Appender.hh"
#include "log4cpp/FileAppender.hh"
#include "log4cpp/OstreamAppender.hh"
#include "log4cpp/Layout.hh"
#include "log4cpp/BasicLayout.hh"
#include "log4cpp/PatternLayout.hh"
#include "log4cpp/Priority.hh"

#include "GameSprite.h"

// short names for log4cpp Priorities;
const int DEBUG = log4cpp::Priority::DEBUG;
const int INFO = log4cpp::Priority::INFO;
const int WARN = log4cpp::Priority::WARN;
const int ERROR = log4cpp::Priority::ERROR;

//system data
const int version = 0;
const int revision = 1;
const int width = 1280;
const int height = 720;
const string title = "SpaceFight";
sf::RenderWindow* window;
string fileLogName = title + ".log";
log4cpp::Category& alog = log4cpp::Category::getRoot();
log4cpp::Category& clog = log4cpp::Category::getInstance("cons");
log4cpp::Category& flog = log4cpp::Category::getInstance("file");

// game data
const float deadZone = 15;
const float keySpeed = 75;
GameSprite* player;

// system functions
void initializeSystem();
void processEvents();
void updateControls();
void updateWorld(sf::Time);
void renderWorld();

void initializeSystem()
{
	window = new sf::RenderWindow(sf::VideoMode(width, height), title, sf::Style::Titlebar | sf::Style::Close);
	if(window->isOpen()) {
		sf::ContextSettings settings = window->getSettings();
		alog.info("Using OpenGL v%d.%d", settings.majorVersion, settings.minorVersion);
		alog.info("Created the main window %dx%d", width, height);
		window->setVerticalSyncEnabled(true);
		alog.info("Enabled VSync");
		// center the window
		sf::VideoMode desktop = sf::VideoMode::getDesktopMode();
		int h = sf::VideoMode::getDesktopMode().height;
		window->setPosition(sf::Vector2i(
		                        desktop.width / 2 - width / 2,
		                        desktop.height / 2 - height / 2 - 36
		                    ));
	} else {
		alog.error("Could not create main window");
		exit(EXIT_FAILURE);
	}

	player = new GameSprite(sf::Color::Blue);
	player->setPosition(width / 2, height / 2);
	alog.info("Loaded sprite");
}

void processEvents()
{
	static sf::Event event;

	while(window->pollEvent(event)) {
		switch(event.type) {
		case sf::Event::Closed:
			alog.info("Window closed");
			window->close();
			break;
		case sf::Event::KeyPressed:
			switch(event.key.code) {
			case sf::Keyboard::Escape:
				alog.info("Player exited");
				window->close();
				break;
			default:
				break;
			}
			break;
		case sf::Event::KeyReleased:
			switch(event.key.code) {
			default:
				break;
			}
			break;
		default:
			break;
		}
	}
}

void updateControls()
{
	float x, y = 0;

	float joy0_X = sf::Joystick::getAxisPosition(0, sf::Joystick::X);
	float joy0_y = sf::Joystick::getAxisPosition(0, sf::Joystick::Y);
	x = abs(joy0_X) < deadZone ? 0 : joy0_X;
	y = abs(joy0_y) < deadZone ? 0 : joy0_y;

	if(sf::Keyboard::isKeyPressed(sf::Keyboard::Up)) {
		y += -keySpeed;
	}
	if(sf::Keyboard::isKeyPressed(sf::Keyboard::Right)) {
		x += keySpeed;
	}
	if(sf::Keyboard::isKeyPressed(sf::Keyboard::Down)) {
		y += keySpeed;
	}
	if(sf::Keyboard::isKeyPressed(sf::Keyboard::Left)) {
		x += -keySpeed;
	}
	player->moveBy(x, y);
}

void updateWorld(sf::Time elapsed)
{
	const int millis = elapsed.asMilliseconds();
	player->update(millis);
}

void renderWorld()
{
	window->clear(sf::Color::Black);
	window->draw(*player);
	window->display();
}

int main()
{
	log4cpp::Category::setRootPriority(DEBUG);

	// console log: 'time priority message'
	log4cpp::PatternLayout* consLogLayout = new log4cpp::PatternLayout();
	consLogLayout->setConversionPattern("%d{%H:%M:%S,%l} %p %m%n");
	log4cpp::Appender* consLog = new log4cpp::OstreamAppender("cons", &std::clog);
	consLog->setLayout(consLogLayout);
	// show debug priority & above when debugging
#ifdef DO_DEBUG
	consLog->setThreshold(DEBUG);
#else
	// show only info priority & above normally
	consLog->setThreshold(INFO);
#endif

	// file log: 'date time priority message'
	log4cpp::PatternLayout* fileLogLayout = new log4cpp::PatternLayout();
	fileLogLayout->setConversionPattern("%d{%Y-%m-%d %H:%M:%S,%l} %p %m%n");
	log4cpp::Appender* fileLog = new log4cpp::FileAppender("file", fileLogName, false);
	fileLog->setLayout(fileLogLayout);
	// always show debug priority & above
	fileLog->setThreshold(DEBUG);

	alog.addAppender(consLog);
	alog.addAppender(fileLog);

	clog.addAppender(consLog);
	clog.setAdditivity(false);
	flog.addAppender(fileLog);
	flog.setAdditivity(false);

	flog << DEBUG << "Opened logFile " << fileLogName;

	alog.info("Spacefight v%d.%d", version, revision);
	alog.info("Built %s %s", __DATE__, __TIME__);
	alog.info("GCC %s", __VERSION__);
	alog.info("SFML %d.%d", SFML_VERSION_MAJOR, SFML_VERSION_MINOR);
	initializeSystem();
	sf::Clock gameClock;
	sf::Time elapsed;
	alog.info("Running...");
	while(window->isOpen()) {
		elapsed = gameClock.restart();
		processEvents();
		updateControls();
		updateWorld(elapsed);
		renderWorld();
	}
	alog.info("Stopped");

	flog << DEBUG << "Closed logFile " << fileLogName;
	fileLog->close();

	return EXIT_SUCCESS;
}
<|endoftext|>


<commit_before>#include "cirkit_unit03_driver.hpp"

// dependency to ROS
#include <nav_msgs/Odometry.h> // odom

// dependency to Boost
#include <boost/thread.hpp>

// dependency to std
#include <iostream>
#include <stdexcept>

cirkit::CirkitUnit03Driver::CirkitUnit03Driver(const std::string& imcs01_port, const ros::NodeHandle& nh)
: nh_ {nh},
  rate_ {100},
  odom_pub_ {nh_.advertise<nav_msgs::Odometry>("/odom", 1)},
  steer_pub_ {nh_.advertise<geometry_msgs::Twist>("/steer_ctrl", 1)},
  cmd_vel_sub_ {nh_.subscribe<geometry_msgs::Twist>("/cmd_vel", 1, boost::bind(&cirkit::CirkitUnit03Driver::cmdVelReceived, this, _1))},
  cirkit_unit03_ {imcs01_port, 0},
  odom_broadcaster_ {},
  imcs01_port_ {imcs01_port},
  current_time_ {},
  last_time_ {},
  access_mutex_ {},
  steer_dir_ {}
{
  double pulse_rate {40.0};
  double geer_rate {33.0};
  double wheel_diameter_right {0.275};
  double wheel_diameter_left {0.275};
  double tred_width {0.595};
  ros::NodeHandle n {"~"};
  n.param("pulse_rate", pulse_rate, pulse_rate);
  n.param("geer_rate", geer_rate, geer_rate);
  n.param("wheel_diameter_right", wheel_diameter_right, wheel_diameter_right);
  n.param("wheel_diameter_left", wheel_diameter_left, wheel_diameter_left);
  n.param("tred_width", tred_width, tred_width);

  cirkit_unit03_.setParams(pulse_rate, geer_rate, wheel_diameter_right, wheel_diameter_left, tred_width);

  resetCommunication();
}

cirkit::CirkitUnit03Driver::~CirkitUnit03Driver() {
  cirkit_unit03_.closeSerialPort();
}

void cirkit::CirkitUnit03Driver::resetCommunication() {
  if (cirkit_unit03_.openSerialPort() == 0) {
    ROS_INFO("Connected to cirkit unit03.");
    cirkit_unit03_.driveDirect(0, 0);
  } else {
    ROS_FATAL("Could not connect to cirkit unit03.");
    throw std::runtime_error {"Could not connect to cirkit unit03"};
  }

  cirkit_unit03_.resetOdometry();
  cirkit_unit03_.setOdometry(0, 0, 0);
}

void cirkit::CirkitUnit03Driver::run() {
  double last_x, last_y, last_yaw;
  double vel_x, vel_y, vel_yaw;
  double dt;

  while (nh_.ok()) {
    current_time_ = ros::Time::now();
    last_x = cirkit_unit03_.odometry_x_;
    last_y = cirkit_unit03_.odometry_y_;
    last_yaw = cirkit_unit03_.odometry_yaw_;
    {
      boost::mutex::scoped_lock {access_mutex_}; // why use mutex?
      if (cirkit_unit03_.getEncoderPacket() == -1) ROS_ERROR("Could not retrieve encoder packet.");
      else cirkit_unit03_.calculateOdometry();
    }
    dt = (current_time_ - last_time_).toSec();
    vel_x = (cirkit_unit03_.odometry_x_ - last_x)/dt;
    vel_y = (cirkit_unit03_.odometry_y_ - last_y)/dt;
    vel_yaw = (cirkit_unit03_.odometry_yaw_ - last_yaw)/dt;

    geometry_msgs::Quaternion odom_quat {tf::createQuaternionMsgFromYaw(cirkit_unit03_.odometry_yaw_)};
    geometry_msgs::TransformStamped odom_trans;
    odom_trans.header.stamp = current_time_;
    odom_trans.header.frame_id = "odom";
    odom_trans.child_frame_id = "base_link";

    odom_trans.transform.translation.x = cirkit_unit03_.odometry_x_;
    odom_trans.transform.translation.y = cirkit_unit03_.odometry_y_;
    odom_trans.transform.translation.z = 0.0;
    odom_trans.transform.rotation = odom_quat;

    odom_broadcaster_.sendTransform(odom_trans);

    nav_msgs::Odometry odom;
    odom.header.stamp = current_time_;
    odom.header.frame_id = "odom";

    //set the position
    odom.pose.pose.position.x = cirkit_unit03_.odometry_x_;
    odom.pose.pose.position.y = cirkit_unit03_.odometry_y_;
    odom.pose.pose.position.z = 0.0;
    odom.pose.pose.orientation = odom_quat;

    //set the velocity
    odom.child_frame_id = "base_link";
    odom.twist.twist.linear.x = vel_x;
    odom.twist.twist.linear.y = vel_y;
    odom.twist.twist.angular.z = vel_yaw;

    //publish the message
    odom_pub_.publish(odom);

    ros::spinOnce();
    rate_.sleep();
  }
}

void cirkit::CirkitUnit03Driver::cmdVelReceived(const geometry_msgs::Twist::ConstPtr& cmd_vel) {
  {
    boost::mutex::scoped_lock {access_mutex_}; // why use mutex?
    steer_dir_ = cirkit_unit03_.drive(cmd_vel->linear.x, cmd_vel->angular.z);
  }
  steer_pub_.publish(steer_dir_);
}
<commit_msg>Refactor boost::bind (func obj) to method and this<commit_after>#include "cirkit_unit03_driver.hpp"

// dependency to ROS
#include <nav_msgs/Odometry.h> // odom

// dependency to Boost
#include <boost/thread.hpp>

// dependency to std
#include <iostream>
#include <stdexcept>

cirkit::CirkitUnit03Driver::CirkitUnit03Driver(const std::string& imcs01_port, const ros::NodeHandle& nh)
: nh_ {nh},
  rate_ {100},
  odom_pub_ {nh_.advertise<nav_msgs::Odometry>("/odom", 1)},
  steer_pub_ {nh_.advertise<geometry_msgs::Twist>("/steer_ctrl", 1)},
  cmd_vel_sub_ {nh_.subscribe<geometry_msgs::Twist>("/cmd_vel", 1, &cirkit::CirkitUnit03Driver::cmdVelReceived, this)},
  cirkit_unit03_ {imcs01_port, 0},
  odom_broadcaster_ {},
  imcs01_port_ {imcs01_port},
  current_time_ {},
  last_time_ {},
  access_mutex_ {},
  steer_dir_ {}
{
  double pulse_rate {40.0};
  double geer_rate {33.0};
  double wheel_diameter_right {0.275};
  double wheel_diameter_left {0.275};
  double tred_width {0.595};
  ros::NodeHandle n {"~"};
  n.param("pulse_rate", pulse_rate, pulse_rate);
  n.param("geer_rate", geer_rate, geer_rate);
  n.param("wheel_diameter_right", wheel_diameter_right, wheel_diameter_right);
  n.param("wheel_diameter_left", wheel_diameter_left, wheel_diameter_left);
  n.param("tred_width", tred_width, tred_width);

  cirkit_unit03_.setParams(pulse_rate, geer_rate, wheel_diameter_right, wheel_diameter_left, tred_width);

  resetCommunication();
}

cirkit::CirkitUnit03Driver::~CirkitUnit03Driver() {
  cirkit_unit03_.closeSerialPort();
}

void cirkit::CirkitUnit03Driver::resetCommunication() {
  if (cirkit_unit03_.openSerialPort() == 0) {
    ROS_INFO("Connected to cirkit unit03.");
    cirkit_unit03_.driveDirect(0, 0);
  } else {
    ROS_FATAL("Could not connect to cirkit unit03.");
    throw std::runtime_error {"Could not connect to cirkit unit03"};
  }

  cirkit_unit03_.resetOdometry();
  cirkit_unit03_.setOdometry(0, 0, 0);
}

void cirkit::CirkitUnit03Driver::run() {
  double last_x, last_y, last_yaw;
  double vel_x, vel_y, vel_yaw;
  double dt;

  while (nh_.ok()) {
    current_time_ = ros::Time::now();
    last_x = cirkit_unit03_.odometry_x_;
    last_y = cirkit_unit03_.odometry_y_;
    last_yaw = cirkit_unit03_.odometry_yaw_;
    {
      boost::mutex::scoped_lock {access_mutex_}; // why use mutex?
      if (cirkit_unit03_.getEncoderPacket() == -1) ROS_ERROR("Could not retrieve encoder packet.");
      else cirkit_unit03_.calculateOdometry();
    }
    dt = (current_time_ - last_time_).toSec();
    vel_x = (cirkit_unit03_.odometry_x_ - last_x)/dt;
    vel_y = (cirkit_unit03_.odometry_y_ - last_y)/dt;
    vel_yaw = (cirkit_unit03_.odometry_yaw_ - last_yaw)/dt;

    geometry_msgs::Quaternion odom_quat {tf::createQuaternionMsgFromYaw(cirkit_unit03_.odometry_yaw_)};
    geometry_msgs::TransformStamped odom_trans;
    odom_trans.header.stamp = current_time_;
    odom_trans.header.frame_id = "odom";
    odom_trans.child_frame_id = "base_link";

    odom_trans.transform.translation.x = cirkit_unit03_.odometry_x_;
    odom_trans.transform.translation.y = cirkit_unit03_.odometry_y_;
    odom_trans.transform.translation.z = 0.0;
    odom_trans.transform.rotation = odom_quat;

    odom_broadcaster_.sendTransform(odom_trans);

    nav_msgs::Odometry odom;
    odom.header.stamp = current_time_;
    odom.header.frame_id = "odom";

    //set the position
    odom.pose.pose.position.x = cirkit_unit03_.odometry_x_;
    odom.pose.pose.position.y = cirkit_unit03_.odometry_y_;
    odom.pose.pose.position.z = 0.0;
    odom.pose.pose.orientation = odom_quat;

    //set the velocity
    odom.child_frame_id = "base_link";
    odom.twist.twist.linear.x = vel_x;
    odom.twist.twist.linear.y = vel_y;
    odom.twist.twist.angular.z = vel_yaw;

    //publish the message
    odom_pub_.publish(odom);

    ros::spinOnce();
    rate_.sleep();
  }
}

void cirkit::CirkitUnit03Driver::cmdVelReceived(const geometry_msgs::Twist::ConstPtr& cmd_vel) {
  {
    boost::mutex::scoped_lock {access_mutex_}; // why use mutex?
    steer_dir_ = cirkit_unit03_.drive(cmd_vel->linear.x, cmd_vel->angular.z);
  }
  steer_pub_.publish(steer_dir_);
}
<|endoftext|>