<commit_before>#include "oddlib/compressiontype6or7aepsx.hpp"
#include "oddlib/stream.hpp"
#include "logger.hpp"
#include <vector>
#include <cassert>

namespace Oddlib
{
    template<Uint32 BitsSize, typename OutType>
    void NextBits(unsigned int& bitCounter, unsigned int& srcWorkBits, Uint16 *&pSrc1, Uint16 *&pSrcCopy, const signed int kFixedMask, OutType& maskedSrcBits1)
    {
        if (bitCounter < 16)
        {
            const int srcBits = *pSrc1 << bitCounter;
            bitCounter += 16;
            srcWorkBits |= srcBits;
            ++pSrc1;
            pSrcCopy = pSrc1;
        }

        bitCounter -= BitsSize;
        maskedSrcBits1 = static_cast<OutType>(srcWorkBits & (kFixedMask - 1));
        srcWorkBits >>= BitsSize;
    }

    // Function 0x004ABB90 in AE, function 0x8005B09C in AE PSX demo
    template<Uint32 BitsSize>
    std::vector<Uint8> CompressionType6or7AePsx<BitsSize>::Decompress(IStream& stream, Uint32 finalW, Uint32 /*w*/, Uint32 h, Uint32 dataSize)
    {
        std::vector<Uint8> out(finalW*h * 400);
        std::vector<Uint8> in(dataSize);
        stream.ReadBytes(in.data(), in.size());

        Uint16* pInput = (Uint16*)in.data();
        Uint8* pOutput = (Uint8*)out.data();
        int whDWORD = dataSize;

        unsigned int bitCounter = 0; // edx@1
        Uint16 *pSrc1 = pInput; // ebp@1
        Uint16 *pSrcCopy = pInput; // [sp+Ch] [bp-31Ch]@1

        unsigned int srcWorkBits = 0; // esi@1
        int count = 0; // eax@2
        unsigned int maskedSrcBits1 = 0; // ebx@5
        int v14 = 0; // ebx@15
        char v16 = 0; // bl@18
        char bLastByte = 0; // zf@19
        int v19 = 0; // eax@23
        int v23 = 0; // eax@25
        int v24 = 0; // ebx@27
        int v25 = 0; // ebx@28
        int i = 0; // ebp@32
        unsigned char v28 = 0; // cl@33

        int count2 = 0; // [sp+10h] [bp-318h]@11
        int v33 = 0; // [sp+10h] [bp-318h]@25

        unsigned char tmp1[256] = {}; // [sp+28h] [bp-300h]@15
        unsigned char tmp2[256] = {}; // [sp+128h] [bp-200h]@8
        unsigned char tmp3[256] = {}; // [sp+228h] [bp-100h]@27

        const signed int kFixedMask = 1 << BitsSize;

        const unsigned int v36 = ((unsigned int)(kFixedMask) >> 1) - 1;

        while (pSrc1 < (Uint16 *)((char *)pInput + ((unsigned int)(BitsSize * whDWORD) >> 3)))// could be the first dword of the frame which is usually the size?
        {
            count = 0;
            do
            {
                NextBits<BitsSize>(bitCounter, srcWorkBits, pSrc1, pSrcCopy, kFixedMask, maskedSrcBits1);

                int maskedSrcBits1Copy = maskedSrcBits1;

                if (maskedSrcBits1 > v36)
                {
                    int remainder = maskedSrcBits1 - v36;
                    maskedSrcBits1Copy = remainder;
                    if (remainder)
                    {
                        int remainderCopy = remainder;
                        do
                        {
                            tmp2[count] = static_cast<char>(count);
                            ++count;
                            --remainder;
                            --remainderCopy;
                        } while (remainderCopy);
                        maskedSrcBits1Copy = remainder;
                    }
                }

                if (count == kFixedMask)
                {
                    break;
                }

                count2 = maskedSrcBits1Copy + 1;
                for (;;)
                {
                    NextBits<BitsSize>(bitCounter, srcWorkBits, pSrc1, pSrcCopy, kFixedMask, v14);
                    *(&tmp1[count] + (tmp2 - tmp1)) = static_cast<char>(v14);
                    if (count != v14)
                    {
                        NextBits<BitsSize>(bitCounter, srcWorkBits, pSrc1, pSrcCopy, kFixedMask, v16);
                        tmp1[count] = static_cast<unsigned char>(v16);
                    }
                    ++count;
                    bLastByte = count2-- == 1;
                    if (bLastByte)
                    {
                        break;
                    }

                    pSrc1 = pSrcCopy; // dead?
                }
                pSrc1 = pSrcCopy; // dead?
            } while (count != kFixedMask);

            NextBits<BitsSize>(bitCounter, srcWorkBits, pSrc1, pSrcCopy, kFixedMask, v19);
            v19 = v19 << BitsSize; // Extra

            NextBits<BitsSize>(bitCounter, srcWorkBits, pSrc1, pSrcCopy, kFixedMask, v33);

            v33 = v33 + v19; // Extra
            v23 = 0;
            for (;;)
            {
                if (v23)
                {
                    --v23;
                    v24 = tmp3[v23];
                }
                else
                {
                    v25 = v33--;
                    if (!v25)
                    {
                        break;
                    }

                    NextBits<BitsSize>(bitCounter, srcWorkBits, pSrc1, pSrcCopy, kFixedMask, v24);
                }

                for (i = tmp2[v24]; v24 != i; i = tmp2[i])
                {
                    v28 = tmp1[v24];
                    v24 = i;
                    tmp3[v23++] = v28;
                }
                pSrc1 = pSrcCopy; // dead?
                *pOutput++ = static_cast<Uint8>(v24);
            }
        }

        return out;

    }

    // Explicit template instantiation
    template class CompressionType6or7AePsx<6>;
    template class CompressionType6or7AePsx<8>;
}
<commit_msg>read correct amount of input data<commit_after>#include "oddlib/compressiontype6or7aepsx.hpp"
#include "oddlib/stream.hpp"
#include "logger.hpp"
#include <vector>
#include <cassert>

namespace Oddlib
{
    template<Uint32 BitsSize, typename OutType>
    void NextBits(unsigned int& bitCounter, unsigned int& srcWorkBits, Uint16 *&pSrc1, Uint16 *&pSrcCopy, const signed int kFixedMask, OutType& maskedSrcBits1)
    {
        if (bitCounter < 16)
        {
            const int srcBits = *pSrc1 << bitCounter;
            bitCounter += 16;
            srcWorkBits |= srcBits;
            ++pSrc1;
            pSrcCopy = pSrc1;
        }

        bitCounter -= BitsSize;
        maskedSrcBits1 = static_cast<OutType>(srcWorkBits & (kFixedMask - 1));
        srcWorkBits >>= BitsSize;
    }

    // Function 0x004ABB90 in AE, function 0x8005B09C in AE PSX demo
    template<Uint32 BitsSize>
    std::vector<Uint8> CompressionType6or7AePsx<BitsSize>::Decompress(IStream& stream, Uint32 finalW, Uint32 /*w*/, Uint32 h, Uint32 dataSize)
    {
        unsigned int kInputSize = (BitsSize * dataSize) >> 3;

        std::vector<Uint8> out(finalW*h * 4);
        std::vector<Uint8> in(kInputSize);
        stream.ReadBytes(in.data(), in.size());

        Uint16* pInput = (Uint16*)in.data();
        Uint8* pOutput = (Uint8*)out.data();

        unsigned int bitCounter = 0; // edx@1
        Uint16 *pSrc1 = pInput; // ebp@1
        Uint16 *pSrcCopy = pInput; // [sp+Ch] [bp-31Ch]@1

        unsigned int srcWorkBits = 0; // esi@1
        int count = 0; // eax@2
        unsigned int maskedSrcBits1 = 0; // ebx@5
        int v14 = 0; // ebx@15
        char v16 = 0; // bl@18
        char bLastByte = 0; // zf@19
        int v19 = 0; // eax@23
        int v23 = 0; // eax@25
        int v24 = 0; // ebx@27
        int v25 = 0; // ebx@28
        int i = 0; // ebp@32
        unsigned char v28 = 0; // cl@33

        int count2 = 0; // [sp+10h] [bp-318h]@11
        int v33 = 0; // [sp+10h] [bp-318h]@25

        unsigned char tmp1[256] = {}; // [sp+28h] [bp-300h]@15
        unsigned char tmp2[256] = {}; // [sp+128h] [bp-200h]@8
        unsigned char tmp3[256] = {}; // [sp+228h] [bp-100h]@27

        const signed int kFixedMask = 1 << BitsSize;

        const unsigned int v36 = ((unsigned int)(kFixedMask) >> 1) - 1;

        while (pSrc1 < (Uint16 *)( ((char *)pInput) + kInputSize))// could be the first dword of the frame which is usually the size?
        {
            count = 0;
            do
            {
                NextBits<BitsSize>(bitCounter, srcWorkBits, pSrc1, pSrcCopy, kFixedMask, maskedSrcBits1);

                int maskedSrcBits1Copy = maskedSrcBits1;

                if (maskedSrcBits1 > v36)
                {
                    int remainder = maskedSrcBits1 - v36;
                    maskedSrcBits1Copy = remainder;
                    if (remainder)
                    {
                        int remainderCopy = remainder;
                        do
                        {
                            tmp2[count] = static_cast<char>(count);
                            ++count;
                            --remainder;
                            --remainderCopy;
                        } while (remainderCopy);
                        maskedSrcBits1Copy = remainder;
                    }
                }

                if (count == kFixedMask)
                {
                    break;
                }

                count2 = maskedSrcBits1Copy + 1;
                for (;;)
                {
                    NextBits<BitsSize>(bitCounter, srcWorkBits, pSrc1, pSrcCopy, kFixedMask, v14);
                    *(&tmp1[count] + (tmp2 - tmp1)) = static_cast<char>(v14);
                    if (count != v14)
                    {
                        NextBits<BitsSize>(bitCounter, srcWorkBits, pSrc1, pSrcCopy, kFixedMask, v16);
                        tmp1[count] = static_cast<unsigned char>(v16);
                    }
                    ++count;
                    bLastByte = count2-- == 1;
                    if (bLastByte)
                    {
                        break;
                    }

                    pSrc1 = pSrcCopy; // dead?
                }
                pSrc1 = pSrcCopy; // dead?
            } while (count != kFixedMask);

            NextBits<BitsSize>(bitCounter, srcWorkBits, pSrc1, pSrcCopy, kFixedMask, v19);
            v19 = v19 << BitsSize; // Extra

            NextBits<BitsSize>(bitCounter, srcWorkBits, pSrc1, pSrcCopy, kFixedMask, v33);

            v33 = v33 + v19; // Extra
            v23 = 0;
            for (;;)
            {
                if (v23)
                {
                    --v23;
                    v24 = tmp3[v23];
                }
                else
                {
                    v25 = v33--;
                    if (!v25)
                    {
                        break;
                    }

                    NextBits<BitsSize>(bitCounter, srcWorkBits, pSrc1, pSrcCopy, kFixedMask, v24);
                }

                for (i = tmp2[v24]; v24 != i; i = tmp2[i])
                {
                    v28 = tmp1[v24];
                    v24 = i;
                    tmp3[v23++] = v28;
                }
                pSrc1 = pSrcCopy; // dead?
                *pOutput++ = static_cast<Uint8>(v24);
            }
        }

        return out;
    }

    // Explicit template instantiation
    template class CompressionType6or7AePsx<6>;
    template class CompressionType6or7AePsx<8>;
}
<|endoftext|>


