<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/file_path.h"
#include "chrome/browser/browser_list.h"
#include "chrome/browser/defaults.h"
#include "chrome/browser/profiles/profile.h"
#include "chrome/browser/sessions/tab_restore_service.h"
#include "chrome/browser/tabs/tab_strip_model.h"
#include "chrome/browser/ui/browser.h"
#include "chrome/browser/ui/browser_list.h"
#include "chrome/browser/ui/browser_window.h"
#include "chrome/test/in_process_browser_test.h"
#include "chrome/test/ui_test_utils.h"
#include "content/browser/tab_contents/tab_contents.h"
#include "content/common/page_transition_types.h"

namespace {

// BrowserList::Observer implementation that waits for a browser to be
// removed.
class BrowserListObserverImpl : public BrowserList::Observer {
 public:
  BrowserListObserverImpl() : did_remove_(false), running_(false) {
    BrowserList::AddObserver(this);
  }

  ~BrowserListObserverImpl() {
    BrowserList::RemoveObserver(this);
  }

  // Returns when a browser has been removed.
  void Run() {
    running_ = true;
    if (!did_remove_)
      ui_test_utils::RunMessageLoop();
  }

  // BrowserList::Observer
  virtual void OnBrowserAdded(const Browser* browser) OVERRIDE {
  }
  virtual void OnBrowserRemoved(const Browser* browser) OVERRIDE {
    did_remove_ = true;
    if (running_)
      MessageLoop::current()->Quit();
  }

 private:
  // Was OnBrowserRemoved invoked?
  bool did_remove_;

  // Was Run invoked?
  bool running_;

  DISALLOW_COPY_AND_ASSIGN(BrowserListObserverImpl);
};

}  // namespace

typedef InProcessBrowserTest SessionRestoreTest;

#if defined(OS_LINUX) && defined(TOOLKIT_VIEWS)
// Crashes on Linux Views: http://crbug.com/39476
#define MAYBE_RestoreOnNewWindowWithNoTabbedBrowsers \
        DISABLED_RestoreOnNewWindowWithNoTabbedBrowsers
#else
#define MAYBE_RestoreOnNewWindowWithNoTabbedBrowsers \
        RestoreOnNewWindowWithNoTabbedBrowsers
#endif

// Makes sure when session restore is triggered in the same process we don't end
// up with an extra tab.
IN_PROC_BROWSER_TEST_F(SessionRestoreTest,
                       MAYBE_RestoreOnNewWindowWithNoTabbedBrowsers) {
  if (browser_defaults::kRestorePopups)
    return;

  const FilePath::CharType* kTitle1File = FILE_PATH_LITERAL("title1.html");
  GURL url(ui_test_utils::GetTestUrl(FilePath(FilePath::kCurrentDirectory),
                                     FilePath(kTitle1File)));
  ui_test_utils::NavigateToURL(browser(), url);

  // Turn on session restore.
  SessionStartupPref::SetStartupPref(
      browser()->profile(),
      SessionStartupPref(SessionStartupPref::LAST));

  // Create a new popup.
  Profile* profile = browser()->profile();
  Browser* popup = Browser::CreateForType(Browser::TYPE_POPUP, profile);
  popup->window()->Show();

  // Close the browser.
  browser()->window()->Close();

  // Create a new window, which should trigger session restore.
  popup->NewWindow();

  Browser* new_browser = ui_test_utils::WaitForNewBrowser();

  ASSERT_TRUE(new_browser != NULL);

  // The browser should only have one tab.
  ASSERT_EQ(1, new_browser->tab_count());

  // And the first url should be url.
  EXPECT_EQ(url, new_browser->GetTabContentsAt(0)->GetURL());
}

IN_PROC_BROWSER_TEST_F(SessionRestoreTest, RestoreIndividualTabFromWindow) {
  GURL url1(ui_test_utils::GetTestUrl(
      FilePath(FilePath::kCurrentDirectory),
      FilePath(FILE_PATH_LITERAL("title1.html"))));
  GURL url2(ui_test_utils::GetTestUrl(
      FilePath(FilePath::kCurrentDirectory),
      FilePath(FILE_PATH_LITERAL("title2.html"))));
  GURL url3(ui_test_utils::GetTestUrl(
      FilePath(FilePath::kCurrentDirectory),
      FilePath(FILE_PATH_LITERAL("title3.html"))));

  // Add and navigate three tabs.
  ui_test_utils::NavigateToURL(browser(), url1);
  browser()->AddSelectedTabWithURL(url2, PageTransition::LINK);
  ui_test_utils::WaitForNavigationInCurrentTab(browser());

  browser()->AddSelectedTabWithURL(url3, PageTransition::LINK);
  ui_test_utils::WaitForNavigationInCurrentTab(browser());

  TabRestoreService* service = browser()->profile()->GetTabRestoreService();
  service->ClearEntries();

  browser()->window()->Close();

  // Expect a window with three tabs.
  EXPECT_EQ(1U, service->entries().size());
  ASSERT_EQ(TabRestoreService::WINDOW, service->entries().front()->type);
  const TabRestoreService::Window* window =
      static_cast<TabRestoreService::Window*>(service->entries().front());
  EXPECT_EQ(3U, window->tabs.size());

  // Find the SessionID for entry2. Since the session service was destroyed,
  // there is no guarantee that the SessionID for the tab has remained the same.
  std::vector<TabRestoreService::Tab>::const_iterator it = window->tabs.begin();
  for ( ; it != window->tabs.end(); ++it) {
    const TabRestoreService::Tab& tab = *it;
    // If this tab held url2, then restore this single tab.
    if (tab.navigations[0].virtual_url() == url2) {
      service->RestoreEntryById(NULL, tab.id, false);
      break;
    }
  }

  // Make sure that the Window got updated.
  EXPECT_EQ(1U, service->entries().size());
  ASSERT_EQ(TabRestoreService::WINDOW, service->entries().front()->type);
  window = static_cast<TabRestoreService::Window*>(service->entries().front());
  EXPECT_EQ(2U, window->tabs.size());
}

IN_PROC_BROWSER_TEST_F(SessionRestoreTest, WindowWithOneTab) {
  GURL url(ui_test_utils::GetTestUrl(
      FilePath(FilePath::kCurrentDirectory),
      FilePath(FILE_PATH_LITERAL("title1.html"))));

  // Add a single tab.
  ui_test_utils::NavigateToURL(browser(), url);

  TabRestoreService* service = browser()->profile()->GetTabRestoreService();
  service->ClearEntries();
  EXPECT_EQ(0U, service->entries().size());

  // Close the window.
  browser()->window()->Close();

  // Expect the window to be converted to a tab by the TRS.
  EXPECT_EQ(1U, service->entries().size());
  ASSERT_EQ(TabRestoreService::TAB, service->entries().front()->type);
  const TabRestoreService::Tab* tab =
      static_cast<TabRestoreService::Tab*>(service->entries().front());

  // Restore the tab.
  service->RestoreEntryById(NULL, tab->id, false);

  // Make sure the restore was successful.
  EXPECT_EQ(0U, service->entries().size());
}

// Verifies we remember the last browser window when closing the last
// non-incognito window while an incognito window is open.
IN_PROC_BROWSER_TEST_F(SessionRestoreTest, IncognitotoNonIncognito) {
  // Turn on session restore.
  SessionStartupPref pref(SessionStartupPref::LAST);
  SessionStartupPref::SetStartupPref(browser()->profile(), pref);

  GURL url(ui_test_utils::GetTestUrl(
      FilePath(FilePath::kCurrentDirectory),
      FilePath(FILE_PATH_LITERAL("title1.html"))));

  // Add a single tab.
  ui_test_utils::NavigateToURL(browser(), url);

  // Create a new incognito window.
  Browser* incognito_browser = CreateIncognitoBrowser();
  incognito_browser->AddBlankTab(true);
  incognito_browser->window()->Show();

  // Close the normal browser. After this we only have the incognito window
  // open. We wait until the window closes as window closing is async.
  {
    BrowserListObserverImpl observer;
    browser()->window()->Close();
    observer.Run();
  }

  // Create a new window, which should trigger session restore.
  incognito_browser->NewWindow();

  // The first tab should have 'url' as its url.
  Browser* new_browser = ui_test_utils::WaitForNewBrowser();
  ASSERT_TRUE(new_browser);
  EXPECT_EQ(url, new_browser->GetTabContentsAt(0)->GetURL());
}
<commit_msg>Fix header include for reals.<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/file_path.h"
#include "chrome/browser/defaults.h"
#include "chrome/browser/profiles/profile.h"
#include "chrome/browser/sessions/tab_restore_service.h"
#include "chrome/browser/tabs/tab_strip_model.h"
#include "chrome/browser/ui/browser.h"
#include "chrome/browser/ui/browser_list.h"
#include "chrome/browser/ui/browser_window.h"
#include "chrome/test/in_process_browser_test.h"
#include "chrome/test/ui_test_utils.h"
#include "content/browser/tab_contents/tab_contents.h"
#include "content/common/page_transition_types.h"

namespace {

// BrowserList::Observer implementation that waits for a browser to be
// removed.
class BrowserListObserverImpl : public BrowserList::Observer {
 public:
  BrowserListObserverImpl() : did_remove_(false), running_(false) {
    BrowserList::AddObserver(this);
  }

  ~BrowserListObserverImpl() {
    BrowserList::RemoveObserver(this);
  }

  // Returns when a browser has been removed.
  void Run() {
    running_ = true;
    if (!did_remove_)
      ui_test_utils::RunMessageLoop();
  }

  // BrowserList::Observer
  virtual void OnBrowserAdded(const Browser* browser) OVERRIDE {
  }
  virtual void OnBrowserRemoved(const Browser* browser) OVERRIDE {
    did_remove_ = true;
    if (running_)
      MessageLoop::current()->Quit();
  }

 private:
  // Was OnBrowserRemoved invoked?
  bool did_remove_;

  // Was Run invoked?
  bool running_;

  DISALLOW_COPY_AND_ASSIGN(BrowserListObserverImpl);
};

}  // namespace

typedef InProcessBrowserTest SessionRestoreTest;

#if defined(OS_LINUX) && defined(TOOLKIT_VIEWS)
// Crashes on Linux Views: http://crbug.com/39476
#define MAYBE_RestoreOnNewWindowWithNoTabbedBrowsers \
        DISABLED_RestoreOnNewWindowWithNoTabbedBrowsers
#else
#define MAYBE_RestoreOnNewWindowWithNoTabbedBrowsers \
        RestoreOnNewWindowWithNoTabbedBrowsers
#endif

// Makes sure when session restore is triggered in the same process we don't end
// up with an extra tab.
IN_PROC_BROWSER_TEST_F(SessionRestoreTest,
                       MAYBE_RestoreOnNewWindowWithNoTabbedBrowsers) {
  if (browser_defaults::kRestorePopups)
    return;

  const FilePath::CharType* kTitle1File = FILE_PATH_LITERAL("title1.html");
  GURL url(ui_test_utils::GetTestUrl(FilePath(FilePath::kCurrentDirectory),
                                     FilePath(kTitle1File)));
  ui_test_utils::NavigateToURL(browser(), url);

  // Turn on session restore.
  SessionStartupPref::SetStartupPref(
      browser()->profile(),
      SessionStartupPref(SessionStartupPref::LAST));

  // Create a new popup.
  Profile* profile = browser()->profile();
  Browser* popup = Browser::CreateForType(Browser::TYPE_POPUP, profile);
  popup->window()->Show();

  // Close the browser.
  browser()->window()->Close();

  // Create a new window, which should trigger session restore.
  popup->NewWindow();

  Browser* new_browser = ui_test_utils::WaitForNewBrowser();

  ASSERT_TRUE(new_browser != NULL);

  // The browser should only have one tab.
  ASSERT_EQ(1, new_browser->tab_count());

  // And the first url should be url.
  EXPECT_EQ(url, new_browser->GetTabContentsAt(0)->GetURL());
}

