<commit_before>/*-------------------------------------------------------------------------
 * help_config.c
 *
 * Displays available options under grand unified configuration scheme
 *
 * Options whose flag bits are set to GUC_NO_SHOW_ALL, GUC_NOT_IN_SAMPLE,
 * or GUC_DISALLOW_IN_FILE are not displayed, unless the user specifically
 * requests that variable by name
 *
 * Portions Copyright (c) 1996-2015, PostgreSQL Global Development Group
 *
 * IDENTIFICATION
 *	  src/backend/utils/misc/help_config.c
 *
 *-------------------------------------------------------------------------
 */
#include "postgres.h"

#include <float.h>
#include <limits.h>
#include <unistd.h>

#include "utils/guc_tables.h"
#include "utils/help_config.h"

/*
 * This union allows us to mix the numerous different types of structs
 * that we are organizing.
 */
typedef union
{
	struct config_generic generic;
	struct config_bool bool;
	struct config_real real;
	struct config_int integer;
	struct config_string string;
	struct config_enum _enum;
} mixedStruct;

static void printMixedStruct(mixedStruct *structToPrint);
static bool displayStruct(mixedStruct *structToDisplay);

void
GucInfoMain(void)
{
	struct config_generic **guc_vars;
	int			numOpts,
				i;

	/* Initialize the guc_variables[] array */
	build_guc_variables();

	guc_vars = get_guc_variables();
	numOpts = GetNumConfigOptions();

	for (i = 0; i < numOpts; i++)
	{
		mixedStruct *var = (mixedStruct *) guc_vars[i];

		if (displayStruct(var))
			printMixedStruct(var);
	}

	exit(0);
}

/*
 * This function will return true if the struct passed to it
 * should be displayed to the user.
 */
static bool
displayStruct(mixedStruct *structToDisplay)
{
	return !(structToDisplay->generic.flags & (GUC_NO_SHOW_ALL |
											   GUC_NOT_IN_SAMPLE |
											   GUC_DISALLOW_IN_FILE));
}

/*
 * This function prints out the generic struct passed to it. It will print out
 * a different format, depending on what the user wants to see.
 */
static void
printMixedStruct(mixedStruct *structToPrint)
{
	printf("%s\t%s\t%s\t",
		   structToPrint->generic.name,
		   GucContext_Names[structToPrint->generic.context],
		   _(config_group_names[structToPrint->generic.group]));

	switch (structToPrint->generic.vartype)
	{

		case PGC_BOOL:
			printf("BOOLEAN\t%s\t\t\t",
				   (structToPrint->bool.reset_val == 0) ?
				   "FALSE" : "TRUE");
			break;

		case PGC_INT:
			printf("INTEGER\t%d\t%d\t%d\t",
				   structToPrint->integer.reset_val,
				   structToPrint->integer.min,
				   structToPrint->integer.max);
			break;

		case PGC_REAL:
			printf("REAL\t%g\t%g\t%g\t",
				   structToPrint->real.reset_val,
				   structToPrint->real.min,
				   structToPrint->real.max);
			break;

		case PGC_STRING:
			printf("STRING\t%s\t\t\t",
				   structToPrint->string.boot_val ? structToPrint->string.boot_val : "");
			break;

		case PGC_ENUM:
			printf("ENUM\t%s\t\t\t",
				   config_enum_lookup_by_value(&structToPrint->_enum,
											 structToPrint->_enum.boot_val));
			break;

		default:
			write_stderr("internal error: unrecognized run-time parameter type\n");
			break;
	}

	printf("%s\t%s\n",
		   (structToPrint->generic.short_desc == NULL) ? "" : _(structToPrint->generic.short_desc),
		   (structToPrint->generic.long_desc == NULL) ? "" : _(structToPrint->generic.long_desc));
}
<commit_msg>change variable name bool to boolean<commit_after>/*-------------------------------------------------------------------------
 * help_config.c
 *
 * Displays available options under grand unified configuration scheme
 *
 * Options whose flag bits are set to GUC_NO_SHOW_ALL, GUC_NOT_IN_SAMPLE,
 * or GUC_DISALLOW_IN_FILE are not displayed, unless the user specifically
 * requests that variable by name
 *
 * Portions Copyright (c) 1996-2015, PostgreSQL Global Development Group
 *
 * IDENTIFICATION
 *	  src/backend/utils/misc/help_config.c
 *
 *-------------------------------------------------------------------------
 */
#include "postgres.h"

#include <float.h>
#include <limits.h>
#include <unistd.h>

#include "utils/guc_tables.h"
#include "utils/help_config.h"

/*
 * This union allows us to mix the numerous different types of structs
 * that we are organizing.
 */
typedef union
{
	struct config_generic generic;
	struct config_bool boolean;
	struct config_real real;
	struct config_int integer;
	struct config_string string;
	struct config_enum _enum;
} mixedStruct;

static void printMixedStruct(mixedStruct *structToPrint);
static bool displayStruct(mixedStruct *structToDisplay);

void
GucInfoMain(void)
{
	struct config_generic **guc_vars;
	int			numOpts,
				i;

	/* Initialize the guc_variables[] array */
	build_guc_variables();

	guc_vars = get_guc_variables();
	numOpts = GetNumConfigOptions();

	for (i = 0; i < numOpts; i++)
	{
		mixedStruct *var = (mixedStruct *) guc_vars[i];

		if (displayStruct(var))
			printMixedStruct(var);
	}

	exit(0);
}

/*
 * This function will return true if the struct passed to it
 * should be displayed to the user.
 */
static bool
displayStruct(mixedStruct *structToDisplay)
{
	return !(structToDisplay->generic.flags & (GUC_NO_SHOW_ALL |
											   GUC_NOT_IN_SAMPLE |
											   GUC_DISALLOW_IN_FILE));
}

/*
 * This function prints out the generic struct passed to it. It will print out
 * a different format, depending on what the user wants to see.
 */
static void
printMixedStruct(mixedStruct *structToPrint)
{
	printf("%s\t%s\t%s\t",
		   structToPrint->generic.name,
		   GucContext_Names[structToPrint->generic.context],
		   _(config_group_names[structToPrint->generic.group]));

	switch (structToPrint->generic.vartype)
	{

		case PGC_BOOL:
			printf("BOOLEAN\t%s\t\t\t",
				   (structToPrint->boolean.reset_val == 0) ?
				   "FALSE" : "TRUE");
			break;

		case PGC_INT:
			printf("INTEGER\t%d\t%d\t%d\t",
				   structToPrint->integer.reset_val,
				   structToPrint->integer.min,
				   structToPrint->integer.max);
			break;

		case PGC_REAL:
			printf("REAL\t%g\t%g\t%g\t",
				   structToPrint->real.reset_val,
				   structToPrint->real.min,
				   structToPrint->real.max);
			break;

		case PGC_STRING:
			printf("STRING\t%s\t\t\t",
				   structToPrint->string.boot_val ? structToPrint->string.boot_val : "");
			break;

		case PGC_ENUM:
			printf("ENUM\t%s\t\t\t",
				   config_enum_lookup_by_value(&structToPrint->_enum,
											 structToPrint->_enum.boot_val));
			break;

		default:
			write_stderr("internal error: unrecognized run-time parameter type\n");
			break;
	}

	printf("%s\t%s\n",
		   (structToPrint->generic.short_desc == NULL) ? "" : _(structToPrint->generic.short_desc),
		   (structToPrint->generic.long_desc == NULL) ? "" : _(structToPrint->generic.long_desc));
}
<|endoftext|>


<commit_before>/*
	Flexisip, a flexible SIP proxy server with media capabilities.
	Copyright (C) 2010-2015  Belledonne Communications SARL, All rights reserved.

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

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

	You should have received a copy of the GNU Affero General Public License
	along with this program.  If not, see <http://www.gnu.org/licenses/>.
*/
#include <sys/types.h>
#include <dirent.h>

#include "pushnotificationservice.hh"
#include "pushnotificationclient.hh"
#include "common.hh"

#include <sstream>
#include <openssl/x509.h>
#include <openssl/x509_vfy.h>
#include <openssl/err.h>
#include <openssl/pem.h>

	using namespace std;

	static const char *APN_DEV_ADDRESS = "gateway.sandbox.push.apple.com";
	static const char *APN_PROD_ADDRESS = "gateway.push.apple.com";
	static const char *APN_PORT = "2195";

	static const char *GPN_ADDRESS = "android.googleapis.com";
	static const char *GPN_PORT = "443";

	static const char *WPPN_PORT = "80";

	PushNotificationService::PushNotificationService(int maxQueueSize)
	: mMaxQueueSize(maxQueueSize), mClients(), mCountFailed(NULL), mCountSent(NULL) {
		SSL_library_init();
		SSL_load_error_strings();
	}

	PushNotificationService::~PushNotificationService() {
		ERR_free_strings();
	}

	int PushNotificationService::sendPush(const std::shared_ptr<PushNotificationRequest> &pn) {
		std::shared_ptr<PushNotificationClient> client = mClients[pn->getAppIdentifier()];
		if (client == 0) {
			if (pn->getType().compare(string("wp")) == 0) {
				string wpClient = pn->getAppIdentifier();

				SSL_CTX* ctx = SSL_CTX_new(SSLv23_client_method());
				SSL_CTX_set_verify(ctx, SSL_VERIFY_NONE, NULL);

				LOGD("Creating PN client for %s", pn->getAppIdentifier().c_str());
				mClients[wpClient] = std::make_shared<PushNotificationClient>(wpClient, this, ctx,
					pn->getAppIdentifier(), WPPN_PORT, mMaxQueueSize, false);
				client = mClients[wpClient];
			} else {
				LOGE("No push notification certificate for client %s", pn->getAppIdentifier().c_str());
				return -1;
			}
		}
		client->sendPush(pn);
		return 0;
	}

bool PushNotificationService::isIdle() {
	map<string, std::shared_ptr<PushNotificationClient>>::const_iterator it;
	for (it = mClients.begin(); it != mClients.end(); ++it) {
		if (!it->second->isIdle()) {
			return false;
		}
	}
	return true;
}

void PushNotificationService::setupGenericClient(const url_t *url) {
	SSL_CTX* ctx = SSL_CTX_new(SSLv23_client_method());
	SSL_CTX_set_verify(ctx, SSL_VERIFY_NONE, NULL);

	mClients["generic"] = std::make_shared<PushNotificationClient>("generic", this, ctx, url->url_host, url_port(url),
		mMaxQueueSize, false);
}