<commit_before>#include "JME_Time.h"
#include "boost/date_time/posix_time/posix_time.hpp"

namespace JMEngine
{
	namespace game
	{

		bool JME_Time::isTimeToday(time_t t)
		{
			auto ct = boost::posix_time::from_time_t(t);
			auto nt = boost::posix_time::second_clock::local_time();

			return ct.date() == nt.date();
		}

		int JME_Time::todayYearday()
		{
			auto nt = boost::posix_time::second_clock::local_time();
			return nt.date().day_of_year();
		}

		tm JME_Time::localTime()
		{
			return boost::posix_time::to_tm(boost::posix_time::second_clock::local_time());
		}

		tm JME_Time::localTime(time_t t)
		{
			tm * timeinfo = localtime(&t);
			return *timeinfo;
		}

	}
}<commit_msg>JID:NO 判断时间戳 是否 当天错误<commit_after>#include "JME_Time.h"
#include "boost/date_time/posix_time/posix_time.hpp"

namespace JMEngine
{
	namespace game
	{

		bool JME_Time::isTimeToday(time_t t)
		{
			tm timeinfo = *localtime(&t);

			auto ct = boost::posix_time::ptime_from_tm(timeinfo);
			auto nt = boost::posix_time::second_clock::local_time();

			return ct.date() == nt.date();
		}

		int JME_Time::todayYearday()
		{
			auto nt = boost::posix_time::second_clock::local_time();
			return nt.date().day_of_year();
		}

		tm JME_Time::localTime()
		{
			return boost::posix_time::to_tm(boost::posix_time::second_clock::local_time());
		}

		tm JME_Time::localTime(time_t t)
		{
			tm * timeinfo = localtime(&t);
			return *timeinfo;
		}

	}
}<|endoftext|>


<commit_before>/***
Copyright (C) 2013-2014 Aniket Deole <aniket.deole@gmail.com>
This program is free software: you can redistribute it and/or modify it
under the terms of the GNU Lesser General Public License version 2.1, as published
by the Free Software Foundation.

This program is distributed in the hope that it will be useful, but
WITHOUT ANY WARRANTY; without even the implied warranties of
MERCHANTABILITY, SATISFACTORY QUALITY, 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 <protocol/TBinaryProtocol.h>
#include <transport/THttpClient.h>
#include <transport/TSSLSocket.h>
#include "evernote.hh"

void print_md5_sum(unsigned char* md) {
    int i;
    for(i=0; i <MD5_DIGEST_LENGTH; i++) {
            printf("%02x",md[i]);
    }
}

evernote::UserStore::UserStore (std::string eU, int p, std::string pT,
            std::string authenticationToken) {

    evernoteUrl = eU;
    port = p;
    parameterThree = pT;

    auth_http = boost::shared_ptr<apache::thrift::transport::THttpClient>(
        new apache::thrift::transport::THttpClient(evernoteUrl, port, parameterThree));
    auth_http->open();
    boost::shared_ptr<apache::thrift::protocol::TBinaryProtocol> userStoreProt(
        new apache::thrift::protocol::TBinaryProtocol(auth_http));
    userStore = new evernote::edam::UserStoreClient (userStoreProt, userStoreProt);
    /**
     * We have the userStore working.
     */
    delete userStore;
    auth_http->close ();
}

evernote::UserStore::~UserStore () {
    auth_http->close ();
}

std::string evernote::UserStore::getNoteStoreUrl (std::string authToken) {
    auth_http = boost::shared_ptr<apache::thrift::transport::THttpClient>(
        new apache::thrift::transport::THttpClient(evernoteUrl, port, parameterThree));
    auth_http->open();
    boost::shared_ptr<apache::thrift::protocol::TBinaryProtocol> userStoreProt(
        new apache::thrift::protocol::TBinaryProtocol(auth_http));
    userStore = new evernote::edam::UserStoreClient (userStoreProt, userStoreProt);
    std::string noteStoreUrl;
    userStore->getNoteStoreUrl (noteStoreUrl, authToken);
    auth_http->close ();
    delete userStore;
    return noteStoreUrl;
}

evernote::NoteStore::NoteStore (std::string noteStoreUrl) {
    boost::shared_ptr<apache::thrift::transport::TSSLSocketFactory> sslSocketFactory =
    boost::shared_ptr<apache::thrift::transport::TSSLSocketFactory>(
        new apache::thrift::transport::TSSLSocketFactory());;

    boost::shared_ptr<apache::thrift::transport::TSocket> sslSocket = sslSocketFactory->
        createSocket("sandbox.evernote.com", 443);
    boost::shared_ptr<apache::thrift::transport::TBufferedTransport> bufferedTransport(
        new apache::thrift::transport::TBufferedTransport(sslSocket));
    userStoreHttpClient = boost::shared_ptr<apache::thrift::transport::THttpClient>(
        new apache::thrift::transport::THttpClient(bufferedTransport, "sandbox.evernote.com", noteStoreUrl));

    userStoreHttpClient->open();

    boost::shared_ptr<apache::thrift::protocol::TBinaryProtocol> noteStoreProt(
        new apache::thrift::protocol::TBinaryProtocol(userStoreHttpClient) );
    noteStore = new evernote::edam::NoteStoreClient (noteStoreProt, noteStoreProt);
}

evernote::NoteStore::~NoteStore () {
    userStoreHttpClient->close ();
}<commit_msg>Added Exception Handling.<commit_after>/***
Copyright (C) 2013-2014 Aniket Deole <aniket.deole@gmail.com>
This program is free software: you can redistribute it and/or modify it
under the terms of the GNU Lesser General Public License version 2.1, as published
by the Free Software Foundation.

This program is distributed in the hope that it will be useful, but
WITHOUT ANY WARRANTY; without even the implied warranties of
MERCHANTABILITY, SATISFACTORY QUALITY, 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 <protocol/TBinaryProtocol.h>
#include <transport/THttpClient.h>
#include <transport/TSSLSocket.h>
#include "evernote.hh"

void print_md5_sum(unsigned char* md) {
    int i;
    for(i=0; i <MD5_DIGEST_LENGTH; i++) {
            printf("%02x",md[i]);
    }
}

evernote::UserStore::UserStore (std::string eU, int p, std::string pT,
            std::string authenticationToken) {

    evernoteUrl = eU;
    port = p;
    parameterThree = pT;

    auth_http = boost::shared_ptr<apache::thrift::transport::THttpClient>(
        new apache::thrift::transport::THttpClient(evernoteUrl, port, parameterThree));
    auth_http->open();
    boost::shared_ptr<apache::thrift::protocol::TBinaryProtocol> userStoreProt(
        new apache::thrift::protocol::TBinaryProtocol(auth_http));
    userStore = new evernote::edam::UserStoreClient (userStoreProt, userStoreProt);
    /**
     * We have the userStore working.
     */
}

evernote::UserStore::~UserStore () {
    auth_http->close ();
}

std::string evernote::UserStore::getNoteStoreUrl (std::string authToken) {
    try {
        std::string noteStoreUrl;
        userStore->getNoteStoreUrl (noteStoreUrl, authToken);
        return noteStoreUrl;
    } catch (apache::thrift::transport::TTransportException e) {
        auth_http->close ();
        delete userStore;
        auth_http = boost::shared_ptr<apache::thrift::transport::THttpClient>(
            new apache::thrift::transport::THttpClient(evernoteUrl, port, parameterThree));
        auth_http->open();
        boost::shared_ptr<apache::thrift::protocol::TBinaryProtocol> userStoreProt(
            new apache::thrift::protocol::TBinaryProtocol(auth_http));
        userStore = new evernote::edam::UserStoreClient (userStoreProt, userStoreProt);
        std::string noteStoreUrl;
        userStore->getNoteStoreUrl (noteStoreUrl, authToken);
        auth_http->close ();
        delete userStore;
        return noteStoreUrl;
    }
}

evernote::NoteStore::NoteStore (std::string noteStoreUrl) {
    boost::shared_ptr<apache::thrift::transport::TSSLSocketFactory> sslSocketFactory =
    boost::shared_ptr<apache::thrift::transport::TSSLSocketFactory>(
        new apache::thrift::transport::TSSLSocketFactory());;

    boost::shared_ptr<apache::thrift::transport::TSocket> sslSocket = sslSocketFactory->
        createSocket("sandbox.evernote.com", 443);
    boost::shared_ptr<apache::thrift::transport::TBufferedTransport> bufferedTransport(
        new apache::thrift::transport::TBufferedTransport(sslSocket));
    userStoreHttpClient = boost::shared_ptr<apache::thrift::transport::THttpClient>(
        new apache::thrift::transport::THttpClient(bufferedTransport, "sandbox.evernote.com", noteStoreUrl));

    userStoreHttpClient->open();

    boost::shared_ptr<apache::thrift::protocol::TBinaryProtocol> noteStoreProt(
        new apache::thrift::protocol::TBinaryProtocol(userStoreHttpClient) );
    noteStore = new evernote::edam::NoteStoreClient (noteStoreProt, noteStoreProt);
}

evernote::NoteStore::~NoteStore () {
    userStoreHttpClient->close ();
}<|endoftext|>


<commit_before>// Copyright (c) 2006-2008 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.
//
// See the corresponding header file for description of the functions in this
// file.

#include "install_util.h"

#include <algorithm>
#include <shellapi.h>
#include <shlobj.h>

#include "base/logging.h"
#include "base/registry.h"
#include "base/string_util.h"
#include "base/win_util.h"

#include "chrome/installer/util/browser_distribution.h"
#include "chrome/installer/util/google_update_constants.h"
#include "chrome/installer/util/l10n_string_util.h"
#include "chrome/installer/util/work_item_list.h"

bool InstallUtil::ExecuteExeAsAdmin(const std::wstring& exe,
                                    const std::wstring& params,
                                    DWORD* exit_code) {
  SHELLEXECUTEINFO info = {0};
  info.cbSize = sizeof(SHELLEXECUTEINFO);
  info.fMask = SEE_MASK_NOCLOSEPROCESS;
  info.lpVerb = L"runas";
  info.lpFile = exe.c_str();
  info.lpParameters = params.c_str();
  info.nShow = SW_SHOW;
  if (::ShellExecuteEx(&info) == FALSE)
    return false;

  ::WaitForSingleObject(info.hProcess, INFINITE);
  DWORD ret_val = 0;
  if (!::GetExitCodeProcess(info.hProcess, &ret_val))
    return false;

  if (exit_code)
    *exit_code = ret_val;
  return true;
}

std::wstring InstallUtil::GetChromeUninstallCmd(bool system_install) {
  HKEY root = system_install ? HKEY_LOCAL_MACHINE : HKEY_CURRENT_USER;
  BrowserDistribution* dist = BrowserDistribution::GetDistribution();
  RegKey key(root, dist->GetUninstallRegPath().c_str());
  std::wstring uninstall_cmd;
  key.ReadValue(installer_util::kUninstallStringField, &uninstall_cmd);
  return uninstall_cmd;
}

installer::Version* InstallUtil::GetChromeVersion(bool system_install) {
  RegKey key;
  std::wstring version_str;

  HKEY reg_root = (system_install) ? HKEY_LOCAL_MACHINE : HKEY_CURRENT_USER;
  BrowserDistribution* dist = BrowserDistribution::GetDistribution();
  if (!key.Open(reg_root, dist->GetVersionKey().c_str(), KEY_READ) ||
      !key.ReadValue(google_update::kRegVersionField, &version_str)) {
    LOG(INFO) << "No existing Chrome install found.";
    key.Close();
    return NULL;
  }
  key.Close();
  LOG(INFO) << "Existing Chrome version found " << version_str;
  return installer::Version::GetVersionFromString(version_str);
}