IN_PROC_BROWSER_TEST_F(SessionRestoreTest, RestoreIndividualTabFromWindow) {
  GURL url1(ui_test_utils::GetTestUrl(
      FilePath(FilePath::kCurrentDirectory),
      FilePath(FILE_PATH_LITERAL("title1.html"))));
  GURL url2(ui_test_utils::GetTestUrl(
      FilePath(FilePath::kCurrentDirectory),
      FilePath(FILE_PATH_LITERAL("title2.html"))));
  GURL url3(ui_test_utils::GetTestUrl(
      FilePath(FilePath::kCurrentDirectory),
      FilePath(FILE_PATH_LITERAL("title3.html"))));

  // Add and navigate three tabs.
  ui_test_utils::NavigateToURL(browser(), url1);
  browser()->AddSelectedTabWithURL(url2, PageTransition::LINK);
  ui_test_utils::WaitForNavigationInCurrentTab(browser());

  browser()->AddSelectedTabWithURL(url3, PageTransition::LINK);
  ui_test_utils::WaitForNavigationInCurrentTab(browser());

  TabRestoreService* service = browser()->profile()->GetTabRestoreService();
  service->ClearEntries();

  browser()->window()->Close();

  // Expect a window with three tabs.
  EXPECT_EQ(1U, service->entries().size());
  ASSERT_EQ(TabRestoreService::WINDOW, service->entries().front()->type);
  const TabRestoreService::Window* window =
      static_cast<TabRestoreService::Window*>(service->entries().front());
  EXPECT_EQ(3U, window->tabs.size());

  // Find the SessionID for entry2. Since the session service was destroyed,
  // there is no guarantee that the SessionID for the tab has remained the same.
  std::vector<TabRestoreService::Tab>::const_iterator it = window->tabs.begin();
  for ( ; it != window->tabs.end(); ++it) {
    const TabRestoreService::Tab& tab = *it;
    // If this tab held url2, then restore this single tab.
    if (tab.navigations[0].virtual_url() == url2) {
      service->RestoreEntryById(NULL, tab.id, false);
      break;
    }
  }

  // Make sure that the Window got updated.
  EXPECT_EQ(1U, service->entries().size());
  ASSERT_EQ(TabRestoreService::WINDOW, service->entries().front()->type);
  window = static_cast<TabRestoreService::Window*>(service->entries().front());
  EXPECT_EQ(2U, window->tabs.size());
}

IN_PROC_BROWSER_TEST_F(SessionRestoreTest, WindowWithOneTab) {
  GURL url(ui_test_utils::GetTestUrl(
      FilePath(FilePath::kCurrentDirectory),
      FilePath(FILE_PATH_LITERAL("title1.html"))));

  // Add a single tab.
  ui_test_utils::NavigateToURL(browser(), url);

  TabRestoreService* service = browser()->profile()->GetTabRestoreService();
  service->ClearEntries();
  EXPECT_EQ(0U, service->entries().size());

  // Close the window.
  browser()->window()->Close();

  // Expect the window to be converted to a tab by the TRS.
  EXPECT_EQ(1U, service->entries().size());
  ASSERT_EQ(TabRestoreService::TAB, service->entries().front()->type);
  const TabRestoreService::Tab* tab =
      static_cast<TabRestoreService::Tab*>(service->entries().front());

  // Restore the tab.
  service->RestoreEntryById(NULL, tab->id, false);

  // Make sure the restore was successful.
  EXPECT_EQ(0U, service->entries().size());
}

// Verifies we remember the last browser window when closing the last
// non-incognito window while an incognito window is open.
IN_PROC_BROWSER_TEST_F(SessionRestoreTest, IncognitotoNonIncognito) {
  // Turn on session restore.
  SessionStartupPref pref(SessionStartupPref::LAST);
  SessionStartupPref::SetStartupPref(browser()->profile(), pref);

  GURL url(ui_test_utils::GetTestUrl(
      FilePath(FilePath::kCurrentDirectory),
      FilePath(FILE_PATH_LITERAL("title1.html"))));

  // Add a single tab.
  ui_test_utils::NavigateToURL(browser(), url);

  // Create a new incognito window.
  Browser* incognito_browser = CreateIncognitoBrowser();
  incognito_browser->AddBlankTab(true);
  incognito_browser->window()->Show();

  // Close the normal browser. After this we only have the incognito window
  // open. We wait until the window closes as window closing is async.
  {
    BrowserListObserverImpl observer;
    browser()->window()->Close();
    observer.Run();
  }

  // Create a new window, which should trigger session restore.
  incognito_browser->NewWindow();

  // The first tab should have 'url' as its url.
  Browser* new_browser = ui_test_utils::WaitForNewBrowser();
  ASSERT_TRUE(new_browser);
  EXPECT_EQ(url, new_browser->GetTabContentsAt(0)->GetURL());
}
<|endoftext|>


<commit_before>// Copyright (c) 2010 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/browser/tab_contents/tab_contents_ssl_helper.h"

#include "app/l10n_util.h"
#include "app/resource_bundle.h"
#include "base/basictypes.h"
#include "base/string_number_conversions.h"
#include "base/utf_string_conversions.h"
#include "chrome/browser/certificate_viewer.h"
#include "chrome/browser/ssl/ssl_add_cert_handler.h"
#include "chrome/browser/ssl/ssl_client_auth_handler.h"
#include "chrome/browser/ssl_client_certificate_selector.h"
#include "chrome/browser/tab_contents/infobar_delegate.h"
#include "chrome/browser/tab_contents/tab_contents.h"
#include "chrome/common/notification_service.h"
#include "grit/generated_resources.h"
#include "grit/theme_resources.h"
#include "net/base/net_errors.h"

namespace {

SkBitmap* GetCertIcon() {
  // TODO(davidben): use a more appropriate icon.
  return ResourceBundle::GetSharedInstance().GetBitmapNamed(
      IDR_INFOBAR_SAVE_PASSWORD);
}

class SSLCertAddedInfoBarDelegate : public ConfirmInfoBarDelegate {
 public:
  SSLCertAddedInfoBarDelegate(TabContents* tab_contents,
                              net::X509Certificate* cert)
      : ConfirmInfoBarDelegate(tab_contents),
        tab_contents_(tab_contents),
        cert_(cert) {
  }

  virtual ~SSLCertAddedInfoBarDelegate() {
  }

  // Overridden from ConfirmInfoBarDelegate:
  virtual string16 GetMessageText() const {
    // TODO(evanm): GetDisplayName should return UTF-16.
    return l10n_util::GetStringFUTF16(
        IDS_ADD_CERT_SUCCESS_INFOBAR_LABEL,
        UTF8ToUTF16(cert_->issuer().GetDisplayName()));
  }

  virtual SkBitmap* GetIcon() const {
    return GetCertIcon();
  }

  virtual int GetButtons() const {
    return BUTTON_OK;
  }

  virtual string16 GetButtonLabel(InfoBarButton button) const {
    switch (button) {
      case BUTTON_OK:
        return l10n_util::GetStringUTF16(IDS_ADD_CERT_SUCCESS_INFOBAR_BUTTON);
      default:
        return string16();
    }
  }

  virtual Type GetInfoBarType() {
    return PAGE_ACTION_TYPE;
  }

  virtual bool Accept() {
    ShowCertificateViewer(tab_contents_->GetMessageBoxRootWindow(), cert_);
    return false;  // Hiding the infobar just as the dialog opens looks weird.
  }

  virtual void InfoBarClosed() {
    // ConfirmInfoBarDelegate doesn't delete itself.
    delete this;
  }

 private:
  // The TabContents we are attached to
  TabContents* tab_contents_;
  // The cert we added.
  scoped_refptr<net::X509Certificate> cert_;
};

}  // namespace

class TabContentsSSLHelper::SSLAddCertData : public NotificationObserver {
 public:
  SSLAddCertData(TabContents* tab, SSLAddCertHandler* handler)
      : tab_(tab),
        handler_(handler),
        infobar_delegate_(NULL) {
    // Listen for disappearing InfoBars.
    Source<TabContents> tc_source(tab_);
    registrar_.Add(this, NotificationType::TAB_CONTENTS_INFOBAR_REMOVED,
                   tc_source);
    registrar_.Add(this, NotificationType::TAB_CONTENTS_INFOBAR_REPLACED,
                   tc_source);
  }
  ~SSLAddCertData() {}

  // Displays |delegate| as an infobar in |tab_|, replacing our current one if
  // still active.
  void ShowInfoBar(InfoBarDelegate* delegate) {
    if (infobar_delegate_) {
      tab_->ReplaceInfoBar(infobar_delegate_, delegate);
    } else {
      tab_->AddInfoBar(delegate);
    }
    infobar_delegate_ = delegate;
  }

  void ShowErrorInfoBar(const std::wstring& message) {
    ShowInfoBar(
        new SimpleAlertInfoBarDelegate(tab_,
                                       WideToUTF16(message),
                                       GetCertIcon(),
                                       true));
  }

  // NotificationObserver implementation.
  virtual void Observe(NotificationType type,
                       const NotificationSource& source,
                       const NotificationDetails& details) {
    switch (type.value) {
      case NotificationType::TAB_CONTENTS_INFOBAR_REMOVED:
        InfoBarClosed(Details<InfoBarDelegate>(details).ptr());
        break;
      case NotificationType::TAB_CONTENTS_INFOBAR_REPLACED:
        typedef std::pair<InfoBarDelegate*, InfoBarDelegate*>
            InfoBarDelegatePair;
        InfoBarClosed(Details<InfoBarDelegatePair>(details).ptr()->first);
        break;
      default:
        NOTREACHED();
        break;
    }
  }

 private:
  void InfoBarClosed(InfoBarDelegate* delegate) {
    if (infobar_delegate_ == delegate)
      infobar_delegate_ = NULL;
  }

  // The TabContents we are attached to.
  TabContents* tab_;
  // The handler we call back to.
  scoped_refptr<SSLAddCertHandler> handler_;
  // The current InfoBarDelegate we're displaying.
  InfoBarDelegate* infobar_delegate_;

  NotificationRegistrar registrar_;

  DISALLOW_COPY_AND_ASSIGN(SSLAddCertData);
};

TabContentsSSLHelper::TabContentsSSLHelper(TabContents* tab_contents)
    : tab_contents_(tab_contents) {
}

TabContentsSSLHelper::~TabContentsSSLHelper() {
}

void TabContentsSSLHelper::ShowClientCertificateRequestDialog(
    scoped_refptr<SSLClientAuthHandler> handler) {
  browser::ShowSSLClientCertificateSelector(
      tab_contents_, handler->cert_request_info(), handler);
}

void TabContentsSSLHelper::OnVerifyClientCertificateError(
    scoped_refptr<SSLAddCertHandler> handler, int error_code) {
  SSLAddCertData* add_cert_data = GetAddCertData(handler);
  // Display an infobar with the error message.
  // TODO(davidben): Display a more user-friendly error string.
  add_cert_data->ShowErrorInfoBar(
      l10n_util::GetStringF(IDS_ADD_CERT_ERR_INVALID_CERT,
                            UTF8ToWide(base::IntToString(-error_code)),
                            ASCIIToWide(net::ErrorToString(error_code))));
}

void TabContentsSSLHelper::AskToAddClientCertificate(
    scoped_refptr<SSLAddCertHandler> handler) {
  NOTREACHED();  // Not implemented yet.
}

void TabContentsSSLHelper::OnAddClientCertificateSuccess(
    scoped_refptr<SSLAddCertHandler> handler) {
  SSLAddCertData* add_cert_data = GetAddCertData(handler);
  // Display an infobar to inform the user.
  add_cert_data->ShowInfoBar(
      new SSLCertAddedInfoBarDelegate(tab_contents_, handler->cert()));
}