/* Utility function to convert ASN1_TIME to a printable string in a buffer */
static int ASN1_TIME_toString( const ASN1_TIME* time, char* buffer, uint32_t buff_length){
	int write = 0;
	BIO* bio = BIO_new(BIO_s_mem());
	if (bio) {
		if (ASN1_TIME_print(bio, time))
			write = BIO_read(bio, buffer, buff_length-1);
		BIO_free_all(bio);
	}
	buffer[write]='\0';
	return write;
}

bool PushNotificationService::isCertExpired( const std::string &certPath ){
	bool expired = true;
	BIO* certbio = BIO_new(BIO_s_file());
	int err = BIO_read_filename(certbio, certPath.c_str());
	if( err == 0 ){
		LOGE("BIO_read_filename failed for %s", certPath.c_str());
		BIO_free_all(certbio);
		return expired;
	}

	X509* cert = PEM_read_bio_X509(certbio, NULL, 0, 0);
	if( !cert ){
		char buf[128] = {};
		unsigned long error = ERR_get_error();
		ERR_error_string(error, buf);
		LOGE("Couldn't parse certificate at %s : %s", certPath.c_str(), buf);
		BIO_free_all(certbio);
		return expired;
	} else {
		ASN1_TIME *notBefore = X509_get_notBefore(cert);
		ASN1_TIME *notAfter = X509_get_notAfter(cert);
		char beforeStr[128] = {};
		char afterStr[128] = {};
		int validDates = ( ASN1_TIME_toString(notBefore, beforeStr, 128) && ASN1_TIME_toString(notAfter, afterStr, 128));
		if( X509_cmp_current_time(notBefore) <= 0 && X509_cmp_current_time(notAfter) >= 0 ) {
			LOGD("Certificate %s has a valid expiration: %s.", certPath.c_str(), afterStr);
			expired = false;
		} else {
			// the certificate has an expire or not before value that makes it not valid regarding the server's date.
			if (validDates) {
				LOGD("Certificate %s is expired or not yet valid! Not Before: %s, Not After: %s", certPath.c_str(),
					beforeStr, afterStr);
			} else {
				LOGD("Certificate %s is expired or not yet valid!", certPath.c_str());
			}
		}
	}
	X509_free(cert);
	BIO_free_all(certbio);

	return expired;
}

int handle_verify_callback(X509_STORE_CTX* mCtx, void* ud) {
	char subject_name[256];

	X509 *cert = X509_STORE_CTX_get_current_cert(mCtx);
	if (!cert) {
		SLOGE << "No certificate found!";
		return 0;
	}
	X509_NAME_oneline(X509_get_subject_name(cert), subject_name, 256);
	SLOGD << "Verifying " << subject_name;

	int error = X509_STORE_CTX_get_error(mCtx);
	if( error != 0 ){
		switch (error) {
			case X509_V_ERR_CERT_NOT_YET_VALID:
			case X509_V_ERR_CRL_NOT_YET_VALID:
			SLOGE << "Certificate for " <<  subject_name << " is not yet valid. Push won't work.";
			break;
			case X509_V_ERR_CERT_HAS_EXPIRED:
			case X509_V_ERR_CRL_HAS_EXPIRED:
			SLOGE << "Certificate for " <<  subject_name << " is expired. Push won't work.";
			break;
			default:{
				const char* errString = X509_verify_cert_error_string(error);
				SLOGE << "Certificate for " << subject_name << " is invalid (reason: " << error << ": " << (errString ? errString:"unknown") << "). Push won't work.";
				break;
			}
		}
	}

	return 0;
}

void PushNotificationService::setupiOSClient(const std::string &certdir, const std::string &cafile) {
	struct dirent *dirent;
	DIR *dirp;

	dirp = opendir(certdir.c_str());
	if (dirp == NULL) {
		LOGE("Could not open push notification certificates directory (%s): %s", certdir.c_str(), strerror(errno));
		return;
	}
	SLOGD << "Searching push notification client on dir [" << certdir << "]";

	while (true) {
		errno = 0;
		if ((dirent = readdir(dirp)) == NULL) {
			if (errno)
				SLOGE << "Cannot read dir [" << certdir << "] because [" << strerror(errno) << "]";
			break;
		}

		string cert = string(dirent->d_name);
		// only consider files which end with .pem
		string suffix = ".pem";
		if (cert.compare(".") == 0 || cert.compare("..") == 0 ||
			(cert.compare(cert.length() - suffix.length(), suffix.length(), suffix) != 0)) {
			continue;
		}

		SSL_CTX* ctx = SSL_CTX_new(TLSv1_2_client_method());
		if (!ctx) {
			SLOGE << "Could not create ctx!";
			ERR_print_errors_fp(stderr);
			continue;
		}

		if (cafile.empty()) {
			SSL_CTX_set_verify(ctx, SSL_VERIFY_NONE, NULL);
		} else {
			SSL_CTX_set_verify(ctx, SSL_VERIFY_PEER, NULL);
			SSL_CTX_set_cert_verify_callback(ctx, handle_verify_callback, NULL);
		}

		if(! SSL_CTX_load_verify_locations(ctx, cafile.empty()?NULL:cafile.c_str(), "/etc/ssl/certs")) {
			SLOGE << "Error loading trust store";
			ERR_print_errors_fp(stderr);
			SSL_CTX_free(ctx);
			continue;
		}

		string certpath = string(certdir) + "/" + cert;
		if (!cert.empty()) {
			int error = SSL_CTX_use_certificate_file(ctx, certpath.c_str(), SSL_FILETYPE_PEM);
			if (error != 1) {
				LOGE("SSL_CTX_use_certificate_file for %s failed: %d", certpath.c_str(), error);
				continue;
			} else if ( isCertExpired(certpath) ){
				LOGEN("Certificate %s is expired! You won't be able to use it for push notifications. Please update your certificate or remove it entirely.", certpath.c_str());
			}
		}
		if (!certpath.empty()) {
			int error = SSL_CTX_use_PrivateKey_file(ctx, certpath.c_str(), SSL_FILETYPE_PEM);
			if (error != 1 || SSL_CTX_check_private_key(ctx) != 1) {
				SLOGE << "Private key does not match the certificate public key for " << certpath << ": " << error;
				continue;
			}
		}

		string certName = cert.substr(0, cert.size() - 4); // Remove .pem at the end of cert
		const char *apn_server = (certName.find(".dev") != string::npos) ? APN_DEV_ADDRESS : APN_PROD_ADDRESS;
		mClients[certName] = std::make_shared<PushNotificationClient>(cert, this, ctx, apn_server, APN_PORT, mMaxQueueSize, true);
		SLOGD << "Adding ios push notification client [" << certName << "]";
	}
	closedir(dirp);
}

void PushNotificationService::setupAndroidClient(const std::map<std::string, std::string> googleKeys) {
	map<string, string>::const_iterator it;
	for (it = googleKeys.begin(); it != googleKeys.end(); ++it) {
		string android_app_id = it->first;

		SSL_CTX* ctx = SSL_CTX_new(SSLv23_client_method());
		SSL_CTX_set_verify(ctx, SSL_VERIFY_NONE, NULL);

		mClients[android_app_id] = std::make_shared<PushNotificationClient>("google", this, ctx, GPN_ADDRESS, GPN_PORT, mMaxQueueSize, true);
		SLOGD << "Adding android push notification client [" << android_app_id << "]";
	}
}

<commit_msg>fix ssl version for apple production push notif server, that doesn't like TLS > 1.0<commit_after>/*
	Flexisip, a flexible SIP proxy server with media capabilities.
	Copyright (C) 2010-2015  Belledonne Communications SARL, All rights reserved.

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

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

	You should have received a copy of the GNU Affero General Public License
	along with this program.  If not, see <http://www.gnu.org/licenses/>.
*/
#include <sys/types.h>
#include <dirent.h>

#include "pushnotificationservice.hh"
#include "pushnotificationclient.hh"
#include "common.hh"

#include <sstream>
#include <openssl/x509.h>
#include <openssl/x509_vfy.h>
#include <openssl/err.h>
#include <openssl/pem.h>

	using namespace std;

	static const char *APN_DEV_ADDRESS = "gateway.sandbox.push.apple.com";
	static const char *APN_PROD_ADDRESS = "gateway.push.apple.com";
	static const char *APN_PORT = "2195";

	static const char *GPN_ADDRESS = "android.googleapis.com";
	static const char *GPN_PORT = "443";

	static const char *WPPN_PORT = "80";

	PushNotificationService::PushNotificationService(int maxQueueSize)
	: mMaxQueueSize(maxQueueSize), mClients(), mCountFailed(NULL), mCountSent(NULL) {
		SSL_library_init();
		SSL_load_error_strings();
	}

	PushNotificationService::~PushNotificationService() {
		ERR_free_strings();
	}

	int PushNotificationService::sendPush(const std::shared_ptr<PushNotificationRequest> &pn) {
		std::shared_ptr<PushNotificationClient> client = mClients[pn->getAppIdentifier()];
		if (client == 0) {
			if (pn->getType().compare(string("wp")) == 0) {
				string wpClient = pn->getAppIdentifier();

				SSL_CTX* ctx = SSL_CTX_new(SSLv23_client_method());
				SSL_CTX_set_verify(ctx, SSL_VERIFY_NONE, NULL);

				LOGD("Creating PN client for %s", pn->getAppIdentifier().c_str());
				mClients[wpClient] = std::make_shared<PushNotificationClient>(wpClient, this, ctx,
					pn->getAppIdentifier(), WPPN_PORT, mMaxQueueSize, false);
				client = mClients[wpClient];
			} else {
				LOGE("No push notification certificate for client %s", pn->getAppIdentifier().c_str());
				return -1;
			}
		}
		client->sendPush(pn);
		return 0;
	}

bool PushNotificationService::isIdle() {
	map<string, std::shared_ptr<PushNotificationClient>>::const_iterator it;
	for (it = mClients.begin(); it != mClients.end(); ++it) {
		if (!it->second->isIdle()) {
			return false;
		}
	}
	return true;
}

void PushNotificationService::setupGenericClient(const url_t *url) {
	SSL_CTX* ctx = SSL_CTX_new(TLSv1_client_method());
	SSL_CTX_set_verify(ctx, SSL_VERIFY_NONE, NULL);

	mClients["generic"] = std::make_shared<PushNotificationClient>("generic", this, ctx, url->url_host, url_port(url),
		mMaxQueueSize, false);
}

/* Utility function to convert ASN1_TIME to a printable string in a buffer */
static int ASN1_TIME_toString( const ASN1_TIME* time, char* buffer, uint32_t buff_length){
	int write = 0;
	BIO* bio = BIO_new(BIO_s_mem());
	if (bio) {
		if (ASN1_TIME_print(bio, time))
			write = BIO_read(bio, buffer, buff_length-1);
		BIO_free_all(bio);
	}
	buffer[write]='\0';
	return write;
}