bool InstallUtil::IsOSSupported() {
  int major, minor;
  win_util::WinVersion version = win_util::GetWinVersion();
  win_util::GetServicePackLevel(&major, &minor);

  // We do not support Win2K or older, or XP without service pack 1.
  LOG(INFO) << "Windows Version: " << version
            << ", Service Pack: " << major << "." << minor;
  if ((version == win_util::WINVERSION_VISTA) ||
      (version == win_util::WINVERSION_SERVER_2003) ||
      (version == win_util::WINVERSION_XP && major >= 1)) {
    return true;
  }
  return false;
}

void InstallUtil::WriteInstallerResult(bool system_install,
                                       installer_util::InstallStatus status,
                                       int string_resource_id,
                                       const std::wstring* const launch_cmd) {
  HKEY root = system_install ? HKEY_LOCAL_MACHINE : HKEY_CURRENT_USER;
  BrowserDistribution* dist = BrowserDistribution::GetDistribution();
  std::wstring key = dist->GetVersionKey();
  int installer_result = (dist->GetInstallReturnCode(status) == 0) ? 0 : 1;
  scoped_ptr<WorkItemList> install_list(WorkItem::CreateWorkItemList());
  install_list->AddSetRegValueWorkItem(root, key, L"InstallerResult",
                                       installer_result, true);
  install_list->AddSetRegValueWorkItem(root, key, L"InstallerError",
                                       status, true);
  if (string_resource_id != 0) {
    std::wstring msg = installer_util::GetLocalizedString(string_resource_id);
    install_list->AddSetRegValueWorkItem(root, key, L"InstallerResultUIString",
                                         msg, true);
  }
  if (launch_cmd != NULL) {
    install_list->AddSetRegValueWorkItem(root, key,
                                         L"InstallerSuccessLaunchCmdLine",
                                         *launch_cmd, true);
  }
  if (!install_list->Do())
    LOG(ERROR) << "Failed to record installer error information in registry.";
}

bool InstallUtil::IsPerUserInstall(const wchar_t* const exe_path) {
  std::wstring exe_path_copy = exe_path;

  wchar_t program_files_path[MAX_PATH] = {0};
  if (SUCCEEDED(SHGetFolderPath(NULL, CSIDL_PROGRAM_FILES, NULL,
                                SHGFP_TYPE_CURRENT, program_files_path))) {
    std::wstring program_files_path_copy = program_files_path;

    if (std::equal(program_files_path_copy.begin(),
                   program_files_path_copy.end(), exe_path_copy.begin(),
                   CaseInsensitiveCompare<wchar_t>())) {
      return false;
    }
  } else {
    NOTREACHED();
  }
  return true;
}<commit_msg>Fixes a crash if you put chrome in a very short directory - like c:\bang. - it will crash at startup on a bad iterator use.<commit_after>// Copyright (c) 2006-2008 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.
//
// See the corresponding header file for description of the functions in this
// file.

#include "install_util.h"

#include <algorithm>
#include <shellapi.h>
#include <shlobj.h>

#include "base/logging.h"
#include "base/registry.h"
#include "base/string_util.h"
#include "base/win_util.h"

#include "chrome/installer/util/browser_distribution.h"
#include "chrome/installer/util/google_update_constants.h"
#include "chrome/installer/util/l10n_string_util.h"
#include "chrome/installer/util/work_item_list.h"

bool InstallUtil::ExecuteExeAsAdmin(const std::wstring& exe,
                                    const std::wstring& params,
                                    DWORD* exit_code) {
  SHELLEXECUTEINFO info = {0};
  info.cbSize = sizeof(SHELLEXECUTEINFO);
  info.fMask = SEE_MASK_NOCLOSEPROCESS;
  info.lpVerb = L"runas";
  info.lpFile = exe.c_str();
  info.lpParameters = params.c_str();
  info.nShow = SW_SHOW;
  if (::ShellExecuteEx(&info) == FALSE)
    return false;

  ::WaitForSingleObject(info.hProcess, INFINITE);
  DWORD ret_val = 0;
  if (!::GetExitCodeProcess(info.hProcess, &ret_val))
    return false;

  if (exit_code)
    *exit_code = ret_val;
  return true;
}

std::wstring InstallUtil::GetChromeUninstallCmd(bool system_install) {
  HKEY root = system_install ? HKEY_LOCAL_MACHINE : HKEY_CURRENT_USER;
  BrowserDistribution* dist = BrowserDistribution::GetDistribution();
  RegKey key(root, dist->GetUninstallRegPath().c_str());
  std::wstring uninstall_cmd;
  key.ReadValue(installer_util::kUninstallStringField, &uninstall_cmd);
  return uninstall_cmd;
}

installer::Version* InstallUtil::GetChromeVersion(bool system_install) {
  RegKey key;
  std::wstring version_str;

  HKEY reg_root = (system_install) ? HKEY_LOCAL_MACHINE : HKEY_CURRENT_USER;
  BrowserDistribution* dist = BrowserDistribution::GetDistribution();
  if (!key.Open(reg_root, dist->GetVersionKey().c_str(), KEY_READ) ||
      !key.ReadValue(google_update::kRegVersionField, &version_str)) {
    LOG(INFO) << "No existing Chrome install found.";
    key.Close();
    return NULL;
  }
  key.Close();
  LOG(INFO) << "Existing Chrome version found " << version_str;
  return installer::Version::GetVersionFromString(version_str);
}

bool InstallUtil::IsOSSupported() {
  int major, minor;
  win_util::WinVersion version = win_util::GetWinVersion();
  win_util::GetServicePackLevel(&major, &minor);

  // We do not support Win2K or older, or XP without service pack 1.
  LOG(INFO) << "Windows Version: " << version
            << ", Service Pack: " << major << "." << minor;
  if ((version == win_util::WINVERSION_VISTA) ||
      (version == win_util::WINVERSION_SERVER_2003) ||
      (version == win_util::WINVERSION_XP && major >= 1)) {
    return true;
  }
  return false;
}

void InstallUtil::WriteInstallerResult(bool system_install,
                                       installer_util::InstallStatus status,
                                       int string_resource_id,
                                       const std::wstring* const launch_cmd) {
  HKEY root = system_install ? HKEY_LOCAL_MACHINE : HKEY_CURRENT_USER;
  BrowserDistribution* dist = BrowserDistribution::GetDistribution();
  std::wstring key = dist->GetVersionKey();
  int installer_result = (dist->GetInstallReturnCode(status) == 0) ? 0 : 1;
  scoped_ptr<WorkItemList> install_list(WorkItem::CreateWorkItemList());
  install_list->AddSetRegValueWorkItem(root, key, L"InstallerResult",
                                       installer_result, true);
  install_list->AddSetRegValueWorkItem(root, key, L"InstallerError",
                                       status, true);
  if (string_resource_id != 0) {
    std::wstring msg = installer_util::GetLocalizedString(string_resource_id);
    install_list->AddSetRegValueWorkItem(root, key, L"InstallerResultUIString",
                                         msg, true);
  }
  if (launch_cmd != NULL) {
    install_list->AddSetRegValueWorkItem(root, key,
                                         L"InstallerSuccessLaunchCmdLine",
                                         *launch_cmd, true);
  }
  if (!install_list->Do())
    LOG(ERROR) << "Failed to record installer error information in registry.";
}

bool InstallUtil::IsPerUserInstall(const wchar_t* const exe_path) {

  wchar_t program_files_path[MAX_PATH] = {0};
  if (SUCCEEDED(SHGetFolderPath(NULL, CSIDL_PROGRAM_FILES, NULL,
                                SHGFP_TYPE_CURRENT, program_files_path))) {
    return !StartsWith(exe_path, program_files_path, false);
  } else {
    NOTREACHED();
  }
  return true;
}
<|endoftext|>


<commit_before>/*************************************************************************
 *
 *  OpenOffice.org - a multi-platform office productivity suite
 *
 *  $RCSfile: anytostring.cxx,v $
 *
 *  $Revision: 1.5 $
 *
 *  last change: $Author: rt $ $Date: 2005-09-08 02:48:34 $
 *
 *  The Contents of this file are made available subject to
 *  the terms of GNU Lesser General Public License Version 2.1.
 *
 *
 *    GNU Lesser General Public License Version 2.1
 *    =============================================
 *    Copyright 2005 by Sun Microsystems, Inc.
 *    901 San Antonio Road, Palo Alto, CA 94303, USA
 *
 *    This library is free software; you can redistribute it and/or
 *    modify it under the terms of the GNU Lesser General Public
 *    License version 2.1, as published by the Free Software Foundation.
 *
 *    This library 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
 *    Lesser General Public License for more details.
 *
 *    You should have received a copy of the GNU Lesser General Public
 *    License along with this library; if not, write to the Free Software
 *    Foundation, Inc., 59 Temple Place, Suite 330, Boston,
 *    MA  02111-1307  USA
 *
 ************************************************************************/

#include "comphelper/anytostring.hxx"

#include "rtl/ustring.hxx"
#include "rtl/ustrbuf.hxx"
#include "typelib/typedescription.h"
#include "com/sun/star/uno/Any.hxx"
#include "com/sun/star/lang/XServiceInfo.hpp"

using namespace ::com::sun::star;
using namespace ::com::sun::star::uno;
using ::rtl::OUString;
using ::rtl::OUStringBuffer;