void TabContentsSSLHelper::OnAddClientCertificateError(
    scoped_refptr<SSLAddCertHandler> handler, int error_code) {
  SSLAddCertData* add_cert_data = GetAddCertData(handler);
  // Display an infobar with the error message.
  // TODO(davidben): Display a more user-friendly error string.
  add_cert_data->ShowErrorInfoBar(
      l10n_util::GetStringF(IDS_ADD_CERT_ERR_FAILED,
                            UTF8ToWide(base::IntToString(-error_code)),
                            ASCIIToWide(net::ErrorToString(error_code))));
}

void TabContentsSSLHelper::OnAddClientCertificateFinished(
    scoped_refptr<SSLAddCertHandler> handler) {
  // Clean up.
  request_id_to_add_cert_data_.erase(handler->network_request_id());
}

TabContentsSSLHelper::SSLAddCertData* TabContentsSSLHelper::GetAddCertData(
    SSLAddCertHandler* handler) {
  // Find/create the slot.
  linked_ptr<SSLAddCertData>& ptr_ref =
      request_id_to_add_cert_data_[handler->network_request_id()];
  // Fill it if necessary.
  if (!ptr_ref.get())
    ptr_ref.reset(new SSLAddCertData(tab_contents_, handler));
  return ptr_ref.get();
}
<commit_msg>Rmeove another wstring from infobar code.<commit_after>// Copyright (c) 2010 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/browser/tab_contents/tab_contents_ssl_helper.h"

#include "app/l10n_util.h"
#include "app/resource_bundle.h"
#include "base/basictypes.h"
#include "base/string_number_conversions.h"
#include "base/utf_string_conversions.h"
#include "chrome/browser/certificate_viewer.h"
#include "chrome/browser/ssl/ssl_add_cert_handler.h"
#include "chrome/browser/ssl/ssl_client_auth_handler.h"
#include "chrome/browser/ssl_client_certificate_selector.h"
#include "chrome/browser/tab_contents/infobar_delegate.h"
#include "chrome/browser/tab_contents/tab_contents.h"
#include "chrome/common/notification_service.h"
#include "grit/generated_resources.h"
#include "grit/theme_resources.h"
#include "net/base/net_errors.h"

namespace {

SkBitmap* GetCertIcon() {
  // TODO(davidben): use a more appropriate icon.
  return ResourceBundle::GetSharedInstance().GetBitmapNamed(
      IDR_INFOBAR_SAVE_PASSWORD);
}

class SSLCertAddedInfoBarDelegate : public ConfirmInfoBarDelegate {
 public:
  SSLCertAddedInfoBarDelegate(TabContents* tab_contents,
                              net::X509Certificate* cert)
      : ConfirmInfoBarDelegate(tab_contents),
        tab_contents_(tab_contents),
        cert_(cert) {
  }

  virtual ~SSLCertAddedInfoBarDelegate() {
  }

  // Overridden from ConfirmInfoBarDelegate:
  virtual string16 GetMessageText() const {
    // TODO(evanm): GetDisplayName should return UTF-16.
    return l10n_util::GetStringFUTF16(
        IDS_ADD_CERT_SUCCESS_INFOBAR_LABEL,
        UTF8ToUTF16(cert_->issuer().GetDisplayName()));
  }

  virtual SkBitmap* GetIcon() const {
    return GetCertIcon();
  }

  virtual int GetButtons() const {
    return BUTTON_OK;
  }

  virtual string16 GetButtonLabel(InfoBarButton button) const {
    switch (button) {
      case BUTTON_OK:
        return l10n_util::GetStringUTF16(IDS_ADD_CERT_SUCCESS_INFOBAR_BUTTON);
      default:
        return string16();
    }
  }

  virtual Type GetInfoBarType() {
    return PAGE_ACTION_TYPE;
  }

  virtual bool Accept() {
    ShowCertificateViewer(tab_contents_->GetMessageBoxRootWindow(), cert_);
    return false;  // Hiding the infobar just as the dialog opens looks weird.
  }

  virtual void InfoBarClosed() {
    // ConfirmInfoBarDelegate doesn't delete itself.
    delete this;
  }

 private:
  // The TabContents we are attached to
  TabContents* tab_contents_;
  // The cert we added.
  scoped_refptr<net::X509Certificate> cert_;
};

}  // namespace

class TabContentsSSLHelper::SSLAddCertData : public NotificationObserver {
 public:
  SSLAddCertData(TabContents* tab, SSLAddCertHandler* handler)
      : tab_(tab),
        handler_(handler),
        infobar_delegate_(NULL) {
    // Listen for disappearing InfoBars.
    Source<TabContents> tc_source(tab_);
    registrar_.Add(this, NotificationType::TAB_CONTENTS_INFOBAR_REMOVED,
                   tc_source);
    registrar_.Add(this, NotificationType::TAB_CONTENTS_INFOBAR_REPLACED,
                   tc_source);
  }
  ~SSLAddCertData() {}

  // Displays |delegate| as an infobar in |tab_|, replacing our current one if
  // still active.
  void ShowInfoBar(InfoBarDelegate* delegate) {
    if (infobar_delegate_) {
      tab_->ReplaceInfoBar(infobar_delegate_, delegate);
    } else {
      tab_->AddInfoBar(delegate);
    }
    infobar_delegate_ = delegate;
  }

  void ShowErrorInfoBar(const string16& message) {
    ShowInfoBar(
        new SimpleAlertInfoBarDelegate(tab_, message, GetCertIcon(), true));
  }

  // NotificationObserver implementation.
  virtual void Observe(NotificationType type,
                       const NotificationSource& source,
                       const NotificationDetails& details) {
    switch (type.value) {
      case NotificationType::TAB_CONTENTS_INFOBAR_REMOVED:
        InfoBarClosed(Details<InfoBarDelegate>(details).ptr());
        break;
      case NotificationType::TAB_CONTENTS_INFOBAR_REPLACED:
        typedef std::pair<InfoBarDelegate*, InfoBarDelegate*>
            InfoBarDelegatePair;
        InfoBarClosed(Details<InfoBarDelegatePair>(details).ptr()->first);
        break;
      default:
        NOTREACHED();
        break;
    }
  }

 private:
  void InfoBarClosed(InfoBarDelegate* delegate) {
    if (infobar_delegate_ == delegate)
      infobar_delegate_ = NULL;
  }

  // The TabContents we are attached to.
  TabContents* tab_;
  // The handler we call back to.
  scoped_refptr<SSLAddCertHandler> handler_;
  // The current InfoBarDelegate we're displaying.
  InfoBarDelegate* infobar_delegate_;

  NotificationRegistrar registrar_;

  DISALLOW_COPY_AND_ASSIGN(SSLAddCertData);
};

TabContentsSSLHelper::TabContentsSSLHelper(TabContents* tab_contents)
    : tab_contents_(tab_contents) {
}

TabContentsSSLHelper::~TabContentsSSLHelper() {
}

void TabContentsSSLHelper::ShowClientCertificateRequestDialog(
    scoped_refptr<SSLClientAuthHandler> handler) {
  browser::ShowSSLClientCertificateSelector(
      tab_contents_, handler->cert_request_info(), handler);
}

void TabContentsSSLHelper::OnVerifyClientCertificateError(
    scoped_refptr<SSLAddCertHandler> handler, int error_code) {
  SSLAddCertData* add_cert_data = GetAddCertData(handler);
  // Display an infobar with the error message.
  // TODO(davidben): Display a more user-friendly error string.
  add_cert_data->ShowErrorInfoBar(
      l10n_util::GetStringFUTF16(IDS_ADD_CERT_ERR_INVALID_CERT,
                                 base::IntToString16(-error_code),
                                 ASCIIToUTF16(net::ErrorToString(error_code))));
}

void TabContentsSSLHelper::AskToAddClientCertificate(
    scoped_refptr<SSLAddCertHandler> handler) {
  NOTREACHED();  // Not implemented yet.
}

void TabContentsSSLHelper::OnAddClientCertificateSuccess(
    scoped_refptr<SSLAddCertHandler> handler) {
  SSLAddCertData* add_cert_data = GetAddCertData(handler);
  // Display an infobar to inform the user.
  add_cert_data->ShowInfoBar(
      new SSLCertAddedInfoBarDelegate(tab_contents_, handler->cert()));
}

void TabContentsSSLHelper::OnAddClientCertificateError(
    scoped_refptr<SSLAddCertHandler> handler, int error_code) {
  SSLAddCertData* add_cert_data = GetAddCertData(handler);
  // Display an infobar with the error message.
  // TODO(davidben): Display a more user-friendly error string.
  add_cert_data->ShowErrorInfoBar(
      l10n_util::GetStringFUTF16(IDS_ADD_CERT_ERR_FAILED,
                                 base::IntToString16(-error_code),
                                 ASCIIToUTF16(net::ErrorToString(error_code))));
}

void TabContentsSSLHelper::OnAddClientCertificateFinished(
    scoped_refptr<SSLAddCertHandler> handler) {
  // Clean up.
  request_id_to_add_cert_data_.erase(handler->network_request_id());
}

TabContentsSSLHelper::SSLAddCertData* TabContentsSSLHelper::GetAddCertData(
    SSLAddCertHandler* handler) {
  // Find/create the slot.
  linked_ptr<SSLAddCertData>& ptr_ref =
      request_id_to_add_cert_data_[handler->network_request_id()];
  // Fill it if necessary.
  if (!ptr_ref.get())
    ptr_ref.reset(new SSLAddCertData(tab_contents_, handler));
  return ptr_ref.get();
}
<|endoftext|>


<commit_before>/**
 * This file is part of the CernVM File System.
 *
 * Fills an internal map of key-value pairs from ASCII files in key=value
 * style.  Parameters can be overwritten.  Used to read configuration from
 * /etc/cvmfs/...
 */

#include "cvmfs_config.h"
#include "options.h"

#include <fcntl.h>
#include <sys/wait.h>
#include <unistd.h>

#include <cassert>
#include <cstdio>
#include <cstdlib>
#include <utility>

#include "logging.h"
#include "sanitizer.h"
#include "util.h"

using namespace std;  // NOLINT

