osquery-1/osquery/core/darwin/conversions.cpp

72 lines
1.8 KiB
C++
Raw Normal View History

/*
* Copyright (c) 2014, Facebook, Inc.
* All rights reserved.
*
* This source code is licensed under the BSD-style license found in the
* LICENSE file in the root directory of this source tree. An additional grant
* of patent rights can be found in the PATENTS file in the same directory.
*
*/
2014-12-10 09:17:24 +00:00
2015-01-20 01:10:40 +00:00
#include <iomanip>
2014-12-10 09:17:24 +00:00
#include <boost/lexical_cast.hpp>
#include "osquery/core/conversions.h"
namespace osquery {
2014-12-10 09:52:02 +00:00
std::string stringFromCFString(const CFStringRef& cf_string) {
2014-12-10 09:17:24 +00:00
// Access, then convert the CFString. CFStringGetCStringPtr is less-safe.
2014-12-10 22:51:43 +00:00
CFIndex length = CFStringGetLength(cf_string);
char* buffer = (char*)malloc(length + 1);
2014-12-10 09:17:24 +00:00
if (!CFStringGetCString(
cf_string, buffer, length + 1, kCFStringEncodingASCII)) {
free(buffer);
return "";
}
// Cleanup allocations.
std::string result(buffer);
free(buffer);
return result;
}
2014-12-10 22:51:43 +00:00
std::string stringFromCFData(const CFDataRef& cf_data) {
CFRange range = CFRangeMake(0, CFDataGetLength(cf_data));
2015-01-20 01:10:40 +00:00
2014-12-10 22:51:43 +00:00
char* buffer = (char*)malloc(range.length + 1);
memset(buffer, 0, range.length + 1);
2015-01-20 01:10:40 +00:00
std::stringstream result;
uint8_t byte;
2014-12-10 22:51:43 +00:00
CFDataGetBytes(cf_data, range, (UInt8*)buffer);
for (CFIndex i = 0; i < range.length; ++i) {
2015-01-20 01:10:40 +00:00
byte = buffer[i];
if (isprint(byte)) {
result << byte;
} else if (buffer[i] == 0) {
result << ' ';
} else {
result << '%' << std::setfill('0') << std::setw(2) << std::hex
<< (int)byte;
2014-12-10 22:51:43 +00:00
}
}
// Cleanup allocations.
free(buffer);
2015-01-20 01:10:40 +00:00
return result.str();
2014-12-10 22:51:43 +00:00
}
2014-12-10 09:17:24 +00:00
std::string stringFromCFNumber(const CFDataRef& cf_number) {
unsigned int value;
if (CFGetTypeID(cf_number) != CFNumberGetTypeID() ||
!CFNumberGetValue((CFNumberRef)cf_number, kCFNumberIntType, &value)) {
return "0";
}
// Cast as a string.
return boost::lexical_cast<std::string>(value);
}
}