namespace comphelper
{

//------------------------------------------------------------------------------
static void appendTypeError(
    OUStringBuffer & buf, typelib_TypeDescriptionReference * typeRef )
{
    buf.appendAscii(
        RTL_CONSTASCII_STRINGPARAM("<cannot get type description of type ") );
    buf.append( OUString::unacquired( &typeRef->pTypeName ) );
    buf.append( static_cast< sal_Unicode >('>') );
}

//------------------------------------------------------------------------------
static inline void appendChar( OUStringBuffer & buf, sal_Unicode c )
{
    if (c < ' ' || c > '~')
    {
        buf.appendAscii( RTL_CONSTASCII_STRINGPARAM("\\X") );
        OUString s( OUString::valueOf( static_cast< sal_Int32 >(c), 16 ) );
        for ( sal_Int32 f = 4 - s.getLength(); f > 0; --f )
            buf.append( static_cast< sal_Unicode >('0') );
        buf.append( s );
    }
    else
    {
        buf.append( c );
    }
}

//------------------------------------------------------------------------------
static void appendValue(
    OUStringBuffer & buf,
    void const * val, typelib_TypeDescriptionReference * typeRef,
    bool prependType )
{
    if (typeRef->eTypeClass == typelib_TypeClass_VOID)
    {
        buf.appendAscii( RTL_CONSTASCII_STRINGPARAM("void") );
        return;
    }
    OSL_ASSERT( val != 0 );

    if (prependType &&
        typeRef->eTypeClass != typelib_TypeClass_STRING &&
        typeRef->eTypeClass != typelib_TypeClass_CHAR &&
        typeRef->eTypeClass != typelib_TypeClass_BOOLEAN)
    {
        buf.append( static_cast< sal_Unicode >('(') );
        buf.append( OUString::unacquired( &typeRef->pTypeName ) );
        buf.appendAscii( RTL_CONSTASCII_STRINGPARAM(") ") );
    }

    switch (typeRef->eTypeClass)
    {
    case typelib_TypeClass_INTERFACE:
    {
        buf.appendAscii( RTL_CONSTASCII_STRINGPARAM("0x") );
        buf.append( reinterpret_cast< sal_Int64 >(
                        *reinterpret_cast< void * const * >(val) ), 16 );
        Reference< lang::XServiceInfo > xServiceInfo(
            *reinterpret_cast< XInterface * const * >(val), UNO_QUERY );
        if (xServiceInfo.is())
        {
            buf.appendAscii( RTL_CONSTASCII_STRINGPARAM(
                                 " (ImplementationName = \"") );
            buf.append( xServiceInfo->getImplementationName() );
            buf.appendAscii( RTL_CONSTASCII_STRINGPARAM("\")") );
        }
        break;
    }
    case typelib_TypeClass_STRUCT:
    case typelib_TypeClass_EXCEPTION:
    {
        buf.appendAscii( RTL_CONSTASCII_STRINGPARAM("{ ") );
        typelib_TypeDescription * typeDescr = 0;
        typelib_typedescriptionreference_getDescription( &typeDescr, typeRef );
        if (typeDescr == 0 || !typelib_typedescription_complete( &typeDescr )) {
            appendTypeError( buf, typeRef );
        }
        else
        {
            typelib_CompoundTypeDescription * compType =
                reinterpret_cast< typelib_CompoundTypeDescription * >(
                    typeDescr );
            sal_Int32 nDescr = compType->nMembers;

            if (compType->pBaseTypeDescription)
            {
                appendValue(
                    buf, val, reinterpret_cast<
                    typelib_TypeDescription * >(
                        compType->pBaseTypeDescription)->pWeakRef, false );
                if (nDescr > 0)
                    buf.appendAscii( RTL_CONSTASCII_STRINGPARAM(", ") );
            }

            typelib_TypeDescriptionReference ** ppTypeRefs =
                compType->ppTypeRefs;
            sal_Int32 * memberOffsets = compType->pMemberOffsets;
            rtl_uString ** ppMemberNames = compType->ppMemberNames;

            for ( sal_Int32 nPos = 0; nPos < nDescr; ++nPos )
            {
                buf.append( ppMemberNames[ nPos ] );
                buf.appendAscii( RTL_CONSTASCII_STRINGPARAM(" = ") );
                typelib_TypeDescription * memberType = 0;
                TYPELIB_DANGER_GET( &memberType, ppTypeRefs[ nPos ] );
                if (memberType == 0)
                {
                    appendTypeError( buf, ppTypeRefs[ nPos ] );
                }
                else
                {
                    appendValue( buf,
                                 reinterpret_cast< char const * >(
                                     val ) + memberOffsets[ nPos ],
                                 memberType->pWeakRef, true );
                    TYPELIB_DANGER_RELEASE( memberType );
                }
                if (nPos < (nDescr - 1))
                    buf.appendAscii( RTL_CONSTASCII_STRINGPARAM(", ") );
            }
        }
        buf.appendAscii( RTL_CONSTASCII_STRINGPARAM(" }") );
        if (typeDescr != 0)
            typelib_typedescription_release( typeDescr );
        break;
    }
    case typelib_TypeClass_SEQUENCE:
    {
        typelib_TypeDescription * typeDescr = 0;
        TYPELIB_DANGER_GET( &typeDescr, typeRef );
        if (typeDescr == 0)
        {
            appendTypeError( buf,typeRef );
        }
        else
        {
            typelib_TypeDescriptionReference * elementTypeRef =
                reinterpret_cast<
                typelib_IndirectTypeDescription * >(typeDescr)->pType;
            typelib_TypeDescription * elementTypeDescr = 0;
            TYPELIB_DANGER_GET( &elementTypeDescr, elementTypeRef );
            if (elementTypeDescr == 0)
            {
                appendTypeError( buf, elementTypeRef );
            }
            else
            {
                sal_Int32 nElementSize = elementTypeDescr->nSize;
                uno_Sequence * seq =
                    *reinterpret_cast< uno_Sequence * const * >(val);
                sal_Int32 nElements = seq->nElements;

                if (nElements > 0)
                {
                    buf.appendAscii( RTL_CONSTASCII_STRINGPARAM("{ ") );
                    char const * pElements = seq->elements;
                    for ( sal_Int32 nPos = 0; nPos < nElements; ++nPos )
                    {
                        appendValue(
                            buf, pElements + (nElementSize * nPos),
                            elementTypeDescr->pWeakRef, false );
                        if (nPos < (nElements - 1))
                            buf.appendAscii( RTL_CONSTASCII_STRINGPARAM(", ") );
                    }
                    buf.appendAscii( RTL_CONSTASCII_STRINGPARAM(" }") );
                }
                else
                {
                    buf.appendAscii( RTL_CONSTASCII_STRINGPARAM("{}") );
                }
                TYPELIB_DANGER_RELEASE( elementTypeDescr );
            }
            TYPELIB_DANGER_RELEASE( typeDescr );
        }
        break;
    }
    case typelib_TypeClass_ANY:
    {
        buf.appendAscii( RTL_CONSTASCII_STRINGPARAM("{ ") );
        uno_Any const * pAny = reinterpret_cast< uno_Any const * >(val);
        appendValue( buf, pAny->pData, pAny->pType, true );
        buf.appendAscii( RTL_CONSTASCII_STRINGPARAM(" }") );
        break;
    }
    case typelib_TypeClass_TYPE:
        buf.append( (*reinterpret_cast<
                     typelib_TypeDescriptionReference * const * >(val)
                        )->pTypeName );
        break;
    case typelib_TypeClass_STRING:
    {
        buf.append( static_cast< sal_Unicode >('\"') );
        OUString const & str = OUString::unacquired(
            reinterpret_cast< rtl_uString * const * >(val) );
        sal_Int32 len = str.getLength();
        for ( sal_Int32 pos = 0; pos < len; ++pos )
        {
            sal_Unicode c = str[ pos ];
            if (c == '\"')
                buf.appendAscii( RTL_CONSTASCII_STRINGPARAM("\\\"") );
            else if (c == '\\')
                buf.appendAscii( RTL_CONSTASCII_STRINGPARAM("\\\\") );
            else
                appendChar( buf, c );
        }
        buf.append( static_cast< sal_Unicode >('\"') );
        break;
    }
    case typelib_TypeClass_ENUM:
    {
        typelib_TypeDescription * typeDescr = 0;
        typelib_typedescriptionreference_getDescription( &typeDescr, typeRef );
        if (typeDescr == 0 || !typelib_typedescription_complete( &typeDescr )) {
            appendTypeError( buf, typeRef );
        }
        else
        {
            sal_Int32 * pValues =
                reinterpret_cast< typelib_EnumTypeDescription * >(
                    typeDescr )->pEnumValues;
            sal_Int32 nPos = reinterpret_cast< typelib_EnumTypeDescription * >(
                typeDescr )->nEnumValues;
            while (nPos--)
            {
                if (pValues[ nPos ] == *reinterpret_cast< int const * >(val))
                    break;
            }
            if (nPos >= 0)
            {
                buf.append( reinterpret_cast< typelib_EnumTypeDescription * >(
                                typeDescr )->ppEnumNames[ nPos ] );
            }
            else
            {
                buf.appendAscii(
                    RTL_CONSTASCII_STRINGPARAM("?unknown enum value?") );
            }
        }
        if (typeDescr != 0)
            typelib_typedescription_release( typeDescr );
        break;
    }
    case typelib_TypeClass_BOOLEAN:
        if (*reinterpret_cast< sal_Bool const * >(val) != sal_False)
            buf.appendAscii( RTL_CONSTASCII_STRINGPARAM("true") );
        else
            buf.appendAscii( RTL_CONSTASCII_STRINGPARAM("false") );
        break;
    case typelib_TypeClass_CHAR:
    {
        buf.append( static_cast< sal_Unicode >('\'') );
        sal_Unicode c = *reinterpret_cast< sal_Unicode const * >(val);
        if (c == '\'')
            buf.appendAscii( RTL_CONSTASCII_STRINGPARAM("\\\'") );
        else if (c == '\\')
            buf.appendAscii( RTL_CONSTASCII_STRINGPARAM("\\\\") );
        else
            appendChar( buf, c );
        buf.append( static_cast< sal_Unicode >('\'') );
        break;
    }
    case typelib_TypeClass_FLOAT:
        buf.append( *reinterpret_cast< float const * >(val) );
        break;
    case typelib_TypeClass_DOUBLE:
        buf.append( *reinterpret_cast< double const * >(val) );
        break;
    case typelib_TypeClass_BYTE:
        buf.append( static_cast< sal_Int32 >(
                        *reinterpret_cast< sal_Int8 const * >(val) ) );
        break;
    case typelib_TypeClass_SHORT:
        buf.append( static_cast< sal_Int32 >(
                        *reinterpret_cast< sal_Int16 const * >(val) ) );
        break;
    case typelib_TypeClass_UNSIGNED_SHORT:
        buf.append( static_cast< sal_Int32 >(
                        *reinterpret_cast< sal_uInt16 const * >(val) ) );
        break;
    case typelib_TypeClass_LONG:
        buf.append( *reinterpret_cast< sal_Int32 const * >(val) );
        break;
    case typelib_TypeClass_UNSIGNED_LONG:
        buf.append( static_cast< sal_Int64 >(
                        *reinterpret_cast< sal_uInt32 const * >(val) ) );
        break;
    case typelib_TypeClass_HYPER:
    case typelib_TypeClass_UNSIGNED_HYPER:
        buf.append( *reinterpret_cast< sal_Int64 const * >(val) );
        break;
//     case typelib_TypeClass_UNION:
//     case typelib_TypeClass_ARRAY:
//     case typelib_TypeClass_UNKNOWN:
//     case typelib_TypeClass_SERVICE:
//     case typelib_TypeClass_MODULE:
    default:
        buf.append( static_cast< sal_Unicode >('?') );
        break;
    }
}

//==============================================================================
OUString anyToString( Any const & value )
{
    OUStringBuffer buf;
    appendValue( buf, value.getValue(), value.getValueTypeRef(), true );
    return buf.makeStringAndClear();
}

}

<commit_msg>INTEGRATION: CWS dbo510 (1.5.24); FILE MERGED 2005/10/31 10:27:04 dbo 1.5.24.1: cleanup, printing @ADDR instead of 0xADDR<commit_after>/*************************************************************************
 *
 *  OpenOffice.org - a multi-platform office productivity suite
 *
 *  $RCSfile: anytostring.cxx,v $
 *
 *  $Revision: 1.6 $
 *
 *  last change: $Author: rt $ $Date: 2006-03-06 10:13:45 $
 *
 *  The Contents of this file are made available subject to
 *  the terms of GNU Lesser General Public License Version 2.1.
 *
 *
 *    GNU Lesser General Public License Version 2.1
 *    =============================================
 *    Copyright 2005 by Sun Microsystems, Inc.
 *    901 San Antonio Road, Palo Alto, CA 94303, USA
 *
 *    This library is free software; you can redistribute it and/or
 *    modify it under the terms of the GNU Lesser General Public
 *    License version 2.1, as published by the Free Software Foundation.
 *
 *    This library 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
 *    Lesser General Public License for more details.
 *
 *    You should have received a copy of the GNU Lesser General Public
 *    License along with this library; if not, write to the Free Software
 *    Foundation, Inc., 59 Temple Place, Suite 330, Boston,
 *    MA  02111-1307  USA
 *
 ************************************************************************/