#ifdef CVMFS_NAMESPACE_GUARD
namespace CVMFS_NAMESPACE_GUARD {
#endif

static string EscapeShell(const std::string &raw) {
  for (unsigned i = 0, l = raw.length(); i < l; ++i) {
    if (!(((raw[i] >= '0') && (raw[i] <= '9')) ||
          ((raw[i] >= 'A') && (raw[i] <= 'Z')) ||
          ((raw[i] >= 'a') && (raw[i] <= 'z')) ||
          (raw[i] == '/') || (raw[i] == ':') || (raw[i] == '.') ||
          (raw[i] == '_') || (raw[i] == '-') || (raw[i] == ',')))
    {
      goto escape_shell_quote;
    }
  }
  return raw;

 escape_shell_quote:
  string result = "'";
  for (unsigned i = 0, l = raw.length(); i < l; ++i) {
    if (raw[i] == '\'')
      result += "\\";
    result += raw[i];
  }
  result += "'";
  return result;
}

void SimpleOptionsParser::ParsePath(const string &config_file,
                                 const bool external __attribute__((unused))) {
  LogCvmfs(kLogCvmfs, kLogDebug, "Fast-parsing config file %s",
      config_file.c_str());
  int retval;
  string line;
  FILE *fconfig = fopen(config_file.c_str(), "r");
  if (fconfig == NULL)
    return;

  // Read line by line and extract parameters
  while (GetLineFile(fconfig, &line)) {
    line = Trim(line);
    if (line.empty() || line[0] == '#' || line.find(" ") < string::npos)
      continue;
    vector<string> tokens = SplitString(line, '=');
    if (tokens.size() < 2 || tokens.size() > 2)
      continue;

    ConfigValue value;
    value.source = config_file;
    value.value = tokens[1];
    string parameter = tokens[0];
    config_[parameter] = value;
    retval = setenv(parameter.c_str(), value.value.c_str(), 1);
    assert(retval == 0);
  }
  fclose(fconfig);
}

void BashOptionsManager::ParsePath(const string &config_file,
                                   const bool external) {
  LogCvmfs(kLogCvmfs, kLogDebug, "Parsing config file %s", config_file.c_str());
  int retval;
  int pipe_open[2];
  int pipe_quit[2];
  pid_t pid_child = 0;
  if (external) {
    // cvmfs can run in the process group of automount in which case
    // autofs won't mount an additional config repository.  We create a
    // short-lived process that detaches from the process group and triggers
    // autofs to mount the config repository, if necessary.  It holds a file
    // handle to the config file until the main process opened the file, too.
    MakePipe(pipe_open);
    MakePipe(pipe_quit);
    switch (pid_child = fork()) {
      case -1:
        abort();
      case 0: {  // Child
        close(pipe_open[0]);
        close(pipe_quit[1]);
        // If this is not a process group leader, create a new session
        if (getpgrp() != getpid()) {
          pid_t new_session = setsid();
          assert(new_session != (pid_t)-1);
        }
        (void)open(config_file.c_str(), O_RDONLY);
        char ready = 'R';
        WritePipe(pipe_open[1], &ready, 1);
        read(pipe_quit[0], &ready, 1);
        _exit(0);  // Don't flush shared file descriptors
      }
    }
    // Parent
    close(pipe_open[1]);
    close(pipe_quit[0]);
    char ready = 0;
    ReadPipe(pipe_open[0], &ready, 1);
    assert(ready == 'R');
    close(pipe_open[0]);
  }
  const string config_path = GetParentPath(config_file);
  FILE *fconfig = fopen(config_file.c_str(), "r");
  if (pid_child > 0) {
    char c = 'C';
    WritePipe(pipe_quit[1], &c, 1);
    int statloc;
    waitpid(pid_child, &statloc, 0);
    close(pipe_quit[1]);
  }
  if (!fconfig) {
    if (external && !DirectoryExists(config_path)) {
      LogCvmfs(kLogCvmfs, kLogDebug | kLogSyslogWarn,
               "external location for configuration files does not exist: %s",
               config_path.c_str());
    }
    return;
  }

  int fd_stdin;
  int fd_stdout;
  int fd_stderr;
  retval = Shell(&fd_stdin, &fd_stdout, &fd_stderr);
  assert(retval);

  // Let the shell read the file
  string line;
  const string newline = "\n";
  const string cd = "cd \"" + ((config_path == "") ? "/" : config_path) + "\"" +
                    newline;
  WritePipe(fd_stdin, cd.data(), cd.length());
  while (GetLineFile(fconfig, &line)) {
    WritePipe(fd_stdin, line.data(), line.length());
    WritePipe(fd_stdin, newline.data(), newline.length());
  }
  rewind(fconfig);

  // Read line by line and extract parameters
  while (GetLineFile(fconfig, &line)) {
    line = Trim(line);
    if (line.empty() || line[0] == '#' || line.find("if ") == 0)
      continue;
    vector<string> tokens = SplitString(line, '=');
    if (tokens.size() < 2)
      continue;

    ConfigValue value;
    value.source = config_file;
    string parameter = tokens[0];
    // Strip "readonly"
    if (parameter.find("readonly") == 0) {
      parameter = parameter.substr(8);
      parameter = Trim(parameter);
    }
    // Strip export
    if (parameter.find("export") == 0) {
      parameter = parameter.substr(6);
      parameter = Trim(parameter);
    }
    // Strip eval
    if (parameter.find("eval") == 0) {
      parameter = parameter.substr(4);
      parameter = Trim(parameter);
    }

    const string sh_echo = "echo $" + parameter + "\n";
    WritePipe(fd_stdin, sh_echo.data(), sh_echo.length());
    GetLineFd(fd_stdout, &value.value);
    config_[parameter] = value;
    retval = setenv(parameter.c_str(), value.value.c_str(), 1);
    assert(retval == 0);
  }

  close(fd_stderr);
  close(fd_stdout);
  close(fd_stdin);
  fclose(fconfig);
}

bool OptionsManager::HasConfigRepository(const string &fqrn,
                                         string *config_path) {
  string cvmfs_mount_dir;
  if (!GetValue("CVMFS_MOUNT_DIR", &cvmfs_mount_dir)) {
    LogCvmfs(kLogCvmfs, kLogDebug | kLogSyslogErr, "CVMFS_MOUNT_DIR missing");
    return false;
  }

  string config_repository;
  if (GetValue("CVMFS_CONFIG_REPOSITORY", &config_repository)) {
    if (config_repository.empty() || (config_repository == fqrn))
      return false;
    sanitizer::RepositorySanitizer repository_sanitizer;
    if (!repository_sanitizer.IsValid(config_repository)) {
      LogCvmfs(kLogCvmfs, kLogDebug | kLogSyslogErr,
               "invalid CVMFS_CONFIG_REPOSITORY: %s",
               config_repository.c_str());
      return false;
    }
    *config_path = cvmfs_mount_dir + "/" + config_repository + "/etc/cvmfs/";
    return true;
  }
  return false;
}

void OptionsManager::ParseDefault(const string &fqrn) {
  int retval = setenv("CVMFS_FQRN", fqrn.c_str(), 1);
  assert(retval == 0);

  ParsePath("/etc/cvmfs/default.conf", false);
  vector<string> dist_defaults = FindFiles("/etc/cvmfs/default.d", ".conf");
  for (unsigned i = 0; i < dist_defaults.size(); ++i) {
    ParsePath(dist_defaults[i], false);
  }
  ParsePath("/etc/cvmfs/default.local", false);

  if (fqrn != "") {
    string domain;
    vector<string> tokens = SplitString(fqrn, '.');
    assert(tokens.size() > 1);
    tokens.erase(tokens.begin());
    domain = JoinStrings(tokens, ".");

    string external_config_path;
    if (HasConfigRepository(fqrn, &external_config_path))
      ParsePath(external_config_path + "domain.d/" + domain + ".conf", true);
    ParsePath("/etc/cvmfs/domain.d/" + domain + ".conf", false);
    ParsePath("/etc/cvmfs/domain.d/" + domain + ".local", false);

    if (HasConfigRepository(fqrn, &external_config_path))
      ParsePath(external_config_path + "config.d/" + fqrn + ".conf", true);
    ParsePath("/etc/cvmfs/config.d/" + fqrn + ".conf", false);
    ParsePath("/etc/cvmfs/config.d/" + fqrn + ".local", false);
  }
}

void OptionsManager::ClearConfig() {
  config_.clear();
}

bool OptionsManager::IsDefined(const std::string &key) {
  map<string, ConfigValue>::const_iterator iter = config_.find(key);
  return iter != config_.end();
}

bool OptionsManager::GetValue(const string &key, string *value) {
  map<string, ConfigValue>::const_iterator iter = config_.find(key);
  if (iter != config_.end()) {
    *value = iter->second.value;
    return true;
  }
  *value = "";
  return false;
}

bool OptionsManager::GetSource(const string &key, string *value) {
  map<string, ConfigValue>::const_iterator iter = config_.find(key);
  if (iter != config_.end()) {
    *value = iter->second.source;
    return true;
  }
  *value = "";
  return false;
}

bool OptionsManager::IsOn(const std::string &param_value) {
  const string uppercase = ToUpper(param_value);
  return ((uppercase == "YES") || (uppercase == "ON") || (uppercase == "1"));
}

vector<string> OptionsManager::GetAllKeys() {
  vector<string> result;
  for (map<string, ConfigValue>::const_iterator i = config_.begin(),
       iEnd = config_.end(); i != iEnd; ++i)
  {
    result.push_back(i->first);
  }
  return result;
}

string OptionsManager::Dump() {
  string result;
  vector<string> keys = GetAllKeys();
  for (unsigned i = 0, l = keys.size(); i < l; ++i) {
    bool retval;
    string value;
    string source;

    retval = GetValue(keys[i], &value);
    assert(retval);
    retval = GetSource(keys[i], &source);
    assert(retval);
    result += keys[i] + "=" + EscapeShell(value) +
              "    # from " + source + "\n";
  }
  return result;
}

#ifdef CVMFS_NAMESPACE_GUARD
}  // namespace CVMFS_NAMESPACE_GUARD
#endif
<commit_msg>add looking for default.conf in config repo<commit_after>/**
 * This file is part of the CernVM File System.
 *
 * Fills an internal map of key-value pairs from ASCII files in key=value
 * style.  Parameters can be overwritten.  Used to read configuration from
 * /etc/cvmfs/...
 */

#include "cvmfs_config.h"
#include "options.h"

#include <fcntl.h>
#include <sys/wait.h>
#include <unistd.h>

#include <cassert>
#include <cstdio>
#include <cstdlib>
#include <utility>

#include "logging.h"
#include "sanitizer.h"
#include "util.h"

using namespace std;  // NOLINT