bool PushNotificationService::isCertExpired( const std::string &certPath ){
	bool expired = true;
	BIO* certbio = BIO_new(BIO_s_file());
	int err = BIO_read_filename(certbio, certPath.c_str());
	if( err == 0 ){
		LOGE("BIO_read_filename failed for %s", certPath.c_str());
		BIO_free_all(certbio);
		return expired;
	}

	X509* cert = PEM_read_bio_X509(certbio, NULL, 0, 0);
	if( !cert ){
		char buf[128] = {};
		unsigned long error = ERR_get_error();
		ERR_error_string(error, buf);
		LOGE("Couldn't parse certificate at %s : %s", certPath.c_str(), buf);
		BIO_free_all(certbio);
		return expired;
	} else {
		ASN1_TIME *notBefore = X509_get_notBefore(cert);
		ASN1_TIME *notAfter = X509_get_notAfter(cert);
		char beforeStr[128] = {};
		char afterStr[128] = {};
		int validDates = ( ASN1_TIME_toString(notBefore, beforeStr, 128) && ASN1_TIME_toString(notAfter, afterStr, 128));
		if( X509_cmp_current_time(notBefore) <= 0 && X509_cmp_current_time(notAfter) >= 0 ) {
			LOGD("Certificate %s has a valid expiration: %s.", certPath.c_str(), afterStr);
			expired = false;
		} else {
			// the certificate has an expire or not before value that makes it not valid regarding the server's date.
			if (validDates) {
				LOGD("Certificate %s is expired or not yet valid! Not Before: %s, Not After: %s", certPath.c_str(),
					beforeStr, afterStr);
			} else {
				LOGD("Certificate %s is expired or not yet valid!", certPath.c_str());
			}
		}
	}
	X509_free(cert);
	BIO_free_all(certbio);

	return expired;
}

int handle_verify_callback(X509_STORE_CTX* mCtx, void* ud) {
	char subject_name[256];

	X509 *cert = X509_STORE_CTX_get_current_cert(mCtx);
	if (!cert) {
		SLOGE << "No certificate found!";
		return 0;
	}
	X509_NAME_oneline(X509_get_subject_name(cert), subject_name, 256);
	SLOGD << "Verifying " << subject_name;

	int error = X509_STORE_CTX_get_error(mCtx);
	if( error != 0 ){
		switch (error) {
			case X509_V_ERR_CERT_NOT_YET_VALID:
			case X509_V_ERR_CRL_NOT_YET_VALID:
			SLOGE << "Certificate for " <<  subject_name << " is not yet valid. Push won't work.";
			break;
			case X509_V_ERR_CERT_HAS_EXPIRED:
			case X509_V_ERR_CRL_HAS_EXPIRED:
			SLOGE << "Certificate for " <<  subject_name << " is expired. Push won't work.";
			break;
			default:{
				const char* errString = X509_verify_cert_error_string(error);
				SLOGE << "Certificate for " << subject_name << " is invalid (reason: " << error << ": " << (errString ? errString:"unknown") << "). Push won't work.";
				break;
			}
		}
	}

	return 0;
}

void PushNotificationService::setupiOSClient(const std::string &certdir, const std::string &cafile) {
	struct dirent *dirent;
	DIR *dirp;

	dirp = opendir(certdir.c_str());
	if (dirp == NULL) {
		LOGE("Could not open push notification certificates directory (%s): %s", certdir.c_str(), strerror(errno));
		return;
	}
	SLOGD << "Searching push notification client on dir [" << certdir << "]";

	while (true) {
		errno = 0;
		if ((dirent = readdir(dirp)) == NULL) {
			if (errno)
				SLOGE << "Cannot read dir [" << certdir << "] because [" << strerror(errno) << "]";
			break;
		}

		string cert = string(dirent->d_name);
		// only consider files which end with .pem
		string suffix = ".pem";
		if (cert.compare(".") == 0 || cert.compare("..") == 0 ||
			(cert.compare(cert.length() - suffix.length(), suffix.length(), suffix) != 0)) {
			continue;
		}
		/*March 2016: Yes Apple production push server doesn't support TLS > 1.0*/
		SSL_CTX* ctx = SSL_CTX_new(TLSv1_client_method());
		if (!ctx) {
			SLOGE << "Could not create ctx!";
			ERR_print_errors_fp(stderr);
			continue;
		}

		if (cafile.empty()) {
			SSL_CTX_set_verify(ctx, SSL_VERIFY_NONE, NULL);
		} else {
			SSL_CTX_set_verify(ctx, SSL_VERIFY_PEER, NULL);
			SSL_CTX_set_cert_verify_callback(ctx, handle_verify_callback, NULL);
		}

		if(! SSL_CTX_load_verify_locations(ctx, cafile.empty()?NULL:cafile.c_str(), "/etc/ssl/certs")) {
			SLOGE << "Error loading trust store";
			ERR_print_errors_fp(stderr);
			SSL_CTX_free(ctx);
			continue;
		}

		string certpath = string(certdir) + "/" + cert;
		if (!cert.empty()) {
			int error = SSL_CTX_use_certificate_file(ctx, certpath.c_str(), SSL_FILETYPE_PEM);
			if (error != 1) {
				LOGE("SSL_CTX_use_certificate_file for %s failed: %d", certpath.c_str(), error);
				continue;
			} else if ( isCertExpired(certpath) ){
				LOGEN("Certificate %s is expired! You won't be able to use it for push notifications. Please update your certificate or remove it entirely.", certpath.c_str());
			}
		}
		if (!certpath.empty()) {
			int error = SSL_CTX_use_PrivateKey_file(ctx, certpath.c_str(), SSL_FILETYPE_PEM);
			if (error != 1 || SSL_CTX_check_private_key(ctx) != 1) {
				SLOGE << "Private key does not match the certificate public key for " << certpath << ": " << error;
				continue;
			}
		}

		string certName = cert.substr(0, cert.size() - 4); // Remove .pem at the end of cert
		const char *apn_server = (certName.find(".dev") != string::npos) ? APN_DEV_ADDRESS : APN_PROD_ADDRESS;
		mClients[certName] = std::make_shared<PushNotificationClient>(cert, this, ctx, apn_server, APN_PORT, mMaxQueueSize, true);
		SLOGD << "Adding ios push notification client [" << certName << "]";
	}
	closedir(dirp);
}

void PushNotificationService::setupAndroidClient(const std::map<std::string, std::string> googleKeys) {
	map<string, string>::const_iterator it;
	for (it = googleKeys.begin(); it != googleKeys.end(); ++it) {
		string android_app_id = it->first;

		SSL_CTX* ctx = SSL_CTX_new(SSLv23_client_method());
		SSL_CTX_set_verify(ctx, SSL_VERIFY_NONE, NULL);

		mClients[android_app_id] = std::make_shared<PushNotificationClient>("google", this, ctx, GPN_ADDRESS, GPN_PORT, mMaxQueueSize, true);
		SLOGD << "Adding android push notification client [" << android_app_id << "]";
	}
}

<|endoftext|>


<commit_before>#include "command.h"
#include "debug.h"
#include "thread.h"
#include "dwi/tractography/rng.h"
#include "image.h"

using namespace MR;
using namespace App;

std::mutex mutex;

void usage ()
{
  AUTHOR = "Joe Bloggs (joe.bloggs@acme.org)";

  DESCRIPTION
  + "raise each voxel intensity to the given power (default: 2)";

  ARGUMENTS
  + Argument ("in", "the input image.").type_image_in ()
  + Argument ("out", "the output image.").type_image_out ();

  OPTIONS
  + Option ("power", "the power by which to raise each value (default: 1)")
  +   Argument ("value").type_float()

  + Option ("noise", "the std. dev. of the noise to add to each value (default: 1)")
  +   Argument ("value").type_float();
}

typedef float value_type;

using namespace DWI::Tractography;

//struct thread_func {
//  void execute () {
//    std::lock_guard<std::mutex> lock (mutex);
//    std::cerr << &rng << ": " << rng() << " " << rng() << " " << rng() << "\n";
//  }
//};

void run ()
{

  auto input = Image<float>::open (argument[0]);
  auto output = Image<float>::create (argument[1], input);

  output.index(0) = input.index(0);
  output.valid() = input.value();

//  std::cerr << &rng << ": " << rng() << " " << rng() << " " << rng() << "\n";
//  Thread::run (Thread::multi (thread_func()));
}

<commit_msg>change to bogus command to demonstrate issue with new syntax and assigning indices and values between images<commit_after>#include "command.h"
#include "debug.h"
#include "thread.h"
#include "dwi/tractography/rng.h"
#include "image.h"

using namespace MR;
using namespace App;

std::mutex mutex;

void usage ()
{
  AUTHOR = "Joe Bloggs (joe.bloggs@acme.org)";

  DESCRIPTION
  + "raise each voxel intensity to the given power (default: 2)";

  ARGUMENTS
  + Argument ("in", "the input image.").type_image_in ()
  + Argument ("out", "the output image.").type_image_out ();

  OPTIONS
  + Option ("power", "the power by which to raise each value (default: 1)")
  +   Argument ("value").type_float()

  + Option ("noise", "the std. dev. of the noise to add to each value (default: 1)")
  +   Argument ("value").type_float();
}

typedef float value_type;

using namespace DWI::Tractography;

//struct thread_func {
//  void execute () {
//    std::lock_guard<std::mutex> lock (mutex);
//    std::cerr << &rng << ": " << rng() << " " << rng() << " " << rng() << "\n";
//  }
//};

void run ()
{

  auto input = Image<float>::open (argument[0]);
  auto output = Image<float>::create (argument[1], input);

  output.index(0) = input.index(0);
  output.value() = input.value();

//  std::cerr << &rng << ": " << rng() << " " << rng() << " " << rng() << "\n";
//  Thread::run (Thread::multi (thread_func()));
}

<|endoftext|>