#include "comphelper/anytostring.hxx"
#include "osl/diagnose.h"
#include "rtl/ustrbuf.hxx"
#include "typelib/typedescription.h"
#include "com/sun/star/lang/XServiceInfo.hpp"

using namespace ::com::sun::star;

namespace comphelper {
namespace {

void appendTypeError(
    rtl::OUStringBuffer & buf, typelib_TypeDescriptionReference * typeRef )
{
    buf.appendAscii(
        RTL_CONSTASCII_STRINGPARAM("<cannot get type description of type ") );
    buf.append( rtl::OUString::unacquired( &typeRef->pTypeName ) );
    buf.append( static_cast< sal_Unicode >('>') );
}

inline void appendChar( rtl::OUStringBuffer & buf, sal_Unicode c )
{
    if (c < ' ' || c > '~') {
        buf.appendAscii( RTL_CONSTASCII_STRINGPARAM("\\X") );
        rtl::OUString const s(
            rtl::OUString::valueOf( static_cast< sal_Int32 >(c), 16 ) );
        for ( sal_Int32 f = 4 - s.getLength(); f > 0; --f )
            buf.append( static_cast< sal_Unicode >('0') );
        buf.append( s );
    }
    else {
        buf.append( c );
    }
}

//------------------------------------------------------------------------------
void appendValue( rtl::OUStringBuffer & buf,
                  void const * val, typelib_TypeDescriptionReference * typeRef,
                  bool prependType )
{
    if (typeRef->eTypeClass == typelib_TypeClass_VOID) {
        buf.appendAscii( RTL_CONSTASCII_STRINGPARAM("void") );
        return;
    }
    OSL_ASSERT( val != 0 );

    if (prependType &&
        typeRef->eTypeClass != typelib_TypeClass_STRING &&
        typeRef->eTypeClass != typelib_TypeClass_CHAR &&
        typeRef->eTypeClass != typelib_TypeClass_BOOLEAN)
    {
        buf.append( static_cast< sal_Unicode >('(') );
        buf.append( rtl::OUString::unacquired( &typeRef->pTypeName ) );
        buf.appendAscii( RTL_CONSTASCII_STRINGPARAM(") ") );
    }

    switch (typeRef->eTypeClass) {
    case typelib_TypeClass_INTERFACE: {
        buf.append( static_cast<sal_Unicode>('@') );
        buf.append( reinterpret_cast< sal_Int64 >(
                        *static_cast< void * const * >(val) ), 16 );
        uno::Reference< lang::XServiceInfo > xServiceInfo(
            *static_cast< uno::XInterface * const * >(val),
            uno::UNO_QUERY );
        if (xServiceInfo.is()) {
            buf.appendAscii( RTL_CONSTASCII_STRINGPARAM(
                                 " (ImplementationName = \"") );
            buf.append( xServiceInfo->getImplementationName() );
            buf.appendAscii( RTL_CONSTASCII_STRINGPARAM("\")") );
        }
        break;
    }
    case typelib_TypeClass_STRUCT:
    case typelib_TypeClass_EXCEPTION: {
        buf.appendAscii( RTL_CONSTASCII_STRINGPARAM("{ ") );
        typelib_TypeDescription * typeDescr = 0;
        typelib_typedescriptionreference_getDescription( &typeDescr, typeRef );
        if (typeDescr == 0 || !typelib_typedescription_complete( &typeDescr )) {
            appendTypeError( buf, typeRef );
        }
        else {
            typelib_CompoundTypeDescription * compType =
                reinterpret_cast< typelib_CompoundTypeDescription * >(
                    typeDescr );
            sal_Int32 nDescr = compType->nMembers;

            if (compType->pBaseTypeDescription) {
                appendValue(
                    buf, val, reinterpret_cast<
                    typelib_TypeDescription * >(
                        compType->pBaseTypeDescription)->pWeakRef, false );
                if (nDescr > 0)
                    buf.appendAscii( RTL_CONSTASCII_STRINGPARAM(", ") );
            }

            typelib_TypeDescriptionReference ** ppTypeRefs =
                compType->ppTypeRefs;
            sal_Int32 * memberOffsets = compType->pMemberOffsets;
            rtl_uString ** ppMemberNames = compType->ppMemberNames;

            for ( sal_Int32 nPos = 0; nPos < nDescr; ++nPos )
            {
                buf.append( ppMemberNames[ nPos ] );
                buf.appendAscii( RTL_CONSTASCII_STRINGPARAM(" = ") );
                typelib_TypeDescription * memberType = 0;
                TYPELIB_DANGER_GET( &memberType, ppTypeRefs[ nPos ] );
                if (memberType == 0) {
                    appendTypeError( buf, ppTypeRefs[ nPos ] );
                }
                else {
                    appendValue( buf,
                                 static_cast< char const * >(
                                     val ) + memberOffsets[ nPos ],
                                 memberType->pWeakRef, true );
                    TYPELIB_DANGER_RELEASE( memberType );
                }
                if (nPos < (nDescr - 1))
                    buf.appendAscii( RTL_CONSTASCII_STRINGPARAM(", ") );
            }
        }
        buf.appendAscii( RTL_CONSTASCII_STRINGPARAM(" }") );
        if (typeDescr != 0)
            typelib_typedescription_release( typeDescr );
        break;
    }
    case typelib_TypeClass_SEQUENCE: {
        typelib_TypeDescription * typeDescr = 0;
        TYPELIB_DANGER_GET( &typeDescr, typeRef );
        if (typeDescr == 0) {
            appendTypeError( buf,typeRef );
        }
        else {
            typelib_TypeDescriptionReference * elementTypeRef =
                reinterpret_cast<
                typelib_IndirectTypeDescription * >(typeDescr)->pType;
            typelib_TypeDescription * elementTypeDescr = 0;
            TYPELIB_DANGER_GET( &elementTypeDescr, elementTypeRef );
            if (elementTypeDescr == 0)
            {
                appendTypeError( buf, elementTypeRef );
            }
            else
            {
                sal_Int32 nElementSize = elementTypeDescr->nSize;
                uno_Sequence * seq =
                    *static_cast< uno_Sequence * const * >(val);
                sal_Int32 nElements = seq->nElements;

                if (nElements > 0)
                {
                    buf.appendAscii( RTL_CONSTASCII_STRINGPARAM("{ ") );
                    char const * pElements = seq->elements;
                    for ( sal_Int32 nPos = 0; nPos < nElements; ++nPos )
                    {
                        appendValue(
                            buf, pElements + (nElementSize * nPos),
                            elementTypeDescr->pWeakRef, false );
                        if (nPos < (nElements - 1))
                            buf.appendAscii( RTL_CONSTASCII_STRINGPARAM(", ") );
                    }
                    buf.appendAscii( RTL_CONSTASCII_STRINGPARAM(" }") );
                }
                else
                {
                    buf.appendAscii( RTL_CONSTASCII_STRINGPARAM("{}") );
                }
                TYPELIB_DANGER_RELEASE( elementTypeDescr );
            }
            TYPELIB_DANGER_RELEASE( typeDescr );
        }
        break;
    }
    case typelib_TypeClass_ANY: {
        buf.appendAscii( RTL_CONSTASCII_STRINGPARAM("{ ") );
        uno_Any const * pAny = static_cast< uno_Any const * >(val);
        appendValue( buf, pAny->pData, pAny->pType, true );
        buf.appendAscii( RTL_CONSTASCII_STRINGPARAM(" }") );
        break;
    }
    case typelib_TypeClass_TYPE:
        buf.append( (*reinterpret_cast<
                     typelib_TypeDescriptionReference * const * >(val)
                        )->pTypeName );
        break;
    case typelib_TypeClass_STRING: {
        buf.append( static_cast< sal_Unicode >('\"') );
        rtl::OUString const & str = rtl::OUString::unacquired(
            static_cast< rtl_uString * const * >(val) );
        sal_Int32 len = str.getLength();
        for ( sal_Int32 pos = 0; pos < len; ++pos )
        {
            sal_Unicode c = str[ pos ];
            if (c == '\"')
                buf.appendAscii( RTL_CONSTASCII_STRINGPARAM("\\\"") );
            else if (c == '\\')
                buf.appendAscii( RTL_CONSTASCII_STRINGPARAM("\\\\") );
            else
                appendChar( buf, c );
        }
        buf.append( static_cast< sal_Unicode >('\"') );
        break;
    }
    case typelib_TypeClass_ENUM: {
        typelib_TypeDescription * typeDescr = 0;
        typelib_typedescriptionreference_getDescription( &typeDescr, typeRef );
        if (typeDescr == 0 || !typelib_typedescription_complete( &typeDescr )) {
            appendTypeError( buf, typeRef );
        }
        else
        {
            sal_Int32 * pValues =
                reinterpret_cast< typelib_EnumTypeDescription * >(
                    typeDescr )->pEnumValues;
            sal_Int32 nPos = reinterpret_cast< typelib_EnumTypeDescription * >(
                typeDescr )->nEnumValues;
            while (nPos--)
            {
                if (pValues[ nPos ] == *static_cast< int const * >(val))
                    break;
            }
            if (nPos >= 0)
            {
                buf.append( reinterpret_cast< typelib_EnumTypeDescription * >(
                                typeDescr )->ppEnumNames[ nPos ] );
            }
            else
            {
                buf.appendAscii(
                    RTL_CONSTASCII_STRINGPARAM("?unknown enum value?") );
            }
        }
        if (typeDescr != 0)
            typelib_typedescription_release( typeDescr );
        break;
    }
    case typelib_TypeClass_BOOLEAN:
        if (*static_cast< sal_Bool const * >(val) != sal_False)
            buf.appendAscii( RTL_CONSTASCII_STRINGPARAM("true") );
        else
            buf.appendAscii( RTL_CONSTASCII_STRINGPARAM("false") );
        break;
    case typelib_TypeClass_CHAR: {
        buf.append( static_cast< sal_Unicode >('\'') );
        sal_Unicode c = *static_cast< sal_Unicode const * >(val);
        if (c == '\'')
            buf.appendAscii( RTL_CONSTASCII_STRINGPARAM("\\\'") );
        else if (c == '\\')
            buf.appendAscii( RTL_CONSTASCII_STRINGPARAM("\\\\") );
        else
            appendChar( buf, c );
        buf.append( static_cast< sal_Unicode >('\'') );
        break;
    }
    case typelib_TypeClass_FLOAT:
        buf.append( *static_cast< float const * >(val) );
        break;
    case typelib_TypeClass_DOUBLE:
        buf.append( *static_cast< double const * >(val) );
        break;
    case typelib_TypeClass_BYTE:
        buf.append( static_cast< sal_Int32 >(
                        *static_cast< sal_Int8 const * >(val) ) );
        break;
    case typelib_TypeClass_SHORT:
        buf.append( static_cast< sal_Int32 >(
                        *static_cast< sal_Int16 const * >(val) ) );
        break;
    case typelib_TypeClass_UNSIGNED_SHORT:
        buf.append( static_cast< sal_Int32 >(
                        *static_cast< sal_uInt16 const * >(val) ) );
        break;
    case typelib_TypeClass_LONG:
        buf.append( *static_cast< sal_Int32 const * >(val) );
        break;
    case typelib_TypeClass_UNSIGNED_LONG:
        buf.append( static_cast< sal_Int64 >(
                        *static_cast< sal_uInt32 const * >(val) ) );
        break;
    case typelib_TypeClass_HYPER:
    case typelib_TypeClass_UNSIGNED_HYPER:
        buf.append( *static_cast< sal_Int64 const * >(val) );
        break;
//     case typelib_TypeClass_UNION:
//     case typelib_TypeClass_ARRAY:
//     case typelib_TypeClass_UNKNOWN:
//     case typelib_TypeClass_SERVICE:
//     case typelib_TypeClass_MODULE:
    default:
        buf.append( static_cast< sal_Unicode >('?') );
        break;
    }
}

} // anon namespace

//==============================================================================
rtl::OUString anyToString( uno::Any const & value )
{
    rtl::OUStringBuffer buf;
    appendValue( buf, value.getValue(), value.getValueTypeRef(), true );
    return buf.makeStringAndClear();
}

} // namespace comphelper