#ifdef CVMFS_NAMESPACE_GUARD
namespace CVMFS_NAMESPACE_GUARD {
#endif

static string EscapeShell(const std::string &raw) {
  for (unsigned i = 0, l = raw.length(); i < l; ++i) {
    if (!(((raw[i] >= '0') && (raw[i] <= '9')) ||
          ((raw[i] >= 'A') && (raw[i] <= 'Z')) ||
          ((raw[i] >= 'a') && (raw[i] <= 'z')) ||
          (raw[i] == '/') || (raw[i] == ':') || (raw[i] == '.') ||
          (raw[i] == '_') || (raw[i] == '-') || (raw[i] == ',')))
    {
      goto escape_shell_quote;
    }
  }
  return raw;

 escape_shell_quote:
  string result = "'";
  for (unsigned i = 0, l = raw.length(); i < l; ++i) {
    if (raw[i] == '\'')
      result += "\\";
    result += raw[i];
  }
  result += "'";
  return result;
}

void SimpleOptionsParser::ParsePath(const string &config_file,
                                 const bool external __attribute__((unused))) {
  LogCvmfs(kLogCvmfs, kLogDebug, "Fast-parsing config file %s",
      config_file.c_str());
  int retval;
  string line;
  FILE *fconfig = fopen(config_file.c_str(), "r");
  if (fconfig == NULL)
    return;

  // Read line by line and extract parameters
  while (GetLineFile(fconfig, &line)) {
    line = Trim(line);
    if (line.empty() || line[0] == '#' || line.find(" ") < string::npos)
      continue;
    vector<string> tokens = SplitString(line, '=');
    if (tokens.size() < 2 || tokens.size() > 2)
      continue;

    ConfigValue value;
    value.source = config_file;
    value.value = tokens[1];
    string parameter = tokens[0];
    config_[parameter] = value;
    retval = setenv(parameter.c_str(), value.value.c_str(), 1);
    assert(retval == 0);
  }
  fclose(fconfig);
}

void BashOptionsManager::ParsePath(const string &config_file,
                                   const bool external) {
  LogCvmfs(kLogCvmfs, kLogDebug, "Parsing config file %s", config_file.c_str());
  int retval;
  int pipe_open[2];
  int pipe_quit[2];
  pid_t pid_child = 0;
  if (external) {
    // cvmfs can run in the process group of automount in which case
    // autofs won't mount an additional config repository.  We create a
    // short-lived process that detaches from the process group and triggers
    // autofs to mount the config repository, if necessary.  It holds a file
    // handle to the config file until the main process opened the file, too.
    MakePipe(pipe_open);
    MakePipe(pipe_quit);
    switch (pid_child = fork()) {
      case -1:
        abort();
      case 0: {  // Child
        close(pipe_open[0]);
        close(pipe_quit[1]);
        // If this is not a process group leader, create a new session
        if (getpgrp() != getpid()) {
          pid_t new_session = setsid();
          assert(new_session != (pid_t)-1);
        }
        (void)open(config_file.c_str(), O_RDONLY);
        char ready = 'R';
        WritePipe(pipe_open[1], &ready, 1);
        read(pipe_quit[0], &ready, 1);
        _exit(0);  // Don't flush shared file descriptors
      }
    }
    // Parent
    close(pipe_open[1]);
    close(pipe_quit[0]);
    char ready = 0;
    ReadPipe(pipe_open[0], &ready, 1);
    assert(ready == 'R');
    close(pipe_open[0]);
  }
  const string config_path = GetParentPath(config_file);
  FILE *fconfig = fopen(config_file.c_str(), "r");
  if (pid_child > 0) {
    char c = 'C';
    WritePipe(pipe_quit[1], &c, 1);
    int statloc;
    waitpid(pid_child, &statloc, 0);
    close(pipe_quit[1]);
  }
  if (!fconfig) {
    if (external && !DirectoryExists(config_path)) {
      LogCvmfs(kLogCvmfs, kLogDebug | kLogSyslogWarn,
               "external location for configuration files does not exist: %s",
               config_path.c_str());
    }
    return;
  }

  int fd_stdin;
  int fd_stdout;
  int fd_stderr;
  retval = Shell(&fd_stdin, &fd_stdout, &fd_stderr);
  assert(retval);

  // Let the shell read the file
  string line;
  const string newline = "\n";
  const string cd = "cd \"" + ((config_path == "") ? "/" : config_path) + "\"" +
                    newline;
  WritePipe(fd_stdin, cd.data(), cd.length());
  while (GetLineFile(fconfig, &line)) {
    WritePipe(fd_stdin, line.data(), line.length());
    WritePipe(fd_stdin, newline.data(), newline.length());
  }
  rewind(fconfig);

  // Read line by line and extract parameters
  while (GetLineFile(fconfig, &line)) {
    line = Trim(line);
    if (line.empty() || line[0] == '#' || line.find("if ") == 0)
      continue;
    vector<string> tokens = SplitString(line, '=');
    if (tokens.size() < 2)
      continue;

    ConfigValue value;
    value.source = config_file;
    string parameter = tokens[0];
    // Strip "readonly"
    if (parameter.find("readonly") == 0) {
      parameter = parameter.substr(8);
      parameter = Trim(parameter);
    }
    // Strip export
    if (parameter.find("export") == 0) {
      parameter = parameter.substr(6);
      parameter = Trim(parameter);
    }
    // Strip eval
    if (parameter.find("eval") == 0) {
      parameter = parameter.substr(4);
      parameter = Trim(parameter);
    }

    const string sh_echo = "echo $" + parameter + "\n";
    WritePipe(fd_stdin, sh_echo.data(), sh_echo.length());
    GetLineFd(fd_stdout, &value.value);
    config_[parameter] = value;
    retval = setenv(parameter.c_str(), value.value.c_str(), 1);
    assert(retval == 0);
  }

  close(fd_stderr);
  close(fd_stdout);
  close(fd_stdin);
  fclose(fconfig);
}

bool OptionsManager::HasConfigRepository(const string &fqrn,
                                         string *config_path) {
  string cvmfs_mount_dir;
  if (!GetValue("CVMFS_MOUNT_DIR", &cvmfs_mount_dir)) {
    LogCvmfs(kLogCvmfs, kLogDebug | kLogSyslogErr, "CVMFS_MOUNT_DIR missing");
    return false;
  }

  string config_repository;
  if (GetValue("CVMFS_CONFIG_REPOSITORY", &config_repository)) {
    if (config_repository.empty() || (config_repository == fqrn))
      return false;
    sanitizer::RepositorySanitizer repository_sanitizer;
    if (!repository_sanitizer.IsValid(config_repository)) {
      LogCvmfs(kLogCvmfs, kLogDebug | kLogSyslogErr,
               "invalid CVMFS_CONFIG_REPOSITORY: %s",
               config_repository.c_str());
      return false;
    }
    *config_path = cvmfs_mount_dir + "/" + config_repository + "/etc/cvmfs/";
    return true;
  }
  return false;
}

void OptionsManager::ParseDefault(const string &fqrn) {
  int retval = setenv("CVMFS_FQRN", fqrn.c_str(), 1);
  assert(retval == 0);

  ParsePath("/etc/cvmfs/default.conf", false);
  vector<string> dist_defaults = FindFiles("/etc/cvmfs/default.d", ".conf");
  for (unsigned i = 0; i < dist_defaults.size(); ++i) {
    ParsePath(dist_defaults[i], false);
  }
  string external_config_path;
  if ((fqrn != "") && HasConfigRepository(fqrn, &external_config_path))
    ParsePath(external_config_path + "default.conf", true);
  ParsePath("/etc/cvmfs/default.local", false);

  if (fqrn != "") {
    string domain;
    vector<string> tokens = SplitString(fqrn, '.');
    assert(tokens.size() > 1);
    tokens.erase(tokens.begin());
    domain = JoinStrings(tokens, ".");

    if (HasConfigRepository(fqrn, &external_config_path))
      ParsePath(external_config_path + "domain.d/" + domain + ".conf", true);
    ParsePath("/etc/cvmfs/domain.d/" + domain + ".conf", false);
    ParsePath("/etc/cvmfs/domain.d/" + domain + ".local", false);

    if (HasConfigRepository(fqrn, &external_config_path))
      ParsePath(external_config_path + "config.d/" + fqrn + ".conf", true);
    ParsePath("/etc/cvmfs/config.d/" + fqrn + ".conf", false);
    ParsePath("/etc/cvmfs/config.d/" + fqrn + ".local", false);
  }
}

void OptionsManager::ClearConfig() {
  config_.clear();
}

bool OptionsManager::IsDefined(const std::string &key) {
  map<string, ConfigValue>::const_iterator iter = config_.find(key);
  return iter != config_.end();
}

bool OptionsManager::GetValue(const string &key, string *value) {
  map<string, ConfigValue>::const_iterator iter = config_.find(key);
  if (iter != config_.end()) {
    *value = iter->second.value;
    return true;
  }
  *value = "";
  return false;
}

bool OptionsManager::GetSource(const string &key, string *value) {
  map<string, ConfigValue>::const_iterator iter = config_.find(key);
  if (iter != config_.end()) {
    *value = iter->second.source;
    return true;
  }
  *value = "";
  return false;
}

bool OptionsManager::IsOn(const std::string &param_value) {
  const string uppercase = ToUpper(param_value);
  return ((uppercase == "YES") || (uppercase == "ON") || (uppercase == "1"));
}

vector<string> OptionsManager::GetAllKeys() {
  vector<string> result;
  for (map<string, ConfigValue>::const_iterator i = config_.begin(),
       iEnd = config_.end(); i != iEnd; ++i)
  {
    result.push_back(i->first);
  }
  return result;
}

string OptionsManager::Dump() {
  string result;
  vector<string> keys = GetAllKeys();
  for (unsigned i = 0, l = keys.size(); i < l; ++i) {
    bool retval;
    string value;
    string source;

    retval = GetValue(keys[i], &value);
    assert(retval);
    retval = GetSource(keys[i], &source);
    assert(retval);
    result += keys[i] + "=" + EscapeShell(value) +
              "    # from " + source + "\n";
  }
  return result;
}

#ifdef CVMFS_NAMESPACE_GUARD
}  // namespace CVMFS_NAMESPACE_GUARD
#endif
<|endoftext|>


<commit_before>#include "StdAfxUnitTests.h"
#include "DnsUnitTests.h"

CPPUNIT_TEST_SUITE_REGISTRATION(AppSecInc::UnitTests::TcpIp::DNS::DnsUnitTests);

using namespace AppSecInc::UnitTests::TcpIp::DNS;

void DnsUnitTests::testGetHostByAddress()
{
	AppSecInc::TcpIp::CWSAStartup wsa;

	struct TestData
	{
		LPCSTR ip;
		LPCSTR host;
	};

	TestData testdata[] =
	{
		{ "65.55.11.218", "*.codeplex.com" }
	};

	for (int i = 0; i < ARRAYSIZE(testdata); i++)
	{
		std::string host = AppSecInc::TcpIp::DNS::GetHostByAddress(testdata[i].ip);
		std::cout << std::endl << testdata[i].ip << " -> " << host;
		CPPUNIT_ASSERT(host == testdata[i].host);
	}
}

void DnsUnitTests::testGetHostByInvalidAddress()
{
	AppSecInc::TcpIp::CWSAStartup wsa;

	LPCSTR testdata[] =
	{
		{ "abcdefgh" },
	};

	for (int i = 0; i < ARRAYSIZE(testdata); i++)
	{
		try
		{
			AppSecInc::TcpIp::DNS::GetHostByAddress(testdata[i]);
			throw "Expected std::exception";
		}
		catch(std::exception& ex)
		{
			std::cout << std::endl << "Expected exception for " << testdata[i] << ": " << ex.what();
		}
	}
}

void DnsUnitTests::testGetHostByName()
{
	AppSecInc::TcpIp::CWSAStartup wsa;

	struct TestData
	{
		LPCSTR ip;
		LPCSTR host;
	};

	TestData testdata[] =
	{
		{ "65.55.11.218", "*.codeplex.com" },
		{ "www.codeplex.com", "lb.codeplex.com.microsoft.akadns.net" },
	};

	for (int i = 0; i < ARRAYSIZE(testdata); i++)
	{
		std::string host = AppSecInc::TcpIp::DNS::GetHostByName(testdata[i].ip);
		std::cout << std::endl << testdata[i].ip << " -> " << host;
		CPPUNIT_ASSERT(host == testdata[i].host);
	}
}

void DnsUnitTests::testGetHostIpAddresses()
{
	AppSecInc::TcpIp::CWSAStartup wsa;

	struct TestData
	{
		LPCSTR host;
		LPCSTR ip;
	};

	TestData testdata[] =
	{
		{ "65.55.11.218", "65.55.11.218" },
		{ "www.codeplex.com", "65.55.11.218" },
	};

	for (int i = 0; i < ARRAYSIZE(testdata); i++)
	{
		std::string ip = AppSecInc::TcpIp::DNS::GetHostIpAddresses(testdata[i].ip)[0];
		std::cout << std::endl << testdata[i].host << " -> " << ip;
		CPPUNIT_ASSERT(ip == testdata[i].ip);
	}
}

void DnsUnitTests::testGetHostInfo()
{
	AppSecInc::TcpIp::CWSAStartup wsa;

	struct TestData
	{
		LPCSTR host;
		LPCSTR hostname; // expected host name
	};

	TestData testdata[] =
	{
		{ "www.codeplex.com", "lb.codeplex.com.microsoft.akadns.net" },
	};

	for (int i = 0; i < ARRAYSIZE(testdata); i++)
	{
		std::string hostname;
		std::vector<std::string> aliases;
		std::vector<std::string> addresses;
		AppSecInc::TcpIp::DNS::GetHostInfo(testdata[i].host, hostname, aliases, addresses);

		std::cout << std::endl << testdata[i].host << " -> " << hostname;
		CPPUNIT_ASSERT(hostname == testdata[i].hostname);

		for each (const std::string& alias in aliases)
			std::cout << std::endl << " alias: " << alias;

		for each (const std::string& address in addresses)
			std::cout << std::endl << " address: " << address;
	}
}

void DnsUnitTests::testGetLocal()
{
	AppSecInc::TcpIp::CWSAStartup wsa;

	char computername[MAX_COMPUTERNAME_LENGTH + 1] = { 0 };
	DWORD size = MAX_COMPUTERNAME_LENGTH;
	CPPUNIT_ASSERT(::GetComputerNameA(computername, & size));
	std::cout << std::endl << "Host: " << computername;

	std::string tcpaddress = AppSecInc::TcpIp::DNS::GetHostIpAddresses(computername)[0];
	std::cout << std::endl << "Ip: " << tcpaddress;
	CPPUNIT_ASSERT(! tcpaddress.empty());

	std::string host = AppSecInc::TcpIp::DNS::GetHostByName(computername);
	std::cout << std::endl << "Host: " << host;
	CPPUNIT_ASSERT(! host.empty());
}