<commit_before>/*
Copyright (c) 2010 Sony Pictures Imageworks Inc., et al.
All Rights Reserved.

Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are
met:
* Redistributions of source code must retain the above copyright
  notice, this list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above copyright
  notice, this list of conditions and the following disclaimer in the
  documentation and/or other materials provided with the distribution.
* Neither the name of Sony Pictures Imageworks nor the names of its
  contributors may be used to endorse or promote products derived from
  this software without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
"AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/

#include "oslops.h"
#include "oslexec_pvt.h"

#ifdef OSL_NAMESPACE
namespace OSL_NAMESPACE {
#endif
namespace OSL {
namespace pvt {

/////////////////////////////////////////////////////////////////////////
// Notes on how messages work:
//
// The messages are stored in a ParamValueList in the ShadingContext.
// For simple types, just slurp them up into the PVL.
//
// Closures are tricky because of the memory management and that PVL's
// don't know anything about them. For those we allocate new closures
// in the context's closure_msgs vector, and just store their indices in
// the PVL.
//
// FIXME -- setmessage only stores message values, not derivs, so
// getmessage only retrieves the values and has zero derivs.
// We should come back and fix this later.
//
// FIXME -- I believe that if you try to set a message that is an array
// of closures, it will only store the first element.  Also something to
// come back to, not an emergency at the moment.
//
// FIXME -- because we store closures by int index, there's an error
// condition if a shader does a setmessage with a closure, then does a
// getmessage of the same message name into int, or vice versa.  Instead
// that should be a type mismatch and getmessage() should return 0.

// void setmessage (string name, ANY value).
DECLOP (OP_setmessage)
{
    ASSERT (nargs == 2);
    Symbol &Name (exec->sym (args[0]));
    Symbol &Val (exec->sym (args[1]));
    ASSERT (Name.typespec().is_string());

    VaryingRef<ustring> name ((ustring *)Name.data(), Name.step());
    ParamValueList &messages (exec->context()->messages());
    std::vector<ClosureColor> &closure_msgs (exec->context()->closure_msgs());

    bool varying = (Name.is_varying() || Val.is_varying() ||
                    ! exec->all_points_on());
    TypeDesc type = Val.typespec().simpletype();
    if (Val.typespec().is_closure ())
        type = TypeDesc::TypeInt;     // Actually store closure indices only
    size_t datasize = type.size();

    ustring lastname;       // Last message name that we matched
    ParamValue *p = NULL;   // Pointer to the PV for the message

    for (int i = beginpoint;  i < endpoint;  ++i) {
        if (runflags[i]) {
            if (i == beginpoint || name[i] != lastname) {
                // Different message than last time -- search anew
                p = NULL;
                for (size_t m = 0;  m < messages.size() && !p;  ++m)
                    if (messages[m].name() == name[i] &&
                          messages[m].type() == type)
                        p = &messages[m];
                // If the message doesn't already exist, create it
                if (! p) {
                    p = & messages.grow ();
                    p->init (name[i], type,
                             varying ? exec->npoints() : 1, NULL);
                }
                lastname = name[i];
            }

            // Copy the data
            DASSERT (p != NULL);
            char *msgdata = (char *)p->data() + varying*datasize*i;
            if (Val.typespec().is_closure()) {
                // Add the closure data to the end of the closure messages
                closure_msgs.push_back (**(ClosureColor **)Val.data(i));
                // and store its index in the PVL
                *(int *)msgdata = (int)closure_msgs.size() - 1;
            } else {
                // Non-closure types, just memcpy
                memcpy (msgdata, Val.data(i), datasize);
            }
        }
        if (! varying)
            break;      // Non-uniform case can take early out
    }
}

// int getmessage (string name, ANY value)
DECLOP (OP_getmessage)
{
    ASSERT (nargs == 3);
    Symbol &Result (exec->sym (args[0]));
    Symbol &Name (exec->sym (args[1]));
    Symbol &Val (exec->sym (args[2]));
    ASSERT (Result.typespec().is_int() && Name.typespec().is_string());

    bool varying = (Name.is_varying());
    exec->adjust_varying (Result, varying);
    exec->adjust_varying (Val, varying);

    VaryingRef<int> result ((int *)Result.data(), Result.step());
    VaryingRef<ustring> name ((ustring *)Name.data(), Name.step());
    ParamValueList &messages (exec->context()->messages());
    std::vector<ClosureColor> &closure_msgs (exec->context()->closure_msgs());

    TypeDesc type = Val.typespec().simpletype();
    if (Val.typespec().is_closure ())
        type = TypeDesc::TypeInt;     // Actually store closure indices only
    size_t datasize = type.size();

    ustring lastname;       // Last message name that we matched
    ParamValue *p = NULL;   // Pointer to the PV for the message

    for (int i = beginpoint;  i < endpoint;  ++i) {
        if (runflags[i]) {
            if (i == beginpoint || name[i] != lastname) {
                // Different message than last time -- search anew
                p = NULL;
                for (size_t m = 0;  m < messages.size() && !p;  ++m)
                    if (messages[m].name() == name[i] &&
                          messages[m].type() == type)
                        p = &messages[m];
                if (p && (! varying || Val.is_uniform()) && p->nvalues() > 1) {
                    // all the parameters to the function were uniform,
                    // but the message itself is varying, so adjust Val.
                    exec->adjust_varying (Val, true);
                    varying = true;
                }
                lastname = name[i];
            }

            if (p) {
                result[i] = 1;   // found
                char *msgdata = (char *)p->data() + varying*datasize*i;
                if (Val.typespec().is_closure()) {
                    // Retrieve the closure index from the PVL
                    int index = *(int *)msgdata;
                    ClosureColor *valclose = *(ClosureColor **) Val.data(i);
                    // then copy the closure (or clear it, if out of range)
                    if (index < (int)closure_msgs.size())
                        *valclose = closure_msgs.back();
                    else
                        valclose->clear ();
                } else {
                    memcpy (Val.data(i), msgdata, datasize);
                }
            } else {
                result[i] = 0;   // not found
            }
        }
        if (! varying)
            break;      // Non-uniform case can take early out
    }

    if (Val.has_derivs ())
        exec->zero_derivs (Val);
}

}; // namespace pvt
}; // namespace OSL
#ifdef OSL_NAMESPACE
}; // end namespace OSL_NAMESPACE
#endif
<commit_msg>Fix bug in getmessage when all args are varying but the op occurs in a varying conditional.<commit_after>/*
Copyright (c) 2010 Sony Pictures Imageworks Inc., et al.
All Rights Reserved.

Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are
met:
* Redistributions of source code must retain the above copyright
  notice, this list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above copyright
  notice, this list of conditions and the following disclaimer in the
  documentation and/or other materials provided with the distribution.
* Neither the name of Sony Pictures Imageworks nor the names of its
  contributors may be used to endorse or promote products derived from
  this software without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
"AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/

#include "oslops.h"
#include "oslexec_pvt.h"

#ifdef OSL_NAMESPACE
namespace OSL_NAMESPACE {
#endif
namespace OSL {
namespace pvt {

/////////////////////////////////////////////////////////////////////////
// Notes on how messages work:
//
// The messages are stored in a ParamValueList in the ShadingContext.
// For simple types, just slurp them up into the PVL.
//
// Closures are tricky because of the memory management and that PVL's
// don't know anything about them. For those we allocate new closures
// in the context's closure_msgs vector, and just store their indices in
// the PVL.
//
// FIXME -- setmessage only stores message values, not derivs, so
// getmessage only retrieves the values and has zero derivs.
// We should come back and fix this later.
//
// FIXME -- I believe that if you try to set a message that is an array
// of closures, it will only store the first element.  Also something to
// come back to, not an emergency at the moment.
//
// FIXME -- because we store closures by int index, there's an error
// condition if a shader does a setmessage with a closure, then does a
// getmessage of the same message name into int, or vice versa.  Instead
// that should be a type mismatch and getmessage() should return 0.

// void setmessage (string name, ANY value).
DECLOP (OP_setmessage)
{
    ASSERT (nargs == 2);
    Symbol &Name (exec->sym (args[0]));
    Symbol &Val (exec->sym (args[1]));
    ASSERT (Name.typespec().is_string());

    VaryingRef<ustring> name ((ustring *)Name.data(), Name.step());
    ParamValueList &messages (exec->context()->messages());
    std::vector<ClosureColor> &closure_msgs (exec->context()->closure_msgs());

    bool varying = (Name.is_varying() || Val.is_varying() ||
                    ! exec->all_points_on());
    TypeDesc type = Val.typespec().simpletype();
    if (Val.typespec().is_closure ())
        type = TypeDesc::TypeInt;     // Actually store closure indices only
    size_t datasize = type.size();

    ustring lastname;       // Last message name that we matched
    ParamValue *p = NULL;   // Pointer to the PV for the message

    for (int i = beginpoint;  i < endpoint;  ++i) {
        if (runflags[i]) {
            if (i == beginpoint || name[i] != lastname) {
                // Different message than last time -- search anew
                p = NULL;
                for (size_t m = 0;  m < messages.size() && !p;  ++m)
                    if (messages[m].name() == name[i] &&
                          messages[m].type() == type)
                        p = &messages[m];
                // If the message doesn't already exist, create it
                if (! p) {
                    p = & messages.grow ();
                    p->init (name[i], type,
                             varying ? exec->npoints() : 1, NULL);
                }
                lastname = name[i];
            }

            // Copy the data
            DASSERT (p != NULL);
            char *msgdata = (char *)p->data() + varying*datasize*i;
            if (Val.typespec().is_closure()) {
                // Add the closure data to the end of the closure messages
                closure_msgs.push_back (**(ClosureColor **)Val.data(i));
                // and store its index in the PVL
                *(int *)msgdata = (int)closure_msgs.size() - 1;
            } else {
                // Non-closure types, just memcpy
                memcpy (msgdata, Val.data(i), datasize);
            }
        }
        if (! varying)
            break;      // Non-uniform case can take early out
    }
}

// int getmessage (string name, ANY value)
DECLOP (OP_getmessage)
{
    ASSERT (nargs == 3);
    Symbol &Result (exec->sym (args[0]));
    Symbol &Name (exec->sym (args[1]));
    Symbol &Val (exec->sym (args[2]));
    ASSERT (Result.typespec().is_int() && Name.typespec().is_string());

    bool varying = (Name.is_varying());
    exec->adjust_varying (Result, varying);
    exec->adjust_varying (Val, varying);
    varying |= Result.is_varying();  // adjust in case we're in a conditional

    VaryingRef<int> result ((int *)Result.data(), Result.step());
    VaryingRef<ustring> name ((ustring *)Name.data(), Name.step());
    ParamValueList &messages (exec->context()->messages());
    std::vector<ClosureColor> &closure_msgs (exec->context()->closure_msgs());

    TypeDesc type = Val.typespec().simpletype();
    if (Val.typespec().is_closure ())
        type = TypeDesc::TypeInt;     // Actually store closure indices only
    size_t datasize = type.size();

    ustring lastname;       // Last message name that we matched
    ParamValue *p = NULL;   // Pointer to the PV for the message

    for (int i = beginpoint;  i < endpoint;  ++i) {
        if (runflags[i]) {
            if (i == beginpoint || name[i] != lastname) {
                // Different message than last time -- search anew
                p = NULL;
                for (size_t m = 0;  m < messages.size() && !p;  ++m)
                    if (messages[m].name() == name[i] &&
                          messages[m].type() == type)
                        p = &messages[m];
                if (p && (! varying || Val.is_uniform()) && p->nvalues() > 1) {
                    // all the parameters to the function were uniform,
                    // but the message itself is varying, so adjust Val.
                    exec->adjust_varying (Val, true);
                    varying = true;
                }
                lastname = name[i];
            }

            if (p) {
                result[i] = 1;   // found
                char *msgdata = (char *)p->data() + varying*datasize*i;
                if (Val.typespec().is_closure()) {
                    // Retrieve the closure index from the PVL
                    int index = *(int *)msgdata;
                    ClosureColor *valclose = *(ClosureColor **) Val.data(i);
                    // then copy the closure (or clear it, if out of range)
                    if (index < (int)closure_msgs.size())
                        *valclose = closure_msgs.back();
                    else
                        valclose->clear ();
                } else {
                    memcpy (Val.data(i), msgdata, datasize);
                }
            } else {
                result[i] = 0;   // not found
            }
        }
        if (! varying)
            break;      // Non-uniform case can take early out
    }

    if (Val.has_derivs ())
        exec->zero_derivs (Val);
}

}; // namespace pvt
}; // namespace OSL
#ifdef OSL_NAMESPACE
}; // end namespace OSL_NAMESPACE
#endif
<|endoftext|>


<commit_before>/*
Copyright (c) 2009 Sony Pictures Imageworks, et al.
All Rights Reserved.

Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are
met:
* Redistributions of source code must retain the above copyright
  notice, this list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above copyright
  notice, this list of conditions and the following disclaimer in the
  documentation and/or other materials provided with the distribution.
* Neither the name of Sony Pictures Imageworks nor the names of its
  contributors may be used to endorse or promote products derived from
  this software without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
"AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/

#include "oslops.h"
#include "oslexec_pvt.h"

#include "OpenImageIO/sysutil.h"

#ifdef OSL_NAMESPACE
namespace OSL_NAMESPACE {
#endif
namespace OSL {
namespace pvt {

namespace {  // anonymous

inline TextureOptions::Wrap
decode_wrap (ustring w)
{
    if (w == Strings::black)
        return TextureOptions::WrapBlack;
    if (w == Strings::clamp)
        return TextureOptions::WrapClamp;
    if (w == Strings::periodic)
        return TextureOptions::WrapPeriodic;
    if (w == Strings::mirror)
        return TextureOptions::WrapMirror;
    return TextureOptions::WrapDefault;
}

};  // end anonymous namespace

DECLOP (OP_texture)
{
    // Grab the required arguments: result, filename, s, t
    DASSERT (nargs >= 4);
    Symbol &Result (exec->sym (args[0]));
    Symbol &Filename (exec->sym (args[1]));
    DASSERT (Filename.typespec().is_string());
    Symbol &S (exec->sym (args[2]));
    Symbol &T (exec->sym (args[3]));
    DASSERT (S.typespec().is_float() && T.typespec().is_float());

    // Adjust the result's uniform/varying status
    exec->adjust_varying (Result, true /* Assume texture always varies */);

    // FIXME -- we should allow derivs of texture
    if (Result.has_derivs ())
        exec->zero_derivs (Result);

    float zero = 0.0f;
    VaryingRef<float> result ((float *)Result.data(), Result.step());
    VaryingRef<float> s ((float *)S.data(), S.step());
    VaryingRef<float> t ((float *)T.data(), T.step());
    VaryingRef<ustring> filename ((ustring *)Filename.data(), Filename.step());
    VaryingRef<ustring> swrap (NULL), twrap (NULL);
    VaryingRef<int> firstchannel (NULL);
    VaryingRef<float> alpha (NULL);

    TextureSystem *texturesys = exec->texturesys ();
    TextureOptions options;
    options.firstchannel = 0;
    options.nchannels = Result.typespec().simpletype().aggregate;
    options.fill.init (&zero);

    // Set up derivs
    VaryingRef<float> dsdx, dsdy, dtdx, dtdy;
    if (S.has_derivs()) {
        dsdx.init ((float *)S.data() + 1, S.step());
        dsdy.init ((float *)S.data() + 2, S.step());
    } else {
        dsdx.init (&zero);
        dsdy.init (&zero);
    }
    if (T.has_derivs()) {
        dtdx.init ((float *)T.data() + 1, T.step());
        dtdy.init ((float *)T.data() + 2, T.step());
    } else {
        dtdx.init (&zero);
        dtdy.init (&zero);
    }

    // Parse all the optional arguments
    for (int a = 4;  a < nargs;  ++a) {
        Symbol &Name (exec->sym (args[a]));
        DASSERT (Name.typespec().is_string() &&
                 "optional texture token must be a string");
        DASSERT (a+1 < nargs && "malformed argument list for texture");
        if (Name.is_varying()) {
            exec->warning ("optional texture argument is a varying string! Seems pretty fishy.");
        }
        ++a;  // advance to next argument
        Symbol &Val (exec->sym (args[a]));
        TypeDesc valtype = Val.typespec().simpletype ();
        ustring name = * (ustring *) Name.data();
        if (name == Strings::width && valtype == TypeDesc::FLOAT) {
            options.swidth.init ((float *)Val.data(), Val.step());
            options.twidth.init ((float *)Val.data(), Val.step());
        } else if (name == Strings::swidth && valtype == TypeDesc::FLOAT) {
            options.swidth.init ((float *)Val.data(), Val.step());
        } else if (name == Strings::twidth && valtype == TypeDesc::FLOAT) {
            options.twidth.init ((float *)Val.data(), Val.step());

        } else if (name == Strings::blur && valtype == TypeDesc::FLOAT) {
            options.sblur.init ((float *)Val.data(), Val.step());
            options.tblur.init ((float *)Val.data(), Val.step());
        } else if (name == Strings::sblur && valtype == TypeDesc::FLOAT) {
            options.sblur.init ((float *)Val.data(), Val.step());
        } else if (name == Strings::tblur && valtype == TypeDesc::FLOAT) {
            options.tblur.init ((float *)Val.data(), Val.step());

        } else if (name == Strings::wrap && valtype == TypeDesc::STRING) {
            swrap.init ((ustring *)Val.data(), Val.step());
            twrap.init ((ustring *)Val.data(), Val.step());
        } else if (name == Strings::swrap && valtype == TypeDesc::STRING) {
            swrap.init ((ustring *)Val.data(), Val.step());
        } else if (name == Strings::twrap && valtype == TypeDesc::STRING) {
            twrap.init ((ustring *)Val.data(), Val.step());

        } else if (name == Strings::firstchannel && valtype == TypeDesc::INT) {
            firstchannel.init ((int *)Val.data(), Val.step());
        } else if (name == Strings::fill && valtype == TypeDesc::FLOAT) {
            options.fill.init ((float *)Val.data(), Val.step());

        } else if (name == Strings::alpha && valtype == TypeDesc::FLOAT) {
            exec->adjust_varying (Val, true);
            alpha.init ((float *)Val.data(), Val.step());

        } else {
            exec->error ("Unknown texture optional argument: \"%s\", <%s>",
                         name.c_str(), valtype.c_str());
        }
    }

    if (alpha)
        options.nchannels += 1;

    float *r = &result[0];
    bool tempresult = false;
    if (Result.has_derivs() || alpha) {
        tempresult = true;
        r = ALLOCA (float, endpoint*options.nchannels);
    }
    for (int i = beginpoint;  i < endpoint;  ++i) {
        // FIXME -- this calls texture system separately for each point!
        // We really want to batch it into groups that share the same texture
        // filename.
        if (runflags[i]) {
            if (swrap)
                options.swrap = decode_wrap (swrap[i]);
            if (twrap)
                options.twrap = decode_wrap (twrap[i]);
            if (firstchannel)
                options.firstchannel = firstchannel[i];

            bool ok = texturesys->texture (filename[i], options,
                                           runflags, i /*beginpoint*/, i+1 /*endpoint*/,
                                           s, t, dsdx, dtdx, dsdy, dtdy,
                                           r);
            if (! ok) {
                std::string err = texturesys->geterror ();
                if (err.length())
                    exec->error ("%s", err.c_str());
            }
         }
    }

    if (tempresult) {
        // We need to re-copy results back to the right destinations.
        int resultchans = Result.typespec().simpletype().aggregate;
        for (int i = beginpoint;  i < endpoint;  ++i) {
            if (runflags[i])
                for (int c = 0;  c < resultchans;  ++c)
                    (&result[i])[c] = r[i*options.nchannels+c];
        }
        if (alpha) {
            for (int i = beginpoint;  i < endpoint;  ++i)
                if (runflags[i])
                    alpha[i] = r[i*options.nchannels+resultchans];
        }
    }
}

}; // namespace pvt
}; // namespace OSL
#ifdef OSL_NAMESPACE
}; // end namespace OSL_NAMESPACE
#endif
<commit_msg>Add texture derivatives (trac#22)<commit_after>/*
Copyright (c) 2009 Sony Pictures Imageworks, et al.
All Rights Reserved.

Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are
met:
* Redistributions of source code must retain the above copyright
  notice, this list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above copyright
  notice, this list of conditions and the following disclaimer in the
  documentation and/or other materials provided with the distribution.
* Neither the name of Sony Pictures Imageworks nor the names of its
  contributors may be used to endorse or promote products derived from
  this software without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
"AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/

#include "oslops.h"
#include "oslexec_pvt.h"

#include "OpenImageIO/sysutil.h"

#ifdef OSL_NAMESPACE
namespace OSL_NAMESPACE {
#endif
namespace OSL {
namespace pvt {

namespace {  // anonymous

inline TextureOptions::Wrap
decode_wrap (ustring w)
{
    if (w == Strings::black)
        return TextureOptions::WrapBlack;
    if (w == Strings::clamp)
        return TextureOptions::WrapClamp;
    if (w == Strings::periodic)
        return TextureOptions::WrapPeriodic;
    if (w == Strings::mirror)
        return TextureOptions::WrapMirror;
    return TextureOptions::WrapDefault;
}

};  // end anonymous namespace

DECLOP (OP_texture)
{
    // Grab the required arguments: result, filename, s, t
    DASSERT (nargs >= 4);
    Symbol &Result (exec->sym (args[0]));
    Symbol &Filename (exec->sym (args[1]));
    DASSERT (Filename.typespec().is_string());
    Symbol &S (exec->sym (args[2]));
    Symbol &T (exec->sym (args[3]));
    DASSERT (S.typespec().is_float() && T.typespec().is_float());

    // Adjust the result's uniform/varying status
    exec->adjust_varying (Result, true /* Assume texture always varies */);

    float zero = 0.0f;
    VaryingRef<float> result ((float *)Result.data(), Result.step());
    VaryingRef<float> s ((float *)S.data(), S.step());
    VaryingRef<float> t ((float *)T.data(), T.step());
    VaryingRef<ustring> filename ((ustring *)Filename.data(), Filename.step());
    VaryingRef<ustring> swrap (NULL), twrap (NULL);
    VaryingRef<int> firstchannel (NULL);
    VaryingRef<float> alpha (NULL);
    Symbol* Alpha = NULL;

    TextureSystem *texturesys = exec->texturesys ();
    TextureOptions options;
    options.firstchannel = 0;
    options.nchannels = Result.typespec().simpletype().aggregate;
    options.fill.init (&zero);

    // Set up derivs
    VaryingRef<float> dsdx, dsdy, dtdx, dtdy;
    if (S.has_derivs()) {
        dsdx.init ((float *)S.data() + 1, S.step());
        dsdy.init ((float *)S.data() + 2, S.step());
    } else {
        dsdx.init (&zero);
        dsdy.init (&zero);
    }
    if (T.has_derivs()) {
        dtdx.init ((float *)T.data() + 1, T.step());
        dtdy.init ((float *)T.data() + 2, T.step());
    } else {
        dtdx.init (&zero);
        dtdy.init (&zero);
    }

    // Parse all the optional arguments
    for (int a = 4;  a < nargs;  ++a) {
        Symbol &Name (exec->sym (args[a]));
        DASSERT (Name.typespec().is_string() &&
                 "optional texture token must be a string");
        DASSERT (a+1 < nargs && "malformed argument list for texture");
        if (Name.is_varying()) {
            exec->warning ("optional texture argument is a varying string! Seems pretty fishy.");
        }
        ++a;  // advance to next argument
        Symbol &Val (exec->sym (args[a]));
        TypeDesc valtype = Val.typespec().simpletype ();
        ustring name = * (ustring *) Name.data();
        if (name == Strings::width && valtype == TypeDesc::FLOAT) {
            options.swidth.init ((float *)Val.data(), Val.step());
            options.twidth.init ((float *)Val.data(), Val.step());
        } else if (name == Strings::swidth && valtype == TypeDesc::FLOAT) {
            options.swidth.init ((float *)Val.data(), Val.step());
        } else if (name == Strings::twidth && valtype == TypeDesc::FLOAT) {
            options.twidth.init ((float *)Val.data(), Val.step());

        } else if (name == Strings::blur && valtype == TypeDesc::FLOAT) {
            options.sblur.init ((float *)Val.data(), Val.step());
            options.tblur.init ((float *)Val.data(), Val.step());
        } else if (name == Strings::sblur && valtype == TypeDesc::FLOAT) {
            options.sblur.init ((float *)Val.data(), Val.step());
        } else if (name == Strings::tblur && valtype == TypeDesc::FLOAT) {
            options.tblur.init ((float *)Val.data(), Val.step());

        } else if (name == Strings::wrap && valtype == TypeDesc::STRING) {
            swrap.init ((ustring *)Val.data(), Val.step());
            twrap.init ((ustring *)Val.data(), Val.step());
        } else if (name == Strings::swrap && valtype == TypeDesc::STRING) {
            swrap.init ((ustring *)Val.data(), Val.step());
        } else if (name == Strings::twrap && valtype == TypeDesc::STRING) {
            twrap.init ((ustring *)Val.data(), Val.step());

        } else if (name == Strings::firstchannel && valtype == TypeDesc::INT) {
            firstchannel.init ((int *)Val.data(), Val.step());
        } else if (name == Strings::fill && valtype == TypeDesc::FLOAT) {
            options.fill.init ((float *)Val.data(), Val.step());

        } else if (name == Strings::alpha && valtype == TypeDesc::FLOAT) {
            exec->adjust_varying (Val, true);
            alpha.init ((float *)Val.data(), Val.step());
            Alpha = &Val;

        } else {
            exec->error ("Unknown texture optional argument: \"%s\", <%s>",
                         name.c_str(), valtype.c_str());
        }
    }

    if (alpha)
        options.nchannels += 1;

    float *r = &result[0];
    bool tempresult = false;
    if (Result.has_derivs() || alpha) {
        tempresult = true;
        r = ALLOCA (float, endpoint*options.nchannels);
        // allocate some space to track the derivatives of the result
        // NOTE: even though OIIO doesn't need derivatives from S and T to
        // compute the gradients, we need them on the OSL side to be able to
        // rotate the gradients via the chain rule
        if (S.has_derivs() && T.has_derivs()) {
            options.dresultds = ALLOCA (float, endpoint*options.nchannels);
            options.dresultdt = ALLOCA (float, endpoint*options.nchannels);
        } else {
            // we won't be able to provide derivatives properly
            if (Result.has_derivs())
                exec->zero_derivs(Result);
            if (Alpha && Alpha->has_derivs())
                exec->zero_derivs(*Alpha);
        }
    }
    for (int i = beginpoint;  i < endpoint;  ++i) {
        // FIXME -- this calls texture system separately for each point!
        // We really want to batch it into groups that share the same texture
        // filename.
        if (runflags[i]) {
            if (swrap)
                options.swrap = decode_wrap (swrap[i]);
            if (twrap)
                options.twrap = decode_wrap (twrap[i]);
            if (firstchannel)
                options.firstchannel = firstchannel[i];

            bool ok = texturesys->texture (filename[i], options,
                                           runflags, i /*beginpoint*/, i+1 /*endpoint*/,
                                           s, t, dsdx, dtdx, dsdy, dtdy,
                                           r);
            if (! ok) {
                std::string err = texturesys->geterror ();
                if (err.length())
                    exec->error ("%s", err.c_str());
            }
         }
    }

    if (tempresult) {
        // We need to re-copy results back to the right destinations.
        int resultchans = Result.typespec().simpletype().aggregate;
        for (int i = beginpoint;  i < endpoint;  ++i) {
            if (runflags[i])
                for (int c = 0;  c < resultchans;  ++c)
                    (&result[i])[c] = r[i*options.nchannels+c];
        }
        if (alpha) {
            for (int i = beginpoint;  i < endpoint;  ++i)
                if (runflags[i])
                    alpha[i] = r[i*options.nchannels+resultchans];
        }
        // now figure out derivatives (as needed)
        // we use the multi-variate chain rule:
        // dTdx = dTds * dsdx + dTdt * dtdx
        // dTdy = dTds * dsdy + dTdt * dtdy
        if (options.dresultds) {
            for (int i = beginpoint;  i < endpoint;  ++i) {
                if (runflags[i]) {
                    for (int c = 0;  c < resultchans;  ++c) {
                        (&result[i])[1 * resultchans + c] = options.dresultds[i*options.nchannels+c] * dsdx[i] + options.dresultdt[i*options.nchannels+c] * dtdx[i];
                        (&result[i])[2 * resultchans + c] = options.dresultds[i*options.nchannels+c] * dsdy[i] + options.dresultdt[i*options.nchannels+c] * dtdy[i];
                    }
                    if (alpha) {
                        (&alpha[i])[1] = options.dresultds[i*options.nchannels+resultchans] * dsdx[i] + options.dresultdt[i*options.nchannels+resultchans] * dtdx[i];
                        (&alpha[i])[2] = options.dresultds[i*options.nchannels+resultchans] * dsdy[i] + options.dresultdt[i*options.nchannels+resultchans] * dtdy[i];
                    }
                }
            }
        }
    }
}

}; // namespace pvt
}; // namespace OSL
#ifdef OSL_NAMESPACE
}; // end namespace OSL_NAMESPACE
#endif
<|endoftext|>


<commit_before>
/*
 * This file is part of cryptopp-bindings-api.
 *
 * (c) Stephen Berquet <stephen.berquet@gmail.com>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */

#include "api_mac_abstract.h"

NAMESPACE_BEGIN(CryptoppApi)

MacAbstract::MacAbstract()
    : m_mac(NULL)
    , m_name(NULL)
{
}

const char *MacAbstract::getName() const
{
    return m_name;
}

void MacAbstract::setCryptoppObject(CryptoPP::MessageAuthenticationCode *mac)
{
    m_mac = mac;
}

bool MacAbstract::isValidKeyLength(size_t length) const
{
    return m_mac->IsValidKeyLength(length);
}

void MacAbstract::setKey(const byte *key, const size_t keyLength)
{
    SymmetricKeyAbstract::setKey(key, keyLength);
    m_mac->SetKey(key, keyLength);
}

void MacAbstract::setName(const std::string name)
{
    m_name = const_cast<char*>(name.c_str());
}

const char *BlockCipherAbstract::getName() const
{
    return m_name;
}

size_t MacAbstract::getDigestSize() const
{
    return m_mac->DigestSize();
}

size_t MacAbstract::getBlockSize() const
{
    return m_mac->BlockSize();
}

void MacAbstract::calculateDigest(byte *input, size_t inputLength, byte *output)
{
    m_mac->CalculateDigest(output, input, inputLength);
}

void MacAbstract::update(byte *input, size_t inputLength)
{
    m_mac->Update(input, inputLength);
}

void MacAbstract::finalize(byte *output)
{
    m_mac->Final(output);
}

void MacAbstract::restart()
{
    m_mac->Restart();
}

NAMESPACE_END
<commit_msg>mac abstract: removed unnecessary method<commit_after>
/*
 * This file is part of cryptopp-bindings-api.
 *
 * (c) Stephen Berquet <stephen.berquet@gmail.com>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */

#include "api_mac_abstract.h"

NAMESPACE_BEGIN(CryptoppApi)

MacAbstract::MacAbstract()
    : m_mac(NULL)
    , m_name(NULL)
{
}

const char *MacAbstract::getName() const
{
    return m_name;
}

void MacAbstract::setCryptoppObject(CryptoPP::MessageAuthenticationCode *mac)
{
    m_mac = mac;
}

bool MacAbstract::isValidKeyLength(size_t length) const
{
    return m_mac->IsValidKeyLength(length);
}

void MacAbstract::setKey(const byte *key, const size_t keyLength)
{
    SymmetricKeyAbstract::setKey(key, keyLength);
    m_mac->SetKey(key, keyLength);
}

void MacAbstract::setName(const std::string name)
{
    m_name = const_cast<char*>(name.c_str());
}

size_t MacAbstract::getDigestSize() const
{
    return m_mac->DigestSize();
}

size_t MacAbstract::getBlockSize() const
{
    return m_mac->BlockSize();
}

void MacAbstract::calculateDigest(byte *input, size_t inputLength, byte *output)
{
    m_mac->CalculateDigest(output, input, inputLength);
}

void MacAbstract::update(byte *input, size_t inputLength)
{
    m_mac->Update(input, inputLength);
}

void MacAbstract::finalize(byte *output)
{
    m_mac->Final(output);
}

void MacAbstract::restart()
{
    m_mac->Restart();
}

NAMESPACE_END
<|endoftext|>


<commit_before>#include <stdio.h>
#include <assert.h>
#include <string.h>

#include <google/dense_hash_set>

#include <locale>
#include <list>
#include <iostream>
#include <string>

#include <re2/re2.h>

#include "smart_git.h"
#include "timer.h"

using google::dense_hash_set;
using re2::RE2;
using re2::StringPiece;
using namespace std;

#define CHUNK_SIZE (1 << 20)

struct search_file {
    string path;
    const char *ref;
    git_oid oid;
};

struct chunk_file {
    search_file *file;
    unsigned int left;
    unsigned int right;
};

#define CHUNK_MAGIC 0xC407FADE

struct chunk {
    int size;
    unsigned magic;
    vector<chunk_file> files;
    char data[0];

    chunk()
        : size(0), magic(CHUNK_MAGIC), files() {
    }

    void add_chunk_file(search_file *sf, const StringPiece &line) {
        unsigned l = line.data() - data;
        unsigned r = l + line.size();
        if (files.empty() || files.back().file != sf) {
            files.push_back(chunk_file());
            chunk_file &cf = files.back();
            cf.file = sf;
            cf.left = l;
            cf.right = r;
        } else {
            chunk_file &cf = files.back();
            cf.left = min(l, cf.left);
            cf.right = max(r, cf.right);
        }
    }
};

#define CHUNK_SPACE  (CHUNK_SIZE - (sizeof(chunk)))

chunk *alloc_chunk() {
    void *p;
    if (posix_memalign(&p, CHUNK_SIZE, CHUNK_SIZE) != 0)
        return NULL;
    return new(p) chunk;
};

class chunk_allocator {
public:
    chunk_allocator() : current_() {
        new_chunk();
    }

    char *alloc(size_t len) {
        assert(len < CHUNK_SPACE);
        if ((current_->size + len) > CHUNK_SPACE)
            new_chunk();
        char *out = current_->data + current_->size;
        current_->size += len;
        return out;
    }

    list<chunk*>::iterator begin () {
        return chunks_.begin();
    }

    typename list<chunk*>::iterator end () {
        return chunks_.end();
    }

    chunk *current_chunk() {
        return current_;
    }

protected:
    void new_chunk() {
        current_ = alloc_chunk();
        chunks_.push_back(current_);
    }

    list<chunk*> chunks_;
    chunk *current_;
};

/*
 * We special-case data() == NULL to provide an "empty" element for
 * dense_hash_set.
 *
 * StringPiece::operator== will consider a zero-length string equal to a
 * zero-length string with a NULL data().
 */
struct eqstr {
    bool operator()(const StringPiece& lhs, const StringPiece& rhs) const {
        if (lhs.data() == NULL && rhs.data() == NULL)
            return true;
        if (lhs.data() == NULL || rhs.data() == NULL)
            return false;
        return lhs == rhs;
    }
};

struct hashstr {
    locale loc;
    size_t operator()(const StringPiece &str) const {
        const collate<char> &coll = use_facet<collate<char> >(loc);
        return coll.hash(str.data(), str.data() + str.size());
    }
};

const StringPiece empty_string(NULL, 0);

typedef dense_hash_set<StringPiece, hashstr, eqstr> string_hash;

class code_counter {
public:
    code_counter(git_repository *repo)
        : repo_(repo), stats_()
    {
        lines_.set_empty_key(empty_string);
    }

    void walk_ref(const char *ref) {
        smart_object<git_commit> commit;
        smart_object<git_tree> tree;
        resolve_ref(commit, ref);
        git_commit_tree(tree, commit);

        walk_tree(ref, "", tree);
    }

    void dump_stats() {
        printf("Bytes: %ld (dedup: %ld)\n", stats_.bytes, stats_.dedup_bytes);
        printf("Lines: %ld (dedup: %ld)\n", stats_.lines, stats_.dedup_lines);
    }

    bool match(RE2& pat) {
        list<chunk*>::iterator it;
        StringPiece match;
        int matches = 0;

        for (it = alloc_.begin(); it != alloc_.end(); it++) {
            StringPiece str((*it)->data, (*it)->size);
            int pos = 0;
            while (pos < str.size()) {
                    if (!pat.Match(str, pos, str.size(), RE2::UNANCHORED, &match, 1))
                        break;
                    assert(memchr(match.data(), '\n', match.size()) == NULL);
                    StringPiece line = find_line(str, match);
                    print_match(line);
                    pos = line.size() + line.data() - str.data();
                    if (++matches == 10)
                        return true;
                }
        }
        return matches > 0;
    }
protected:
    void print_match (const StringPiece& line) {
        chunk *c = find_chunk(line.data());
        unsigned int off = line.data() - c->data;
        int lno;
        int matches = 0;
        for(vector<chunk_file>::iterator it = c->files.begin();
            it != c->files.end(); it++) {
            if (off >= it->left && off < it->right) {
                lno = try_match(line, it->file);
                if (lno > 0) {
                    printf("%s:%s:%d: %.*s\n",
                           it->file->ref,
                           it->file->path.c_str(),
                           lno,
                           line.size(), line.data());
                    if (++matches == 10)
                        break;
                }
            }
        }
    }

    int try_match(const StringPiece &line, search_file *sf) {
        smart_object<git_blob> blob;
        git_blob_lookup(blob, repo_, &sf->oid);
        int pos;
        StringPiece search(static_cast<const char*>(git_blob_rawcontent(blob)),
                           git_blob_rawsize(blob));
        pos = search.find(line);
        if (pos == StringPiece::npos) {
            return 0;
        }
        return 1 + count(search.data(), search.data() + pos, '\n');
    }

    StringPiece find_line(const StringPiece& chunk, const StringPiece& match) {
        const char *start, *end;
        assert(match.data() >= chunk.data());
        assert(match.data() < chunk.data() + chunk.size());
        assert(match.size() < (chunk.size() - (match.data() - chunk.data())));
        start = static_cast<const char*>
            (memrchr(chunk.data(), '\n', match.data() - chunk.data()));
        if (start == NULL)
            start = chunk.data();
        else
            start++;
        end = static_cast<const char*>
            (memchr(match.data() + match.size(), '\n',
                    chunk.size() - (match.data() - chunk.data()) - match.size()));
        if (end == NULL)
            end = chunk.data() + chunk.size();
        return StringPiece(start, end - start);
    }

    void walk_tree(const char *ref, const string& pfx, git_tree *tree) {
        string path;
        int entries = git_tree_entrycount(tree);
        int i;
        for (i = 0; i < entries; i++) {
            const git_tree_entry *ent = git_tree_entry_byindex(tree, i);
            path = pfx + git_tree_entry_name(ent);
            smart_object<git_object> obj;
            git_tree_entry_2object(obj, repo_, ent);
            if (git_tree_entry_type(ent) == GIT_OBJ_TREE) {
                walk_tree(ref, path + "/", obj);
            } else if (git_tree_entry_type(ent) == GIT_OBJ_BLOB) {
                update_stats(ref, path, obj);
            }
        }
    }

    chunk* find_chunk(const char *p) {
        chunk *out = reinterpret_cast<chunk*>
            (reinterpret_cast<uintptr_t>(p) & ~(CHUNK_SIZE - 1));
        assert(out->magic == CHUNK_MAGIC);
        return out;
    }

    void update_stats(const char *ref, const string& path, git_blob *blob) {
        size_t len = git_blob_rawsize(blob);
        const char *p = static_cast<const char*>(git_blob_rawcontent(blob));
        const char *end = p + len;
        const char *f;
        string_hash::iterator it;
        search_file *sf = new search_file;
        sf->path = path;
        sf->ref = ref;
        git_oid_cpy(&sf->oid, git_object_id(reinterpret_cast<git_object*>(blob)));
        chunk *c;
        StringPiece line;

        while ((f = static_cast<const char*>(memchr(p, '\n', end - p))) != 0) {
            it = lines_.find(StringPiece(p, f - p));
            if (it == lines_.end()) {
                stats_.dedup_bytes += (f - p) + 1;
                stats_.dedup_lines ++;

                // Include the trailing '\n' in the chunk buffer
                char *alloc = alloc_.alloc(f - p + 1);
                memcpy(alloc, p, f - p + 1);
                line = StringPiece(alloc, f - p);
                lines_.insert(line);
                c = alloc_.current_chunk();
            } else {
                line = *it;
                c = find_chunk(line.data());
            }
            c->add_chunk_file(sf, line);
            p = f + 1;
            stats_.lines++;
        }

        stats_.bytes += len;
    }

    void resolve_ref(smart_object<git_commit> &out, const char *refname) {
        git_reference *ref;
        const git_oid *oid;
        git_oid tmp;
        smart_object<git_object> obj;
        if (git_oid_fromstr(&tmp, refname) == GIT_SUCCESS) {
            git_object_lookup(obj, repo_, &tmp, GIT_OBJ_ANY);
        } else {
            git_reference_lookup(&ref, repo_, refname);
            git_reference_resolve(&ref, ref);
            oid = git_reference_oid(ref);
            git_object_lookup(obj, repo_, oid, GIT_OBJ_ANY);
        }
        if (git_object_type(obj) == GIT_OBJ_TAG) {
            git_tag_target(out, obj);
        } else {
            out = obj.release();
        }
    }

    git_repository *repo_;
    string_hash lines_;
    struct {
        unsigned long bytes, dedup_bytes;
        unsigned long lines, dedup_lines;
    } stats_;
    chunk_allocator alloc_;
};

int main(int argc, char **argv) {
    git_repository *repo;
    git_repository_open(&repo, ".git");

    code_counter counter(repo);

    for (int i = 1; i < argc; i++) {
        timer tm;
        struct timeval elapsed;
        printf("Walking %s...", argv[i]);
        fflush(stdout);
        counter.walk_ref(argv[i]);
        elapsed = tm.elapsed();
        printf(" done in %d.%06ds\n",
               (int)elapsed.tv_sec, (int)elapsed.tv_usec);
    }
    counter.dump_stats();
    RE2::Options opts;
    opts.set_never_nl(true);
    opts.set_one_line(false);
    opts.set_posix_syntax(true);
    while (true) {
        printf("regex> ");
        string line;
        getline(cin, line);
        if (cin.eof())
            break;
        RE2 re(line, opts);
        if (re.ok()) {
            timer tm;
            struct timeval elapsed;
            if (!counter.match(re)) {
                printf("no match\n");
            }
            elapsed = tm.elapsed();
            printf("Match completed in %d.%06ds.\n",
                   (int)elapsed.tv_sec, (int)elapsed.tv_usec);
        }
    }

    return 0;
}
<commit_msg>Shrink CHUNK_SIZE.<commit_after>#include <stdio.h>
#include <assert.h>
#include <string.h>

#include <google/dense_hash_set>

#include <locale>
#include <list>
#include <iostream>
#include <string>

#include <re2/re2.h>

#include "smart_git.h"
#include "timer.h"

using google::dense_hash_set;
using re2::RE2;
using re2::StringPiece;
using namespace std;

#define CHUNK_SIZE (1 << 16)

struct search_file {
    string path;
    const char *ref;
    git_oid oid;
};

struct chunk_file {
    search_file *file;
    unsigned int left;
    unsigned int right;
};

#define CHUNK_MAGIC 0xC407FADE

struct chunk {
    int size;
    unsigned magic;
    vector<chunk_file> files;
    char data[0];

    chunk()
        : size(0), magic(CHUNK_MAGIC), files() {
    }

    void add_chunk_file(search_file *sf, const StringPiece &line) {
        unsigned l = line.data() - data;
        unsigned r = l + line.size();
        if (files.empty() || files.back().file != sf) {
            files.push_back(chunk_file());
            chunk_file &cf = files.back();
            cf.file = sf;
            cf.left = l;
            cf.right = r;
        } else {
            chunk_file &cf = files.back();
            cf.left = min(l, cf.left);
            cf.right = max(r, cf.right);
        }
    }
};

#define CHUNK_SPACE  (CHUNK_SIZE - (sizeof(chunk)))

chunk *alloc_chunk() {
    void *p;
    if (posix_memalign(&p, CHUNK_SIZE, CHUNK_SIZE) != 0)
        return NULL;
    return new(p) chunk;
};

class chunk_allocator {
public:
    chunk_allocator() : current_() {
        new_chunk();
    }

    char *alloc(size_t len) {
        assert(len < CHUNK_SPACE);
        if ((current_->size + len) > CHUNK_SPACE)
            new_chunk();
        char *out = current_->data + current_->size;
        current_->size += len;
        return out;
    }

    list<chunk*>::iterator begin () {
        return chunks_.begin();
    }

    typename list<chunk*>::iterator end () {
        return chunks_.end();
    }

    chunk *current_chunk() {
        return current_;
    }

protected:
    void new_chunk() {
        current_ = alloc_chunk();
        chunks_.push_back(current_);
    }

    list<chunk*> chunks_;
    chunk *current_;
};

/*
 * We special-case data() == NULL to provide an "empty" element for
 * dense_hash_set.
 *
 * StringPiece::operator== will consider a zero-length string equal to a
 * zero-length string with a NULL data().
 */
struct eqstr {
    bool operator()(const StringPiece& lhs, const StringPiece& rhs) const {
        if (lhs.data() == NULL && rhs.data() == NULL)
            return true;
        if (lhs.data() == NULL || rhs.data() == NULL)
            return false;
        return lhs == rhs;
    }
};

struct hashstr {
    locale loc;
    size_t operator()(const StringPiece &str) const {
        const collate<char> &coll = use_facet<collate<char> >(loc);
        return coll.hash(str.data(), str.data() + str.size());
    }
};

const StringPiece empty_string(NULL, 0);

typedef dense_hash_set<StringPiece, hashstr, eqstr> string_hash;

class code_counter {
public:
    code_counter(git_repository *repo)
        : repo_(repo), stats_()
    {
        lines_.set_empty_key(empty_string);
    }

    void walk_ref(const char *ref) {
        smart_object<git_commit> commit;
        smart_object<git_tree> tree;
        resolve_ref(commit, ref);
        git_commit_tree(tree, commit);

        walk_tree(ref, "", tree);
    }

    void dump_stats() {
        printf("Bytes: %ld (dedup: %ld)\n", stats_.bytes, stats_.dedup_bytes);
        printf("Lines: %ld (dedup: %ld)\n", stats_.lines, stats_.dedup_lines);
    }

    bool match(RE2& pat) {
        list<chunk*>::iterator it;
        StringPiece match;
        int matches = 0;

        for (it = alloc_.begin(); it != alloc_.end(); it++) {
            StringPiece str((*it)->data, (*it)->size);
            int pos = 0;
            while (pos < str.size()) {
                    if (!pat.Match(str, pos, str.size(), RE2::UNANCHORED, &match, 1))
                        break;
                    assert(memchr(match.data(), '\n', match.size()) == NULL);
                    StringPiece line = find_line(str, match);
                    print_match(line);
                    pos = line.size() + line.data() - str.data();
                    if (++matches == 10)
                        return true;
                }
        }
        return matches > 0;
    }
protected:
    void print_match (const StringPiece& line) {
        chunk *c = find_chunk(line.data());
        unsigned int off = line.data() - c->data;
        int lno;
        int matches = 0;
        for(vector<chunk_file>::iterator it = c->files.begin();
            it != c->files.end(); it++) {
            if (off >= it->left && off < it->right) {
                lno = try_match(line, it->file);
                if (lno > 0) {
                    printf("%s:%s:%d: %.*s\n",
                           it->file->ref,
                           it->file->path.c_str(),
                           lno,
                           line.size(), line.data());
                    if (++matches == 10)
                        break;
                }
            }
        }
    }

    int try_match(const StringPiece &line, search_file *sf) {
        smart_object<git_blob> blob;
        git_blob_lookup(blob, repo_, &sf->oid);
        int pos;
        StringPiece search(static_cast<const char*>(git_blob_rawcontent(blob)),
                           git_blob_rawsize(blob));
        pos = search.find(line);
        if (pos == StringPiece::npos) {
            return 0;
        }
        return 1 + count(search.data(), search.data() + pos, '\n');
    }

    StringPiece find_line(const StringPiece& chunk, const StringPiece& match) {
        const char *start, *end;
        assert(match.data() >= chunk.data());
        assert(match.data() < chunk.data() + chunk.size());
        assert(match.size() < (chunk.size() - (match.data() - chunk.data())));
        start = static_cast<const char*>
            (memrchr(chunk.data(), '\n', match.data() - chunk.data()));
        if (start == NULL)
            start = chunk.data();
        else
            start++;
        end = static_cast<const char*>
            (memchr(match.data() + match.size(), '\n',
                    chunk.size() - (match.data() - chunk.data()) - match.size()));
        if (end == NULL)
            end = chunk.data() + chunk.size();
        return StringPiece(start, end - start);
    }

    void walk_tree(const char *ref, const string& pfx, git_tree *tree) {
        string path;
        int entries = git_tree_entrycount(tree);
        int i;
        for (i = 0; i < entries; i++) {
            const git_tree_entry *ent = git_tree_entry_byindex(tree, i);
            path = pfx + git_tree_entry_name(ent);
            smart_object<git_object> obj;
            git_tree_entry_2object(obj, repo_, ent);
            if (git_tree_entry_type(ent) == GIT_OBJ_TREE) {
                walk_tree(ref, path + "/", obj);
            } else if (git_tree_entry_type(ent) == GIT_OBJ_BLOB) {
                update_stats(ref, path, obj);
            }
        }
    }

    chunk* find_chunk(const char *p) {
        chunk *out = reinterpret_cast<chunk*>
            (reinterpret_cast<uintptr_t>(p) & ~(CHUNK_SIZE - 1));
        assert(out->magic == CHUNK_MAGIC);
        return out;
    }

    void update_stats(const char *ref, const string& path, git_blob *blob) {
        size_t len = git_blob_rawsize(blob);
        const char *p = static_cast<const char*>(git_blob_rawcontent(blob));
        const char *end = p + len;
        const char *f;
        string_hash::iterator it;
        search_file *sf = new search_file;
        sf->path = path;
        sf->ref = ref;
        git_oid_cpy(&sf->oid, git_object_id(reinterpret_cast<git_object*>(blob)));
        chunk *c;
        StringPiece line;

        while ((f = static_cast<const char*>(memchr(p, '\n', end - p))) != 0) {
            it = lines_.find(StringPiece(p, f - p));
            if (it == lines_.end()) {
                stats_.dedup_bytes += (f - p) + 1;
                stats_.dedup_lines ++;

                // Include the trailing '\n' in the chunk buffer
                char *alloc = alloc_.alloc(f - p + 1);
                memcpy(alloc, p, f - p + 1);
                line = StringPiece(alloc, f - p);
                lines_.insert(line);
                c = alloc_.current_chunk();
            } else {
                line = *it;
                c = find_chunk(line.data());
            }
            c->add_chunk_file(sf, line);
            p = f + 1;
            stats_.lines++;
        }

        stats_.bytes += len;
    }

    void resolve_ref(smart_object<git_commit> &out, const char *refname) {
        git_reference *ref;
        const git_oid *oid;
        git_oid tmp;
        smart_object<git_object> obj;
        if (git_oid_fromstr(&tmp, refname) == GIT_SUCCESS) {
            git_object_lookup(obj, repo_, &tmp, GIT_OBJ_ANY);
        } else {
            git_reference_lookup(&ref, repo_, refname);
            git_reference_resolve(&ref, ref);
            oid = git_reference_oid(ref);
            git_object_lookup(obj, repo_, oid, GIT_OBJ_ANY);
        }
        if (git_object_type(obj) == GIT_OBJ_TAG) {
            git_tag_target(out, obj);
        } else {
            out = obj.release();
        }
    }

    git_repository *repo_;
    string_hash lines_;
    struct {
        unsigned long bytes, dedup_bytes;
        unsigned long lines, dedup_lines;
    } stats_;
    chunk_allocator alloc_;
};

int main(int argc, char **argv) {
    git_repository *repo;
    git_repository_open(&repo, ".git");

    code_counter counter(repo);

    for (int i = 1; i < argc; i++) {
        timer tm;
        struct timeval elapsed;
        printf("Walking %s...", argv[i]);
        fflush(stdout);
        counter.walk_ref(argv[i]);
        elapsed = tm.elapsed();
        printf(" done in %d.%06ds\n",
               (int)elapsed.tv_sec, (int)elapsed.tv_usec);
    }
    counter.dump_stats();
    RE2::Options opts;
    opts.set_never_nl(true);
    opts.set_one_line(false);
    opts.set_posix_syntax(true);
    while (true) {
        printf("regex> ");
        string line;
        getline(cin, line);
        if (cin.eof())
            break;
        RE2 re(line, opts);
        if (re.ok()) {
            timer tm;
            struct timeval elapsed;
            if (!counter.match(re)) {
                printf("no match\n");
            }
            elapsed = tm.elapsed();
            printf("Match completed in %d.%06ds.\n",
                   (int)elapsed.tv_sec, (int)elapsed.tv_usec);
        }
    }

    return 0;
}
<|endoftext|>