<|endoftext|>


<commit_before>// Copyright 2016 Yahoo Inc. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root.
#define BOOST_TEST_DYN_LINK
#define BOOST_TEST_MAIN

#include <vespa/fastos/fastos.h>
#include <vespa/filedistribution/distributor/filedownloader.h>
#include <vespa/filedistribution/distributor/filedistributortrackerimpl.h>

#include <fstream>

#include <boost/test/unit_test.hpp>
#include <boost/filesystem.hpp>
#include <boost/filesystem/fstream.hpp>

#include <libtorrent/session.hpp>
#include <libtorrent/tracker_manager.hpp>
#include <libtorrent/torrent.hpp>

#include <vespa/filedistribution/manager/createtorrent.h>
#include <vespa/filedistribution/model/filedistributionmodel.h>
#include <vespa/filedistribution/common/componentsdeleter.h>

namespace fs = boost::filesystem;

using namespace filedistribution;

namespace {
const std::string localHost("localhost");
const int uploaderPort = 9113;
const int downloaderPort = 9112;

#if 0
std::shared_ptr<FileDownloader>
createDownloader(ComponentsDeleter& deleter,
                 int port, const fs::path& downloaderPath,
                 const std::shared_ptr<FileDistributionModel>& model)
{
    std::shared_ptr<FileDistributorTrackerImpl> tracker(deleter.track(new FileDistributorTrackerImpl(model)));
    std::shared_ptr<FileDownloader> downloader(deleter.track(new FileDownloader(tracker,
                            localHost, port, downloaderPath)));

    tracker->setDownloader(downloader);
    return downloader;
}
#endif

} //anonymous namespace

class MockFileDistributionModel : public FileDistributionModel {
    virtual FileDBModel& getFileDBModel() {
        abort();
    }

    virtual std::set<std::string> getFilesToDownload() {
        return std::set<std::string>();
    }

    virtual PeerEntries getPeers(const std::string& , size_t) {
        PeerEntries peers(2);
        peers[0].ip = localHost;
        peers[0].port = uploaderPort;

        peers[1].ip = localHost;
        peers[1].port = downloaderPort;

        return peers;
    }

    virtual void addPeer(const std::string&) {}
    virtual void removePeer(const std::string&) {}
    virtual void peerFinished(const std::string&) {}
};

#if 0
BOOST_AUTO_TEST_CASE(fileDownloaderTest) {
    fs::path testPath = "/tmp/filedownloadertest";
    fs::remove_all(testPath);

    fs::path downloaderPath = testPath / "downloader";
    fs::path uploaderPath   = testPath / "uploader";

    const std::string fileReference = "0123456789012345678901234567890123456789";
    const std::string fileToSend = "filetosend.txt";

    fs::create_directories(downloaderPath);
    fs::create_directories(uploaderPath / fileReference);

    fs::path fileToUploadPath = uploaderPath / fileReference / "filetosend.txt";

    {
    fs::ofstream stream(fileToUploadPath);
    stream <<"Hello, world!" <<std::endl;
    }

    CreateTorrent createTorrent(fileToUploadPath);
    Buffer buffer(createTorrent.bencode());

    ComponentsDeleter deleter;

    std::shared_ptr<FileDistributionModel> model(deleter.track(new MockFileDistributionModel()));
    std::shared_ptr<FileDownloader> downloader =
        createDownloader(deleter, downloaderPort, downloaderPath, model);

    std::shared_ptr<FileDownloader> uploader =
        createDownloader(deleter, uploaderPort, uploaderPath, model);

    std::thread uploaderThread( [&] () { uploader->runEventLoop(); });
    std::thread downloaderThread( [&] () { downloader->runEventLoop(); });

    uploader->addTorrent(fileReference, buffer);
    downloader->addTorrent(fileReference, buffer);

    sleep(5);
    BOOST_CHECK(fs::exists(downloaderPath / fileReference / fileToSend));

    uploaderThread.interrupt();
    uploaderThread.join();

    downloaderThread.interrupt();
    downloaderThread.join();

    fs::remove_all(testPath);
}
#endif

//TODO: cleanup
libtorrent::sha1_hash
toInfoHash(const std::string& fileReference) {
    assert (fileReference.size() == 40);
    std::istringstream s(fileReference);

    libtorrent::sha1_hash infoHash;
    s >> infoHash;
    return infoHash;
}

BOOST_AUTO_TEST_CASE(test_filereference_infohash_conversion) {
    const std::string fileReference = "3a281c905c9b6ebe4d969037a198454fedefbdf3";

    libtorrent::sha1_hash infoHash = toInfoHash(fileReference);

    std::ostringstream fileReferenceString;
    fileReferenceString <<infoHash;

    BOOST_CHECK(fileReference == fileReferenceString.str());

    std::cout <<fileReference <<std::endl <<fileReferenceString.str() <<std::endl;
}
<commit_msg>capture by value<commit_after>// Copyright 2016 Yahoo Inc. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root.
#define BOOST_TEST_DYN_LINK
#define BOOST_TEST_MAIN

#include <vespa/fastos/fastos.h>
#include <vespa/filedistribution/distributor/filedownloader.h>
#include <vespa/filedistribution/distributor/filedistributortrackerimpl.h>

#include <fstream>

#include <boost/test/unit_test.hpp>
#include <boost/filesystem.hpp>
#include <boost/filesystem/fstream.hpp>

#include <libtorrent/session.hpp>
#include <libtorrent/tracker_manager.hpp>
#include <libtorrent/torrent.hpp>

#include <vespa/filedistribution/manager/createtorrent.h>
#include <vespa/filedistribution/model/filedistributionmodel.h>
#include <vespa/filedistribution/common/componentsdeleter.h>

namespace fs = boost::filesystem;

using namespace filedistribution;

namespace {
const std::string localHost("localhost");
const int uploaderPort = 9113;
const int downloaderPort = 9112;

#if 0
std::shared_ptr<FileDownloader>
createDownloader(ComponentsDeleter& deleter,
                 int port, const fs::path& downloaderPath,
                 const std::shared_ptr<FileDistributionModel>& model)
{
    std::shared_ptr<FileDistributorTrackerImpl> tracker(deleter.track(new FileDistributorTrackerImpl(model)));
    std::shared_ptr<FileDownloader> downloader(deleter.track(new FileDownloader(tracker,
                            localHost, port, downloaderPath)));

    tracker->setDownloader(downloader);
    return downloader;
}
#endif

} //anonymous namespace

class MockFileDistributionModel : public FileDistributionModel {
    virtual FileDBModel& getFileDBModel() {
        abort();
    }

    virtual std::set<std::string> getFilesToDownload() {
        return std::set<std::string>();
    }

    virtual PeerEntries getPeers(const std::string& , size_t) {
        PeerEntries peers(2);
        peers[0].ip = localHost;
        peers[0].port = uploaderPort;

        peers[1].ip = localHost;
        peers[1].port = downloaderPort;

        return peers;
    }

    virtual void addPeer(const std::string&) {}
    virtual void removePeer(const std::string&) {}
    virtual void peerFinished(const std::string&) {}
};

#if 0
BOOST_AUTO_TEST_CASE(fileDownloaderTest) {
    fs::path testPath = "/tmp/filedownloadertest";
    fs::remove_all(testPath);

    fs::path downloaderPath = testPath / "downloader";
    fs::path uploaderPath   = testPath / "uploader";

    const std::string fileReference = "0123456789012345678901234567890123456789";
    const std::string fileToSend = "filetosend.txt";

    fs::create_directories(downloaderPath);
    fs::create_directories(uploaderPath / fileReference);

    fs::path fileToUploadPath = uploaderPath / fileReference / "filetosend.txt";

    {
    fs::ofstream stream(fileToUploadPath);
    stream <<"Hello, world!" <<std::endl;
    }

    CreateTorrent createTorrent(fileToUploadPath);
    Buffer buffer(createTorrent.bencode());

    ComponentsDeleter deleter;

    std::shared_ptr<FileDistributionModel> model(deleter.track(new MockFileDistributionModel()));
    std::shared_ptr<FileDownloader> downloader =
        createDownloader(deleter, downloaderPort, downloaderPath, model);

    std::shared_ptr<FileDownloader> uploader =
        createDownloader(deleter, uploaderPort, uploaderPath, model);

    std::thread uploaderThread( [uploader] () { uploader->runEventLoop(); });
    std::thread downloaderThread( [downloader] () { downloader->runEventLoop(); });

    uploader->addTorrent(fileReference, buffer);
    downloader->addTorrent(fileReference, buffer);

    sleep(5);
    BOOST_CHECK(fs::exists(downloaderPath / fileReference / fileToSend));

    uploaderThread.interrupt();
    uploaderThread.join();

    downloaderThread.interrupt();
    downloaderThread.join();

    fs::remove_all(testPath);
}
#endif

//TODO: cleanup
libtorrent::sha1_hash
toInfoHash(const std::string& fileReference) {
    assert (fileReference.size() == 40);
    std::istringstream s(fileReference);

    libtorrent::sha1_hash infoHash;
    s >> infoHash;
    return infoHash;
}

BOOST_AUTO_TEST_CASE(test_filereference_infohash_conversion) {
    const std::string fileReference = "3a281c905c9b6ebe4d969037a198454fedefbdf3";

    libtorrent::sha1_hash infoHash = toInfoHash(fileReference);

    std::ostringstream fileReferenceString;
    fileReferenceString <<infoHash;

    BOOST_CHECK(fileReference == fileReferenceString.str());

    std::cout <<fileReference <<std::endl <<fileReferenceString.str() <<std::endl;
}
<|endoftext|>


<commit_before>#pragma once

#include <libgen.h>
#include <iomanip>
#include <iostream>
#include <sstream>

#include "logging/log.hh"
#include "macros.hh"