void DnsUnitTests::testGetHostName()
{
	wchar_t computername[MAX_COMPUTERNAME_LENGTH + 1] = { 0 };
	DWORD size = MAX_COMPUTERNAME_LENGTH;
	CPPUNIT_ASSERT(::GetComputerNameW(computername, & size));
	std::wcout << std::endl << L"Computer: " << computername;
    std::wstring hostname = AppSecInc::TcpIp::DNS::GetHostNameW();
	std::wcout << std::endl << L"Host: " << hostname;
    CPPUNIT_ASSERT(0 == ::_wcsicmp(computername, hostname.c_str()));
}

void DnsUnitTests::testIsIpAddress()
{
	AppSecInc::TcpIp::CWSAStartup wsa;

	struct TestData
	{
		LPCSTR ip;
		bool isIp; // expected true/false
	};

	TestData testdata[] =
	{
		{ "", false },
		{ "127.0.0.1", true },
		{ "localhost", false },
		{ "0", false },
		{ "192.168.0.1", true },
		{ "10.10.10.10", true },
		{ "fe80::8081:ade5:e522:4a3c%14", false }, // IPv6 is not supported by this function
	};

	for (int i = 0; i < ARRAYSIZE(testdata); i++)
	{
		bool ip = AppSecInc::TcpIp::DNS::IsIpAddress(testdata[i].ip);
		std::cout << std::endl << testdata[i].ip << " -> " << (ip ? "ip" : "not ip");
		CPPUNIT_ASSERT(ip == testdata[i].isIp);
	}
}<commit_msg>Changed sample IPs in test.<commit_after>#include "StdAfxUnitTests.h"
#include "DnsUnitTests.h"

CPPUNIT_TEST_SUITE_REGISTRATION(AppSecInc::UnitTests::TcpIp::DNS::DnsUnitTests);

using namespace AppSecInc::UnitTests::TcpIp::DNS;

void DnsUnitTests::testGetHostByAddress()
{
	AppSecInc::TcpIp::CWSAStartup wsa;

	struct TestData
	{
		LPCSTR ip;
		LPCSTR host;
	};

	TestData testdata[] =
	{
		{ "207.97.227.239", "github.com" }
	};

	for (int i = 0; i < ARRAYSIZE(testdata); i++)
	{
		std::string host = AppSecInc::TcpIp::DNS::GetHostByAddress(testdata[i].ip);
		std::cout << std::endl << testdata[i].ip << " -> " << host;
		CPPUNIT_ASSERT(host == testdata[i].host);
	}
}

void DnsUnitTests::testGetHostByInvalidAddress()
{
	AppSecInc::TcpIp::CWSAStartup wsa;

	LPCSTR testdata[] =
	{
		{ "abcdefgh" },
	};

	for (int i = 0; i < ARRAYSIZE(testdata); i++)
	{
		try
		{
			AppSecInc::TcpIp::DNS::GetHostByAddress(testdata[i]);
			throw "Expected std::exception";
		}
		catch(std::exception& ex)
		{
			std::cout << std::endl << "Expected exception for " << testdata[i] << ": " << ex.what();
		}
	}
}

void DnsUnitTests::testGetHostByName()
{
	AppSecInc::TcpIp::CWSAStartup wsa;

	struct TestData
	{
		LPCSTR ip;
		LPCSTR host;
	};

	TestData testdata[] =
	{
		{ "207.97.227.239", "github.com" },
		{ "www.codeplex.com", "lb.codeplex.com.microsoft.akadns.net" },
	};

	for (int i = 0; i < ARRAYSIZE(testdata); i++)
	{
		std::string host = AppSecInc::TcpIp::DNS::GetHostByName(testdata[i].ip);
		std::cout << std::endl << testdata[i].ip << " -> " << host;
		CPPUNIT_ASSERT(host == testdata[i].host);
	}
}

void DnsUnitTests::testGetHostIpAddresses()
{
	AppSecInc::TcpIp::CWSAStartup wsa;

	struct TestData
	{
		LPCSTR host;
		LPCSTR ip;
	};

	TestData testdata[] =
	{
		{ "207.97.227.239", "207.97.227.239" },
		{ "www.github.com", "207.97.227.239" },
	};

	for (int i = 0; i < ARRAYSIZE(testdata); i++)
	{
		std::string ip = AppSecInc::TcpIp::DNS::GetHostIpAddresses(testdata[i].ip)[0];
		std::cout << std::endl << testdata[i].host << " -> " << ip;
		CPPUNIT_ASSERT(ip == testdata[i].ip);
	}
}

void DnsUnitTests::testGetHostInfo()
{
	AppSecInc::TcpIp::CWSAStartup wsa;

	struct TestData
	{
		LPCSTR host;
		LPCSTR hostname; // expected host name
	};

	TestData testdata[] =
	{
		{ "www.codeplex.com", "lb.codeplex.com.microsoft.akadns.net" },
	};

	for (int i = 0; i < ARRAYSIZE(testdata); i++)
	{
		std::string hostname;
		std::vector<std::string> aliases;
		std::vector<std::string> addresses;
		AppSecInc::TcpIp::DNS::GetHostInfo(testdata[i].host, hostname, aliases, addresses);

		std::cout << std::endl << testdata[i].host << " -> " << hostname;
		CPPUNIT_ASSERT(hostname == testdata[i].hostname);

		for each (const std::string& alias in aliases)
			std::cout << std::endl << " alias: " << alias;

		for each (const std::string& address in addresses)
			std::cout << std::endl << " address: " << address;
	}
}

void DnsUnitTests::testGetLocal()
{
	AppSecInc::TcpIp::CWSAStartup wsa;

	char computername[MAX_COMPUTERNAME_LENGTH + 1] = { 0 };
	DWORD size = MAX_COMPUTERNAME_LENGTH;
	CPPUNIT_ASSERT(::GetComputerNameA(computername, & size));
	std::cout << std::endl << "Host: " << computername;

	std::string tcpaddress = AppSecInc::TcpIp::DNS::GetHostIpAddresses(computername)[0];
	std::cout << std::endl << "Ip: " << tcpaddress;
	CPPUNIT_ASSERT(! tcpaddress.empty());

	std::string host = AppSecInc::TcpIp::DNS::GetHostByName(computername);
	std::cout << std::endl << "Host: " << host;
	CPPUNIT_ASSERT(! host.empty());
}

void DnsUnitTests::testGetHostName()
{
	wchar_t computername[MAX_COMPUTERNAME_LENGTH + 1] = { 0 };
	DWORD size = MAX_COMPUTERNAME_LENGTH;
	CPPUNIT_ASSERT(::GetComputerNameW(computername, & size));
	std::wcout << std::endl << L"Computer: " << computername;
    std::wstring hostname = AppSecInc::TcpIp::DNS::GetHostNameW();
	std::wcout << std::endl << L"Host: " << hostname;
    CPPUNIT_ASSERT(0 == ::_wcsicmp(computername, hostname.c_str()));
}

void DnsUnitTests::testIsIpAddress()
{
	AppSecInc::TcpIp::CWSAStartup wsa;

	struct TestData
	{
		LPCSTR ip;
		bool isIp; // expected true/false
	};

	TestData testdata[] =
	{
		{ "", false },
		{ "127.0.0.1", true },
		{ "localhost", false },
		{ "0", false },
		{ "192.168.0.1", true },
		{ "10.10.10.10", true },
		{ "fe80::8081:ade5:e522:4a3c%14", false }, // IPv6 is not supported by this function
	};

	for (int i = 0; i < ARRAYSIZE(testdata); i++)
	{
		bool ip = AppSecInc::TcpIp::DNS::IsIpAddress(testdata[i].ip);
		std::cout << std::endl << testdata[i].ip << " -> " << (ip ? "ip" : "not ip");
		CPPUNIT_ASSERT(ip == testdata[i].isIp);
	}
}<|endoftext|>


<commit_before>#undef isnan
#undef isfinite

#include "kfusion.h"
#include "helpers.h"

#include <iostream>
#include <sstream>
#include <iomanip>

#include <cvd/glwindow.h>
#include "perfstats.h"

using namespace std;
using namespace TooN;

#include <libfreenect/libfreenect.h>

freenect_context *f_ctx;
freenect_device *f_dev;
bool gotDepth;

void depth_cb(freenect_device *dev, void *v_depth, uint32_t timestamp)
{
    gotDepth = true;
}

int InitKinect( uint16_t * buffer ){
    if (freenect_init(&f_ctx, NULL) < 0) {
        cout << "freenect_init() failed" << endl;
        return 1;
    }

    freenect_set_log_level(f_ctx, FREENECT_LOG_WARNING);
    freenect_select_subdevices(f_ctx, (freenect_device_flags)(FREENECT_DEVICE_MOTOR | FREENECT_DEVICE_CAMERA));

    int nr_devices = freenect_num_devices (f_ctx);
    cout << "Number of devices found: " << nr_devices << endl;

    if (nr_devices < 1)
        return 1;

    if (freenect_open_device(f_ctx, &f_dev, 0) < 0) {
        cout << "Could not open device" << endl;
        return 1;
    }

    freenect_set_depth_callback(f_dev, depth_cb);
    freenect_set_depth_mode(f_dev, freenect_find_depth_mode(FREENECT_RESOLUTION_MEDIUM, FREENECT_DEPTH_11BIT));
    freenect_set_depth_buffer(f_dev, buffer);
    freenect_start_depth(f_dev);

    gotDepth = false;

    return 0;
}

void CloseKinect(){
    freenect_stop_depth(f_dev);
    freenect_close_device(f_dev);
    freenect_shutdown(f_ctx);
}

void DepthFrameKinect() {
    while (!gotDepth && freenect_process_events(f_ctx) >= 0){
    }
    gotDepth = false;
}

int main(int argc, char ** argv) {
    const float size = (argc > 1) ? atof(argv[1]) : 2.f;

    KFusionConfig config;

    // it is enough now to set the volume resolution once.
    // everything else is derived from that.
    // config.volumeSize = make_uint3(64);
    config.volumeSize = make_uint3(128);
    // config.volumeSize = make_uint3(256);

    // these are physical dimensions in meters
    config.volumeDimensions = make_float3(size);
    config.nearPlane = 0.4f;
    config.farPlane = 5.0f;
    config.mu = 0.1;
    config.combinedTrackAndReduce = false;

    config.camera =  make_float4(297.12732, 296.24240, 169.89365, 121.25151);

    config.iterations[0] = 10;
    config.iterations[1] = 5;
    config.iterations[2] = 4;

    config.dist_threshold = (argc > 2 ) ? atof(argv[2]) : config.dist_threshold;
    config.normal_threshold = (argc > 3 ) ? atof(argv[3]) : config.normal_threshold;

    const uint2 imageSize = config.renderSize();

    CVD::GLWindow window(CVD::ImageRef(imageSize.x * 2, imageSize.y * 2));
    CVD::GLWindow::EventSummary events;
    glDisable(GL_DEPTH_TEST);

    KFusion kfusion;
    kfusion.Init(config);
    if(printCUDAError()){
        kfusion.Clear();
        cudaDeviceReset();
        return 1;
    }

    Image<uchar4, HostDevice> lightScene(imageSize), depth(imageSize), lightModel(imageSize);
    Image<uint16_t, HostDevice> depthImage(make_uint2(640, 480));

    const float3 light = make_float3(1.0, -2, 1.0);
    const float3 ambient = make_float3(0.1, 0.1, 0.1);
    const float4 renderCamera = make_float4(297.12732, 296.24240, 169.89365+160, 121.25151);

    SE3<float> initPose(makeVector(size/2, size/2, 0, 0, 0, 0));

    kfusion.setPose(toMatrix4(initPose), toMatrix4(initPose.inverse()));

    if(InitKinect(depthImage.data()))
        return 1;

    bool integrate = true;
    bool reset = true;

    int counter = 0;
    while(!events.should_quit()){
        glClear( GL_COLOR_BUFFER_BIT );
        const double startFrame = Stats.start();
        ++counter;

        DepthFrameKinect();
        const double startProcessing = Stats.sample("kinect");

        kfusion.setKinectDeviceDepth(depthImage.getDeviceImage());
        Stats.sample("raw to cooked");

        integrate = kfusion.Track();
        Stats.sample("track");

        if(integrate || reset ){
            kfusion.Integrate();
            Stats.sample("integrate");
            reset = false;
        }

        renderLight( lightModel.getDeviceImage(), kfusion.vertex, kfusion.normal, light, ambient);
        renderLight( lightScene.getDeviceImage(), kfusion.inputVertex[0], kfusion.inputNormal[0], light, ambient );
        renderTrackResult( depth.getDeviceImage(), kfusion.reduction );
        cudaDeviceSynchronize();

        Stats.sample("render");

        glClear( GL_COLOR_BUFFER_BIT );
        glRasterPos2i(0,imageSize.y * 0);
        glDrawPixels(lightScene);
        glRasterPos2i(imageSize.x, imageSize.y * 0);
        glDrawPixels(depth);
        glRasterPos2i(0,imageSize.y * 1);
        glDrawPixels(lightModel);
        Stats.sample("draw");

        window.swap_buffers();
        events.clear();
        window.get_events(events);

        if(events.key_up.count('c')){
            kfusion.Reset();
            kfusion.setPose(toMatrix4(initPose), toMatrix4(initPose.inverse()));
            reset = true;
        }

        if(counter % 50 == 0){
            Stats.print();
            Stats.reset();
            cout << endl;
        }

        if(printCUDAError())
            break;

        const double endProcessing = Stats.sample("events");
        Stats.sample("total", endProcessing - startFrame, PerfStats::TIME);
        Stats.sample("total_proc", endProcessing - startProcessing, PerfStats::TIME);
    }

    CloseKinect();
    kfusion.Clear();

    cudaDeviceReset();
    return 0;
}
<commit_msg>vectors instead of arrays, to make config copyable etc and everything more flexible, missed a file<commit_after>#undef isnan
#undef isfinite

#include "kfusion.h"
#include "helpers.h"

#include <iostream>
#include <sstream>
#include <iomanip>

#include <cvd/glwindow.h>
#include "perfstats.h"

using namespace std;
using namespace TooN;

#include <libfreenect/libfreenect.h>

freenect_context *f_ctx;
freenect_device *f_dev;
bool gotDepth;

void depth_cb(freenect_device *dev, void *v_depth, uint32_t timestamp)
{
    gotDepth = true;
}

int InitKinect( uint16_t * buffer ){
    if (freenect_init(&f_ctx, NULL) < 0) {
        cout << "freenect_init() failed" << endl;
        return 1;
    }

    freenect_set_log_level(f_ctx, FREENECT_LOG_WARNING);
    freenect_select_subdevices(f_ctx, (freenect_device_flags)(FREENECT_DEVICE_MOTOR | FREENECT_DEVICE_CAMERA));

    int nr_devices = freenect_num_devices (f_ctx);
    cout << "Number of devices found: " << nr_devices << endl;

    if (nr_devices < 1)
        return 1;

    if (freenect_open_device(f_ctx, &f_dev, 0) < 0) {
        cout << "Could not open device" << endl;
        return 1;
    }

    freenect_set_depth_callback(f_dev, depth_cb);
    freenect_set_depth_mode(f_dev, freenect_find_depth_mode(FREENECT_RESOLUTION_MEDIUM, FREENECT_DEPTH_11BIT));
    freenect_set_depth_buffer(f_dev, buffer);
    freenect_start_depth(f_dev);

    gotDepth = false;

    return 0;
}

void CloseKinect(){
    freenect_stop_depth(f_dev);
    freenect_close_device(f_dev);
    freenect_shutdown(f_ctx);
}

void DepthFrameKinect() {
    while (!gotDepth && freenect_process_events(f_ctx) >= 0){
    }
    gotDepth = false;
}

int main(int argc, char ** argv) {
    const float size = (argc > 1) ? atof(argv[1]) : 2.f;

    KFusionConfig config;

    // it is enough now to set the volume resolution once.
    // everything else is derived from that.
    // config.volumeSize = make_uint3(64);
    config.volumeSize = make_uint3(128);
    // config.volumeSize = make_uint3(256);

    // these are physical dimensions in meters
    config.volumeDimensions = make_float3(size);
    config.nearPlane = 0.4f;
    config.farPlane = 5.0f;
    config.mu = 0.1;
    config.combinedTrackAndReduce = false;

    config.camera =  make_float4(297.12732, 296.24240, 169.89365, 121.25151);

    // config.iterations is a vector<int>, the length determines
    // the number of levels to be used in tracking
    // push back more then 3 iteraton numbers to get more levels.
    config.iterations[0] = 10;
    config.iterations[1] = 5;
    config.iterations[2] = 4;

    config.dist_threshold = (argc > 2 ) ? atof(argv[2]) : config.dist_threshold;
    config.normal_threshold = (argc > 3 ) ? atof(argv[3]) : config.normal_threshold;

    const uint2 imageSize = config.renderSize();

    CVD::GLWindow window(CVD::ImageRef(imageSize.x * 2, imageSize.y * 2));
    CVD::GLWindow::EventSummary events;
    glDisable(GL_DEPTH_TEST);

    KFusion kfusion;
    kfusion.Init(config);
    if(printCUDAError()){
        kfusion.Clear();
        cudaDeviceReset();
        return 1;
    }

    Image<uchar4, HostDevice> lightScene(imageSize), depth(imageSize), lightModel(imageSize);
    Image<uint16_t, HostDevice> depthImage(make_uint2(640, 480));

    const float3 light = make_float3(1.0, -2, 1.0);
    const float3 ambient = make_float3(0.1, 0.1, 0.1);
    const float4 renderCamera = make_float4(297.12732, 296.24240, 169.89365+160, 121.25151);

    SE3<float> initPose(makeVector(size/2, size/2, 0, 0, 0, 0));

    kfusion.setPose(toMatrix4(initPose), toMatrix4(initPose.inverse()));

    if(InitKinect(depthImage.data()))
        return 1;

    bool integrate = true;
    bool reset = true;

    int counter = 0;
    while(!events.should_quit()){
        glClear( GL_COLOR_BUFFER_BIT );
        const double startFrame = Stats.start();
        ++counter;

        DepthFrameKinect();
        const double startProcessing = Stats.sample("kinect");

        kfusion.setKinectDeviceDepth(depthImage.getDeviceImage());
        Stats.sample("raw to cooked");

        integrate = kfusion.Track();
        Stats.sample("track");

        if(integrate || reset ){
            kfusion.Integrate();
            Stats.sample("integrate");
            reset = false;
        }

        renderLight( lightModel.getDeviceImage(), kfusion.vertex, kfusion.normal, light, ambient);
        renderLight( lightScene.getDeviceImage(), kfusion.inputVertex[0], kfusion.inputNormal[0], light, ambient );
        renderTrackResult( depth.getDeviceImage(), kfusion.reduction );
        cudaDeviceSynchronize();

        Stats.sample("render");

        glClear( GL_COLOR_BUFFER_BIT );
        glRasterPos2i(0,imageSize.y * 0);
        glDrawPixels(lightScene);
        glRasterPos2i(imageSize.x, imageSize.y * 0);
        glDrawPixels(depth);
        glRasterPos2i(0,imageSize.y * 1);
        glDrawPixels(lightModel);
        Stats.sample("draw");

        window.swap_buffers();
        events.clear();
        window.get_events(events);

        if(events.key_up.count('c')){
            kfusion.Reset();
            kfusion.setPose(toMatrix4(initPose), toMatrix4(initPose.inverse()));
            reset = true;
        }

        if(counter % 50 == 0){
            Stats.print();
            Stats.reset();
            cout << endl;
        }

        if(printCUDAError())
            break;

        const double endProcessing = Stats.sample("events");
        Stats.sample("total", endProcessing - startFrame, PerfStats::TIME);
        Stats.sample("total_proc", endProcessing - startProcessing, PerfStats::TIME);
    }

    CloseKinect();
    kfusion.Clear();

    cudaDeviceReset();
    return 0;
}
<|endoftext|>


<commit_before>/*
<one line to give the program's name and a brief idea of what it does.>
Copyright (C) <year>  <name of author>

This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.

This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
GNU General Public License for more details.

You should have received a copy of the GNU General Public License
along with this program.  If not, see <http://www.gnu.org/licenses/>.

*/

#include "componentprivate.h"

using namespace Gluon;

ComponentPrivate::ComponentPrivate()
{
}

ComponentPrivate::ComponentPrivate(const ComponentPrivate &other)
    : QSharedData(other)
{
}

ComponentPrivate::~ComponentPrivate()
{
}
<commit_msg>Initialize variables<commit_after>/*
<one line to give the program's name and a brief idea of what it does.>
Copyright (C) <year>  <name of author>

This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.

This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
GNU General Public License for more details.

You should have received a copy of the GNU General Public License
along with this program.  If not, see <http://www.gnu.org/licenses/>.

*/

#include "componentprivate.h"

using namespace Gluon;

ComponentPrivate::ComponentPrivate()
{
    enabled = true;
    gameObject = 0;
}

ComponentPrivate::ComponentPrivate(const ComponentPrivate &other)
    : QSharedData(other)
    , enabled(other.enabled)
    , gameObject(other.gameObject)
{
}

ComponentPrivate::~ComponentPrivate()
{
}
<|endoftext|>


<commit_before>/*
 * Copyright (C) 2017 Rene Herthel
 *
 * This file is subject to the terms and conditions of the MIT License.
 * See the file LICENSE in the top level directory for more details.
 */

/**
 * @ingroup    error_handler
 * @{
 *
 * @brief      Function declaration of the ErrorHandler.
 *
 * @author     Rene Herthel <rene.herthel@haw-hamburg.de>
 */

#include "ErrorHandler.h"

#include "DistanceObservable.h"
#include "DistanceEnum.h"
#include "Signals.h"
#include "CodeDefinition.h"
#include "SerialProtocoll.h"
#include "Signals.h"

#include <iostream>
using namespace std;
using namespace HAL;

ErrorHandler::ErrorHandler( int chid,
                            ConveyorBeltService *conveyorBeltService,
                            LightSystemService *lightSystemService,
                            SerialService *serialService,
                            PuckManager *puckManager)
    :    m_hasError(false)
    ,    m_resetPressed(false)
    ,    m_conveyorBeltService(conveyorBeltService)
    ,    m_lightSystemService(lightSystemService)
	, 	 m_serialService(serialService)
	, 	 m_puckManager(puckManager)
{
    m_lightSystemService->setWarningLevel(Level::OPERATING);
}

ErrorHandler::~ErrorHandler()
{
    // Nothing todo so far.
}