namespace jcc {

namespace {

inline char* filename(char const* const argument) {
  return basename(const_cast<char*>(argument));
}

template <typename T>
inline std::stringstream to_expr(const T& val, char const* const expr) {
  std::stringstream ss;
  ss << expr << " (" << val << ")";
  return ss;
}

template <typename A, typename B>
inline std::stringstream binary_expector_string(const A& a,
                                                const B& b,
                                                char const* const a_expr,
                                                char const* const b_expr,
                                                char const* const msg,
                                                char const* const file_name,
                                                int line_num,
                                                char const* const operator_name) {
  std::stringstream ss;
  ss << Format::yellow() << filename(file_name) << ":" << line_num << ": "
     << Format::red() << "Expected" << Format::reset() << ": " << to_expr(a, a_expr).str()
     << operator_name << " " << to_expr(b, b_expr).str() << ": " << msg;
  return ss;
}

}  // namespace

template <typename A, typename B>
inline void assert_gt(const A& a,
                      const B& b,
                      char const* const a_expr,
                      char const* const b_expr,
                      char const* const msg,
                      char const* const file_name,
                      int line_num) {
  if (UNLIKELY(a <= b)) {
    std::cerr << binary_expector_string(
                     a, b, a_expr, b_expr, msg, file_name, line_num, ">")
                     .str()
              << std::endl;
    std::abort();
  }
}

template <typename A, typename B>
inline void assert_ge(const A& a,
                      const B& b,
                      char const* const a_expr,
                      char const* const b_expr,
                      char const* const msg,
                      char const* const file_name,
                      int line_num) {
  if (UNLIKELY(a < b)) {
    std::cerr << binary_expector_string(
                     a, b, a_expr, b_expr, msg, file_name, line_num, ">=")
                     .str()
              << std::endl;
    std::abort();
  }
}

template <typename A, typename B>
inline void assert_lt(const A& a,
                      const B& b,
                      char const* const a_expr,
                      char const* const b_expr,
                      char const* const msg,
                      char const* const file_name,
                      int line_num) {
  if (UNLIKELY(a >= b)) {
    std::cerr << binary_expector_string(
                     a, b, a_expr, b_expr, msg, file_name, line_num, "<")
                     .str()
              << std::endl;
    std::abort();
  }
}
template <typename A, typename B>
inline void assert_le(const A& a,
                      const B& b,
                      char const* const a_expr,
                      char const* const b_expr,
                      char const* const msg,
                      char const* const file_name,
                      int line_num) {
  if (UNLIKELY(a > b)) {
    std::cerr << binary_expector_string(
                     a, b, a_expr, b_expr, msg, file_name, line_num, "<=")
                     .str()
              << std::endl;
    std::abort();
  }
}

template <typename A, typename B>
inline void assert_eq(const A& a,
                      const B& b,
                      char const* const a_expr,
                      char const* const b_expr,
                      char const* const msg,
                      char const* const file_name,
                      int line_num) {
  if (UNLIKELY(a != b)) {
    std::cerr << binary_expector_string(
                     a, b, a_expr, b_expr, msg, file_name, line_num, "==")
                     .str()
              << std::endl;

    std::abort();
  }
}

template <typename A, typename B>
inline void assert_ne(const A& a,
                      const B& b,
                      char const* const a_expr,
                      char const* const b_expr,
                      char const* const msg,
                      char const* const file_name,
                      int line_num) {
  if (UNLIKELY(a == b)) {
    std::cerr << binary_expector_string(
                     a, b, a_expr, b_expr, msg, file_name, line_num, "!=")
                     .str()
              << std::endl;
    std::abort();
  }
}

template <typename A, typename B>
inline void assert_between(const A& a,
                           const B& b,
                           const B& c,
                           char const* const a_expr,
                           char const* const b_expr,
                           char const* const c_expr,
                           char const* const msg,
                           char const* const file_name,
                           int line_num) {
  if (UNLIKELY(((a < b) || (a > c)))) {
    std::cerr << Format::yellow() << filename(file_name) << ":" << line_num << ": "
              << Format::red() << "Expected" << Format::reset() << ": "
              << to_expr(b, b_expr).str() << " <= " << to_expr(a, a_expr).str()
              << " <= " << to_expr(c, c_expr).str() << ": " << msg;

    std::abort();
  }
}

template <typename A, typename B>
inline void assert_outside(const A& a,
                           const B& b,
                           const B& c,
                           char const* const a_expr,
                           char const* const b_expr,
                           char const* const c_expr,
                           char const* const msg,
                           char const* const file_name,
                           int line_num) {
  if (UNLIKELY(((a < b) || (a > c)))) {
    std::cerr << Format::yellow() << filename(file_name) << ":" << line_num << ": "
              << Format::red() << "Expected" << Format::reset() << ": "
              << to_expr(b, b_expr).str() << " < " << to_expr(a, a_expr).str() << " < "
              << to_expr(c, c_expr).str() << ": " << msg;

    std::abort();
  }
}

inline void assert_true(const bool& a,
                        char const* const a_expr,
                        char const* const msg,
                        char const* const file_name,
                        int line_num) {
  if (UNLIKELY(!a)) {
    std::cerr << Format::yellow() << filename(file_name) << ":" << line_num << ": "
              << Format::red() << "Expected" << Format::reset() << ": " << a_expr
              << std::boolalpha << a << ": " << msg << std::endl;

    std::abort();
  }
}

inline void assert_false(const bool& a,
                         char const* const a_expr,
                         char const* const msg,
                         char const* const file_name,
                         int line_num) {
  if (UNLIKELY(a)) {
    std::cerr << Format::yellow() << filename(file_name) << ":" << line_num << ": "
              << Format::red() << "Expected" << Format::reset() << ": " << a_expr
              << std::boolalpha << a << ": " << msg << std::endl;

    std::abort();
  }
}

}  // namespace jcc

//
// Comparison Assertions
//

#define JASSERT_GE(a, b, msg) jcc::assert_ge(a, b, #a, #b, msg, __FILE__, __LINE__);
#define JASSERT_GT(a, b, msg) jcc::assert_gt(a, b, #a, #b, msg, __FILE__, __LINE__);
#define JASSERT_LE(a, b, msg) jcc::assert_le(a, b, #a, #b, msg, __FILE__, __LINE__);
#define JASSERT_LT(a, b, msg) jcc::assert_lt(a, b, #a, #b, msg, __FILE__, __LINE__);
#define JASSERT_EQ(a, b, msg) jcc::assert_eq(a, b, #a, #b, msg, __FILE__, __LINE__);
#define JASSERT_NE(a, b, msg) jcc::assert_ne(a, b, #a, #b, msg, __FILE__, __LINE__);

//
// Ternary Assertions
//