void ErrorHandler::process(PuckManager::ManagerReturn &manager)
{
	LOG_DEBUG << "[ErrorHandler] Demux Manager return \n";
	LOG_DEBUG << "[ErrorHandler] Actor Flag " << manager.actorFlag << " actorSignal " << (int)manager.actorSignal << "\n";

	//if slide full return a warning
	if (manager.actorFlag && manager.actorSignal == PuckManager::ActorSignal::SEND_SLIDE_FULL){
		 m_lightSystemService->setWarningLevel(Level::WARNING_OCCURED);
		 LOG_DEBUG << "[ErrorHandler] Slide is full \n";
	}
	if (manager.actorFlag && manager.actorSignal == PuckManager::ActorSignal::SEND_SLIDE_EMPTY){
		 m_lightSystemService->setWarningLevel(Level::CLEAR_WARNING);
		 m_lightSystemService->setWarningLevel(Level::OPERATING);
		 LOG_DEBUG << "[ErrorHandler] Slide is empty \n";
	}

	//Only handle when error code
    if (manager.errorFlag) {
		m_hasError = true;

		m_lightSystemService->setWarningLevel(Level::ERROR_OCCURED);

		DistanceObservable &distO = DistanceObservable::getInstance();
		distO.updateSpeed(DistanceSpeed::STOP);

		m_conveyorBeltService->changeState(ConveyorBeltState::STOP);
		m_serialService->sendMsg(Serial_n::ser_proto_msg::STOP_SER);

		switch (manager.errorSignal) {

			case PuckManager::ErrorSignal::PUCK_LOST:
				cout << "[ErrorHandler] PUCK_LOST - Late Timer" << endl;
				LOG_DEBUG << "[ErrorHandler] PUCK_LOST - Late Timer" << endl;
				break;

			case PuckManager::ErrorSignal::PUCK_MOVED:
				cout << "[ErrorHandler] PUCK_MOVED - Puck triggered light barrier before early timer" << endl;
				LOG_DEBUG << "[ErrorHandler] PUCK_MOVED - Puck triggered light barrier before early timer" << endl;
				break;

			case PuckManager::ErrorSignal::UNEXPECTED_SIGNAL:
				cout << "[ErrorHandler] UNEXPECTED_SIGNAL - Signal could not be processed" << endl;
				LOG_DEBUG << "[ErrorHandler] UNEXPECTED_SIGNAL - Signal could not be processed" << endl;
				break;

			case PuckManager::ErrorSignal::MULTIPLE_ACCEPT:
				cout << "[ErrorHandler] MULTIPLE_ACCEPT - Shouldn't happen - multiple pucks were triggered" << endl;
				LOG_DEBUG << "[ErrorHandler] MULTIPLE_ACCEPT - Shouldn't happen - multiple pucks were triggered" << endl;
				break;

			case PuckManager::ErrorSignal::MULTIPLE_WARNING:
				cout << "[ErrorHandler] MULTIPLE_WARNING" << endl;
				LOG_DEBUG << "[ErrorHandler] MULTIPLE_WARNING" << endl;
				break;

			case PuckManager::ErrorSignal::BOTH_SLIDES_FULL:
				cout << "[ErrorHandler] BOTH_SLIDES_FULL" << endl;
				LOG_DEBUG << "[ErrorHandler] BOTH_SLIDES_FULL" << endl;
				break;

			default:
				 LOG_DEBUG << "[ErrorHandler] Unkown Error !!!" << endl;
				break;
		}
    }
}

bool ErrorHandler::hasError()
{
	LOG_DEBUG << "[ErrorHandler] Error: " << m_hasError << "\n";
    return m_hasError;
}

void ErrorHandler::handleEvent(rcv::msg_t event)
{
	LOG_DEBUG << "[ErrorHandler] Trying to demux " << event.code << " " << event.value << "\n";
	switch(event.code){
		case CodeDefinition::SER_IN :
			if( event.value == Serial_n::ser_proto_msg::ESTOP_SER ||
				event.value == Serial_n::ser_proto_msg::ERROR_SER ||
				event.value == Serial_n::ser_proto_msg::NO_CON_SER  ){
				LOG_DEBUG << "[ErrorHandler] Got error from serial \n";
				m_lightSystemService->setWarningLevel(Level::ERROR_OCCURED);
				m_conveyorBeltService->changeState(ConveyorBeltState::STOP);
				m_hasError = true;
				m_resetPressed = false;
			}
			break;
		case CodeDefinition::ISR :
			if(event.value == interrupts::BUTTON_ESTOP_IN){
				LOG_DEBUG << "[ErrorHandler] Got Estop from ISR \n";
				m_lightSystemService->setWarningLevel(Level::ERROR_OCCURED);
				m_serialService->sendMsg(Serial_n::ser_proto_msg::ESTOP_SER);
				m_conveyorBeltService->changeState(ConveyorBeltState::STOP);
				m_hasError = true;
				m_resetPressed = false;
			}
			break;
		default :
			//Nothing to do
			break;
	}

	if(m_hasError){
		 	 bool buttonReset = false;
		    bool buttonStart = false;

		    if (event.code != 5) { // 5 is hardcoded in the ISR. TODO Serial signal needs to get through when error is acknowledged on other machine
		        return; // Do not do anything without code 5!
		    }

		    switch(event.value) {

		        case interrupts::BUTTON_RESET:
		            buttonReset = true;
		            break;

		        case interrupts::BUTTON_START:
		            buttonStart = true;
		            break;

		        default:
		            // Nothing todo so far.
		            break;
		    }

		    if (buttonReset && m_hasError) {
		        m_resetPressed = true;
		        cout << "Error acknowledged" << endl;
		        m_lightSystemService->setWarningLevel(Level::ERROR_ACKNOWLEDGED);
		    } else if (buttonStart && m_resetPressed && m_hasError) { // Only go further when reset was pressed before.
		    	m_puckManager->reset();
				cout << "Clear error" << endl;
				m_lightSystemService->setWarningLevel(Level::OPERATING);
				m_resetPressed = false;
				m_hasError = false;
		    }
	}
}

/** @} */
<commit_msg>ErrorHandler Distributes signals now<commit_after>/*
 * Copyright (C) 2017 Rene Herthel
 *
 * This file is subject to the terms and conditions of the MIT License.
 * See the file LICENSE in the top level directory for more details.
 */

/**
 * @ingroup    error_handler
 * @{
 *
 * @brief      Function declaration of the ErrorHandler.
 *
 * @author     Rene Herthel <rene.herthel@haw-hamburg.de>
 */

#include "ErrorHandler.h"

#include "DistanceObservable.h"
#include "DistanceEnum.h"
#include "Signals.h"
#include "CodeDefinition.h"
#include "SerialProtocoll.h"
#include "Signals.h"

#include <iostream>
using namespace std;
using namespace HAL;

ErrorHandler::ErrorHandler( int chid,
                            ConveyorBeltService *conveyorBeltService,
                            LightSystemService *lightSystemService,
                            SerialService *serialService,
                            PuckManager *puckManager)
    :    m_hasError(false)
    ,    m_resetPressed(false)
    ,    m_conveyorBeltService(conveyorBeltService)
    ,    m_lightSystemService(lightSystemService)
	, 	 m_serialService(serialService)
	, 	 m_puckManager(puckManager)
{
    m_lightSystemService->setWarningLevel(Level::OPERATING);
}

ErrorHandler::~ErrorHandler()
{
    // Nothing todo so far.
}

void ErrorHandler::process(PuckManager::ManagerReturn &manager)
{
	LOG_DEBUG << "[ErrorHandler] Demux Manager return \n";
	LOG_DEBUG << "[ErrorHandler] Actor Flag " << manager.actorFlag << " actorSignal " << (int)manager.actorSignal << "\n";

	//if slide full return a warning
	if (manager.actorFlag && manager.actorSignal == PuckManager::ActorSignal::SEND_SLIDE_FULL){
		 m_lightSystemService->setWarningLevel(Level::WARNING_OCCURED);
		 LOG_DEBUG << "[ErrorHandler] Slide is full \n";
	}
	if (manager.actorFlag && manager.actorSignal == PuckManager::ActorSignal::SEND_SLIDE_EMPTY){
		 m_lightSystemService->setWarningLevel(Level::CLEAR_WARNING);
		 m_lightSystemService->setWarningLevel(Level::OPERATING);
		 LOG_DEBUG << "[ErrorHandler] Slide is empty \n";
	}

	//Only handle when error code
    if (manager.errorFlag) {
		m_hasError = true;

		m_lightSystemService->setWarningLevel(Level::ERROR_OCCURED);

		DistanceObservable &distO = DistanceObservable::getInstance();
		distO.updateSpeed(DistanceSpeed::STOP);

		m_conveyorBeltService->changeState(ConveyorBeltState::STOP);
		m_serialService->sendMsg(Serial_n::ser_proto_msg::STOP_SER);

		switch (manager.errorSignal) {

			case PuckManager::ErrorSignal::PUCK_LOST:
				cout << "[ErrorHandler] PUCK_LOST - Late Timer" << endl;
				LOG_DEBUG << "[ErrorHandler] PUCK_LOST - Late Timer" << endl;
				break;

			case PuckManager::ErrorSignal::PUCK_MOVED:
				cout << "[ErrorHandler] PUCK_MOVED - Puck triggered light barrier before early timer" << endl;
				LOG_DEBUG << "[ErrorHandler] PUCK_MOVED - Puck triggered light barrier before early timer" << endl;
				break;

			case PuckManager::ErrorSignal::UNEXPECTED_SIGNAL:
				cout << "[ErrorHandler] UNEXPECTED_SIGNAL - Signal could not be processed" << endl;
				LOG_DEBUG << "[ErrorHandler] UNEXPECTED_SIGNAL - Signal could not be processed" << endl;
				break;

			case PuckManager::ErrorSignal::MULTIPLE_ACCEPT:
				cout << "[ErrorHandler] MULTIPLE_ACCEPT - Shouldn't happen - multiple pucks were triggered" << endl;
				LOG_DEBUG << "[ErrorHandler] MULTIPLE_ACCEPT - Shouldn't happen - multiple pucks were triggered" << endl;
				break;

			case PuckManager::ErrorSignal::MULTIPLE_WARNING:
				cout << "[ErrorHandler] MULTIPLE_WARNING" << endl;
				LOG_DEBUG << "[ErrorHandler] MULTIPLE_WARNING" << endl;
				break;

			default:
				 LOG_DEBUG << "[ErrorHandler] Unkown Error !!!" << endl;
				break;
		}
    }
}

bool ErrorHandler::hasError()
{
	LOG_DEBUG << "[ErrorHandler] Error: " << m_hasError << "\n";
    return m_hasError;
}

void ErrorHandler::handleEvent(rcv::msg_t event)
{
	LOG_DEBUG << "[ErrorHandler] Trying to demux " << event.code << " " << event.value << "\n";
	switch(event.code){
		case CodeDefinition::SER_IN :
			if( event.value == Serial_n::ser_proto_msg::ESTOP_SER ||
				event.value == Serial_n::ser_proto_msg::ERROR_SER ||
				event.value == Serial_n::ser_proto_msg::NO_CON_SER  ){
				LOG_DEBUG << "[ErrorHandler] Got error from serial \n";
				m_lightSystemService->setWarningLevel(Level::ERROR_OCCURED);
				m_conveyorBeltService->changeState(ConveyorBeltState::STOP);
				m_hasError = true;
				m_resetPressed = false;
			}
			break;
		case CodeDefinition::ISR :
			if(event.value == interrupts::BUTTON_ESTOP_IN){
				LOG_DEBUG << "[ErrorHandler] Got Estop from ISR \n";
				m_lightSystemService->setWarningLevel(Level::ERROR_OCCURED);
				m_serialService->sendMsg(Serial_n::ser_proto_msg::ESTOP_SER);
				m_conveyorBeltService->changeState(ConveyorBeltState::STOP);
				m_hasError = true;
				m_resetPressed = false;
			}
			break;
		default :
			//Nothing to do
			break;
	}

	if(m_hasError){
		 	bool buttonReset = false;
		    bool buttonStart = false;

		    if (event.code != 5) { // 5 is hardcoded in the ISR. TODO Serial signal needs to get through when error is acknowledged on other machine
		        return; // Do not do anything without code 5!
		    }

		    switch(event.value) {

		        case interrupts::BUTTON_RESET:
		            buttonReset = true;
		            break;

		        case interrupts::BUTTON_START:
		            buttonStart = true;
		            break;

		        case interrupts::SLIDE_OUT:
		        	PuckSignal::Signal signal;
		        	signal.signalType = PuckSignal::SignalType::INTERRUPT_SIGNAL;
		        	signal.interruptSignal = event.value;
		        	m_puckManager->process(signal);
		        	break;
		        default:
		            // Nothing todo so far.
		            break;
		    }

		    if (buttonReset && m_hasError) {
		        m_resetPressed = true;
		        cout << "Error acknowledged" << endl;
		        m_lightSystemService->setWarningLevel(Level::ERROR_ACKNOWLEDGED);
		    } else if (buttonStart && m_resetPressed && m_hasError) { // Only go further when reset was pressed before.
		    	m_puckManager->reset();
				cout << "Clear error" << endl;
				m_lightSystemService->setWarningLevel(Level::OPERATING);
				m_resetPressed = false;
				m_hasError = false;
		    }
	}
}

/** @} */
<|endoftext|>