#define JASSERT_BETWEEN(a, b, c, msg) \
  jcc::assert_between(a, b, c, #a, #b, #c, msg, __FILE__, __LINE__);
#define JASSERT_OUTSIDE(a, b, c, msg) \
  jcc::assert_outside(a, b, c, #a, #b, #c, msg, __FILE__, __LINE__);

//
// Unary Assertions
//

#define JASSERT(a, msg) jcc::assert_true(a, #a, msg, __FILE__, __LINE__);
#define JASSERT_TRUE(a, msg) jcc::assert_true(a, #a, msg, __FILE__, __LINE__);
#define JASSERT_FALSE(a, msg) jcc::assert_false(a, #a, msg, __FILE__, __LINE__);
<commit_msg>Fix whitespace in assertions<commit_after>#pragma once

#include <libgen.h>
#include <iomanip>
#include <iostream>
#include <sstream>

#include "logging/log.hh"
#include "macros.hh"

namespace jcc {

namespace {

inline char* filename(char const* const argument) {
  return basename(const_cast<char*>(argument));
}

template <typename T>
inline std::stringstream to_expr(const T& val, char const* const expr) {
  std::stringstream ss;
  ss << expr << " (" << val << ")";
  return ss;
}

template <typename A, typename B>
inline std::stringstream binary_expector_string(const A& a,
                                                const B& b,
                                                char const* const a_expr,
                                                char const* const b_expr,
                                                char const* const msg,
                                                char const* const file_name,
                                                int line_num,
                                                char const* const operator_name) {
  std::stringstream ss;
  ss << Format::yellow() << filename(file_name) << ":" << line_num << ": "
     << Format::red() << "Expected" << Format::reset() << ": " << to_expr(a, a_expr).str()
     << " " << operator_name << " " << to_expr(b, b_expr).str() << ": " << msg;
  return ss;
}

}  // namespace

template <typename A, typename B>
inline void assert_gt(const A& a,
                      const B& b,
                      char const* const a_expr,
                      char const* const b_expr,
                      char const* const msg,
                      char const* const file_name,
                      int line_num) {
  if (UNLIKELY(a <= b)) {
    std::cerr << binary_expector_string(
                     a, b, a_expr, b_expr, msg, file_name, line_num, ">")
                     .str()
              << std::endl;
    std::abort();
  }
}

template <typename A, typename B>
inline void assert_ge(const A& a,
                      const B& b,
                      char const* const a_expr,
                      char const* const b_expr,
                      char const* const msg,
                      char const* const file_name,
                      int line_num) {
  if (UNLIKELY(a < b)) {
    std::cerr << binary_expector_string(
                     a, b, a_expr, b_expr, msg, file_name, line_num, ">=")
                     .str()
              << std::endl;
    std::abort();
  }
}

template <typename A, typename B>
inline void assert_lt(const A& a,
                      const B& b,
                      char const* const a_expr,
                      char const* const b_expr,
                      char const* const msg,
                      char const* const file_name,
                      int line_num) {
  if (UNLIKELY(a >= b)) {
    std::cerr << binary_expector_string(
                     a, b, a_expr, b_expr, msg, file_name, line_num, "<")
                     .str()
              << std::endl;
    std::abort();
  }
}
template <typename A, typename B>
inline void assert_le(const A& a,
                      const B& b,
                      char const* const a_expr,
                      char const* const b_expr,
                      char const* const msg,
                      char const* const file_name,
                      int line_num) {
  if (UNLIKELY(a > b)) {
    std::cerr << binary_expector_string(
                     a, b, a_expr, b_expr, msg, file_name, line_num, "<=")
                     .str()
              << std::endl;
    std::abort();
  }
}

template <typename A, typename B>
inline void assert_eq(const A& a,
                      const B& b,
                      char const* const a_expr,
                      char const* const b_expr,
                      char const* const msg,
                      char const* const file_name,
                      int line_num) {
  if (UNLIKELY(a != b)) {
    std::cerr << binary_expector_string(
                     a, b, a_expr, b_expr, msg, file_name, line_num, "==")
                     .str()
              << std::endl;

    std::abort();
  }
}

template <typename A, typename B>
inline void assert_ne(const A& a,
                      const B& b,
                      char const* const a_expr,
                      char const* const b_expr,
                      char const* const msg,
                      char const* const file_name,
                      int line_num) {
  if (UNLIKELY(a == b)) {
    std::cerr << binary_expector_string(
                     a, b, a_expr, b_expr, msg, file_name, line_num, "!=")
                     .str()
              << std::endl;
    std::abort();
  }
}

template <typename A, typename B>
inline void assert_between(const A& a,
                           const B& b,
                           const B& c,
                           char const* const a_expr,
                           char const* const b_expr,
                           char const* const c_expr,
                           char const* const msg,
                           char const* const file_name,
                           int line_num) {
  if (UNLIKELY(((a < b) || (a > c)))) {
    std::cerr << Format::yellow() << filename(file_name) << ":" << line_num << ": "
              << Format::red() << "Expected" << Format::reset() << ": "
              << to_expr(b, b_expr).str() << " <= " << to_expr(a, a_expr).str()
              << " <= " << to_expr(c, c_expr).str() << ": " << msg;

    std::abort();
  }
}

template <typename A, typename B>
inline void assert_outside(const A& a,
                           const B& b,
                           const B& c,
                           char const* const a_expr,
                           char const* const b_expr,
                           char const* const c_expr,
                           char const* const msg,
                           char const* const file_name,
                           int line_num) {
  if (UNLIKELY(((a < b) || (a > c)))) {
    std::cerr << Format::yellow() << filename(file_name) << ":" << line_num << ": "
              << Format::red() << "Expected" << Format::reset() << ": "
              << to_expr(b, b_expr).str() << " < " << to_expr(a, a_expr).str() << " < "
              << to_expr(c, c_expr).str() << ": " << msg;

    std::abort();
  }
}

inline void assert_true(const bool& a,
                        char const* const a_expr,
                        char const* const msg,
                        char const* const file_name,
                        int line_num) {
  if (UNLIKELY(!a)) {
    std::cerr << Format::yellow() << filename(file_name) << ":" << line_num << ": "
              << Format::red() << "Expected" << Format::reset() << ": " << a_expr
              << std::boolalpha << " " << a << ": " << msg << std::endl;

    std::abort();
  }
}

inline void assert_false(const bool& a,
                         char const* const a_expr,
                         char const* const msg,
                         char const* const file_name,
                         int line_num) {
  if (UNLIKELY(a)) {
    std::cerr << Format::yellow() << filename(file_name) << ":" << line_num << ": "
              << Format::red() << "Expected" << Format::reset() << ": " << a_expr
              << std::boolalpha << " " << a << ": " << msg << std::endl;

    std::abort();
  }
}

}  // namespace jcc

//
// Comparison Assertions
//

#define JASSERT_GE(a, b, msg) jcc::assert_ge(a, b, #a, #b, msg, __FILE__, __LINE__);
#define JASSERT_GT(a, b, msg) jcc::assert_gt(a, b, #a, #b, msg, __FILE__, __LINE__);
#define JASSERT_LE(a, b, msg) jcc::assert_le(a, b, #a, #b, msg, __FILE__, __LINE__);
#define JASSERT_LT(a, b, msg) jcc::assert_lt(a, b, #a, #b, msg, __FILE__, __LINE__);
#define JASSERT_EQ(a, b, msg) jcc::assert_eq(a, b, #a, #b, msg, __FILE__, __LINE__);
#define JASSERT_NE(a, b, msg) jcc::assert_ne(a, b, #a, #b, msg, __FILE__, __LINE__);

//
// Ternary Assertions
//

#define JASSERT_BETWEEN(a, b, c, msg) \
  jcc::assert_between(a, b, c, #a, #b, #c, msg, __FILE__, __LINE__);
#define JASSERT_OUTSIDE(a, b, c, msg) \
  jcc::assert_outside(a, b, c, #a, #b, #c, msg, __FILE__, __LINE__);

//
// Unary Assertions
//

#define JASSERT(a, msg) jcc::assert_true(a, #a, msg, __FILE__, __LINE__);
#define JASSERT_TRUE(a, msg) jcc::assert_true(a, #a, msg, __FILE__, __LINE__);
#define JASSERT_FALSE(a, msg) jcc::assert_false(a, #a, msg, __FILE__, __LINE__);
<|endoftext|>


<commit_before>#include <stdlib.h>
#include <sys/socket.h>
#include <string.h>
#include <netinet/in.h>
#include <cstring>
#include <stdio.h>
#include <string>
#include <iostream>
#include <list>
#include <map>

#include "server.h"
#include "duckchat.h"

// TODO Server can accept connections.
// TODO Server handles Login and Logout from users, and keeps records of which users are logged in.
// TODO Server handles Join and Leave from users, keeps records of which channels a user belongs to,
// and keeps records of which users are in a channel.
// TODO Server handles the Say message.
// TODO Server correctly handles List and Who.
// TODO Create copies of your client and server source. Modify them to send invalid packets to your good client
// and server, to see if you can make your client or server crash. Fix any bugs you find.

//std::string user;

class Channel {
public:
  std::string name;
  std::list<User *> users;

  Channel(std::string name): name(name) {};
};

class User {
public:
  std::string name;
  struct sockaddr_in *address;
  std::list<Channel *> channels;

  User(std::string name, struct sockaddr_in *address): name(name), address(address) {};
};

std::map<std::string, User *> users;
std::map<std::string, Channel *> channels;

void Error(const char *msg) {
  perror(msg);
  exit(1);
}

void ProcessRequest(void *buffer, struct sockaddr_in *address) {
  struct request current_request;
  User *new_user;
  std::map<std::string, User *>::iterator it;

  memcpy(&current_request, buffer, sizeof(struct request));
  std::cout << "request type: " << current_request.req_type << std::endl;
  request_t request_type = current_request.req_type;

  switch(request_type) {
    case REQ_LOGIN:
      struct request_login login_request;
      memcpy(&login_request, buffer, sizeof(struct request_login));

      new_user = new User(login_request.req_username, address);
      users.insert({std::string(login_request.req_username), new_user});

      std::cout << "server: " << login_request.req_username << " logs in" << std::endl;
      break;
    case REQ_LOGOUT:
      struct request_logout logout_request;
      memcpy(&logout_request, buffer, sizeof(struct request_logout));

      for (auto user : users) {
        unsigned short user_port = user.second->address->sin_port;
        in_addr_t user_address = user.second->address->sin_addr.s_addr;

        unsigned short request_port = address->sin_port;
        in_addr_t request_address = address->sin_addr.s_addr;

        std::cout << user_port << " == " << request_port << " && " << user_address << " == " << request_address << std::endl;

        if (user_port == request_port && user_address == request_address) {
          std::cout << "server: " << user.first << " logs out" << std::endl;
          users.erase(user.first);
          break;
        }
      }
      break;
    case REQ_JOIN:
      struct request_join join_request;
      memcpy(&join_request, buffer, sizeof(struct request_join));
//      std::cout << "server: " << username << " joins channel " << join_request.req_channel << std::endl;
      break;
    default:
      break;
  }
//
//  for (auto user : users) {
//    unsigned short user_port = user.second->address->sin_port;
//    in_addr_t user_address = user.second->address->sin_addr.s_addr;
//
//    std::cout << user.first << " " << user_address << ":" << user_port << std::endl;
//  }
}

int main(int argc, char *argv[]) {
  struct sockaddr_in server_addr;

  int server_socket;
  int receive_len;
  void* buffer[kBufferSize];
  int port;

//  user = "";

  if (argc < 2) {
    std::cerr << "server: no port provided" << std::endl;
    exit(1);
  }

  port = atoi(argv[1]);

  memset((char *) &server_addr, 0, sizeof(server_addr));
  server_addr.sin_family = AF_INET;
  server_addr.sin_addr.s_addr = htonl(INADDR_ANY);
  server_addr.sin_port = htons(port);

  if ((server_socket = socket(AF_INET, SOCK_DGRAM, 0)) < 0) {
    Error("server: can't open socket\n");
  }

  if (bind(server_socket, (struct sockaddr *) &server_addr, sizeof(server_addr)) < 0) {
    Error("server: bind failed\n");
  }

  printf("server: waiting on port %d\n", port);
  while (1) {
    struct sockaddr_in client_addr;
    socklen_t client_addr_len = sizeof(client_addr);
//    std::cout << "before recvfrom" << std::endl;
    receive_len = recvfrom(server_socket, buffer, kBufferSize, 0, (struct sockaddr *) &client_addr, &client_addr_len);
    if (receive_len > 0) {
      buffer[receive_len] = 0;
      ProcessRequest(buffer, &client_addr);
    }
  }
}
<commit_msg>more logout testing<commit_after>#include <stdlib.h>
#include <sys/socket.h>
#include <string.h>
#include <netinet/in.h>
#include <cstring>
#include <stdio.h>
#include <string>
#include <iostream>
#include <list>
#include <map>

#include "server.h"
#include "duckchat.h"

// TODO Server can accept connections.
// TODO Server handles Login and Logout from users, and keeps records of which users are logged in.
// TODO Server handles Join and Leave from users, keeps records of which channels a user belongs to,
// and keeps records of which users are in a channel.
// TODO Server handles the Say message.
// TODO Server correctly handles List and Who.
// TODO Create copies of your client and server source. Modify them to send invalid packets to your good client
// and server, to see if you can make your client or server crash. Fix any bugs you find.

//std::string user;

class Channel {
public:
  std::string name;
  std::list<User *> users;

  Channel(std::string name): name(name) {};
};

class User {
public:
  std::string name;
  struct sockaddr_in *address;
  std::list<Channel *> channels;

  User(std::string name, struct sockaddr_in *address): name(name), address(address) {};
};

std::map<std::string, User *> users;
std::map<std::string, Channel *> channels;

void Error(const char *msg) {
  perror(msg);
  exit(1);
}

void ProcessRequest(void *buffer, struct sockaddr_in *address) {
  struct request current_request;
  User *new_user;
  std::map<std::string, User *>::iterator it;

  memcpy(&current_request, buffer, sizeof(struct request));
  std::cout << "request type: " << current_request.req_type << std::endl;
  request_t request_type = current_request.req_type;

  switch(request_type) {
    case REQ_LOGIN:
      struct request_login login_request;
      memcpy(&login_request, buffer, sizeof(struct request_login));

      new_user = new User(login_request.req_username, address);
      users.insert({std::string(login_request.req_username), new_user});

      for (auto user : users) {
        unsigned short user_port = user.second->address->sin_port;
        in_addr_t user_address = user.second->address->sin_addr.s_addr;

        std::cout << user.first << " " << user_address << ":" << user_port << std::endl;
        std::cout << std::endl;
      }

      std::cout << "server: " << login_request.req_username << " logs in" << std::endl;
      break;
    case REQ_LOGOUT:
      struct request_logout logout_request;
      memcpy(&logout_request, buffer, sizeof(struct request_logout));

      for (auto user : users) {
        unsigned short user_port = user.second->address->sin_port;
        in_addr_t user_address = user.second->address->sin_addr.s_addr;

        unsigned short request_port = address->sin_port;
        in_addr_t request_address = address->sin_addr.s_addr;

        std::cout << user_port << " == " << request_port << " && " << user_address << " == " << request_address << std::endl;

        if (user_port == request_port && user_address == request_address) {
          std::cout << "server: " << user.first << " logs out" << std::endl;
          users.erase(user.first);
          break;
        }
      }
      break;
    case REQ_JOIN:
      struct request_join join_request;
      memcpy(&join_request, buffer, sizeof(struct request_join));
//      std::cout << "server: " << username << " joins channel " << join_request.req_channel << std::endl;
      break;
    default:
      break;
  }
}

int main(int argc, char *argv[]) {
  struct sockaddr_in server_addr;

  int server_socket;
  int receive_len;
  void* buffer[kBufferSize];
  int port;

//  user = "";

  if (argc < 2) {
    std::cerr << "server: no port provided" << std::endl;
    exit(1);
  }

  port = atoi(argv[1]);

  memset((char *) &server_addr, 0, sizeof(server_addr));
  server_addr.sin_family = AF_INET;
  server_addr.sin_addr.s_addr = htonl(INADDR_ANY);
  server_addr.sin_port = htons(port);

  if ((server_socket = socket(AF_INET, SOCK_DGRAM, 0)) < 0) {
    Error("server: can't open socket\n");
  }

  if (bind(server_socket, (struct sockaddr *) &server_addr, sizeof(server_addr)) < 0) {
    Error("server: bind failed\n");
  }

  printf("server: waiting on port %d\n", port);
  while (1) {
    struct sockaddr_in client_addr;
    socklen_t client_addr_len = sizeof(client_addr);
//    std::cout << "before recvfrom" << std::endl;
    receive_len = recvfrom(server_socket, buffer, kBufferSize, 0, (struct sockaddr *) &client_addr, &client_addr_len);
    if (receive_len > 0) {
      buffer[receive_len] = 0;
      ProcessRequest(buffer, &client_addr);
    }
  }
}
<|endoftext|>