pax_global_header00006660000000000000000000000064137424722470014526gustar00rootroot0000000000000052 comment=9cfbac4ace3d69d4d5145340bee0b4e05d9fa339 php-pinba-1.1.2/000077500000000000000000000000001374247224700134055ustar00rootroot00000000000000php-pinba-1.1.2/.gitignore000066400000000000000000000004761374247224700154040ustar00rootroot00000000000000run-tests.php modules mkinstalldirs missing ltmain.sh libtool install-sh include configure.in configure config.sub config.status config.nice config.log config.h.in config.h config.guess build autom4te.cache aclocal.m4 acinclude.m4 Makefile.objects Makefile.global Makefile.fragments Makefile .libs .deps *.lo *.o *.la php-pinba-1.1.2/CREDITS000066400000000000000000000000051374247224700144200ustar00rootroot00000000000000pinbaphp-pinba-1.1.2/NEWS000066400000000000000000000043071374247224700141100ustar00rootroot00000000000000Pinba 1.1.2 31 Aug 2020 ---------------------------- - Fixed build with PHP 7.3+ - Added optional hit_count argument to pinba_timer_add(). - Added per-process resolver cache. New INI setting pinba.resolve_interval=SECONDS is used to to manage it. - Removed mmap()'ed blocks from mallinfo() stats (memory stats may change!). - Updated protobuf-c.c code to newer version. Pinba 1.1.1 01 Feb 2018 ---------------------------- - Fixed a bug causing incorrect timer rusage data to be sent. - Added pinba_reset() function to be able to reset current data without calling pinba_flush(). Pinba 1.1.0 09 Sep 2016 ---------------------------- - Added flag to reset request data when doing pinba_flush(), use PINBA_FLUSH_RESET_DATA constant for that. - Added pinba.auto_flush INI option to control automatic flush at the end of each request. Default value is On. - Reimplemented the extension using protobuf-c instead of C++ Protobuf lib. - Added memory_footprint field to the data (uses mallinfo() where available). - Added pinba_timers_get() function. - Added pinba_schema_set() function. - Added error message on hostname resolution failure. - Added rusage to timers (it was actually there, but wasn't sent to the server). - Fixed issue #9 (php segfault on shutdown) - Updated the sources to support PHP7 API, PHP5 version moved to branch 'php5'. Pinba 1.0.0 17 Aug 2012 ---------------------------- - Fixed 5_4 build. - Fixed several minor memleaks. - Added optional flag to pinba_flush() to flush only stopped timers (use PINBA_FLUSH_ONLY_STOPPED_TIMERS). Pinba 0.0.6 26 Nov 2010 ---------------------------- - Added pinba_timer_delete() function. - Added pinba_hostname_set() function. - Added experimental IPv6 support. (Florian Forster) - Fixed extension crash on empty tag value. Pinba 0.0.5 19 Oct 2009 ---------------------------- - Added rusage to timers (not aggregated on server (yet?)). Pinba extension 0.0.4 26 Aug 2009 -------------------------------------- - Added HTTP response status to the response data. - Added support of Google Protocol Buffers 2.1.0+. - Added pinba_script_name_set() function. Pinba extension 0.0.3 04 May 2009 -------------------------------------- Initial release. php-pinba-1.1.2/README000066400000000000000000000000551374247224700142650ustar00rootroot00000000000000PHP extension for Pinba See http://pinba.org php-pinba-1.1.2/config.m4000066400000000000000000000005261374247224700151170ustar00rootroot00000000000000dnl $Id: config.m4,v 1.2.4.2 2009/03/06 11:12:55 tony Exp $ PHP_ARG_ENABLE(pinba, for Pinba support, [ --enable-pinba[=DIR] Include Pinba support.]) if test "$PHP_PINBA" != "no"; then AC_CHECK_HEADERS(malloc.h) PHP_CHECK_FUNC(mallinfo) PHP_NEW_EXTENSION(pinba, pinba-pb-c.c pinba.c protobuf-c.c, $ext_shared,, -DNDEBUG) fi php-pinba-1.1.2/package.xml000066400000000000000000000066621374247224700155340ustar00rootroot00000000000000 pinba pecl.php.net Pinba Client extension for Pinba statistics server. Antony Dovgal tony2001 tony2001@php.net yes 2013-08-17 1.1.0 1.1.0 stable stable LGPL - Changed extension license to LGPL. 4.4.8 6.0.0 6.0.0 1.4.0b1 pinba 2012-08-17 1.0.01.0.0 stablestable PHP - Fixed 5_4 build. - Fixed several minor memleaks. - Added optional flag to pinba_flush() to flush only stopped timers (use PINBA_FLUSH_ONLY_STOPPED_TIMERS). 2010-11-26 0.0.60.0.6 betabeta PHP - Added pinba_timer_delete() function. - Added pinba_hostname_set() function. - Added experimental IPv6 support. (Florian Forster) - Fixed extension crash on empty tag value. 2009-10-19 0.0.50.0.5 betabeta PHP - Added rusage to timers (not sent to the server, to be discussed) betabeta 0.0.40.0.4 2009-08-26 - Added HTTP response status to the response data. - Added support of Google Protocol Buffers 2.1.0+. - Added pinba_script_name_set() function. betabeta 0.0.30.0.3 2009-05-04 - Initial release. php-pinba-1.1.2/php_pinba.h000066400000000000000000000052271374247224700155240ustar00rootroot00000000000000/* * Authors: Antony Dovgal * Florian Forster (IPv6 support) * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * 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 */ #ifndef PHP_PINBA_H #define PHP_PINBA_H #include extern zend_module_entry pinba_module_entry; #define phpext_pinba_ptr &pinba_module_entry #ifdef ZTS #include "TSRM.h" #endif #define PINBA_COLLECTOR_DEFAULT_PORT "30002" #define PINBA_COLLECTORS_MAX 8 #define PHP_PINBA_VERSION "1.1.2" typedef struct _pinba_req_data { /* {{{ */ char *server_name; char *script_name; size_t req_count; size_t doc_size; size_t mem_peak_usage; struct timeval req_start; struct timeval req_time; struct timeval ru_utime; struct timeval ru_stime; size_t memory_footprint; } pinba_req_data; /* }}} */ typedef struct { int fd; struct sockaddr_storage sockaddr; size_t sockaddr_len; /* shouldn't this be socken_t ? */ time_t sockaddr_time; /* time last resolved */ } pinba_sockaddr; typedef struct _pinba_collector { char *host; char *port; } pinba_collector; ZEND_BEGIN_MODULE_GLOBALS(pinba) /* {{{ */ pinba_collector collectors[PINBA_COLLECTORS_MAX]; unsigned int n_collectors; /* number of collectors we got from ini file */ char *collector_address; /* this is a lil broken, contains last address only */ #if PHP_VERSION_ID < 50400 int (*old_sapi_ub_write) (const char *, unsigned int TSRMLS_DC); #endif char host_name[128]; char schema[17]; char *server_name; char *script_name; double request_time; HashTable timers; HashTable tags; pinba_req_data tmp_req_data; zend_bool timers_stopped; zend_bool in_rshutdown; zend_bool enabled; zend_bool auto_flush; time_t resolve_interval; /* seconds */ ZEND_END_MODULE_GLOBALS(pinba) /* }}} */ #ifdef ZTS #define PINBA_G(v) TSRMG(pinba_globals_id, zend_pinba_globals *, v) #else #define PINBA_G(v) (pinba_globals.v) #endif #endif /* PHP_PINBA_H */ /* * Local variables: * tab-width: 4 * c-basic-offset: 4 * indent-tabs-mode: t * End: */ php-pinba-1.1.2/pinba-pb-c.c000066400000000000000000000276771374247224700155040ustar00rootroot00000000000000/* Generated by the protocol buffer compiler. DO NOT EDIT! */ /* Do not generate deprecated warnings for self */ #ifndef PROTOBUF_C_NO_DEPRECATED #define PROTOBUF_C_NO_DEPRECATED #endif #include "pinba.pb-c.h" void pinba__request__init (Pinba__Request *message) { static Pinba__Request init_value = PINBA__REQUEST__INIT; *message = init_value; } size_t pinba__request__get_packed_size (const Pinba__Request *message) { PROTOBUF_C_ASSERT (message->base.descriptor == &pinba__request__descriptor); return protobuf_c_message_get_packed_size ((const ProtobufCMessage*)(message)); } size_t pinba__request__pack (const Pinba__Request *message, uint8_t *out) { PROTOBUF_C_ASSERT (message->base.descriptor == &pinba__request__descriptor); return protobuf_c_message_pack ((const ProtobufCMessage*)message, out); } size_t pinba__request__pack_to_buffer (const Pinba__Request *message, ProtobufCBuffer *buffer) { PROTOBUF_C_ASSERT (message->base.descriptor == &pinba__request__descriptor); return protobuf_c_message_pack_to_buffer ((const ProtobufCMessage*)message, buffer); } Pinba__Request * pinba__request__unpack (ProtobufCAllocator *allocator, size_t len, const uint8_t *data) { return (Pinba__Request *) protobuf_c_message_unpack (&pinba__request__descriptor, allocator, len, data); } void pinba__request__free_unpacked (Pinba__Request *message, ProtobufCAllocator *allocator) { PROTOBUF_C_ASSERT (message->base.descriptor == &pinba__request__descriptor); protobuf_c_message_free_unpacked ((ProtobufCMessage*)message, allocator); } static const ProtobufCFieldDescriptor pinba__request__field_descriptors[23] = { { .name = "hostname", .id = 1, .label = PROTOBUF_C_LABEL_REQUIRED, .type = PROTOBUF_C_TYPE_STRING, .quantifier_offset = 0, .offset = PROTOBUF_C_OFFSETOF(Pinba__Request, hostname), .descriptor = NULL, .default_value = NULL, }, { .name = "server_name", .id = 2, .label = PROTOBUF_C_LABEL_REQUIRED, .type = PROTOBUF_C_TYPE_STRING, .quantifier_offset = 0, .offset = PROTOBUF_C_OFFSETOF(Pinba__Request, server_name), .descriptor = NULL, .default_value = NULL, }, { .name = "script_name", .id = 3, .label = PROTOBUF_C_LABEL_REQUIRED, .type = PROTOBUF_C_TYPE_STRING, .quantifier_offset = 0, .offset = PROTOBUF_C_OFFSETOF(Pinba__Request, script_name), .descriptor = NULL, .default_value = NULL, }, { .name = "request_count", .id = 4, .label = PROTOBUF_C_LABEL_REQUIRED, .type = PROTOBUF_C_TYPE_UINT32, .quantifier_offset = 0, .offset = PROTOBUF_C_OFFSETOF(Pinba__Request, request_count), .descriptor = NULL, .default_value = NULL, }, { .name = "document_size", .id = 5, .label = PROTOBUF_C_LABEL_REQUIRED, .type = PROTOBUF_C_TYPE_UINT32, .quantifier_offset = 0, .offset = PROTOBUF_C_OFFSETOF(Pinba__Request, document_size), .descriptor = NULL, .default_value = NULL, }, { .name = "memory_peak", .id = 6, .label = PROTOBUF_C_LABEL_REQUIRED, .type = PROTOBUF_C_TYPE_UINT32, .quantifier_offset = 0, .offset = PROTOBUF_C_OFFSETOF(Pinba__Request, memory_peak), .descriptor = NULL, .default_value = NULL, }, { .name = "request_time", .id = 7, .label = PROTOBUF_C_LABEL_REQUIRED, .type = PROTOBUF_C_TYPE_FLOAT, .quantifier_offset = 0, .offset = PROTOBUF_C_OFFSETOF(Pinba__Request, request_time), .descriptor = NULL, .default_value = NULL, }, { .name = "ru_utime", .id = 8, .label = PROTOBUF_C_LABEL_REQUIRED, .type = PROTOBUF_C_TYPE_FLOAT, .quantifier_offset = 0, .offset = PROTOBUF_C_OFFSETOF(Pinba__Request, ru_utime), .descriptor = NULL, .default_value = NULL, }, { .name = "ru_stime", .id = 9, .label = PROTOBUF_C_LABEL_REQUIRED, .type = PROTOBUF_C_TYPE_FLOAT, .quantifier_offset = 0, .offset = PROTOBUF_C_OFFSETOF(Pinba__Request, ru_stime), .descriptor = NULL, .default_value = NULL, }, { .name = "timer_hit_count", .id = 10, .label = PROTOBUF_C_LABEL_REPEATED, .type = PROTOBUF_C_TYPE_UINT32, .quantifier_offset = PROTOBUF_C_OFFSETOF(Pinba__Request, n_timer_hit_count), .offset = PROTOBUF_C_OFFSETOF(Pinba__Request, timer_hit_count), .descriptor = NULL, .default_value = NULL, }, { .name = "timer_value", .id = 11, .label = PROTOBUF_C_LABEL_REPEATED, .type = PROTOBUF_C_TYPE_FLOAT, .quantifier_offset = PROTOBUF_C_OFFSETOF(Pinba__Request, n_timer_value), .offset = PROTOBUF_C_OFFSETOF(Pinba__Request, timer_value), .descriptor = NULL, .default_value = NULL, }, { .name = "timer_tag_count", .id = 12, .label = PROTOBUF_C_LABEL_REPEATED, .type = PROTOBUF_C_TYPE_UINT32, .quantifier_offset = PROTOBUF_C_OFFSETOF(Pinba__Request, n_timer_tag_count), .offset = PROTOBUF_C_OFFSETOF(Pinba__Request, timer_tag_count), .descriptor = NULL, .default_value = NULL, }, { .name = "timer_tag_name", .id = 13, .label = PROTOBUF_C_LABEL_REPEATED, .type = PROTOBUF_C_TYPE_UINT32, .quantifier_offset = PROTOBUF_C_OFFSETOF(Pinba__Request, n_timer_tag_name), .offset = PROTOBUF_C_OFFSETOF(Pinba__Request, timer_tag_name), .descriptor = NULL, .default_value = NULL, }, { .name = "timer_tag_value", .id = 14, .label = PROTOBUF_C_LABEL_REPEATED, .type = PROTOBUF_C_TYPE_UINT32, .quantifier_offset = PROTOBUF_C_OFFSETOF(Pinba__Request, n_timer_tag_value), .offset = PROTOBUF_C_OFFSETOF(Pinba__Request, timer_tag_value), .descriptor = NULL, .default_value = NULL, }, { .name = "dictionary", .id = 15, .label = PROTOBUF_C_LABEL_REPEATED, .type = PROTOBUF_C_TYPE_STRING, .quantifier_offset = PROTOBUF_C_OFFSETOF(Pinba__Request, n_dictionary), .offset = PROTOBUF_C_OFFSETOF(Pinba__Request, dictionary), .descriptor = NULL, .default_value = NULL, }, { .name = "status", .id = 16, .label = PROTOBUF_C_LABEL_OPTIONAL, .type = PROTOBUF_C_TYPE_UINT32, .quantifier_offset = PROTOBUF_C_OFFSETOF(Pinba__Request, has_status), .offset = PROTOBUF_C_OFFSETOF(Pinba__Request, status), .descriptor = NULL, .default_value = NULL, }, { .name = "memory_footprint", .id = 17, .label = PROTOBUF_C_LABEL_OPTIONAL, .type = PROTOBUF_C_TYPE_UINT32, .quantifier_offset = PROTOBUF_C_OFFSETOF(Pinba__Request, has_memory_footprint), .offset = PROTOBUF_C_OFFSETOF(Pinba__Request, memory_footprint), .descriptor = NULL, .default_value = NULL, }, { .name = "requests", .id = 18, .label = PROTOBUF_C_LABEL_REPEATED, .type = PROTOBUF_C_TYPE_MESSAGE, .quantifier_offset = PROTOBUF_C_OFFSETOF(Pinba__Request, n_requests), .offset = PROTOBUF_C_OFFSETOF(Pinba__Request, requests), .descriptor = &pinba__request__descriptor, .default_value = NULL, }, { .name = "schema", .id = 19, .label = PROTOBUF_C_LABEL_OPTIONAL, .type = PROTOBUF_C_TYPE_STRING, .quantifier_offset = 0, .offset = PROTOBUF_C_OFFSETOF(Pinba__Request, schema), .descriptor = NULL, .default_value = NULL, }, { .name = "tag_name", .id = 20, .label = PROTOBUF_C_LABEL_REPEATED, .type = PROTOBUF_C_TYPE_UINT32, .quantifier_offset = PROTOBUF_C_OFFSETOF(Pinba__Request, n_tag_name), .offset = PROTOBUF_C_OFFSETOF(Pinba__Request, tag_name), .descriptor = NULL, .default_value = NULL, }, { .name = "tag_value", .id = 21, .label = PROTOBUF_C_LABEL_REPEATED, .type = PROTOBUF_C_TYPE_UINT32, .quantifier_offset = PROTOBUF_C_OFFSETOF(Pinba__Request, n_tag_value), .offset = PROTOBUF_C_OFFSETOF(Pinba__Request, tag_value), .descriptor = NULL, .default_value = NULL, }, { .name = "timer_ru_utime", .id = 22, .label = PROTOBUF_C_LABEL_REPEATED, .type = PROTOBUF_C_TYPE_FLOAT, .quantifier_offset = PROTOBUF_C_OFFSETOF(Pinba__Request, n_timer_ru_utime), .offset = PROTOBUF_C_OFFSETOF(Pinba__Request, timer_ru_utime), .descriptor = NULL, .default_value = NULL, }, { .name = "timer_ru_stime", .id = 23, .label = PROTOBUF_C_LABEL_REPEATED, .type = PROTOBUF_C_TYPE_FLOAT, .quantifier_offset = PROTOBUF_C_OFFSETOF(Pinba__Request, n_timer_ru_stime), .offset = PROTOBUF_C_OFFSETOF(Pinba__Request, timer_ru_stime), .descriptor = NULL, .default_value = NULL, }, }; static const unsigned pinba__request__field_indices_by_name[] = { 14, /* field[14] = dictionary */ 4, /* field[4] = document_size */ 0, /* field[0] = hostname */ 16, /* field[16] = memory_footprint */ 5, /* field[5] = memory_peak */ 3, /* field[3] = request_count */ 6, /* field[6] = request_time */ 17, /* field[17] = requests */ 8, /* field[8] = ru_stime */ 7, /* field[7] = ru_utime */ 18, /* field[18] = schema */ 2, /* field[2] = script_name */ 1, /* field[1] = server_name */ 15, /* field[15] = status */ 19, /* field[19] = tag_name */ 20, /* field[20] = tag_value */ 9, /* field[9] = timer_hit_count */ 22, /* field[22] = timer_ru_stime */ 21, /* field[21] = timer_ru_utime */ 11, /* field[11] = timer_tag_count */ 12, /* field[12] = timer_tag_name */ 13, /* field[13] = timer_tag_value */ 10, /* field[10] = timer_value */ }; static const ProtobufCIntRange pinba__request__number_ranges[1 + 1] = { { 1, 0 }, { 0, 23 } }; const ProtobufCMessageDescriptor pinba__request__descriptor = { .magic = PROTOBUF_C_MESSAGE_DESCRIPTOR_MAGIC, .name = "Pinba.Request", .short_name = "Request", .c_name = "Pinba__Request", .package_name = "Pinba", .sizeof_message = sizeof(Pinba__Request), .n_fields = 23, .fields = pinba__request__field_descriptors, .fields_sorted_by_name = pinba__request__field_indices_by_name, .n_field_ranges = 1, .field_ranges = pinba__request__number_ranges, .message_init = (ProtobufCMessageInit) pinba__request__init, }; php-pinba-1.1.2/pinba.c000066400000000000000000002161301374247224700146450ustar00rootroot00000000000000/* * Authors: Antony Dovgal * Florian Forster (IPv6 support) * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * 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 */ #ifdef HAVE_CONFIG_H #include "config.h" #endif #include #include #include #include #include #include #include #include #include #include #include "php.h" #include "php_ini.h" #include "SAPI.h" #include "ext/standard/info.h" #include "ext/standard/php_array.h" #ifdef HAVE_MALLOC_H # include #endif #include "php_pinba.h" #include "pinba.pb-c.h" zend_class_entry *pinba_client_ce; static zend_object_handlers pinba_client_handlers; typedef struct { char **servers; int n_servers; char *hostname; char *server_name; char *script_name; char *schema; size_t request_count; size_t document_size; size_t memory_peak; double rusage[2]; float request_time; unsigned int status; size_t memory_footprint; HashTable tags; HashTable timers; pinba_collector collectors[PINBA_COLLECTORS_MAX]; unsigned int n_collectors; long flags; int collectors_initialized:1; int data_sent:1; zend_object std; } pinba_client_t; ZEND_DECLARE_MODULE_GLOBALS(pinba) #ifdef COMPILE_DL_PINBA ZEND_GET_MODULE(pinba) #endif static int le_pinba_timer; size_t (*old_sapi_ub_write) (const char *, size_t); #if ZEND_MODULE_API_NO > 20020429 #define ONUPDATELONGFUNC OnUpdateLong #else #define ONUPDATELONGFUNC OnUpdateInt #endif #define PINBA_FLUSH_ONLY_STOPPED_TIMERS (1<<0) #define PINBA_FLUSH_RESET_DATA (1<<1) #define PINBA_ONLY_RUNNING_TIMERS (1<<2) #define PINBA_AUTO_FLUSH (1<<3) static HashTable resolver_cache; typedef struct _pinba_timer_tag { /* {{{ */ char *name; int name_len; int name_id; char *value; /* we cast all types to string */ int value_len; int value_id; } pinba_timer_tag_t; /* }}} */ typedef struct _pinba_timer { /* {{{ */ int rsrc_id; unsigned int started:1; unsigned int hit_count; pinba_timer_tag_t **tags; int tags_num; struct { int tv_sec; int tv_usec; } start; struct { int tv_sec; int tv_usec; } value; zval data; struct timeval tmp_ru_utime; struct timeval tmp_ru_stime; struct timeval ru_utime; struct timeval ru_stime; unsigned deleted:1; } pinba_timer_t; /* }}} */ #define PHP_ZVAL_TO_TIMER(zval, timer) \ timer = (pinba_timer_t *)zend_fetch_resource(Z_RES_P(zval), "pinba timer", le_pinba_timer); \ if (!timer) { \ RETURN_FALSE; \ } static inline pinba_client_t *php_pinba_client_object(zend_object *obj) { return (pinba_client_t *)((char*)(obj) - XtOffsetOf(pinba_client_t, std)); } #define Z_PINBACLIENT_P(zv) php_pinba_client_object(Z_OBJ_P(zv)) #define timeval_cvt(a, b) do { (a)->tv_sec = (b)->tv_sec; (a)->tv_usec = (b)->tv_usec; } while (0); #define timeval_to_float(t) (float)(t).tv_sec + (float)(t).tv_usec / 1000000.0 #define float_to_timeval(f, t) \ do { \ (t).tv_sec = (int)(f); \ (t).tv_usec = (int)((f - (double)(t).tv_sec) * 1000000.0); \ } while(0); #ifndef timersub # define timersub(a, b, result) \ do { \ (result)->tv_sec = (a)->tv_sec - (b)->tv_sec; \ (result)->tv_usec = (a)->tv_usec - (b)->tv_usec; \ if ((result)->tv_usec < 0) { \ --(result)->tv_sec; \ (result)->tv_usec += 1000000; \ } \ } while (0) #endif #ifndef timeradd # define timeradd(a, b, result) \ do { \ (result)->tv_sec = (a)->tv_sec + (b)->tv_sec; \ (result)->tv_usec = (a)->tv_usec + (b)->tv_usec; \ if ((result)->tv_usec >= 1000000) { \ (result)->tv_sec++; \ (result)->tv_usec -= 1000000; \ } \ } while (0) #endif static int php_pinba_key_compare(const void *a, const void *b); /* {{{ internal funcs */ static inline pinba_collector* php_pinba_collector_add(pinba_collector *collectors, unsigned int *n_collectors) /* {{{ */ { if (*n_collectors >= PINBA_COLLECTORS_MAX) { return NULL; } return &collectors[(*n_collectors)++]; } /* }}} */ static inline void php_pinba_cleanup_collectors(pinba_collector *collectors, unsigned int *n_collectors) /* {{{ */ { int i; for (i = 0; i < *n_collectors; i++) { pinba_collector *collector = &collectors[i]; if (collector->host) { free(collector->host); } if (collector->port) { free(collector->port); } } *n_collectors = 0; } /* }}} */ static inline int php_pinba_parse_server(char *address, char **host, char **port) /* {{{ */ { char *new_node, *new_service = NULL; *host = *port = NULL; if (address[0] == 0) { /* empty string, just skip */ return FAILURE; } /* '[' ']' [':' ] */ if (address[0] == '[') { char *endptr; new_node = address + 1; endptr = strchr(new_node, ']'); if (endptr == NULL) { return FAILURE; } *endptr = 0; endptr++; if (*endptr != ':' && *endptr != 0) { return FAILURE; } if (*endptr != 0) { new_service = endptr + 1; } if (new_service != NULL && *new_service == 0) { new_service = NULL; } } /* [':' ] */ else if ((strchr(address, ':') == NULL) /* no colon */ || (strchr(address, ':') == strrchr(address, ':'))) { /* exactly one colon */ char *endptr = strchr(address, ':'); if (endptr != NULL) { *endptr = 0; new_service = endptr + 1; } new_node = address; } /* */ else { /* multiple colons */ new_node = address; } *host = new_node; *port = new_service; return SUCCESS; } /* }}} */ static inline int php_pinba_timer_stop(pinba_timer_t *t, struct timeval *pnow, struct rusage *pu) /* {{{ */ { struct timeval now; struct rusage u, tmp; if (!t->started) { return FAILURE; } if (pnow) { now = *pnow; } else { if (gettimeofday(&now, 0) != 0) { return FAILURE; } } timersub(&now, &t->start, &t->value); if (pu) { u = *pu; } else { if (getrusage(RUSAGE_SELF, &u) != 0) { return FAILURE; } } timersub(&u.ru_utime, &t->tmp_ru_utime, &tmp.ru_utime); timersub(&u.ru_stime, &t->tmp_ru_stime, &tmp.ru_stime); timeradd(&t->ru_utime, &tmp.ru_utime, &t->ru_utime); timeradd(&t->ru_stime, &tmp.ru_stime, &t->ru_stime); t->started = 0; return SUCCESS; } /* }}} */ static inline void php_pinba_timer_tags_dtor(pinba_timer_tag_t **tags, int tags_num) /* {{{ */ { int i; pinba_timer_tag_t *tag; for (i = 0; i < tags_num; i++) { tag = *(tags + i); if (tag) { if (tag->name) { efree(tag->name); } if (tag->value) { efree(tag->value); } efree(tag); } } } /* }}} */ static void php_pinba_timer_dtor(pinba_timer_t *t) /* {{{ */ { php_pinba_timer_tags_dtor(t->tags, t->tags_num); efree(t->tags); } /* }}} */ static void php_timer_hash_dtor(zval *zv) /* {{{ */ { pinba_timer_t *t = Z_PTR_P(zv); if (t) { php_pinba_timer_dtor(t); efree(t); } } /* }}} */ static void php_tag_hash_dtor(zval *zv) /* {{{ */ { char *tag = Z_PTR_P(zv); if (tag) { efree(tag); } } /* }}} */ static int php_pinba_tags_to_hashed_string(pinba_timer_tag_t **tags, int tags_num, char **hashed_tags, size_t *hashed_tags_len) /* {{{ */ { int i; char *buf; size_t buf_len, wrote_len; *hashed_tags = NULL; *hashed_tags_len = 0; if (!tags_num) { return FAILURE; } buf_len = 4096; wrote_len = 0; buf = (char *)emalloc(buf_len + 1); for (i = 0; i < tags_num; i++) { if (buf_len <= (wrote_len + tags[i]->name_len + 2 + tags[i]->value_len + 1)) { buf_len = wrote_len + tags[i]->name_len + 2 + tags[i]->value_len + 1 + 4096; buf = (char *)erealloc(buf, buf_len + 1); } memcpy(buf + wrote_len, tags[i]->name, tags[i]->name_len); wrote_len += tags[i]->name_len; memcpy(buf + wrote_len, "=>", 2); wrote_len += 2; memcpy(buf + wrote_len, tags[i]->value, tags[i]->value_len); wrote_len += tags[i]->value_len; memcpy(buf + wrote_len, ",", 1); wrote_len += 1; } buf[wrote_len] = '\0'; *hashed_tags = buf; *hashed_tags_len = wrote_len; return SUCCESS; } /* }}} */ static void php_timer_resource_dtor(zend_resource *entry) /* {{{ */ { pinba_timer_t *t = (pinba_timer_t *)entry->ptr; php_pinba_timer_stop(t, NULL, NULL); /* php_pinba_timer_dtor(t); all timers are destroyed at once */ /* but we don't need the user data anymore */ if (!Z_ISUNDEF(t->data)) { zval_ptr_dtor(&t->data); } if (!t->deleted && !PINBA_G(in_rshutdown)) { /* do nothing */ } else { php_pinba_timer_dtor(t); efree(t); } } /* }}} */ static int php_pinba_timer_stop_helper(zval *zv, int num_args, va_list args, zend_hash_key *hash_key) /* {{{ */ { if (Z_RES_TYPE_P(zv) == le_pinba_timer) { long flags = va_arg(args, long); struct timeval *now = va_arg(args, struct timeval *); struct rusage *u = va_arg(args, struct rusage *); pinba_timer_t *t = (pinba_timer_t *)Z_RES_VAL_P(zv); if (t->deleted || ((flags & PINBA_FLUSH_ONLY_STOPPED_TIMERS) != 0 && t->started)) { return ZEND_HASH_APPLY_KEEP; } else { php_pinba_timer_stop(t, now, u); t->deleted = 1; /* ignore next time */ } if (zend_hash_index_exists(&PINBA_G(timers), t->rsrc_id) == 0) { zend_hash_index_update_ptr(&PINBA_G(timers), t->rsrc_id, t); } return ZEND_HASH_APPLY_KEEP; } return ZEND_HASH_APPLY_KEEP; } /* }}} */ static int php_pinba_timer_delete_helper(zval *zv) /* {{{ */ { if (Z_RES_TYPE_P(zv) == le_pinba_timer) { pinba_timer_t *t = (pinba_timer_t *)Z_RES_VAL_P(zv); if (t->deleted) { /* only delete from the list if there are no references to this zval */ if (GC_REFCOUNT(Z_COUNTED_P(zv)) == 1) { return ZEND_HASH_APPLY_REMOVE; } } } return ZEND_HASH_APPLY_KEEP; } /* }}} */ static size_t sapi_ub_write_counter(const char *str, size_t length) /* {{{ */ { PINBA_G(tmp_req_data).doc_size += length; #if PHP_VERSION_ID < 50400 return PINBA_G(old_sapi_ub_write)(str, length); #else return old_sapi_ub_write(str, length); #endif } /* }}} */ static pinba_sockaddr *php_pinba_connect_socket(const char *host, const char *port) /* {{{ */ { pinba_sockaddr *sa; time_t now = time(NULL); char *hostport; size_t hostport_len; hostport_len = spprintf(&hostport, 0, "%s:%s", host, port); sa = zend_hash_str_find_ptr(&resolver_cache, hostport, hostport_len); if (sa) { if ((now - sa->sockaddr_time) < PINBA_G(resolve_interval)) { efree(hostport); return sa; } /* delete the value and proceed to re-resolve */ zend_hash_str_del(&resolver_cache, hostport, hostport_len); sa = NULL; } struct addrinfo *ai_list; struct addrinfo *ai_ptr = NULL; struct addrinfo ai_hints; memset(&ai_hints, 0, sizeof(ai_hints)); ai_hints.ai_flags = 0; #ifdef AI_ADDRCONFIG ai_hints.ai_flags |= AI_ADDRCONFIG; #endif ai_hints.ai_family = AF_UNSPEC; ai_hints.ai_socktype = SOCK_DGRAM; ai_hints.ai_addr = NULL; ai_hints.ai_canonname = NULL; ai_hints.ai_next = NULL; ai_list = NULL; int status = getaddrinfo(host, port, &ai_hints, &ai_list); if (status != 0) { efree(hostport); php_error_docref(NULL, E_WARNING, "failed to resolve Pinba server hostname '%s': %s", host, gai_strerror(status)); return NULL; } else { for (ai_ptr = ai_list; ai_ptr != NULL; ai_ptr = ai_ptr->ai_next) { int fd = socket(ai_ptr->ai_family, ai_ptr->ai_socktype, ai_ptr->ai_protocol); if (fd >= 0) { sa = pecalloc(1, sizeof(pinba_sockaddr), 1); memcpy(&sa->sockaddr, ai_ptr->ai_addr, ai_ptr->ai_addrlen); sa->sockaddr_len = ai_ptr->ai_addrlen; sa->sockaddr_time = now; sa->fd = fd; zend_hash_str_update_ptr(&resolver_cache, hostport, hostport_len, sa); break; } } } freeaddrinfo(ai_list); efree(hostport); return sa; } /* }}} */ static int php_pinba_init_socket(pinba_collector *collectors, int n_collectors) /* {{{ */ { int i; int n_fds; if (n_collectors == 0) { return FAILURE; } n_fds = 0; for (i = 0; i < n_collectors; i++) { pinba_collector *collector = &collectors[i]; pinba_sockaddr *sa = php_pinba_connect_socket(collector->host, collector->port); if (!sa) { continue; /* skip this one in case others are good */ } n_fds++; } return (n_fds > 0) ? SUCCESS : FAILURE; } /* }}} */ static inline int php_pinba_dict_find_or_add(HashTable *ht, char *word, size_t word_len) /* {{{ */ { size_t id, cnt; id = (size_t)zend_hash_str_find_ptr(ht, word, word_len); if (!id) { cnt = zend_hash_num_elements(ht) + 1; if (zend_hash_str_add_ptr(ht, word, word_len, (void *)cnt) == NULL) { return -1; } return cnt - 1; } return id - 1; } /* }}} */ static inline char *_pinba_fetch_global_var(char *name, int name_len) /* {{{ */ { char *res; zval *tmp; if (!PINBA_G(in_rshutdown) && (Z_TYPE(PG(http_globals)[TRACK_VARS_SERVER]) == IS_ARRAY || zend_is_auto_global_str(ZEND_STRL("_SERVER")))) { tmp = zend_hash_str_find(HASH_OF(&PG(http_globals)[TRACK_VARS_SERVER]), name, name_len); if (tmp && Z_TYPE_P(tmp) == IS_STRING && Z_STRLEN_P(tmp) > 0) { res = strdup(Z_STRVAL_P(tmp)); return res; } } res = strdup("unknown"); return res; } /* }}} */ static inline Pinba__Request *php_create_pinba_packet(pinba_client_t *client, const char *custom_script_name, int flags) /* {{{ */ { HashTable dict, *tags, *timers, timers_uniq; HashPosition pos; Pinba__Request *request; char hostname[256], *tag_value; pinba_req_data *req_data = &PINBA_G(tmp_req_data); int timers_num, tags_cnt, *tag_ids = NULL, *tag_value_ids = NULL, i, n; size_t id; request = malloc(sizeof(Pinba__Request)); if (!request) { return NULL; } pinba__request__init(request); if (client) { request->memory_peak = client->memory_peak; request->request_count = client->request_count; request->document_size = client->document_size; request->request_time = client->request_time; request->ru_utime = client->rusage[0]; request->ru_stime = client->rusage[1]; request->status = client->status; request->has_status = 1; request->memory_footprint = client->memory_footprint; request->has_memory_footprint = 1; if (client->schema && client->schema[0] != '\0') { request->schema = strdup(client->schema); } if (client->hostname) { request->hostname = strdup(client->hostname); } else { gethostname(hostname, sizeof(hostname)); hostname[sizeof(hostname) - 1] = '\0'; request->hostname = strdup(hostname); } if (client->server_name) { request->server_name = strdup(client->server_name); } else { request->server_name = _pinba_fetch_global_var("SERVER_NAME", sizeof("SERVER_NAME")-1); } if (custom_script_name) { request->script_name = strdup(custom_script_name); } else if (client->script_name) { request->script_name = strdup(client->script_name); } else { request->script_name = _pinba_fetch_global_var("SCRIPT_NAME", sizeof("SCRIPT_NAME")-1); } tags = &client->tags; timers = &client->timers; } else { struct timeval ru_utime = {0, 0}, ru_stime = {0, 0}; struct rusage u; #if PHP_MAJOR_VERSION >= 5 req_data->mem_peak_usage = zend_memory_peak_usage(1); #elif PHP_MAJOR_VERSION == 4 && MEMORY_LIMIT req_data->mem_peak_usage = AG(allocated_memory_peak); #else /* no data available */ req_data->mem_peak_usage = 0; #endif request->memory_peak = req_data->mem_peak_usage; request->request_count = req_data->req_count; request->document_size = req_data->doc_size; if (PINBA_G(request_time) > 0) { request->request_time = PINBA_G(request_time); } else { struct timeval request_finish, req_time; gettimeofday(&request_finish, 0); timersub(&request_finish, &req_data->req_start, &req_time); request->request_time = timeval_to_float(req_time); } if (getrusage(RUSAGE_SELF, &u) == 0) { timersub(&u.ru_utime, &req_data->ru_utime, &ru_utime); timersub(&u.ru_stime, &req_data->ru_stime, &ru_stime); } request->ru_utime = timeval_to_float(ru_utime); request->ru_stime = timeval_to_float(ru_stime); request->status = SG(sapi_headers).http_response_code; request->has_status = 1; #if defined(HAVE_MALLOC_H) && defined(HAVE_MALLINFO) { struct mallinfo info; info = mallinfo(); request->memory_footprint = info.arena;// + info.hblkhd; } #else request->memory_footprint = 0; #endif request->has_memory_footprint = 1; if (PINBA_G(schema)[0] != '\0') { request->schema = strdup(PINBA_G(schema)); } if (PINBA_G(host_name)[0] != '\0') { request->hostname = strdup(PINBA_G(host_name)); } else { gethostname(hostname, sizeof(hostname)); hostname[sizeof(hostname) - 1] = '\0'; request->hostname = strdup(hostname); } if (PINBA_G(server_name)) { request->server_name = strdup(PINBA_G(server_name)); } else { request->server_name = _pinba_fetch_global_var("SERVER_NAME", sizeof("SERVER_NAME")-1); } if (custom_script_name) { request->script_name = strdup(custom_script_name); } else if (PINBA_G(script_name)) { request->script_name = strdup(PINBA_G(script_name)); } else { request->script_name = _pinba_fetch_global_var("SCRIPT_NAME", sizeof("SCRIPT_NAME")-1); } tags = &PINBA_G(tags); timers = &PINBA_G(timers); } zend_hash_init(&dict, 10, NULL, NULL, 0); tags_cnt = zend_hash_num_elements(tags); if (tags_cnt) { int tag_num = 0; zend_hash_sort(tags, php_pinba_key_compare, 0); tag_ids = ecalloc(tags_cnt, sizeof(int)); tag_value_ids = ecalloc(tags_cnt, sizeof(int)); for (zend_hash_internal_pointer_reset_ex(tags, &pos); (tag_value = zend_hash_get_current_data_ptr_ex(tags, &pos)) != NULL; zend_hash_move_forward_ex(tags, &pos)) { zend_string *key = NULL; zend_ulong num_key; int word_id; word_id = php_pinba_dict_find_or_add(&dict, tag_value, strlen(tag_value)); if (word_id < 0) { continue; } tag_value_ids[tag_num] = word_id; if (zend_hash_get_current_key_ex(tags, &key, &num_key, &pos) == HASH_KEY_IS_STRING) { word_id = php_pinba_dict_find_or_add(&dict, key->val, key->len); if (word_id < 0) { continue; } tag_ids[tag_num] = word_id; } tag_num++; } tags_cnt = tag_num; } timers_num = zend_hash_num_elements(timers); if (timers_num > 0) { pinba_timer_t *t, *old_t; char *hashed_tags; size_t hashed_tags_len; /* make sure we send aggregated timers to the server */ zend_hash_init(&timers_uniq, 10, NULL, NULL, 0); for (zend_hash_internal_pointer_reset_ex(timers, &pos); (t = zend_hash_get_current_data_ptr_ex(timers, &pos)) != NULL; zend_hash_move_forward_ex(timers, &pos)) { /* aggregate only stopped timers */ if ((flags & PINBA_FLUSH_ONLY_STOPPED_TIMERS) != 0 && t->started) { continue; } if (php_pinba_tags_to_hashed_string(t->tags, t->tags_num, &hashed_tags, &hashed_tags_len) != SUCCESS) { continue; } old_t = zend_hash_str_find_ptr(&timers_uniq, hashed_tags, hashed_tags_len); if (old_t != NULL) { timeradd(&old_t->value, &t->value, &old_t->value); timeradd(&old_t->ru_utime, &t->ru_utime, &old_t->ru_utime); timeradd(&old_t->ru_stime, &t->ru_stime, &old_t->ru_stime); if (t->hit_count) { old_t->hit_count += t->hit_count; } else { old_t->hit_count++; } } else { zend_hash_str_add_ptr(&timers_uniq, hashed_tags, hashed_tags_len, t); } efree(hashed_tags); } /* create our temporary dictionary and add ids to timers */ for (zend_hash_internal_pointer_reset_ex(&timers_uniq, &pos); (t = zend_hash_get_current_data_ptr_ex(&timers_uniq, &pos)) != NULL; zend_hash_move_forward_ex(&timers_uniq, &pos)) { for (i = 0; i < t->tags_num; i++) { int word_id; word_id = php_pinba_dict_find_or_add(&dict, t->tags[i]->name, t->tags[i]->name_len); if (word_id < 0) { break; } t->tags[i]->name_id = word_id; word_id = php_pinba_dict_find_or_add(&dict, t->tags[i]->value, t->tags[i]->value_len); if (word_id < 0) { break; } t->tags[i]->value_id = word_id; } } } n = zend_hash_num_elements(&dict); request->dictionary = malloc(sizeof(char *) * n); if (!request->dictionary) { pinba__request__free_unpacked(request, NULL); return NULL; } n = 0; for (zend_hash_internal_pointer_reset_ex(&dict, &pos); (id = (size_t)zend_hash_get_current_data_ex(&dict, &pos) != 0); zend_hash_move_forward_ex(&dict, &pos)) { zend_string *str; zend_ulong num_key; if (zend_hash_get_current_key_ex(&dict, &str, &num_key, &pos) == HASH_KEY_IS_STRING) { request->dictionary[n] = strndup(str->val, str->len); n++; } else { continue; } } zend_hash_destroy(&dict); request->n_dictionary = n; if (tags_cnt) { request->tag_name = malloc(sizeof(unsigned int) * tags_cnt); request->n_tag_name = tags_cnt; request->tag_value = malloc(sizeof(unsigned int) * tags_cnt); request->n_tag_value = tags_cnt; for (i = 0; i < tags_cnt; i++) { request->tag_name[i] = tag_ids[i]; request->tag_value[i] = tag_value_ids[i]; } efree(tag_ids); efree(tag_value_ids); } /* timers */ if (timers_num > 0) { pinba_timer_t *t; n = zend_hash_num_elements(&timers_uniq); request->timer_hit_count = malloc(sizeof(unsigned int) * n); request->timer_tag_count = malloc(sizeof(unsigned int) * n); request->timer_ru_stime = malloc(sizeof(float) * n); request->timer_ru_utime = malloc(sizeof(float) * n); request->timer_tag_name = NULL; request->timer_tag_value = NULL; request->timer_value = malloc(sizeof(float) * n); if (!request->timer_hit_count || !request->timer_tag_count || !request->timer_value || !request->timer_ru_stime || !request->timer_ru_utime) { pinba__request__free_unpacked(request, NULL); return NULL; } n = 0; for (zend_hash_internal_pointer_reset_ex(&timers_uniq, &pos); (t = zend_hash_get_current_data_ptr_ex(&timers_uniq, &pos)) != NULL; zend_hash_move_forward_ex(&timers_uniq, &pos)) { request->timer_tag_name = realloc(request->timer_tag_name, sizeof(unsigned int) * (request->n_timer_tag_name + t->tags_num)); request->timer_tag_value = realloc(request->timer_tag_value, sizeof(unsigned int) * (request->n_timer_tag_value + t->tags_num)); if (!request->timer_tag_name || !request->timer_tag_value) { pinba__request__free_unpacked(request, NULL); return NULL; } for (i = 0; i < t->tags_num; i++) { request->timer_tag_name[request->n_timer_tag_name + i] = t->tags[i]->name_id; request->timer_tag_value[request->n_timer_tag_value + i] = t->tags[i]->value_id; } request->n_timer_tag_name += i; request->n_timer_tag_value += i; request->timer_tag_count[n] = i; request->timer_hit_count[n] = t->hit_count; request->timer_value[n] = timeval_to_float(t->value); request->timer_ru_utime[n] = timeval_to_float(t->ru_utime); request->timer_ru_stime[n] = timeval_to_float(t->ru_stime); n++; } request->n_timer_tag_count = n; request->n_timer_hit_count = n; request->n_timer_ru_utime = n; request->n_timer_ru_stime = n; request->n_timer_value = n; zend_hash_destroy(&timers_uniq); } return request; } /* }}} */ #define PINBA_PACK(request, data, data_len) \ unsigned char _pad[256]; \ ProtobufCBufferSimple _buf = PROTOBUF_C_BUFFER_SIMPLE_INIT (_pad); \ ProtobufCBuffer *_buffer = (ProtobufCBuffer *) &_buf; \ pinba__request__pack_to_buffer((request), _buffer); \ (data) = (char *)_buf.data; \ (data_len) = _buf.len; \ #define PINBA_FREE_BUFFER() \ PROTOBUF_C_BUFFER_SIMPLE_CLEAR(&_buf) static inline int php_pinba_req_data_send(pinba_client_t *client, const char *custom_script_name, int flags) /* {{{ */ { int ret = SUCCESS; Pinba__Request *request; request = php_create_pinba_packet(client, custom_script_name, flags); if (request) { int i, n_collectors, data_len; ssize_t sent; pinba_collector *collectors; char *data; if (client) { /* disable AUTO_FLUSH if data has been sent manually */ client->data_sent = 1; } PINBA_PACK(request, data, data_len); if (client) { n_collectors = client->n_collectors; collectors = client->collectors; } else { n_collectors = PINBA_G(n_collectors); collectors = PINBA_G(collectors); } for (i = 0; i < n_collectors; i++) { pinba_collector *collector = &collectors[i]; pinba_sockaddr *sa = php_pinba_connect_socket(collector->host, collector->port); if (!sa) { continue; /* skip this one in case others are good */ } sent = sendto(sa->fd, data, data_len, 0, (struct sockaddr *) &sa->sockaddr, sa->sockaddr_len); if (sent < data_len) { php_error_docref(NULL, E_WARNING, "failed to send data to Pinba server: %s", strerror(errno)); ret = FAILURE; } } PINBA_FREE_BUFFER(); pinba__request__free_unpacked(request, NULL); } else { ret = FAILURE; } return ret; } /* }}} */ static inline void php_pinba_req_data_dtor(pinba_req_data *record) /* {{{ */ { if (record->server_name) { efree(record->server_name); } if (record->script_name) { efree(record->script_name); } memset(record, 0, sizeof(pinba_req_data)); } /* }}} */ static inline void php_pinba_reset_data(void) /* {{{ */ { struct timeval t; struct rusage u; if (gettimeofday(&t, 0) == 0) { timeval_cvt(&(PINBA_G(tmp_req_data).req_start), &t); } if (getrusage(RUSAGE_SELF, &u) == 0) { timeval_cvt(&(PINBA_G(tmp_req_data).ru_utime), &u.ru_utime); timeval_cvt(&(PINBA_G(tmp_req_data).ru_stime), &u.ru_stime); } PINBA_G(tmp_req_data).doc_size = 0; PINBA_G(tmp_req_data).mem_peak_usage= 0; PINBA_G(tmp_req_data).req_count = 0; zend_hash_clean(&PINBA_G(tags)); zend_hash_clean(&PINBA_G(timers)); } /* }}} */ static void php_pinba_flush_data(const char *custom_script_name, long flags) /* {{{ */ { struct timeval now; struct rusage u; if (gettimeofday(&now, 0) != 0 || getrusage(RUSAGE_SELF, &u) != 0) { return; } /* stop all running timers */ zend_hash_apply_with_arguments(&EG(regular_list), (apply_func_args_t) php_pinba_timer_stop_helper, 3, (void *)flags, (void *)&now, (void *)&u); /* prevent any further access to the timers */ PINBA_G(timers_stopped) = 1; if (!PINBA_G(enabled) || PINBA_G(n_collectors) == 0) { /* disabled or no collectors defined, exit */ zend_hash_clean(&PINBA_G(timers)); zend_hash_apply(&EG(regular_list), (apply_func_t) php_pinba_timer_delete_helper); PINBA_G(timers_stopped) = 0; return; } if (php_pinba_init_socket(PINBA_G(collectors), PINBA_G(n_collectors)) != SUCCESS) { PINBA_G(timers_stopped) = 0; return; } php_pinba_req_data_send(NULL, custom_script_name, flags); if (flags & PINBA_FLUSH_RESET_DATA) { php_pinba_reset_data(); } /* delete all stopped timers */ zend_hash_apply(&EG(regular_list), (apply_func_t) php_pinba_timer_delete_helper); PINBA_G(timers_stopped) = 0; zend_hash_clean(&PINBA_G(timers)); } /* }}} */ static int php_pinba_key_compare(const void *a, const void *b) /* {{{ */ { Bucket *f; Bucket *s; zval first; zval second; f = (Bucket *) a; s = (Bucket *) b; if (f->key == NULL) { ZVAL_LONG(&first, f->h); } else { ZVAL_STR(&first, f->key); } if (s->key == NULL) { ZVAL_LONG(&second, s->h); } else { ZVAL_STR(&second, s->key); } return string_compare_function(&first, &second); } /* }}} */ static int php_pinba_array_to_tags(HashTable *array, pinba_timer_tag_t ***tags) /* {{{ */ { int num, i = 0; zval *value; zend_string *tag_name_str; num = zend_hash_num_elements(array); if (!num) { return FAILURE; } /* sort array, we'll use this when computing tags hash */ zend_hash_sort(array, php_pinba_key_compare, 0); *tags = (pinba_timer_tag_t **)ecalloc(num, sizeof(pinba_timer_tag_t *)); ZEND_HASH_FOREACH_STR_KEY_VAL_IND(array, tag_name_str, value) { zend_string *str; switch (Z_TYPE_P(value)) { case IS_NULL: case IS_STRING: case IS_TRUE: case IS_FALSE: case IS_LONG: case IS_DOUBLE: str = zval_get_string(value); break; default: php_error_docref(NULL, E_WARNING, "tags cannot have non-scalar values"); php_pinba_timer_tags_dtor(*tags, i); efree(*tags); return FAILURE; } if (tag_name_str) { (*tags)[i] = (pinba_timer_tag_t *)emalloc(sizeof(pinba_timer_tag_t)); (*tags)[i]->name = estrndup(tag_name_str->val, tag_name_str->len); (*tags)[i]->name_len = tag_name_str->len; (*tags)[i]->value = estrndup(str->val, str->len); (*tags)[i]->value_len = str->len; zend_string_release(str); } else { zend_string_release(str); php_error_docref(NULL, E_WARNING, "tags can only have string names (i.e. tags array cannot contain numeric indexes)"); php_pinba_timer_tags_dtor(*tags, i); efree(*tags); return FAILURE; } i++; } ZEND_HASH_FOREACH_END(); return SUCCESS; } /* }}} */ static pinba_timer_t *php_pinba_timer_ctor(pinba_timer_tag_t **tags, int tags_num) /* {{{ */ { struct timeval now; pinba_timer_t *t; t = (pinba_timer_t *)ecalloc(1, sizeof(pinba_timer_t)); t->tags_num = tags_num; t->tags = tags; gettimeofday(&now, 0); timeval_cvt(&t->start, &now); return t; } /* }}} */ static void php_pinba_get_timer_info(pinba_timer_t *t, zval *info, struct timeval *pnow) /* {{{ */ { zval tags; pinba_timer_tag_t *tag; struct timeval tmp; int i; array_init(info); if (t->started) { if (pnow) { tmp = *pnow; } else { gettimeofday(&tmp, 0); } timersub(&tmp, &t->start, &tmp); timeradd(&t->value, &tmp, &tmp); } else { timeval_cvt(&tmp, &t->value); } add_assoc_double(info, "value", timeval_to_float(tmp)); array_init(&tags); for (i = 0; i < t->tags_num; i++) { tag = t->tags[i]; add_assoc_stringl(&tags, tag->name, tag->value, tag->value_len); } add_assoc_zval(info, "tags", &tags); add_assoc_bool(info, "started", t->started ? 1 : 0); if (!Z_ISUNDEF(t->data)) { add_assoc_zval(info, "data", &t->data); zval_add_ref(&t->data); } else { add_assoc_null(info, "data"); } add_assoc_double(info, "ru_utime", timeval_to_float(t->ru_utime)); add_assoc_double(info, "ru_stime", timeval_to_float(t->ru_stime)); } /* }}} */ static void pinba_client_object_dtor(zend_object *object) /* {{{ */ { pinba_client_t *client = (pinba_client_t *) php_pinba_client_object(object); if (!client->data_sent && (client->flags & PINBA_AUTO_FLUSH) != 0) { if (client->collectors_initialized || php_pinba_init_socket(client->collectors, client->n_collectors) != FAILURE) { php_pinba_req_data_send(client, NULL, client->flags); } } } /* }}} */ static void pinba_client_free_storage(zend_object *object) /* {{{ */ { int i; pinba_client_t *client = (pinba_client_t *) php_pinba_client_object(object); zend_object_std_dtor(&client->std); if (client->n_servers > 0) { for (i = 0; i < client->n_servers; i++) { efree(client->servers[i]); } efree(client->servers); } php_pinba_cleanup_collectors(client->collectors, &client->n_collectors); if (client->hostname) { efree(client->hostname); } if (client->server_name) { efree(client->server_name); } if (client->script_name) { efree(client->script_name); } if (client->schema) { efree(client->schema); } zend_hash_destroy(&client->timers); zend_hash_destroy(&client->tags); } /* }}} */ zend_object *pinba_client_new(zend_class_entry *ce) /* {{{ */ { pinba_client_t *intern; intern = ecalloc(1, sizeof(pinba_client_t) + zend_object_properties_size(ce)); zend_object_std_init(&(intern->std), ce); object_properties_init(&intern->std, ce); intern->std.handlers = &pinba_client_handlers; zend_hash_init(&intern->timers, 0, NULL, php_timer_hash_dtor, 0); zend_hash_init(&intern->tags, 0, NULL, php_tag_hash_dtor, 0); return &intern->std; } /* }}} */ /* }}} */ /* {{{ proto resource pinba_timer_start(array tags[[, array data], int hit_count]) Start user timer */ static PHP_FUNCTION(pinba_timer_start) { zval *tags_array; zval *data = NULL; pinba_timer_t *t = NULL; pinba_timer_tag_t **tags; int tags_num; long hit_count = 1; struct rusage u; zend_resource *rsrc; if (PINBA_G(timers_stopped)) { php_error_docref(NULL, E_WARNING, "all timers have already been stopped"); RETURN_FALSE; } ZEND_PARSE_PARAMETERS_START(1, 3) Z_PARAM_ARRAY_EX(tags_array, 0, 1) Z_PARAM_OPTIONAL Z_PARAM_ZVAL(data) Z_PARAM_LONG(hit_count) ZEND_PARSE_PARAMETERS_END_EX(RETURN_FALSE); tags_num = zend_hash_num_elements(Z_ARRVAL_P(tags_array)); if (!tags_num) { php_error_docref(NULL, E_WARNING, "tags array cannot be empty"); RETURN_FALSE; } if (hit_count <= 0) { php_error_docref(NULL, E_WARNING, "hit_count must be greater than 0 (%ld was passed)", hit_count); RETURN_FALSE; } if (php_pinba_array_to_tags(Z_ARRVAL_P(tags_array), &tags) != SUCCESS) { RETURN_FALSE; } t = php_pinba_timer_ctor(tags, tags_num); if (data && zend_hash_num_elements(Z_ARRVAL_P(data)) > 0) { ZVAL_DUP(&t->data, data); } t->started = 1; t->hit_count = hit_count; rsrc = zend_register_resource(t, le_pinba_timer); t->rsrc_id = rsrc->handle; if (getrusage(RUSAGE_SELF, &u) == 0) { timeval_cvt(&t->tmp_ru_utime, &u.ru_utime); timeval_cvt(&t->tmp_ru_stime, &u.ru_stime); } /* refcount++ so that the timer is shut down only on request finish if not stopped manually */ #if PHP_VERSION_ID < 70300 GC_REFCOUNT(rsrc)++; #else GC_ADDREF(rsrc); #endif RETURN_RES(rsrc); } /* }}} */ /* {{{ proto resource pinba_timer_add(array tags, float value[[, array data,], int hit_count]) Create user timer with a value */ static PHP_FUNCTION(pinba_timer_add) { zval *tags_array; zval *data = NULL; pinba_timer_t *t = NULL; pinba_timer_tag_t **tags; int tags_num; double value; unsigned long time_l; zend_resource *rsrc; long hit_count = 1; if (PINBA_G(timers_stopped)) { php_error_docref(NULL, E_WARNING, "all timers have already been stopped"); RETURN_FALSE; } ZEND_PARSE_PARAMETERS_START(2, 4) Z_PARAM_ARRAY_EX(tags_array, 0, 1) Z_PARAM_DOUBLE(value) Z_PARAM_OPTIONAL Z_PARAM_ZVAL(data) Z_PARAM_LONG(hit_count) ZEND_PARSE_PARAMETERS_END_EX(RETURN_FALSE); tags_num = zend_hash_num_elements(Z_ARRVAL_P(tags_array)); if (!tags_num) { php_error_docref(NULL, E_WARNING, "tags array cannot be empty"); RETURN_FALSE; } if (hit_count <= 0) { php_error_docref(NULL, E_WARNING, "hit_count must be greater than 0 (%ld was passed)", hit_count); RETURN_FALSE; } if (php_pinba_array_to_tags(Z_ARRVAL_P(tags_array), &tags) != SUCCESS) { RETURN_FALSE; } if (value < 0) { php_error_docref(NULL, E_WARNING, "negative time value passed (%f), changing it to 0", value); value = 0; } t = php_pinba_timer_ctor(tags, tags_num); if (data && zend_hash_num_elements(Z_ARRVAL_P(data)) > 0) { ZVAL_DUP(&t->data, data); } t->started = 0; t->hit_count = hit_count; time_l = (unsigned long)(value * 1000000.0); t->value.tv_sec = time_l / 1000000; t->value.tv_usec = time_l % 1000000; rsrc = zend_register_resource(t, le_pinba_timer); t->rsrc_id = rsrc->handle; /* refcount++ so that the timer is shut down only on request finish if not stopped manually */ #if PHP_VERSION_ID < 70300 GC_REFCOUNT(rsrc)++; #else GC_ADDREF(rsrc); #endif RETURN_RES(rsrc); } /* }}} */ /* {{{ proto bool pinba_timer_stop(resource timer) Stop user timer */ static PHP_FUNCTION(pinba_timer_stop) { zval *timer; pinba_timer_t *t; if (PINBA_G(timers_stopped)) { php_error_docref(NULL, E_WARNING, "all timers have already been stopped"); RETURN_FALSE; } if (zend_parse_parameters(ZEND_NUM_ARGS(), "r", &timer) != SUCCESS) { return; } PHP_ZVAL_TO_TIMER(timer, t); if (!t->started) { php_error_docref(NULL, E_NOTICE, "timer is already stopped"); RETURN_FALSE; } php_pinba_timer_stop(t, NULL, NULL); RETURN_TRUE; } /* }}} */ /* {{{ proto bool pinba_timer_delete(resource timer) Delete user timer */ static PHP_FUNCTION(pinba_timer_delete) { zval *timer; pinba_timer_t *t; if (zend_parse_parameters(ZEND_NUM_ARGS(), "r", &timer) != SUCCESS) { return; } PHP_ZVAL_TO_TIMER(timer, t); if (t->started) { php_pinba_timer_stop(t, NULL, NULL); } t->deleted = 1; zend_list_delete(Z_RES_P(timer)); RETURN_TRUE; } /* }}} */ /* {{{ proto bool pinba_timer_data_merge(resource timer, array data) Merge timer data with new data */ static PHP_FUNCTION(pinba_timer_data_merge) { zval *timer, *data; pinba_timer_t *t; if (PINBA_G(timers_stopped)) { php_error_docref(NULL, E_WARNING, "all timers have already been stopped"); RETURN_FALSE; } if (zend_parse_parameters(ZEND_NUM_ARGS(), "ra", &timer, &data) != SUCCESS) { return; } PHP_ZVAL_TO_TIMER(timer, t); if (Z_ISUNDEF(t->data)) { ZVAL_DUP(&t->data, data); } else { zend_hash_merge(Z_ARRVAL_P(&t->data), Z_ARRVAL_P(data), zval_add_ref, 1); } RETURN_TRUE; } /* }}} */ /* {{{ proto bool pinba_timer_data_replace(resource timer, array data) Replace timer data with new one */ static PHP_FUNCTION(pinba_timer_data_replace) { zval *timer, *data; pinba_timer_t *t; if (PINBA_G(timers_stopped)) { php_error_docref(NULL, E_WARNING, "all timers have already been stopped"); RETURN_FALSE; } if (zend_parse_parameters(ZEND_NUM_ARGS(), "ra!", &timer, &data) != SUCCESS) { return; } PHP_ZVAL_TO_TIMER(timer, t); if (!data) { /* reset */ if (!Z_ISUNDEF(t->data)) { zval_ptr_dtor(&t->data); ZVAL_UNDEF(&t->data); } } else { if (!Z_ISUNDEF(t->data)) { zval_ptr_dtor(&t->data); } ZVAL_DUP(&t->data, data); } RETURN_TRUE; } /* }}} */ /* {{{ proto bool pinba_timer_tags_merge(resource timer, array tags) Merge timer data with new data */ static PHP_FUNCTION(pinba_timer_tags_merge) { zval *tags; zval *timer; pinba_timer_t *t; pinba_timer_tag_t **new_tags; int i, j, tags_num; if (PINBA_G(timers_stopped)) { php_error_docref(NULL, E_WARNING, "all timers have already been stopped"); RETURN_FALSE; } ZEND_PARSE_PARAMETERS_START(2, 2) Z_PARAM_RESOURCE(timer) Z_PARAM_ARRAY_EX(tags, 0, 1) ZEND_PARSE_PARAMETERS_END_EX(RETURN_FALSE); PHP_ZVAL_TO_TIMER(timer, t); tags_num = zend_hash_num_elements(Z_ARRVAL_P(tags)); if (!tags_num) { RETURN_TRUE; } if (php_pinba_array_to_tags(Z_ARRVAL_P(tags), &new_tags) != SUCCESS) { RETURN_FALSE; } for (i = 0; i < tags_num; i++) { int found = 0; for (j = 0; j < t->tags_num; j++) { if (t->tags[j]->name_len == new_tags[i]->name_len && memcmp(t->tags[j]->name, new_tags[i]->name, new_tags[i]->name_len) == 0) { found = 1; break; } } if (found == 1) { /* replace */ efree(t->tags[j]->value); t->tags[j]->value = estrndup(new_tags[i]->value, new_tags[i]->value_len); t->tags[j]->value_len = new_tags[i]->value_len; } else { /* add */ pinba_timer_tag_t *tag; t->tags = (pinba_timer_tag_t **)erealloc(t->tags, (t->tags_num + 1) * sizeof(pinba_timer_tag_t *)); tag = (pinba_timer_tag_t *)emalloc(sizeof(pinba_timer_tag_t)); tag->value = estrndup(new_tags[i]->value, new_tags[i]->value_len); tag->value_len = new_tags[i]->value_len; tag->name = estrndup(new_tags[i]->name, new_tags[i]->name_len); tag->name_len = new_tags[i]->name_len; t->tags[t->tags_num] = tag; t->tags_num++; } } php_pinba_timer_tags_dtor(new_tags, tags_num); efree(new_tags); RETURN_TRUE; } /* }}} */ /* {{{ proto bool pinba_timer_tags_replace(resource timer, array tags) Replace timer data with new one */ static PHP_FUNCTION(pinba_timer_tags_replace) { zval *tags; zval *timer; pinba_timer_t *t; pinba_timer_tag_t **new_tags; int tags_num; if (PINBA_G(timers_stopped)) { php_error_docref(NULL, E_WARNING, "all timers have already been stopped"); RETURN_FALSE; } ZEND_PARSE_PARAMETERS_START(2, 2) Z_PARAM_RESOURCE(timer) Z_PARAM_ARRAY_EX(tags, 0, 1) ZEND_PARSE_PARAMETERS_END_EX(RETURN_FALSE); PHP_ZVAL_TO_TIMER(timer, t); tags_num = zend_hash_num_elements(Z_ARRVAL_P(tags)); if (!tags_num) { php_error_docref(NULL, E_WARNING, "tags array cannot be empty"); RETURN_TRUE; } if (php_pinba_array_to_tags(Z_ARRVAL_P(tags), &new_tags) != SUCCESS) { RETURN_FALSE; } php_pinba_timer_tags_dtor(t->tags, t->tags_num); efree(t->tags); t->tags = new_tags; t->tags_num = tags_num; RETURN_TRUE; } /* }}} */ /* {{{ proto bool pinba_flush([string custom_script_name[, int flags]]) Flush the data */ static PHP_FUNCTION(pinba_flush) { long flags = 0; char *script_name = NULL; size_t script_name_len; if (zend_parse_parameters(ZEND_NUM_ARGS(), "|sl", &script_name, &script_name_len, &flags) != SUCCESS) { return; } if (script_name && script_name_len > 0) { php_pinba_flush_data(script_name, flags); } else { php_pinba_flush_data(NULL, flags); } RETURN_TRUE; } /* }}} */ /* {{{ proto void pinba_reset() Reset the data */ static PHP_FUNCTION(pinba_reset) { php_pinba_reset_data(); } /* }}} */ /* {{{ proto array pinba_get_info() Get request info */ static PHP_FUNCTION(pinba_get_info) { zval timers, timer_info, tags; struct timeval tmp; struct rusage u; HashPosition pos; zval *zv; pinba_timer_t *t; if (zend_parse_parameters(ZEND_NUM_ARGS(), "") != SUCCESS) { return; } array_init(return_value); add_assoc_long(return_value, "mem_peak_usage", zend_memory_peak_usage(1)); if (PINBA_G(request_time) > 0) { /* use custom request time */ add_assoc_double(return_value, "req_time", PINBA_G(request_time)); } else { if (gettimeofday(&tmp, 0) == 0) { timersub(&tmp, &(PINBA_G(tmp_req_data).req_start), &tmp); add_assoc_double(return_value, "req_time", timeval_to_float(tmp)); } else { add_assoc_double(return_value, "req_time", 0); } } if (getrusage(RUSAGE_SELF, &u) == 0) { timersub(&u.ru_utime, &(PINBA_G(tmp_req_data).ru_utime), &tmp); add_assoc_double(return_value, "ru_utime", timeval_to_float(tmp)); timersub(&u.ru_stime, &(PINBA_G(tmp_req_data).ru_stime), &tmp); add_assoc_double(return_value, "ru_stime", timeval_to_float(tmp)); } else { add_assoc_double(return_value, "ru_utime", 0); add_assoc_double(return_value, "ru_stime", 0); } add_assoc_long(return_value, "req_count", PINBA_G(tmp_req_data).req_count + 1); add_assoc_long(return_value, "doc_size", PINBA_G(tmp_req_data).doc_size); if (PINBA_G(schema)) { add_assoc_string(return_value, "schema", PINBA_G(schema)); } else { add_assoc_string(return_value, "schema", (char *)"unknown"); } if (PINBA_G(server_name)) { add_assoc_string(return_value, "server_name", PINBA_G(server_name)); } else { add_assoc_string(return_value, "server_name", (char *)"unknown"); } if (PINBA_G(script_name)) { add_assoc_string(return_value, "script_name", PINBA_G(script_name)); } else { add_assoc_string(return_value, "script_name", (char *)"unknown"); } add_assoc_string(return_value, "hostname", PINBA_G(host_name)); array_init(&timers); gettimeofday(&tmp, 0); for (zend_hash_internal_pointer_reset_ex(&EG(regular_list), &pos); (zv = zend_hash_get_current_data_ex((&EG(regular_list)), &pos)) != NULL; zend_hash_move_forward_ex(&EG(regular_list), &pos)) { zend_resource *rsrc = Z_RES_P(zv); if (rsrc->type == le_pinba_timer) { t = (pinba_timer_t *)rsrc->ptr; if (t->deleted) { continue; } php_pinba_get_timer_info(t, &timer_info, &tmp); add_next_index_zval(&timers, &timer_info); } } add_assoc_zval(return_value, "timers", &timers); array_init(&tags); for (zend_hash_internal_pointer_reset_ex(&PINBA_G(tags), &pos); (zv = zend_hash_get_current_data_ex(&PINBA_G(tags), &pos)) != NULL; zend_hash_move_forward_ex(&PINBA_G(tags), &pos)) { zend_string *key; zend_ulong dummy; char *tag_value = Z_PTR_P(zv); if (zend_hash_get_current_key_ex(&PINBA_G(tags), &key, &dummy, &pos) == HASH_KEY_IS_STRING) { add_assoc_string_ex(&tags, key->val, key->len, tag_value); } else { continue; } } add_assoc_zval(return_value, "tags", &tags); } /* }}} */ /* {{{ proto string pinba_get_data([int flags]) */ static PHP_FUNCTION(pinba_get_data) { Pinba__Request *request; long flags = 0; char *data; int data_len; if (zend_parse_parameters(ZEND_NUM_ARGS(), "|l", &flags) != SUCCESS) { return; } request = php_create_pinba_packet(NULL, NULL, flags); if (!request) { RETURN_FALSE; } PINBA_PACK(request, data, data_len); RETVAL_STRINGL(data, data_len); PINBA_FREE_BUFFER(); pinba__request__free_unpacked(request, NULL); } /* }}} */ /* {{{ proto array pinba_timer_get_info(resource timer) Get timer data */ static PHP_FUNCTION(pinba_timer_get_info) { zval *timer; pinba_timer_t *t; if (zend_parse_parameters(ZEND_NUM_ARGS(), "r", &timer) != SUCCESS) { return; } PHP_ZVAL_TO_TIMER(timer, t); php_pinba_get_timer_info(t, return_value, NULL); } /* }}} */ /* {{{ proto bool pinba_timers_stop() Stop all timers */ static PHP_FUNCTION(pinba_timers_stop) { zval *zv; pinba_timer_t *t; HashPosition pos; struct timeval now; struct rusage u; if (zend_parse_parameters(ZEND_NUM_ARGS(), "") != SUCCESS) { return; } if (gettimeofday(&now, 0) != 0 || getrusage(RUSAGE_SELF, &u) != 0) { RETURN_FALSE; } for (zend_hash_internal_pointer_reset_ex(&EG(regular_list), &pos); (zv = zend_hash_get_current_data_ex((&EG(regular_list)), &pos)) != NULL; zend_hash_move_forward_ex(&EG(regular_list), &pos)) { zend_resource *rsrc = Z_RES_P(zv); if (rsrc->type == le_pinba_timer) { t = (pinba_timer_t *)rsrc->ptr; php_pinba_timer_stop(t, &now, &u); } } RETURN_TRUE; } /* }}} */ /* {{{ proto bool pinba_timers_get() Get timers */ static PHP_FUNCTION(pinba_timers_get) { zval *zv; HashPosition pos; pinba_timer_t *t; long flag = 0; if (zend_parse_parameters(ZEND_NUM_ARGS(), "|l", &flag) != SUCCESS) { return; } array_init(return_value); for (zend_hash_internal_pointer_reset_ex(&EG(regular_list), &pos); (zv = zend_hash_get_current_data_ex((&EG(regular_list)), &pos)) != NULL; zend_hash_move_forward_ex(&EG(regular_list), &pos)) { zend_resource *rsrc = Z_RES_P(zv); if (rsrc->type == le_pinba_timer) { t = (pinba_timer_t *)rsrc->ptr; if (t->deleted || ((flag & PINBA_FLUSH_ONLY_STOPPED_TIMERS) != 0 && t->started)) { continue; } /* refcount++ */ #if PHP_VERSION_ID < 70300 GC_REFCOUNT(rsrc)++; #else GC_ADDREF(rsrc); #endif add_next_index_resource(return_value, rsrc); } } return; } /* }}} */ /* {{{ proto bool pinba_script_name_set(string custom_script_name) Set custom script name */ static PHP_FUNCTION(pinba_script_name_set) { char *script_name; size_t script_name_len; if (zend_parse_parameters(ZEND_NUM_ARGS(), "s", &script_name, &script_name_len) != SUCCESS) { return; } if (PINBA_G(script_name)) { efree(PINBA_G(script_name)); } PINBA_G(script_name) = estrndup(script_name, script_name_len); RETURN_TRUE; } /* }}} */ /* {{{ proto bool pinba_hostname_set(string custom_hostname) Set custom hostname */ static PHP_FUNCTION(pinba_hostname_set) { char *hostname; size_t hostname_len; if (zend_parse_parameters(ZEND_NUM_ARGS(), "s", &hostname, &hostname_len) != SUCCESS) { return; } if (hostname_len < sizeof(PINBA_G(host_name))) { memcpy(PINBA_G(host_name), hostname, hostname_len); PINBA_G(host_name)[hostname_len] = '\0'; } else { memcpy(PINBA_G(host_name), hostname, sizeof(PINBA_G(host_name)) - 1); PINBA_G(host_name)[sizeof(PINBA_G(host_name)) - 1] = '\0'; } RETURN_TRUE; } /* }}} */ /* {{{ proto bool pinba_schema_set(string custom_schema) Set custom schema */ static PHP_FUNCTION(pinba_schema_set) { char *schema; size_t schema_len; if (zend_parse_parameters(ZEND_NUM_ARGS(), "s", &schema, &schema_len) != SUCCESS) { return; } if (schema_len < sizeof(PINBA_G(schema))) { memcpy(PINBA_G(schema), schema, schema_len); PINBA_G(schema)[schema_len] = '\0'; } else { memcpy(PINBA_G(schema), schema, sizeof(PINBA_G(schema)) - 1); PINBA_G(schema)[sizeof(PINBA_G(schema)) - 1] = '\0'; } RETURN_TRUE; } /* }}} */ /* {{{ proto bool pinba_server_name_set(string custom_server_name) Set custom server name */ static PHP_FUNCTION(pinba_server_name_set) { char *server_name; size_t server_name_len; if (zend_parse_parameters(ZEND_NUM_ARGS(), "s", &server_name, &server_name_len) != SUCCESS) { return; } if (PINBA_G(server_name)) { efree(PINBA_G(server_name)); } PINBA_G(server_name) = estrndup(server_name, server_name_len); RETURN_TRUE; } /* }}} */ /* {{{ proto bool pinba_request_time_set(float time) Set custom request time */ static PHP_FUNCTION(pinba_request_time_set) { double time; if (zend_parse_parameters(ZEND_NUM_ARGS(), "d", &time) != SUCCESS) { return; } if (time < 0) { php_error_docref(NULL, E_WARNING, "negative request time value passed (%f), changing it to 0", time); time = 0; } PINBA_G(request_time) = time; RETURN_TRUE; } /* }}} */ /* {{{ proto bool pinba_tag_set(string tag, string value) Set request tag */ static PHP_FUNCTION(pinba_tag_set) { char *tag, *value; size_t tag_len, value_len; if (zend_parse_parameters(ZEND_NUM_ARGS(), "ss", &tag, &tag_len, &value, &value_len) != SUCCESS) { return; } if (tag_len < 1) { php_error_docref(NULL, E_WARNING, "tag name cannot be empty"); RETURN_FALSE; } /* store the copy */ value = estrndup(value, value_len); zend_hash_str_update_ptr(&PINBA_G(tags), tag, tag_len, value); RETURN_TRUE; } /* }}} */ /* {{{ proto string pinba_tag_get(string tag) Get previously set request tag value */ static PHP_FUNCTION(pinba_tag_get) { char *tag, *value; size_t tag_len; if (zend_parse_parameters(ZEND_NUM_ARGS(), "s", &tag, &tag_len) != SUCCESS) { return; } value = zend_hash_str_find_ptr(&PINBA_G(tags), tag, tag_len); if (!value) { RETURN_FALSE; } RETURN_STRING(value); } /* }}} */ /* {{{ proto bool pinba_tag_delete(string tag) Delete previously set request tag */ static PHP_FUNCTION(pinba_tag_delete) { char *tag; size_t tag_len; if (zend_parse_parameters(ZEND_NUM_ARGS(), "s", &tag, &tag_len) != SUCCESS) { return; } if (zend_hash_str_del(&PINBA_G(tags), tag, tag_len) == FAILURE) { RETURN_FALSE; } RETURN_TRUE; } /* }}} */ /* {{{ proto array pinba_tags_get(string tag) List all request tags */ static PHP_FUNCTION(pinba_tags_get) { char *value; HashPosition pos; if (zend_parse_parameters(ZEND_NUM_ARGS(), "") != SUCCESS) { return; } array_init(return_value); for (zend_hash_internal_pointer_reset_ex(&PINBA_G(tags), &pos); (value = zend_hash_get_current_data_ptr_ex(&PINBA_G(tags), &pos)) != NULL; zend_hash_move_forward_ex(&PINBA_G(tags), &pos)) { zend_string *key; zend_ulong dummy; if (zend_hash_get_current_key_ex(&PINBA_G(tags), &key, &dummy, &pos) == HASH_KEY_IS_STRING) { add_assoc_string_ex(return_value, key->val, key->len, value); } else { continue; } } } /* }}} */ /* {{{ proto PinbaClient::__construct(servers) */ static PHP_METHOD(PinbaClient, __construct) { zval *servers; zval *tmp; pinba_collector *new_collector; pinba_client_t *client; long flags = 0; ZEND_PARSE_PARAMETERS_START(1, 2) Z_PARAM_ARRAY_EX(servers, 0, 1) Z_PARAM_OPTIONAL Z_PARAM_LONG(flags) ZEND_PARSE_PARAMETERS_END_EX(RETURN_FALSE); client = Z_PINBACLIENT_P(getThis()); client->flags = flags; for (zend_hash_internal_pointer_reset(Z_ARRVAL_P(servers)); (tmp = zend_hash_get_current_data(Z_ARRVAL_P(servers))) != NULL; zend_hash_move_forward(Z_ARRVAL_P(servers))) { char *host, *port, *address_copy; zend_string *str = zval_get_string(tmp); address_copy = estrndup(str->val, str->len); if (php_pinba_parse_server(address_copy, &host, &port) != SUCCESS) { efree(address_copy); zend_string_release(str); continue; } zend_string_release(str); new_collector = php_pinba_collector_add(client->collectors, &client->n_collectors); if (new_collector == NULL) { efree(address_copy); break; } new_collector->host = strdup(host); new_collector->port = (port == NULL) ? strdup(PINBA_COLLECTOR_DEFAULT_PORT) : strdup(port); efree(address_copy); } } /* }}} */ #define SET_METHOD_STR(name, attr_name) \ static PHP_METHOD(PinbaClient, name) \ { \ pinba_client_t *client; \ char *value; \ size_t value_len; \ \ if (zend_parse_parameters(ZEND_NUM_ARGS(), "s", &value, &value_len) != SUCCESS) { \ return; \ } \ client = Z_PINBACLIENT_P(getThis()); \ \ if (client->attr_name) { \ efree(client->attr_name); \ } \ client->attr_name = estrndup(value, value_len); \ RETURN_TRUE; \ } SET_METHOD_STR(setHostname, hostname); SET_METHOD_STR(setServername, server_name); SET_METHOD_STR(setScriptname, script_name); SET_METHOD_STR(setSchema, schema); #define SET_METHOD_NUM(name, attr_name, type, type_letter) \ static PHP_METHOD(PinbaClient, name) \ { \ pinba_client_t *client; \ type value; \ \ if (zend_parse_parameters(ZEND_NUM_ARGS(), type_letter, &value) != SUCCESS) { \ return; \ } \ client = Z_PINBACLIENT_P(getThis()); \ \ if (value < 0) { \ php_error_docref(NULL, E_WARNING, #attr_name " cannot be less than zero"); \ RETURN_FALSE; \ } \ client->attr_name = value; \ RETURN_TRUE; \ } SET_METHOD_NUM(setRequestCount, request_count, long, "l"); SET_METHOD_NUM(setMemoryFootprint, memory_footprint, long, "l"); SET_METHOD_NUM(setMemoryPeak, memory_peak, long, "l"); SET_METHOD_NUM(setDocumentSize, document_size, long, "l"); SET_METHOD_NUM(setStatus, status, long, "l"); SET_METHOD_NUM(setRequestTime, request_time, double, "d"); /* {{{ proto bool PinbaClient::setRusage(array rusage) */ static PHP_METHOD(PinbaClient, setRusage) { zval *rusage; pinba_client_t *client; zval *tmp; int i; ZEND_PARSE_PARAMETERS_START(1, 1) Z_PARAM_ARRAY_EX(rusage, 0, 1) ZEND_PARSE_PARAMETERS_END_EX(RETURN_FALSE); client = Z_PINBACLIENT_P(getThis()); if (zend_hash_num_elements(Z_ARRVAL_P(rusage)) != 2) { php_error_docref(NULL, E_WARNING, "rusage array must contain exactly 2 elements"); RETURN_FALSE; } for (zend_hash_internal_pointer_reset(Z_ARRVAL_P(rusage)), i = 0; ((tmp = zend_hash_get_current_data(Z_ARRVAL_P(rusage))) != NULL) && i < 2; zend_hash_move_forward(Z_ARRVAL_P(rusage)), i++) { client->rusage[i] = zval_get_double(tmp); } RETURN_TRUE; } /* }}} */ /* {{{ proto bool PinbaClient::setTag(string name, string value) */ static PHP_METHOD(PinbaClient, setTag) { pinba_client_t *client; char *tag, *value; size_t tag_len, value_len; if (zend_parse_parameters(ZEND_NUM_ARGS(), "ss", &tag, &tag_len, &value, &value_len) != SUCCESS) { return; } client = Z_PINBACLIENT_P(getThis()); /* store the copy */ value = estrndup(value, value_len); zend_hash_str_update_ptr(&client->tags, tag, tag_len, value); RETURN_TRUE; } /* }}} */ static void php_pinba_client_timer_add_set(INTERNAL_FUNCTION_PARAMETERS, int add) /* {{{ */ { pinba_client_t *client; long hit_count = 1; double value, ru_utime = 0, ru_stime = 0; zval *tags, *rusage = NULL; char *hashed_tags; size_t hashed_tags_len, i, tags_num; zval *tmp; pinba_timer_t *timer; pinba_timer_tag_t **new_tags; ZEND_PARSE_PARAMETERS_START(2, 4) Z_PARAM_ARRAY_EX(tags, 0, 1) Z_PARAM_DOUBLE(value) Z_PARAM_OPTIONAL Z_PARAM_ARRAY_EX(rusage, 0, 1) Z_PARAM_LONG(hit_count) ZEND_PARSE_PARAMETERS_END_EX(RETURN_FALSE); client = Z_PINBACLIENT_P(getThis()); tags_num = zend_hash_num_elements(Z_ARRVAL_P(tags)); if (!tags_num) { php_error_docref(NULL, E_WARNING, "timer tags array cannot be empty"); RETURN_FALSE; } if (value < 0) { php_error_docref(NULL, E_WARNING, "timer value cannot be less than 0"); RETURN_FALSE; } if (hit_count < 0) { php_error_docref(NULL, E_WARNING, "timer hit count cannot be less than 0"); RETURN_FALSE; } if (rusage && zend_hash_num_elements(Z_ARRVAL_P(rusage)) != 2) { php_error_docref(NULL, E_WARNING, "rusage array must contain exactly 2 elements"); RETURN_FALSE; } if (rusage) { for (zend_hash_internal_pointer_reset(Z_ARRVAL_P(rusage)), i = 0; ((tmp = zend_hash_get_current_data(Z_ARRVAL_P(rusage))) != NULL) && i < 2; zend_hash_move_forward(Z_ARRVAL_P(rusage)), i++) { if (i == 0) { ru_utime = zval_get_double(tmp); } else { ru_stime = zval_get_double(tmp); } } } if (php_pinba_array_to_tags(Z_ARRVAL_P(tags), &new_tags) != SUCCESS) { RETURN_FALSE; } if (php_pinba_tags_to_hashed_string(new_tags, tags_num, &hashed_tags, &hashed_tags_len) != SUCCESS) { php_pinba_timer_tags_dtor(new_tags, tags_num); efree(new_tags); RETURN_FALSE; } timer = ecalloc(1, sizeof(pinba_timer_t)); float_to_timeval(value, timer->value); float_to_timeval(ru_utime, timer->ru_utime); float_to_timeval(ru_stime, timer->ru_stime); timer->tags = new_tags; timer->tags_num = tags_num; timer->hit_count = hit_count; if (add) { pinba_timer_t *old_t; old_t = zend_hash_str_find_ptr(&client->timers, hashed_tags, hashed_tags_len); if (old_t != NULL) { timeradd(&old_t->value, &timer->value, &old_t->value); timeradd(&old_t->ru_utime, &timer->ru_utime, &old_t->ru_utime); timeradd(&old_t->ru_stime, &timer->ru_stime, &old_t->ru_stime); if (timer->hit_count) { old_t->hit_count += timer->hit_count; } else { old_t->hit_count++; } php_pinba_timer_dtor(timer); efree(timer); } else { zend_hash_str_add_ptr(&client->timers, hashed_tags, hashed_tags_len, timer); } } else { zend_hash_str_update_ptr(&client->timers, hashed_tags, hashed_tags_len, timer); } efree(hashed_tags); RETURN_TRUE; } /* }}} */ /* {{{ proto bool PinbaClient::setTimer(array tags, float value[, array rusage[, int hit_count]]) */ static PHP_METHOD(PinbaClient, setTimer) { php_pinba_client_timer_add_set(INTERNAL_FUNCTION_PARAM_PASSTHRU, 0); } /* }}} */ /* {{{ proto bool PinbaClient::addTimer(array tags, float value[, array rusage[, int hit_count]]) */ static PHP_METHOD(PinbaClient, addTimer) { php_pinba_client_timer_add_set(INTERNAL_FUNCTION_PARAM_PASSTHRU, 1); } /* }}} */ /* {{{ proto bool PinbaClient::send([int flags]) */ static PHP_METHOD(PinbaClient, send) { pinba_client_t *client; long flags = 0; if (zend_parse_parameters(ZEND_NUM_ARGS(), "|l", &flags) != SUCCESS) { return; } client = Z_PINBACLIENT_P(getThis()); if (client->n_collectors == 0) { RETURN_FALSE; } /* no need to reinitialize collectors on every send */ if (!client->collectors_initialized) { if (php_pinba_init_socket(client->collectors, client->n_collectors) != SUCCESS) { RETURN_FALSE; } client->collectors_initialized = 1; } /* if set, flags override flags set in the constructor */ if (!flags && client->flags > 0) { flags = client->flags; } php_pinba_req_data_send(client, NULL, flags); RETURN_TRUE; } /* }}} */ /* {{{ proto string PinbaClient::getData([int flags]) */ static PHP_METHOD(PinbaClient, getData) { pinba_client_t *client; Pinba__Request *request; long flags = 0; char *data; int data_len; if (zend_parse_parameters(ZEND_NUM_ARGS(), "|l", &flags) != SUCCESS) { return; } client = Z_PINBACLIENT_P(getThis()); request = php_create_pinba_packet(client, NULL, flags); if (!request) { RETURN_FALSE; } PINBA_PACK(request, data, data_len); RETVAL_STRINGL(data, data_len); PINBA_FREE_BUFFER(); pinba__request__free_unpacked(request, NULL); } /* }}} */ /* {{{ arginfo */ ZEND_BEGIN_ARG_INFO_EX(arginfo_pinba_timer_start, 0, 0, 1) ZEND_ARG_INFO(0, tags) ZEND_ARG_INFO(0, data) ZEND_ARG_INFO(0, hit_count) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO_EX(arginfo_pinba_timer_add, 0, 0, 2) ZEND_ARG_INFO(0, tags) ZEND_ARG_INFO(0, value) ZEND_ARG_INFO(0, data) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO_EX(arginfo_pinba_timer_stop, 0, 0, 1) ZEND_ARG_INFO(0, timer) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO_EX(arginfo_pinba_timer_delete, 0, 0, 1) ZEND_ARG_INFO(0, timer) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO_EX(arginfo_pinba_timer_data_merge, 0, 0, 2) ZEND_ARG_INFO(0, timer) ZEND_ARG_INFO(0, data) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO_EX(arginfo_pinba_timer_data_replace, 0, 0, 2) ZEND_ARG_INFO(0, timer) ZEND_ARG_INFO(0, data) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO_EX(arginfo_pinba_timer_tags_merge, 0, 0, 2) ZEND_ARG_INFO(0, timer) ZEND_ARG_INFO(0, tags) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO_EX(arginfo_pinba_timer_tags_replace, 0, 0, 2) ZEND_ARG_INFO(0, timer) ZEND_ARG_INFO(0, tags) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO_EX(arginfo_pinba_flush, 0, 0, 0) ZEND_ARG_INFO(0, custom_script_name) ZEND_ARG_INFO(0, flags) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO_EX(arginfo_pinba_reset, 0, 0, 0) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO_EX(arginfo_pinba_get_info, 0, 0, 0) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO_EX(arginfo_pinba_get_data, 0, 0, 0) ZEND_ARG_INFO(0, flags) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO_EX(arginfo_pinba_timer_get_info, 0, 0, 1) ZEND_ARG_INFO(0, timer) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO_EX(arginfo_pinba_timers_stop, 0, 0, 0) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO_EX(arginfo_pinba_timers_get, 0, 0, 0) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO_EX(arginfo_pinba_script_name_set, 0, 0, 1) ZEND_ARG_INFO(0, custom_script_name) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO_EX(arginfo_pinba_hostname_set, 0, 0, 1) ZEND_ARG_INFO(0, custom_hostname) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO_EX(arginfo_pinba_schema_set, 0, 0, 1) ZEND_ARG_INFO(0, custom_schema) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO_EX(arginfo_pinba_server_name_set, 0, 0, 1) ZEND_ARG_INFO(0, custom_server_name) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO_EX(arginfo_pinba_request_time_set, 0, 0, 1) ZEND_ARG_INFO(0, request_time) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO_EX(arginfo_pinba_tag_set, 0, 0, 2) ZEND_ARG_INFO(0, tag) ZEND_ARG_INFO(0, value) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO_EX(arginfo_pinba_tag_get, 0, 0, 1) ZEND_ARG_INFO(0, tag) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO_EX(arginfo_pinba_tag_delete, 0, 0, 1) ZEND_ARG_INFO(0, tag) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO_EX(arginfo_pinba_tags_get, 0, 0, 0) ZEND_END_ARG_INFO() /* }}} */ #define PINBA_FUNC(func) PHP_FE(func, arginfo_ ## func) /* {{{ pinba_functions[] */ zend_function_entry pinba_functions[] = { PINBA_FUNC(pinba_timer_start) PINBA_FUNC(pinba_timer_add) PINBA_FUNC(pinba_timer_stop) PINBA_FUNC(pinba_timer_delete) PINBA_FUNC(pinba_timer_data_merge) PINBA_FUNC(pinba_timer_data_replace) PINBA_FUNC(pinba_timer_tags_merge) PINBA_FUNC(pinba_timer_tags_replace) PINBA_FUNC(pinba_flush) PINBA_FUNC(pinba_reset) PINBA_FUNC(pinba_get_info) PINBA_FUNC(pinba_get_data) PINBA_FUNC(pinba_timer_get_info) PINBA_FUNC(pinba_timers_stop) PINBA_FUNC(pinba_timers_get) PINBA_FUNC(pinba_script_name_set) PINBA_FUNC(pinba_hostname_set) PINBA_FUNC(pinba_server_name_set) PINBA_FUNC(pinba_schema_set) PINBA_FUNC(pinba_request_time_set) PINBA_FUNC(pinba_tag_set) PINBA_FUNC(pinba_tag_get) PINBA_FUNC(pinba_tag_delete) PINBA_FUNC(pinba_tags_get) {NULL, NULL, NULL} }; /* }}} */ /* {{{ arginfo */ ZEND_BEGIN_ARG_INFO_EX(arginfo___construct, 0, 0, 1) ZEND_ARG_INFO(0, servers) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO_EX(arginfo_setvalue, 0, 0, 1) ZEND_ARG_INFO(0, value) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO_EX(arginfo_settag, 0, 0, 2) ZEND_ARG_INFO(0, tag) ZEND_ARG_INFO(0, value) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO_EX(arginfo_settimer, 0, 0, 2) ZEND_ARG_INFO(0, tags) ZEND_ARG_INFO(0, value) ZEND_ARG_INFO(0, rusage) ZEND_ARG_INFO(0, hit_count) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO_EX(arginfo_send, 0, 0, 0) ZEND_ARG_INFO(0, flags) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO_EX(arginfo_getdata, 0, 0, 0) ZEND_ARG_INFO(0, flags) ZEND_END_ARG_INFO() /* }}} */ /* {{{ pinba_client_methods[] */ zend_function_entry pinba_client_methods[] = { PHP_ME(PinbaClient, __construct, arginfo___construct, ZEND_ACC_PUBLIC) PHP_ME(PinbaClient, setHostname, arginfo_setvalue, ZEND_ACC_PUBLIC) PHP_ME(PinbaClient, setScriptname, arginfo_setvalue, ZEND_ACC_PUBLIC) PHP_ME(PinbaClient, setServername, arginfo_setvalue, ZEND_ACC_PUBLIC) PHP_ME(PinbaClient, setRequestCount, arginfo_setvalue, ZEND_ACC_PUBLIC) PHP_ME(PinbaClient, setDocumentSize, arginfo_setvalue, ZEND_ACC_PUBLIC) PHP_ME(PinbaClient, setMemoryPeak, arginfo_setvalue, ZEND_ACC_PUBLIC) PHP_ME(PinbaClient, setMemoryFootprint, arginfo_setvalue, ZEND_ACC_PUBLIC) PHP_ME(PinbaClient, setRusage, arginfo_setvalue, ZEND_ACC_PUBLIC) PHP_ME(PinbaClient, setRequestTime, arginfo_setvalue, ZEND_ACC_PUBLIC) PHP_ME(PinbaClient, setStatus, arginfo_setvalue, ZEND_ACC_PUBLIC) PHP_ME(PinbaClient, setSchema, arginfo_setvalue, ZEND_ACC_PUBLIC) PHP_ME(PinbaClient, setTag, arginfo_settag, ZEND_ACC_PUBLIC) PHP_ME(PinbaClient, setTimer, arginfo_settimer, ZEND_ACC_PUBLIC) PHP_ME(PinbaClient, addTimer, arginfo_settimer, ZEND_ACC_PUBLIC) PHP_ME(PinbaClient, send, arginfo_send, ZEND_ACC_PUBLIC) PHP_ME(PinbaClient, getData, arginfo_getdata, ZEND_ACC_PUBLIC) {NULL, NULL, NULL} }; /* }}} */ static void php_pinba_sa_dtor(zval *zv) /* {{{ */ { pinba_sockaddr *sa = Z_PTR_P(zv); if (sa->fd >= 0) { close(sa->fd); } free(sa); } /* }}} */ static PHP_INI_MH(OnUpdateCollectorAddress) /* {{{ */ { char *copy; /* copy of the passed value, so that we can mangle it at will */ char *address; /* address, split off the space separated string */ char *new_node; char *new_service; char *tmp; pinba_collector *new_collector; if (new_value == NULL) { return FAILURE; } copy = strndup(new_value->val, new_value->len); if (copy == NULL) { return FAILURE; } php_pinba_cleanup_collectors(PINBA_G(collectors), &PINBA_G(n_collectors)); for (tmp = copy; (address = strsep(&tmp, ", ")) && (address[0] != '\0'); /**/) { if (php_pinba_parse_server(address, &new_node, &new_service) != SUCCESS) { free(copy); return FAILURE; } new_collector = php_pinba_collector_add(PINBA_G(collectors), &PINBA_G(n_collectors)); if (new_collector == NULL) { /* TODO: log that max collectors has been reached and recompilation is required (will never happen) */ free(copy); return FAILURE; } new_collector->host = strdup(new_node); new_collector->port = (new_service == NULL) ? strdup(PINBA_COLLECTOR_DEFAULT_PORT) : strdup(new_service); } free(copy); /* Sets "collector_address", I assume */ return OnUpdateString(entry, new_value, mh_arg1, mh_arg2, mh_arg3, stage); } /* }}} */ /* {{{ PHP_INI */ PHP_INI_BEGIN() STD_PHP_INI_ENTRY("pinba.server", NULL, PHP_INI_ALL, OnUpdateCollectorAddress, collector_address, zend_pinba_globals, pinba_globals) STD_PHP_INI_ENTRY("pinba.resolve_interval", "60", PHP_INI_ALL, OnUpdateLongGEZero, resolve_interval, zend_pinba_globals, pinba_globals) STD_PHP_INI_ENTRY("pinba.enabled", "0", PHP_INI_ALL, OnUpdateBool, enabled, zend_pinba_globals, pinba_globals) STD_PHP_INI_ENTRY("pinba.auto_flush", "1", PHP_INI_ALL, OnUpdateBool, auto_flush, zend_pinba_globals, pinba_globals) PHP_INI_END() /* }}} */ /* {{{ php_pinba_init_globals */ static void php_pinba_init_globals(zend_pinba_globals *globals) { memset(globals, 0, sizeof(*globals)); globals->timers_stopped = 0; globals->server_name = NULL; globals->script_name = NULL; } /* }}} */ /* {{{ PHP_MINIT_FUNCTION */ static PHP_MINIT_FUNCTION(pinba) { zend_class_entry ce; ZEND_INIT_MODULE_GLOBALS(pinba, php_pinba_init_globals, NULL); REGISTER_INI_ENTRIES(); le_pinba_timer = zend_register_list_destructors_ex(php_timer_resource_dtor, NULL, "pinba timer", module_number); REGISTER_LONG_CONSTANT("PINBA_FLUSH_ONLY_STOPPED_TIMERS", PINBA_FLUSH_ONLY_STOPPED_TIMERS, CONST_CS | CONST_PERSISTENT); REGISTER_LONG_CONSTANT("PINBA_FLUSH_RESET_DATA", PINBA_FLUSH_RESET_DATA, CONST_CS | CONST_PERSISTENT); REGISTER_LONG_CONSTANT("PINBA_ONLY_STOPPED_TIMERS", PINBA_FLUSH_ONLY_STOPPED_TIMERS, CONST_CS | CONST_PERSISTENT); REGISTER_LONG_CONSTANT("PINBA_ONLY_RUNNING_TIMERS", PINBA_ONLY_RUNNING_TIMERS, CONST_CS | CONST_PERSISTENT); REGISTER_LONG_CONSTANT("PINBA_AUTO_FLUSH", PINBA_AUTO_FLUSH, CONST_CS | CONST_PERSISTENT); #if PHP_VERSION_ID >= 50400 old_sapi_ub_write = sapi_module.ub_write; sapi_module.ub_write = sapi_ub_write_counter; #endif INIT_CLASS_ENTRY(ce, "PinbaClient", pinba_client_methods); pinba_client_ce = zend_register_internal_class_ex(&ce, NULL); pinba_client_ce->create_object = pinba_client_new; memcpy(&pinba_client_handlers, zend_get_std_object_handlers(), sizeof(zend_object_handlers)); pinba_client_handlers.dtor_obj = pinba_client_object_dtor; pinba_client_handlers.free_obj = pinba_client_free_storage; pinba_client_handlers.clone_obj = NULL; pinba_client_handlers.offset = XtOffsetOf(pinba_client_t, std); zend_hash_init(&resolver_cache, 10, NULL, php_pinba_sa_dtor, 1); return SUCCESS; } /* }}} */ /* {{{ PHP_MSHUTDOWN_FUNCTION */ static PHP_MSHUTDOWN_FUNCTION(pinba) { UNREGISTER_INI_ENTRIES(); php_pinba_cleanup_collectors(PINBA_G(collectors), &PINBA_G(n_collectors)); zend_hash_destroy(&resolver_cache); return SUCCESS; } /* }}} */ /* {{{ PHP_RINIT_FUNCTION */ static PHP_RINIT_FUNCTION(pinba) { zval *tmp; struct timeval t; struct rusage u; PINBA_G(timers_stopped) = 0; PINBA_G(in_rshutdown) = 0; PINBA_G(request_time) = 0; if (gettimeofday(&t, 0) == 0) { timeval_cvt(&(PINBA_G(tmp_req_data).req_start), &t); } else { return FAILURE; } if (getrusage(RUSAGE_SELF, &u) == 0) { timeval_cvt(&(PINBA_G(tmp_req_data).ru_utime), &u.ru_utime); timeval_cvt(&(PINBA_G(tmp_req_data).ru_stime), &u.ru_stime); } else { return FAILURE; } zend_hash_init(&PINBA_G(timers), 10, NULL, NULL, 0); zend_hash_init(&PINBA_G(tags), 10, NULL, php_tag_hash_dtor, 0); PINBA_G(tmp_req_data).doc_size = 0; PINBA_G(tmp_req_data).mem_peak_usage= 0; PINBA_G(server_name) = NULL; PINBA_G(script_name) = NULL; gethostname(PINBA_G(host_name), sizeof(PINBA_G(host_name))); PINBA_G(host_name)[sizeof(PINBA_G(host_name)) - 1] = '\0'; if (zend_is_auto_global_str("_SERVER", sizeof("_SERVER") - 1)) { tmp = zend_hash_str_find(HASH_OF(&PG(http_globals)[TRACK_VARS_SERVER]), "SCRIPT_NAME", sizeof("SCRIPT_NAME")-1); if (tmp && Z_TYPE_P(tmp) == IS_STRING && Z_STRLEN_P(tmp) > 0) { PINBA_G(script_name) = estrndup(Z_STRVAL_P(tmp), Z_STRLEN_P(tmp)); } tmp = zend_hash_str_find(HASH_OF(&PG(http_globals)[TRACK_VARS_SERVER]), "SERVER_NAME", sizeof("SERVER_NAME")-1); if (tmp != NULL && Z_TYPE_P(tmp) == IS_STRING && Z_STRLEN_P(tmp) > 0) { PINBA_G(server_name) = estrndup(Z_STRVAL_P(tmp), Z_STRLEN_P(tmp)); } } return SUCCESS; } /* }}} */ /* {{{ PHP_RSHUTDOWN_FUNCTION */ static PHP_RSHUTDOWN_FUNCTION(pinba) { if (PINBA_G(auto_flush)) { php_pinba_flush_data(NULL, 0); } zend_hash_destroy(&PINBA_G(timers)); zend_hash_destroy(&PINBA_G(tags)); #if PHP_VERSION_ID < 50400 OG(php_header_write) = PINBA_G(old_sapi_ub_write); #endif if (PINBA_G(server_name)) { efree(PINBA_G(server_name)); PINBA_G(server_name) = NULL; } if (PINBA_G(script_name)) { efree(PINBA_G(script_name)); PINBA_G(script_name) = NULL; } PINBA_G(in_rshutdown) = 1; return SUCCESS; } /* }}} */ /* {{{ PHP_MINFO_FUNCTION */ static PHP_MINFO_FUNCTION(pinba) { php_info_print_table_start(); php_info_print_table_header(2, "Pinba support", "enabled"); php_info_print_table_row(2, "Extension version", PHP_PINBA_VERSION); php_info_print_table_end(); DISPLAY_INI_ENTRIES(); } /* }}} */ /* {{{ pinba_module_entry */ zend_module_entry pinba_module_entry = { #if ZEND_MODULE_API_NO >= 20010901 STANDARD_MODULE_HEADER, #endif "pinba", pinba_functions, PHP_MINIT(pinba), PHP_MSHUTDOWN(pinba), PHP_RINIT(pinba), PHP_RSHUTDOWN(pinba), PHP_MINFO(pinba), #if ZEND_MODULE_API_NO >= 20010901 PHP_PINBA_VERSION, #endif STANDARD_MODULE_PROPERTIES }; /* }}} */ /* * Local variables: * tab-width: 4 * c-basic-offset: 4 * End: * vim600: sw=4 ts=4 fdm=marker * vim<600: sw=4 ts=4 */ php-pinba-1.1.2/pinba.pb-c.h000066400000000000000000000051421374247224700154710ustar00rootroot00000000000000/* Generated by the protocol buffer compiler. DO NOT EDIT! */ #ifndef PROTOBUF_C_pinba_2eproto__INCLUDED #define PROTOBUF_C_pinba_2eproto__INCLUDED #include "protobuf-c.h" PROTOBUF_C_BEGIN_DECLS typedef struct _Pinba__Request Pinba__Request; /* --- enums --- */ /* --- messages --- */ struct _Pinba__Request { ProtobufCMessage base; char *hostname; char *server_name; char *script_name; uint32_t request_count; uint32_t document_size; uint32_t memory_peak; float request_time; float ru_utime; float ru_stime; size_t n_timer_hit_count; uint32_t *timer_hit_count; size_t n_timer_value; float *timer_value; size_t n_timer_tag_count; uint32_t *timer_tag_count; size_t n_timer_tag_name; uint32_t *timer_tag_name; size_t n_timer_tag_value; uint32_t *timer_tag_value; size_t n_dictionary; char **dictionary; protobuf_c_boolean has_status; uint32_t status; protobuf_c_boolean has_memory_footprint; uint32_t memory_footprint; size_t n_requests; Pinba__Request **requests; char *schema; size_t n_tag_name; uint32_t *tag_name; size_t n_tag_value; uint32_t *tag_value; size_t n_timer_ru_utime; float *timer_ru_utime; size_t n_timer_ru_stime; float *timer_ru_stime; }; #define PINBA__REQUEST__INIT \ { PROTOBUF_C_MESSAGE_INIT (&pinba__request__descriptor) \ , NULL, NULL, NULL, 0, 0, 0, 0, 0, 0, 0,NULL, 0,NULL, 0,NULL, 0,NULL, 0,NULL, 0,NULL, 0,0, 0,0, 0,NULL, NULL, 0,NULL, 0,NULL, 0,NULL, 0,NULL } /* Pinba__Request methods */ void pinba__request__init (Pinba__Request *message); size_t pinba__request__get_packed_size (const Pinba__Request *message); size_t pinba__request__pack (const Pinba__Request *message, uint8_t *out); size_t pinba__request__pack_to_buffer (const Pinba__Request *message, ProtobufCBuffer *buffer); Pinba__Request * pinba__request__unpack (ProtobufCAllocator *allocator, size_t len, const uint8_t *data); void pinba__request__free_unpacked (Pinba__Request *message, ProtobufCAllocator *allocator); /* --- per-message closures --- */ typedef void (*Pinba__Request_Closure) (const Pinba__Request *message, void *closure_data); /* --- services --- */ /* --- descriptors --- */ extern const ProtobufCMessageDescriptor pinba__request__descriptor; PROTOBUF_C_END_DECLS #endif /* PROTOBUF_pinba_2eproto__INCLUDED */ php-pinba-1.1.2/pinba.proto000066400000000000000000000015131374247224700155630ustar00rootroot00000000000000package Pinba; option optimize_for = SPEED; message Request { required string hostname = 1; required string server_name = 2; required string script_name = 3; required uint32 request_count = 4; required uint32 document_size = 5; required uint32 memory_peak = 6; required float request_time = 7; required float ru_utime = 8; required float ru_stime = 9; repeated uint32 timer_hit_count = 10; repeated float timer_value = 11; repeated uint32 timer_tag_count = 12; repeated uint32 timer_tag_name = 13; repeated uint32 timer_tag_value = 14; repeated string dictionary = 15; optional uint32 status = 16; optional uint32 memory_footprint = 17; repeated Request requests = 18; optional string schema = 19; repeated uint32 tag_name = 20; repeated uint32 tag_value = 21; } php-pinba-1.1.2/protobuf-c-private.h000066400000000000000000000054411374247224700173120ustar00rootroot00000000000000/* --- protobuf-c-private.h: private structures and functions --- */ /* * Copyright 2008, Dave Benson. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with * the License. You may obtain a copy of the License * at http://www.apache.org/licenses/LICENSE-2.0 Unless * required by applicable law or agreed to in writing, * software distributed under the License is distributed on * an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ /* === needs to be declared for the PROTOBUF_C_BUFFER_SIMPLE_INIT macro === */ void protobuf_c_buffer_simple_append (ProtobufCBuffer *buffer, size_t len, const unsigned char *data); /* === stuff which needs to be declared for use in the generated code === */ struct _ProtobufCEnumValueIndex { const char *name; unsigned index; /* into values[] array */ }; /* IntRange: helper structure for optimizing int => index lookups in the case where the keys are mostly consecutive values, as they presumably are for enums and fields. The data structures assumes that the values in the original array are sorted */ struct _ProtobufCIntRange { int start_value; unsigned orig_index; /* NOTE: the number of values in the range can be inferred by looking at the next element's orig_index. a dummy element is added to make this simple */ }; /* === declared for exposition on ProtobufCIntRange === */ /* note: ranges must have an extra sentinel IntRange at the end whose orig_index is set to the number of actual values in the original array */ /* returns -1 if no orig_index found */ int protobuf_c_int_ranges_lookup (unsigned n_ranges, ProtobufCIntRange *ranges); #define PROTOBUF_C_SERVICE_DESCRIPTOR_MAGIC 0x14159bc3 #define PROTOBUF_C_MESSAGE_DESCRIPTOR_MAGIC 0x28aaeef9 #define PROTOBUF_C_ENUM_DESCRIPTOR_MAGIC 0x114315af /* === behind the scenes on the generated service's __init functions */ typedef void (*ProtobufCServiceDestroy) (ProtobufCService *service); void protobuf_c_service_generated_init (ProtobufCService *service, const ProtobufCServiceDescriptor *descriptor, ProtobufCServiceDestroy destroy); void protobuf_c_service_invoke_internal(ProtobufCService *service, unsigned method_index, const ProtobufCMessage *input, ProtobufCClosure closure, void *closure_data); php-pinba-1.1.2/protobuf-c.c000066400000000000000000001757511374247224700156510ustar00rootroot00000000000000/* --- protobuf-c.c: public protobuf c runtime implementation --- */ /* * Copyright 2008, Dave Benson. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with * the License. You may obtain a copy of the License * at http://www.apache.org/licenses/LICENSE-2.0 Unless * required by applicable law or agreed to in writing, * software distributed under the License is distributed on * an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ /* TODO: certain implementations use 32-bit math even for (uint64_size, uint64_pack, parse_uint64) */ /* TODO: get_packed_size and pack seem to use type-prefixed names, whereas parse uses type-suffixed names. pick one and stick with it. Decision: go with type-suffixed, since the type (or its instance) is typically the object of the verb. NOTE: perhaps the "parse" methods should be reanemd to "unpack" at the same time. */ #include /* for occasional printf()s */ #include /* for abort(), malloc() etc */ #include /* for strlen(), memcpy(), memmove() */ #ifndef PRINT_UNPACK_ERRORS #define PRINT_UNPACK_ERRORS 1 #endif #include "protobuf-c.h" #define MAX_UINT64_ENCODED_SIZE 10 /* convenience macros */ #define TMPALLOC(allocator, size) ((allocator)->tmp_alloc ((allocator)->allocator_data, (size))) #define FREE(allocator, ptr) \ do { if ((ptr) != NULL) ((allocator)->free ((allocator)->allocator_data, (ptr))); } while(0) #define UNALIGNED_ALLOC(allocator, size) ALLOC (allocator, size) /* placeholder */ #define STRUCT_MEMBER_P(struct_p, struct_offset) \ ((void *) ((uint8_t*) (struct_p) + (struct_offset))) #define STRUCT_MEMBER(member_type, struct_p, struct_offset) \ (*(member_type*) STRUCT_MEMBER_P ((struct_p), (struct_offset))) #define STRUCT_MEMBER_PTR(member_type, struct_p, struct_offset) \ ((member_type*) STRUCT_MEMBER_P ((struct_p), (struct_offset))) #define TRUE 1 #define FALSE 0 void (*protobuf_c_error_printer)(char *fmt, ...); static void alloc_failed_warning (unsigned size, const char *filename, unsigned line) { fprintf (stderr, "WARNING: out-of-memory allocating a block of size %u (%s:%u)\n", size, filename, line); } /* Try to allocate memory, running some special code if it fails. */ #define DO_ALLOC(dst, allocator, size, fail_code) \ { size_t da__allocation_size = (size); \ if (da__allocation_size == 0) \ dst = NULL; \ else if ((dst=((allocator)->alloc ((allocator)->allocator_data, \ da__allocation_size))) == NULL) \ { \ alloc_failed_warning (da__allocation_size, __FILE__, __LINE__); \ fail_code; \ } \ } #define DO_UNALIGNED_ALLOC DO_ALLOC /* placeholder */ #define ASSERT_IS_ENUM_DESCRIPTOR(desc) \ assert((desc)->magic == PROTOBUF_C_ENUM_DESCRIPTOR_MAGIC) #define ASSERT_IS_MESSAGE_DESCRIPTOR(desc) \ assert((desc)->magic == PROTOBUF_C_MESSAGE_DESCRIPTOR_MAGIC) #define ASSERT_IS_MESSAGE(message) \ ASSERT_IS_MESSAGE_DESCRIPTOR((message)->descriptor) #define ASSERT_IS_SERVICE_DESCRIPTOR(desc) \ assert((desc)->magic == PROTOBUF_C_SERVICE_DESCRIPTOR_MAGIC) /* --- allocator --- */ static void protobuf_c_out_of_memory_default (void) { fprintf (stderr, "Out Of Memory!!!\n"); abort (); } void (*protobuf_c_out_of_memory) (void) = protobuf_c_out_of_memory_default; static void *system_alloc(void *allocator_data, size_t size) { void *rv; (void) allocator_data; if (size == 0) return NULL; rv = malloc (size); if (rv == NULL) protobuf_c_out_of_memory (); return rv; } static void system_free (void *allocator_data, void *data) { (void) allocator_data; if (data) free (data); } /* Some users may configure the default allocator; providing your own allocator to unpack() is prefered. this allocator is still used for packing nested messages. */ ProtobufCAllocator protobuf_c_default_allocator = { system_alloc, system_free, NULL, 8192, NULL }; /* Users should NOT modify this structure, but it's difficult to prevent. please modify protobuf_c_default_allocator instead. */ ProtobufCAllocator protobuf_c_system_allocator = { system_alloc, system_free, NULL, 8192, NULL }; /* === buffer-simple === */ void protobuf_c_buffer_simple_append (ProtobufCBuffer *buffer, size_t len, const uint8_t *data) { ProtobufCBufferSimple *simp = (ProtobufCBufferSimple *) buffer; size_t new_len = simp->len + len; if (new_len > simp->alloced) { size_t new_alloced = simp->alloced * 2; uint8_t *new_data; while (new_alloced < new_len) new_alloced += new_alloced; DO_ALLOC (new_data, &protobuf_c_default_allocator, new_alloced, return); memcpy (new_data, simp->data, simp->len); if (simp->must_free_data) FREE (&protobuf_c_default_allocator, simp->data); else simp->must_free_data = 1; simp->data = new_data; simp->alloced = new_alloced; } memcpy (simp->data + simp->len, data, len); simp->len = new_len; } /* === get_packed_size() === */ /* Return the number of bytes required to store the tag for the field (which includes 3 bits for the wire-type, and a single bit that denotes the end-of-tag. */ static inline size_t get_tag_size (unsigned number) { if (number < (1<<4)) return 1; else if (number < (1<<11)) return 2; else if (number < (1<<18)) return 3; else if (number < (1<<25)) return 4; else return 5; } /* Return the number of bytes required to store a variable-length unsigned integer that fits in 32-bit uint in base-128 encoding. */ static inline size_t uint32_size (uint32_t v) { if (v < (1<<7)) return 1; else if (v < (1<<14)) return 2; else if (v < (1<<21)) return 3; else if (v < (1<<28)) return 4; else return 5; } /* Return the number of bytes required to store a variable-length signed integer that fits in 32-bit int in base-128 encoding. */ static inline size_t int32_size (int32_t v) { if (v < 0) return 10; else if (v < (1<<7)) return 1; else if (v < (1<<14)) return 2; else if (v < (1<<21)) return 3; else if (v < (1<<28)) return 4; else return 5; } /* return the zigzag-encoded 32-bit unsigned int from a 32-bit signed int */ static inline uint32_t zigzag32 (int32_t v) { if (v < 0) return ((uint32_t)(-v)) * 2 - 1; else return v * 2; } /* Return the number of bytes required to store a variable-length signed integer that fits in 32-bit int, converted to unsigned via the zig-zag algorithm, then packed using base-128 encoding. */ static inline size_t sint32_size (int32_t v) { return uint32_size(zigzag32(v)); } /* Return the number of bytes required to store a variable-length unsigned integer that fits in 64-bit uint in base-128 encoding. */ static inline size_t uint64_size (uint64_t v) { uint32_t upper_v = (v>>32); if (upper_v == 0) return uint32_size ((uint32_t)v); else if (upper_v < (1<<3)) return 5; else if (upper_v < (1<<10)) return 6; else if (upper_v < (1<<17)) return 7; else if (upper_v < (1<<24)) return 8; else if (upper_v < (1U<<31)) return 9; else return 10; } /* return the zigzag-encoded 64-bit unsigned int from a 64-bit signed int */ static inline uint64_t zigzag64 (int64_t v) { if (v < 0) return ((uint64_t)(-v)) * 2 - 1; else return v * 2; } /* Return the number of bytes required to store a variable-length signed integer that fits in 64-bit int, converted to unsigned via the zig-zag algorithm, then packed using base-128 encoding. */ static inline size_t sint64_size (int64_t v) { return uint64_size(zigzag64(v)); } /* Get serialized size of a single field in the message, including the space needed by the identifying tag. */ static size_t required_field_get_packed_size (const ProtobufCFieldDescriptor *field, const void *member) { size_t rv = get_tag_size (field->id); switch (field->type) { case PROTOBUF_C_TYPE_SINT32: return rv + sint32_size (*(const int32_t *) member); case PROTOBUF_C_TYPE_INT32: return rv + int32_size (*(const uint32_t *) member); case PROTOBUF_C_TYPE_UINT32: return rv + uint32_size (*(const uint32_t *) member); case PROTOBUF_C_TYPE_SINT64: return rv + sint64_size (*(const int64_t *) member); case PROTOBUF_C_TYPE_INT64: case PROTOBUF_C_TYPE_UINT64: return rv + uint64_size (*(const uint64_t *) member); case PROTOBUF_C_TYPE_SFIXED32: case PROTOBUF_C_TYPE_FIXED32: return rv + 4; case PROTOBUF_C_TYPE_SFIXED64: case PROTOBUF_C_TYPE_FIXED64: return rv + 8; case PROTOBUF_C_TYPE_BOOL: return rv + 1; case PROTOBUF_C_TYPE_FLOAT: return rv + 4; case PROTOBUF_C_TYPE_DOUBLE: return rv + 8; case PROTOBUF_C_TYPE_ENUM: // TODO: is this correct for negative-valued enums? return rv + uint32_size (*(const uint32_t *) member); case PROTOBUF_C_TYPE_STRING: { const char *str = *(char * const *) member; size_t len = str ? strlen (str) : 0; return rv + uint32_size (len) + len; } case PROTOBUF_C_TYPE_BYTES: { size_t len = ((const ProtobufCBinaryData*) member)->len; return rv + uint32_size (len) + len; } //case PROTOBUF_C_TYPE_GROUP: case PROTOBUF_C_TYPE_MESSAGE: { const ProtobufCMessage *msg = * (ProtobufCMessage * const *) member; size_t subrv = msg ? protobuf_c_message_get_packed_size (msg) : 0; return rv + uint32_size (subrv) + subrv; } } PROTOBUF_C_ASSERT_NOT_REACHED (); return 0; } /* Get serialized size of a single optional field in the message, including the space needed by the identifying tag. Returns 0 if the optional field isn't set. */ static size_t optional_field_get_packed_size (const ProtobufCFieldDescriptor *field, const protobuf_c_boolean *has, const void *member) { if (field->type == PROTOBUF_C_TYPE_MESSAGE || field->type == PROTOBUF_C_TYPE_STRING) { const void *ptr = * (const void * const *) member; if (ptr == NULL || ptr == field->default_value) return 0; } else { if (!*has) return 0; } return required_field_get_packed_size (field, member); } /* Get serialized size of a repeated field in the message, which may consist of any number of values (including 0). Includes the space needed by the identifying tags (as needed). */ static size_t repeated_field_get_packed_size (const ProtobufCFieldDescriptor *field, size_t count, const void *member) { size_t rv = get_tag_size (field->id) * count; unsigned i; void *array = * (void * const *) member; switch (field->type) { case PROTOBUF_C_TYPE_SINT32: for (i = 0; i < count; i++) rv += sint32_size (((int32_t*)array)[i]); break; case PROTOBUF_C_TYPE_INT32: for (i = 0; i < count; i++) rv += int32_size (((uint32_t*)array)[i]); break; case PROTOBUF_C_TYPE_UINT32: case PROTOBUF_C_TYPE_ENUM: for (i = 0; i < count; i++) rv += uint32_size (((uint32_t*)array)[i]); break; case PROTOBUF_C_TYPE_SINT64: for (i = 0; i < count; i++) rv += sint64_size (((int64_t*)array)[i]); break; case PROTOBUF_C_TYPE_INT64: case PROTOBUF_C_TYPE_UINT64: for (i = 0; i < count; i++) rv += uint64_size (((uint64_t*)array)[i]); break; case PROTOBUF_C_TYPE_SFIXED32: case PROTOBUF_C_TYPE_FIXED32: case PROTOBUF_C_TYPE_FLOAT: rv += 4 * count; break; case PROTOBUF_C_TYPE_SFIXED64: case PROTOBUF_C_TYPE_FIXED64: case PROTOBUF_C_TYPE_DOUBLE: rv += 8 * count; break; case PROTOBUF_C_TYPE_BOOL: rv += count; break; case PROTOBUF_C_TYPE_STRING: for (i = 0; i < count; i++) { size_t len = strlen (((char**) array)[i]); rv += uint32_size (len) + len; } break; case PROTOBUF_C_TYPE_BYTES: for (i = 0; i < count; i++) { size_t len = ((ProtobufCBinaryData*) array)[i].len; rv += uint32_size (len) + len; } break; case PROTOBUF_C_TYPE_MESSAGE: for (i = 0; i < count; i++) { size_t len = protobuf_c_message_get_packed_size (((ProtobufCMessage **) array)[i]); rv += uint32_size (len) + len; } break; //case PROTOBUF_C_TYPE_GROUP: // NOT SUPPORTED } return rv; } /* Get the packed size of a unknown field (meaning one that is passed through mostly uninterpreted... this is done for forward compatibilty with the addition of new fields). */ static inline size_t unknown_field_get_packed_size (const ProtobufCMessageUnknownField *field) { return get_tag_size (field->tag) + field->len; } /* Get the number of bytes that the message will occupy once serialized. */ size_t protobuf_c_message_get_packed_size(const ProtobufCMessage *message) { unsigned i; size_t rv = 0; ASSERT_IS_MESSAGE (message); for (i = 0; i < message->descriptor->n_fields; i++) { const ProtobufCFieldDescriptor *field = message->descriptor->fields + i; const void *member = ((const char *) message) + field->offset; const void *qmember = ((const char *) message) + field->quantifier_offset; if (field->label == PROTOBUF_C_LABEL_REQUIRED) rv += required_field_get_packed_size (field, member); else if (field->label == PROTOBUF_C_LABEL_OPTIONAL) rv += optional_field_get_packed_size (field, qmember, member); else rv += repeated_field_get_packed_size (field, * (const size_t *) qmember, member); } for (i = 0; i < message->n_unknown_fields; i++) rv += unknown_field_get_packed_size (&message->unknown_fields[i]); return rv; } /* === pack() === */ /* Pack an unsigned 32-bit integer in base-128 encoding, and return the number of bytes needed: this will be 5 or less. */ static inline size_t uint32_pack (uint32_t value, uint8_t *out) { unsigned rv = 0; if (value >= 0x80) { out[rv++] = value | 0x80; value >>= 7; if (value >= 0x80) { out[rv++] = value | 0x80; value >>= 7; if (value >= 0x80) { out[rv++] = value | 0x80; value >>= 7; if (value >= 0x80) { out[rv++] = value | 0x80; value >>= 7; } } } } /* assert: value<128 */ out[rv++] = value; return rv; } /* Pack a 32-bit signed integer, returning the number of bytes needed. Negative numbers are packed as twos-complement 64-bit integers. */ static inline size_t int32_pack (int32_t value, uint8_t *out) { if (value < 0) { out[0] = value | 0x80; out[1] = (value>>7) | 0x80; out[2] = (value>>14) | 0x80; out[3] = (value>>21) | 0x80; out[4] = (value>>28) | 0x80; out[5] = out[6] = out[7] = out[8] = 0xff; out[9] = 0x01; return 10; } else return uint32_pack (value, out); } /* Pack a 32-bit integer in zigwag encoding. */ static inline size_t sint32_pack (int32_t value, uint8_t *out) { return uint32_pack (zigzag32 (value), out); } /* Pack a 64-bit unsigned integer that fits in a 64-bit uint, using base-128 encoding. */ static size_t uint64_pack (uint64_t value, uint8_t *out) { uint32_t hi = value>>32; uint32_t lo = value; unsigned rv; if (hi == 0) return uint32_pack ((uint32_t)lo, out); out[0] = (lo) | 0x80; out[1] = (lo>>7) | 0x80; out[2] = (lo>>14) | 0x80; out[3] = (lo>>21) | 0x80; if (hi < 8) { out[4] = (hi<<4) | (lo>>28); return 5; } else { out[4] = ((hi&7)<<4) | (lo>>28) | 0x80; hi >>= 3; } rv = 5; while (hi >= 128) { out[rv++] = hi | 0x80; hi >>= 7; } out[rv++] = hi; return rv; } /* Pack a 64-bit signed integer in zigzan encoding, return the size of the packed output. (Max returned value is 10) */ static inline size_t sint64_pack (int64_t value, uint8_t *out) { return uint64_pack (zigzag64 (value), out); } /* Pack a 32-bit value, little-endian. Used for fixed32, sfixed32, float) */ static inline size_t fixed32_pack (uint32_t value, uint8_t *out) { #if IS_LITTLE_ENDIAN memcpy (out, &value, 4); #else out[0] = value; out[1] = value>>8; out[2] = value>>16; out[3] = value>>24; #endif return 4; } /* Pack a 64-bit fixed-length value. (Used for fixed64, sfixed64, double) */ /* XXX: the big-endian impl is really only good for 32-bit machines, a 64-bit version would be appreciated, plus a way to decide to use 64-bit math where convenient. */ static inline size_t fixed64_pack (uint64_t value, uint8_t *out) { #if IS_LITTLE_ENDIAN memcpy (out, &value, 8); #else fixed32_pack (value, out); fixed32_pack (value>>32, out+4); #endif return 8; } /* Pack a boolean as 0 or 1, even though the protobuf_c_boolean can really assume any integer value. */ /* XXX: perhaps on some platforms "*out = !!value" would be a better impl, b/c that is idiotmatic c++ in some stl impls. */ static inline size_t boolean_pack (protobuf_c_boolean value, uint8_t *out) { *out = value ? 1 : 0; return 1; } /* Pack a length-prefixed string. The input string is NUL-terminated. The NULL pointer is treated as an empty string. This isn't really necessary, but it allows people to leave required strings blank. (See Issue 13 in the bug tracker for a little more explanation). */ static inline size_t string_pack (const char * str, uint8_t *out) { if (str == NULL) { out[0] = 0; return 1; } else { size_t len = strlen (str); size_t rv = uint32_pack (len, out); memcpy (out + rv, str, len); return rv + len; } } static inline size_t binary_data_pack (const ProtobufCBinaryData *bd, uint8_t *out) { size_t len = bd->len; size_t rv = uint32_pack (len, out); memcpy (out + rv, bd->data, len); return rv + len; } static inline size_t prefixed_message_pack (const ProtobufCMessage *message, uint8_t *out) { if (message == NULL) { out[0] = 0; return 1; } else { size_t rv = protobuf_c_message_pack (message, out + 1); uint32_t rv_packed_size = uint32_size (rv); if (rv_packed_size != 1) memmove (out + rv_packed_size, out + 1, rv); return uint32_pack (rv, out) + rv; } } /* wire-type will be added in required_field_pack() */ /* XXX: just call uint64_pack on 64-bit platforms. */ static size_t tag_pack (uint32_t id, uint8_t *out) { if (id < (1<<(32-3))) return uint32_pack (id<<3, out); else return uint64_pack (((uint64_t)id) << 3, out); } static size_t required_field_pack (const ProtobufCFieldDescriptor *field, const void *member, uint8_t *out) { size_t rv = tag_pack (field->id, out); switch (field->type) { case PROTOBUF_C_TYPE_SINT32: out[0] |= PROTOBUF_C_WIRE_TYPE_VARINT; return rv + sint32_pack (*(const int32_t *) member, out + rv); case PROTOBUF_C_TYPE_INT32: out[0] |= PROTOBUF_C_WIRE_TYPE_VARINT; return rv + int32_pack (*(const uint32_t *) member, out + rv); case PROTOBUF_C_TYPE_UINT32: case PROTOBUF_C_TYPE_ENUM: out[0] |= PROTOBUF_C_WIRE_TYPE_VARINT; return rv + uint32_pack (*(const uint32_t *) member, out + rv); case PROTOBUF_C_TYPE_SINT64: out[0] |= PROTOBUF_C_WIRE_TYPE_VARINT; return rv + sint64_pack (*(const int64_t *) member, out + rv); case PROTOBUF_C_TYPE_INT64: case PROTOBUF_C_TYPE_UINT64: out[0] |= PROTOBUF_C_WIRE_TYPE_VARINT; return rv + uint64_pack (*(const uint64_t *) member, out + rv); case PROTOBUF_C_TYPE_SFIXED32: case PROTOBUF_C_TYPE_FIXED32: case PROTOBUF_C_TYPE_FLOAT: out[0] |= PROTOBUF_C_WIRE_TYPE_32BIT; return rv + fixed32_pack (*(const uint32_t *) member, out + rv); case PROTOBUF_C_TYPE_SFIXED64: case PROTOBUF_C_TYPE_FIXED64: case PROTOBUF_C_TYPE_DOUBLE: out[0] |= PROTOBUF_C_WIRE_TYPE_64BIT; return rv + fixed64_pack (*(const uint64_t *) member, out + rv); case PROTOBUF_C_TYPE_BOOL: out[0] |= PROTOBUF_C_WIRE_TYPE_VARINT; return rv + boolean_pack (*(const protobuf_c_boolean *) member, out + rv); case PROTOBUF_C_TYPE_STRING: { out[0] |= PROTOBUF_C_WIRE_TYPE_LENGTH_PREFIXED; return rv + string_pack (*(char * const *) member, out + rv); } case PROTOBUF_C_TYPE_BYTES: { const ProtobufCBinaryData * bd = ((const ProtobufCBinaryData*) member); out[0] |= PROTOBUF_C_WIRE_TYPE_LENGTH_PREFIXED; return rv + binary_data_pack (bd, out + rv); } //case PROTOBUF_C_TYPE_GROUP: // NOT SUPPORTED case PROTOBUF_C_TYPE_MESSAGE: { out[0] |= PROTOBUF_C_WIRE_TYPE_LENGTH_PREFIXED; return rv + prefixed_message_pack (*(ProtobufCMessage * const *) member, out + rv); } } PROTOBUF_C_ASSERT_NOT_REACHED (); return 0; } static size_t optional_field_pack (const ProtobufCFieldDescriptor *field, const protobuf_c_boolean *has, const void *member, uint8_t *out) { if (field->type == PROTOBUF_C_TYPE_MESSAGE || field->type == PROTOBUF_C_TYPE_STRING) { const void *ptr = * (const void * const *) member; if (ptr == NULL || ptr == field->default_value) return 0; } else { if (!*has) return 0; } return required_field_pack (field, member, out); } /* TODO: implement as a table lookup */ static inline size_t sizeof_elt_in_repeated_array (ProtobufCType type) { switch (type) { case PROTOBUF_C_TYPE_SINT32: case PROTOBUF_C_TYPE_INT32: case PROTOBUF_C_TYPE_UINT32: case PROTOBUF_C_TYPE_SFIXED32: case PROTOBUF_C_TYPE_FIXED32: case PROTOBUF_C_TYPE_FLOAT: case PROTOBUF_C_TYPE_ENUM: return 4; case PROTOBUF_C_TYPE_SINT64: case PROTOBUF_C_TYPE_INT64: case PROTOBUF_C_TYPE_UINT64: case PROTOBUF_C_TYPE_SFIXED64: case PROTOBUF_C_TYPE_FIXED64: case PROTOBUF_C_TYPE_DOUBLE: return 8; case PROTOBUF_C_TYPE_BOOL: return sizeof (protobuf_c_boolean); case PROTOBUF_C_TYPE_STRING: case PROTOBUF_C_TYPE_MESSAGE: return sizeof (void *); case PROTOBUF_C_TYPE_BYTES: return sizeof (ProtobufCBinaryData); } PROTOBUF_C_ASSERT_NOT_REACHED (); return 0; } static size_t repeated_field_pack (const ProtobufCFieldDescriptor *field, size_t count, const void *member, uint8_t *out) { char *array = * (char * const *) member; size_t siz; unsigned i; size_t rv = 0; /* CONSIDER: optimize this case a bit (by putting the loop inside the switch) */ siz = sizeof_elt_in_repeated_array (field->type); for (i = 0; i < count; i++) { rv += required_field_pack (field, array, out + rv); array += siz; } return rv; } static size_t unknown_field_pack (const ProtobufCMessageUnknownField *field, uint8_t *out) { size_t rv = tag_pack (field->tag, out); out[0] |= field->wire_type; memcpy (out + rv, field->data, field->len); return rv + field->len; } size_t protobuf_c_message_pack (const ProtobufCMessage *message, uint8_t *out) { unsigned i; size_t rv = 0; ASSERT_IS_MESSAGE (message); for (i = 0; i < message->descriptor->n_fields; i++) { const ProtobufCFieldDescriptor *field = message->descriptor->fields + i; const void *member = ((const char *) message) + field->offset; /* it doesn't hurt to compute qmember (a pointer to the quantifier field of the structure), but the pointer is only valid if the field is one of: - a repeated field - an optional field that isn't a pointer type (meaning: not a message or a string) */ const void *qmember = ((const char *) message) + field->quantifier_offset; if (field->label == PROTOBUF_C_LABEL_REQUIRED) rv += required_field_pack (field, member, out + rv); else if (field->label == PROTOBUF_C_LABEL_OPTIONAL) /* note that qmember is bogus for strings and messages, but it isn't used */ rv += optional_field_pack (field, qmember, member, out + rv); else rv += repeated_field_pack (field, * (const size_t *) qmember, member, out + rv); } for (i = 0; i < message->n_unknown_fields; i++) rv += unknown_field_pack (&message->unknown_fields[i], out + rv); return rv; } /* === pack_to_buffer() === */ static size_t required_field_pack_to_buffer (const ProtobufCFieldDescriptor *field, const void *member, ProtobufCBuffer *buffer) { size_t rv; uint8_t scratch[MAX_UINT64_ENCODED_SIZE * 2]; rv = tag_pack (field->id, scratch); switch (field->type) { case PROTOBUF_C_TYPE_SINT32: scratch[0] |= PROTOBUF_C_WIRE_TYPE_VARINT; rv += sint32_pack (*(const int32_t *) member, scratch + rv); buffer->append (buffer, rv, scratch); break; case PROTOBUF_C_TYPE_INT32: scratch[0] |= PROTOBUF_C_WIRE_TYPE_VARINT; rv += int32_pack (*(const uint32_t *) member, scratch + rv); buffer->append (buffer, rv, scratch); break; case PROTOBUF_C_TYPE_UINT32: case PROTOBUF_C_TYPE_ENUM: scratch[0] |= PROTOBUF_C_WIRE_TYPE_VARINT; rv += uint32_pack (*(const uint32_t *) member, scratch + rv); buffer->append (buffer, rv, scratch); break; case PROTOBUF_C_TYPE_SINT64: scratch[0] |= PROTOBUF_C_WIRE_TYPE_VARINT; rv += sint64_pack (*(const int64_t *) member, scratch + rv); buffer->append (buffer, rv, scratch); break; case PROTOBUF_C_TYPE_INT64: case PROTOBUF_C_TYPE_UINT64: scratch[0] |= PROTOBUF_C_WIRE_TYPE_VARINT; rv += uint64_pack (*(const uint64_t *) member, scratch + rv); buffer->append (buffer, rv, scratch); break; case PROTOBUF_C_TYPE_SFIXED32: case PROTOBUF_C_TYPE_FIXED32: case PROTOBUF_C_TYPE_FLOAT: scratch[0] |= PROTOBUF_C_WIRE_TYPE_32BIT; rv += fixed32_pack (*(const uint32_t *) member, scratch + rv); buffer->append (buffer, rv, scratch); break; case PROTOBUF_C_TYPE_SFIXED64: case PROTOBUF_C_TYPE_FIXED64: case PROTOBUF_C_TYPE_DOUBLE: scratch[0] |= PROTOBUF_C_WIRE_TYPE_64BIT; rv += fixed64_pack (*(const uint64_t *) member, scratch + rv); buffer->append (buffer, rv, scratch); break; case PROTOBUF_C_TYPE_BOOL: scratch[0] |= PROTOBUF_C_WIRE_TYPE_VARINT; rv += boolean_pack (*(const protobuf_c_boolean *) member, scratch + rv); buffer->append (buffer, rv, scratch); break; case PROTOBUF_C_TYPE_STRING: { const char *str = *(char * const *) member; size_t sublen = str ? strlen (str) : 0; scratch[0] |= PROTOBUF_C_WIRE_TYPE_LENGTH_PREFIXED; rv += uint32_pack (sublen, scratch + rv); buffer->append (buffer, rv, scratch); buffer->append (buffer, sublen, (const uint8_t *) str); rv += sublen; break; } case PROTOBUF_C_TYPE_BYTES: { const ProtobufCBinaryData * bd = ((const ProtobufCBinaryData*) member); size_t sublen = bd->len; scratch[0] |= PROTOBUF_C_WIRE_TYPE_LENGTH_PREFIXED; rv += uint32_pack (sublen, scratch + rv); buffer->append (buffer, rv, scratch); buffer->append (buffer, sublen, bd->data); rv += sublen; break; } //PROTOBUF_C_TYPE_GROUP, // NOT SUPPORTED case PROTOBUF_C_TYPE_MESSAGE: { uint8_t simple_buffer_scratch[256]; size_t sublen; ProtobufCBufferSimple simple_buffer = PROTOBUF_C_BUFFER_SIMPLE_INIT (simple_buffer_scratch); const ProtobufCMessage *msg = *(ProtobufCMessage * const *) member; scratch[0] |= PROTOBUF_C_WIRE_TYPE_LENGTH_PREFIXED; if (msg == NULL) sublen = 0; else sublen = protobuf_c_message_pack_to_buffer (msg, &simple_buffer.base); rv += uint32_pack (sublen, scratch + rv); buffer->append (buffer, rv, scratch); buffer->append (buffer, sublen, simple_buffer.data); rv += sublen; PROTOBUF_C_BUFFER_SIMPLE_CLEAR (&simple_buffer); break; } default: PROTOBUF_C_ASSERT_NOT_REACHED (); } return rv; } static size_t optional_field_pack_to_buffer (const ProtobufCFieldDescriptor *field, const protobuf_c_boolean *has, const void *member, ProtobufCBuffer *buffer) { if (field->type == PROTOBUF_C_TYPE_MESSAGE || field->type == PROTOBUF_C_TYPE_STRING) { const void *ptr = * (const void * const *) member; if (ptr == NULL || ptr == field->default_value) return 0; } else { if (!*has) return 0; } return required_field_pack_to_buffer (field, member, buffer); } static size_t repeated_field_pack_to_buffer (const ProtobufCFieldDescriptor *field, unsigned count, const void *member, ProtobufCBuffer *buffer) { char *array = * (char * const *) member; size_t siz; unsigned i; /* CONSIDER: optimize this case a bit (by putting the loop inside the switch) */ unsigned rv = 0; siz = sizeof_elt_in_repeated_array (field->type); for (i = 0; i < count; i++) { rv += required_field_pack_to_buffer (field, array, buffer); array += siz; } return rv; } static size_t unknown_field_pack_to_buffer (const ProtobufCMessageUnknownField *field, ProtobufCBuffer *buffer) { uint8_t header[MAX_UINT64_ENCODED_SIZE]; size_t rv = tag_pack (field->tag, header); header[0] |= field->wire_type; buffer->append (buffer, rv, header); buffer->append (buffer, field->len, field->data); return rv + field->len; } size_t protobuf_c_message_pack_to_buffer (const ProtobufCMessage *message, ProtobufCBuffer *buffer) { unsigned i; size_t rv = 0; ASSERT_IS_MESSAGE (message); for (i = 0; i < message->descriptor->n_fields; i++) { const ProtobufCFieldDescriptor *field = message->descriptor->fields + i; const void *member = ((const char *) message) + field->offset; const void *qmember = ((const char *) message) + field->quantifier_offset; if (field->label == PROTOBUF_C_LABEL_REQUIRED) rv += required_field_pack_to_buffer (field, member, buffer); else if (field->label == PROTOBUF_C_LABEL_OPTIONAL) rv += optional_field_pack_to_buffer (field, qmember, member, buffer); else rv += repeated_field_pack_to_buffer (field, * (const size_t *) qmember, member, buffer); } for (i = 0; i < message->n_unknown_fields; i++) rv += unknown_field_pack_to_buffer (&message->unknown_fields[i], buffer); return rv; } /* === unpacking === */ #if PRINT_UNPACK_ERRORS # define UNPACK_ERROR(args) do { printf args;printf("\n"); }while(0) #else # define UNPACK_ERROR(args) do { if (protobuf_c_error_printer) protobuf_c_error_printer args; } while(0) #endif static inline int int_range_lookup (unsigned n_ranges, const ProtobufCIntRange *ranges, int value) { unsigned start, n; if (n_ranges == 0) return -1; start = 0; n = n_ranges; while (n > 1) { unsigned mid = start + n / 2; if (value < ranges[mid].start_value) { n = mid - start; } else if (value >= ranges[mid].start_value + (int)(ranges[mid+1].orig_index-ranges[mid].orig_index)) { unsigned new_start = mid + 1; n = start + n - new_start; start = new_start; } else return (value - ranges[mid].start_value) + ranges[mid].orig_index; } if (n > 0) { unsigned start_orig_index = ranges[start].orig_index; unsigned range_size = ranges[start+1].orig_index - start_orig_index; if (ranges[start].start_value <= value && value < (int)(ranges[start].start_value + range_size)) return (value - ranges[start].start_value) + start_orig_index; } return -1; } static size_t parse_tag_and_wiretype (size_t len, const uint8_t *data, uint32_t *tag_out, ProtobufCWireType *wiretype_out) { unsigned max_rv = len > 5 ? 5 : len; uint32_t tag = (data[0]&0x7f) >> 3; unsigned shift = 4; unsigned rv; *wiretype_out = data[0] & 7; if ((data[0] & 0x80) == 0) { *tag_out = tag; return 1; } for (rv = 1; rv < max_rv; rv++) if (data[rv] & 0x80) { tag |= (data[rv] & 0x7f) << shift; shift += 7; } else { tag |= data[rv] << shift; *tag_out = tag; return rv + 1; } return 0; /* error: bad header */ } /* sizeof(ScannedMember) must be <= (1<descriptor->unknown_field_array_offset) static inline uint32_t scan_length_prefixed_data (size_t len, const uint8_t *data, size_t *prefix_len_out) { unsigned hdr_max = len < 5 ? len : 5; unsigned hdr_len; uint32_t val = 0; unsigned i; unsigned shift = 0; for (i = 0; i < hdr_max; i++) { val |= (data[i] & 0x7f) << shift; shift += 7; if ((data[i] & 0x80) == 0) break; } if (i == hdr_max) { return 0; } hdr_len = i + 1; *prefix_len_out = hdr_len; if (hdr_len + val > len) { return 0; } return hdr_len + val; } static inline uint32_t parse_uint32 (unsigned len, const uint8_t *data) { unsigned rv = data[0] & 0x7f; if (len > 1) { rv |= ((data[1] & 0x7f) << 7); if (len > 2) { rv |= ((data[2] & 0x7f) << 14); if (len > 3) { rv |= ((data[3] & 0x7f) << 21); if (len > 4) rv |= (data[4] << 28); } } } return rv; } static inline uint32_t parse_int32 (unsigned len, const uint8_t *data) { return parse_uint32 (len, data); } static inline int32_t unzigzag32 (uint32_t v) { if (v&1) return -(v>>1) - 1; else return v>>1; } static inline uint32_t parse_fixed_uint32 (const uint8_t *data) { #if IS_LITTLE_ENDIAN uint32_t t; memcpy (&t, data, 4); return t; #else return data[0] | (data[1] << 8) | (data[2] << 16) | (data[3] << 24); #endif } static uint64_t parse_uint64 (unsigned len, const uint8_t *data) { unsigned shift, i; if (len < 5) return parse_uint32 (len, data); uint64_t rv = ((data[0] & 0x7f)) | ((data[1] & 0x7f)<<7) | ((data[2] & 0x7f)<<14) | ((data[3] & 0x7f)<<21); shift = 28; for (i = 4; i < len; i++) { rv |= (((uint64_t)(data[i]&0x7f)) << shift); shift += 7; } return rv; } static inline int64_t unzigzag64 (uint64_t v) { if (v&1) return -(v>>1) - 1; else return v>>1; } static inline uint64_t parse_fixed_uint64 (const uint8_t *data) { #if IS_LITTLE_ENDIAN uint64_t t; memcpy (&t, data, 8); return t; #else return (uint64_t)parse_fixed_uint32 (data) | (((uint64_t)parse_fixed_uint32(data+4)) << 32); #endif } static protobuf_c_boolean parse_boolean (unsigned len, const uint8_t *data) { unsigned i; for (i = 0; i < len; i++) if (data[i] & 0x7f) return 1; return 0; } static protobuf_c_boolean parse_required_member (ScannedMember *scanned_member, void *member, ProtobufCAllocator *allocator, protobuf_c_boolean maybe_clear) { unsigned len = scanned_member->len; const uint8_t *data = scanned_member->data; ProtobufCWireType wire_type = scanned_member->wire_type; switch (scanned_member->field->type) { case PROTOBUF_C_TYPE_INT32: if (wire_type != PROTOBUF_C_WIRE_TYPE_VARINT) return 0; *(uint32_t*)member = parse_int32 (len, data); return 1; case PROTOBUF_C_TYPE_UINT32: if (wire_type != PROTOBUF_C_WIRE_TYPE_VARINT) return 0; *(uint32_t*)member = parse_uint32 (len, data); return 1; case PROTOBUF_C_TYPE_SINT32: if (wire_type != PROTOBUF_C_WIRE_TYPE_VARINT) return 0; *(int32_t*)member = unzigzag32 (parse_uint32 (len, data)); return 1; case PROTOBUF_C_TYPE_SFIXED32: case PROTOBUF_C_TYPE_FIXED32: case PROTOBUF_C_TYPE_FLOAT: if (wire_type != PROTOBUF_C_WIRE_TYPE_32BIT) return 0; *(uint32_t*)member = parse_fixed_uint32 (data); return 1; case PROTOBUF_C_TYPE_INT64: case PROTOBUF_C_TYPE_UINT64: if (wire_type != PROTOBUF_C_WIRE_TYPE_VARINT) return 0; *(uint64_t*)member = parse_uint64 (len, data); return 1; case PROTOBUF_C_TYPE_SINT64: if (wire_type != PROTOBUF_C_WIRE_TYPE_VARINT) return 0; *(int64_t*)member = unzigzag64 (parse_uint64 (len, data)); return 1; case PROTOBUF_C_TYPE_SFIXED64: case PROTOBUF_C_TYPE_FIXED64: case PROTOBUF_C_TYPE_DOUBLE: if (wire_type != PROTOBUF_C_WIRE_TYPE_64BIT) return 0; *(uint64_t*)member = parse_fixed_uint64 (data); return 1; case PROTOBUF_C_TYPE_BOOL: *(protobuf_c_boolean*)member = parse_boolean (len, data); return 1; case PROTOBUF_C_TYPE_ENUM: if (wire_type != PROTOBUF_C_WIRE_TYPE_VARINT) return 0; *(uint32_t*)member = parse_uint32 (len, data); return 1; case PROTOBUF_C_TYPE_STRING: if (wire_type != PROTOBUF_C_WIRE_TYPE_LENGTH_PREFIXED) return 0; { char **pstr = member; unsigned pref_len = scanned_member->length_prefix_len; if (maybe_clear && *pstr != NULL) { const char *def = scanned_member->field->default_value; if (*pstr != NULL && *pstr != def) FREE (allocator, *pstr); } DO_ALLOC (*pstr, allocator, len - pref_len + 1, return 0); memcpy (*pstr, data + pref_len, len - pref_len); (*pstr)[len-pref_len] = 0; return 1; } case PROTOBUF_C_TYPE_BYTES: if (wire_type != PROTOBUF_C_WIRE_TYPE_LENGTH_PREFIXED) return 0; { ProtobufCBinaryData *bd = member; const ProtobufCBinaryData *def_bd; unsigned pref_len = scanned_member->length_prefix_len; def_bd = scanned_member->field->default_value; if (maybe_clear && bd->data != NULL && (def_bd == NULL || bd->data != def_bd->data)) FREE (allocator, bd->data); DO_ALLOC (bd->data, allocator, len - pref_len, return 0); memcpy (bd->data, data + pref_len, len - pref_len); bd->len = len - pref_len; return 1; } //case PROTOBUF_C_TYPE_GROUP, // NOT SUPPORTED case PROTOBUF_C_TYPE_MESSAGE: if (wire_type != PROTOBUF_C_WIRE_TYPE_LENGTH_PREFIXED) return 0; { ProtobufCMessage **pmessage = member; ProtobufCMessage *subm; const ProtobufCMessage *def_mess; unsigned pref_len = scanned_member->length_prefix_len; def_mess = scanned_member->field->default_value; if (maybe_clear && *pmessage != NULL && *pmessage != def_mess) protobuf_c_message_free_unpacked (*pmessage, allocator); subm = protobuf_c_message_unpack (scanned_member->field->descriptor, allocator, len - pref_len, data + pref_len); *pmessage = subm; /* since we freed the message we must clear the field, even if NULL */ if (subm == NULL) return 0; return 1; } } return 0; } static protobuf_c_boolean parse_optional_member (ScannedMember *scanned_member, void *member, ProtobufCMessage *message, ProtobufCAllocator *allocator) { if (!parse_required_member (scanned_member, member, allocator, TRUE)) return 0; if (scanned_member->field->quantifier_offset != 0) STRUCT_MEMBER (protobuf_c_boolean, message, scanned_member->field->quantifier_offset) = 1; return 1; } static protobuf_c_boolean parse_repeated_member (ScannedMember *scanned_member, void *member, ProtobufCMessage *message, ProtobufCAllocator *allocator) { const ProtobufCFieldDescriptor *field = scanned_member->field; size_t *p_n = STRUCT_MEMBER_PTR(size_t, message, field->quantifier_offset); size_t siz = sizeof_elt_in_repeated_array (field->type); char *array = *(char**)member; if (!parse_required_member (scanned_member, array + siz * (*p_n), allocator, FALSE)) return 0; *p_n += 1; return 1; } static protobuf_c_boolean parse_member (ScannedMember *scanned_member, ProtobufCMessage *message, ProtobufCAllocator *allocator) { const ProtobufCFieldDescriptor *field = scanned_member->field; void *member; if (field == NULL) { ProtobufCMessageUnknownField *ufield = message->unknown_fields + (message->n_unknown_fields++); ufield->tag = scanned_member->tag; ufield->wire_type = scanned_member->wire_type; ufield->len = scanned_member->len; DO_UNALIGNED_ALLOC (ufield->data, allocator, scanned_member->len, return 0); memcpy (ufield->data, scanned_member->data, ufield->len); return 1; } member = (char*)message + field->offset; switch (field->label) { case PROTOBUF_C_LABEL_REQUIRED: return parse_required_member (scanned_member, member, allocator, TRUE); case PROTOBUF_C_LABEL_OPTIONAL: return parse_optional_member (scanned_member, member, message, allocator); case PROTOBUF_C_LABEL_REPEATED: return parse_repeated_member (scanned_member, member, message, allocator); } PROTOBUF_C_ASSERT_NOT_REACHED (); return 0; } /* TODO: expose/use this function if desc->message_init==NULL (which occurs for old code, and may be useful for certain programatic techniques for generating descriptors). */ void protobuf_c_message_init_generic (const ProtobufCMessageDescriptor *desc, ProtobufCMessage *message) { unsigned i; memset (message, 0, desc->sizeof_message); message->descriptor = desc; for (i = 0; i < desc->n_fields; i++) if (desc->fields[i].default_value != NULL && desc->fields[i].label != PROTOBUF_C_LABEL_REPEATED) { void *field = STRUCT_MEMBER_P (message, desc->fields[i].offset); const void *dv = desc->fields[i].default_value; switch (desc->fields[i].type) { case PROTOBUF_C_TYPE_INT32: case PROTOBUF_C_TYPE_SINT32: case PROTOBUF_C_TYPE_SFIXED32: case PROTOBUF_C_TYPE_UINT32: case PROTOBUF_C_TYPE_FIXED32: case PROTOBUF_C_TYPE_FLOAT: case PROTOBUF_C_TYPE_ENUM: memcpy (field, dv, 4); break; case PROTOBUF_C_TYPE_INT64: case PROTOBUF_C_TYPE_SINT64: case PROTOBUF_C_TYPE_SFIXED64: case PROTOBUF_C_TYPE_UINT64: case PROTOBUF_C_TYPE_FIXED64: case PROTOBUF_C_TYPE_DOUBLE: memcpy (field, dv, 8); break; case PROTOBUF_C_TYPE_BOOL: memcpy (field, dv, sizeof (protobuf_c_boolean)); break; case PROTOBUF_C_TYPE_BYTES: memcpy (field, dv, sizeof (ProtobufCBinaryData)); break; case PROTOBUF_C_TYPE_STRING: case PROTOBUF_C_TYPE_MESSAGE: /* the next line essentially implements a cast from const, which is totally unavoidable. */ *(const void**)field = dv; break; } } } /* ScannedMember slabs (an unpacking implementation detail). Before doing real unpacking, we first scan through the elements to see how many there are (for repeated fields), and which field to use (for non-repeated fields given twice). * In order to avoid allocations for small messages, we keep a stack-allocated slab of ScannedMembers of size FIRST_SCANNED_MEMBER_SLAB_SIZE (16). After we fill that up, we allocate each slab twice as large as the previous one. */ #define FIRST_SCANNED_MEMBER_SLAB_SIZE_LOG2 4 /* The number of slabs, including the stack-allocated ones; choose the number so that we would overflow if we needed a slab larger than provided. */ #define MAX_SCANNED_MEMBER_SLAB \ (sizeof(void*)*8 - 1 \ - BOUND_SIZEOF_SCANNED_MEMBER_LOG2 \ - FIRST_SCANNED_MEMBER_SLAB_SIZE_LOG2) ProtobufCMessage * protobuf_c_message_unpack (const ProtobufCMessageDescriptor *desc, ProtobufCAllocator *allocator, size_t len, const uint8_t *data) { ProtobufCMessage *rv; size_t rem = len; const uint8_t *at = data; const ProtobufCFieldDescriptor *last_field = desc->fields + 0; ScannedMember first_member_slab[1<n_fields + word_bits - 1) / word_bits; required_fields_bitmap = alloca(required_fields_bitmap_len * sizeof(long)); memset(required_fields_bitmap, 0, required_fields_bitmap_len * sizeof(long)); DO_ALLOC (rv, allocator, desc->sizeof_message, return NULL); scanned_member_slabs[0] = first_member_slab; /* Generated code always defines "message_init". However, we provide a fallback for (1) users of old protobuf-c generated-code that do not provide the function, and (2) descriptors constructed from some other source (most likely, direct construction from the .proto file) */ if (desc->message_init != NULL) protobuf_c_message_init (desc, rv); else protobuf_c_message_init_generic (desc, rv); while (rem > 0) { uint32_t tag; ProtobufCWireType wire_type; size_t used = parse_tag_and_wiretype (rem, at, &tag, &wire_type); const ProtobufCFieldDescriptor *field; ScannedMember tmp; if (used == 0) { UNPACK_ERROR (("message '%s': error parsing tag/wiretype at offset %u", desc->name, (unsigned)(at-data))); goto error_cleanup_during_scan; } /* XXX: consider optimizing for field[1].id == tag, if field[1] exists! */ if (last_field->id != tag) { /* lookup field */ int field_index = int_range_lookup (desc->n_field_ranges, desc->field_ranges, tag); if (field_index < 0) { field = NULL; n_unknown++; } else { field = desc->fields + field_index; last_field = field; last_field_index = field_index; } } else field = last_field; if (field != NULL && field->label == PROTOBUF_C_LABEL_REQUIRED) required_fields_bitmap[last_field_index / word_bits] |= (1UL << (last_field_index % word_bits)); at += used; rem -= used; tmp.tag = tag; tmp.wire_type = wire_type; tmp.field = field; tmp.data = at; switch (wire_type) { case PROTOBUF_C_WIRE_TYPE_VARINT: { unsigned max_len = rem < 10 ? rem : 10; unsigned i; for (i = 0; i < max_len; i++) if ((at[i] & 0x80) == 0) break; if (i == max_len) { UNPACK_ERROR (("message '%s', field '%s': unterminated varint at offset %u", desc->name, field ? field->name : "*unknown*", (unsigned)(at-data))); goto error_cleanup_during_scan; } tmp.len = i + 1; } break; case PROTOBUF_C_WIRE_TYPE_64BIT: if (rem < 8) { UNPACK_ERROR (("message '%s', field '%s': too short after 64bit wiretype at offset %u", desc->name, field ? field->name : "*unknown*", (unsigned)(at-data))); goto error_cleanup_during_scan; } tmp.len = 8; break; case PROTOBUF_C_WIRE_TYPE_LENGTH_PREFIXED: { size_t pref_len; tmp.len = scan_length_prefixed_data (rem, at, &pref_len); if (tmp.len == 0) { UNPACK_ERROR (("message '%s', field '%s': scan of length prefixed data failed", desc->name, field ? field->name : "*unknown*")); goto error_cleanup_during_scan; } tmp.length_prefix_len = pref_len; break; } case PROTOBUF_C_WIRE_TYPE_32BIT: if (rem < 4) { UNPACK_ERROR (("message '%s', field '%s': too short after 32bit wiretype at offset %u", desc->name, field ? field->name : "*unknown*", (unsigned)(at-data))); goto error_cleanup_during_scan; } tmp.len = 4; break; default: UNPACK_ERROR (("message '%s', field '%s': unsupported tag %u at offset %u", desc->name, field ? field->name : "*unknown*", wire_type, (unsigned)(at-data))); goto error_cleanup_during_scan; } if (in_slab_index == (1U<<(which_slab+FIRST_SCANNED_MEMBER_SLAB_SIZE_LOG2))) { size_t size; in_slab_index = 0; if (which_slab == MAX_SCANNED_MEMBER_SLAB) { UNPACK_ERROR (("message '%s', field '%s': too many fields", desc->name, field ? field->name : "*unknown*")); goto error_cleanup_during_scan; } which_slab++; size = sizeof(ScannedMember) << (which_slab+FIRST_SCANNED_MEMBER_SLAB_SIZE_LOG2); /* TODO: consider using alloca() ! */ if (allocator->tmp_alloc != NULL) scanned_member_slabs[which_slab] = TMPALLOC(allocator, size); else DO_ALLOC (scanned_member_slabs[which_slab], allocator, size, goto error_cleanup_during_scan); } scanned_member_slabs[which_slab][in_slab_index++] = tmp; if (field != NULL && field->label == PROTOBUF_C_LABEL_REPEATED) { STRUCT_MEMBER (size_t, rv, field->quantifier_offset) += 1; } at += tmp.len; rem -= tmp.len; } /* allocate space for repeated fields, also check that all required fields have been set */ for (f = 0; f < desc->n_fields; f++) { const ProtobufCFieldDescriptor *field = desc->fields + f; if (field->label == PROTOBUF_C_LABEL_REPEATED) { size_t siz = sizeof_elt_in_repeated_array (field->type); size_t *n_ptr = STRUCT_MEMBER_PTR (size_t, rv, field->quantifier_offset); if (*n_ptr != 0) { unsigned n = *n_ptr; *n_ptr = 0; assert(rv->descriptor != NULL); #define CLEAR_REMAINING_N_PTRS() \ for(f++;f < desc->n_fields; f++) \ { \ field = desc->fields + f; \ if (field->label == PROTOBUF_C_LABEL_REPEATED) \ STRUCT_MEMBER (size_t, rv, field->quantifier_offset) = 0; \ } DO_ALLOC (STRUCT_MEMBER (void *, rv, field->offset), allocator, siz * n, CLEAR_REMAINING_N_PTRS (); goto error_cleanup); } } else if (field->label == PROTOBUF_C_LABEL_REQUIRED) { if (field->default_value == NULL && 0 == (required_fields_bitmap[f / word_bits] & (1UL << (f % word_bits)))) { UNPACK_ERROR (("message '%s': missing required field '%s'", desc->name, field->name)); CLEAR_REMAINING_N_PTRS(); goto error_cleanup; } } } #undef CLEAR_REMAINING_N_PTRS /* allocate space for unknown fields */ if (n_unknown) { DO_ALLOC (rv->unknown_fields, allocator, n_unknown * sizeof (ProtobufCMessageUnknownField), goto error_cleanup); } /* do real parsing */ for (i_slab = 0; i_slab <= which_slab; i_slab++) { unsigned max = (i_slab == which_slab) ? in_slab_index : (1U<<(i_slab+4)); ScannedMember *slab = scanned_member_slabs[i_slab]; unsigned j; for (j = 0; j < max; j++) { if (!parse_member (slab + j, rv, allocator)) { UNPACK_ERROR (("message '%s', field '%s': error parsing member", desc->name, slab->field ? slab->field->name : "*unknown*")); goto error_cleanup; } } } /* cleanup */ if (allocator->tmp_alloc == NULL) { unsigned j; for (j = 1; j <= which_slab; j++) FREE (allocator, scanned_member_slabs[j]); } return rv; error_cleanup: protobuf_c_message_free_unpacked (rv, allocator); if (allocator->tmp_alloc == NULL) { unsigned j; for (j = 1; j <= which_slab; j++) FREE (allocator, scanned_member_slabs[j]); } return NULL; error_cleanup_during_scan: FREE (allocator, rv); if (allocator->tmp_alloc == NULL) { unsigned j; for (j = 1; j <= which_slab; j++) FREE (allocator, scanned_member_slabs[j]); } return NULL; } /* === free_unpacked === */ void protobuf_c_message_free_unpacked (ProtobufCMessage *message, ProtobufCAllocator *allocator) { const ProtobufCMessageDescriptor *desc = message->descriptor; unsigned f; ASSERT_IS_MESSAGE (message); if (allocator == NULL) allocator = &protobuf_c_default_allocator; message->descriptor = NULL; for (f = 0; f < desc->n_fields; f++) { if (desc->fields[f].label == PROTOBUF_C_LABEL_REPEATED) { size_t n = STRUCT_MEMBER (size_t, message, desc->fields[f].quantifier_offset); void * arr = STRUCT_MEMBER (void *, message, desc->fields[f].offset); if (desc->fields[f].type == PROTOBUF_C_TYPE_STRING) { unsigned i; for (i = 0; i < n; i++) FREE (allocator, ((char**)arr)[i]); } else if (desc->fields[f].type == PROTOBUF_C_TYPE_BYTES) { unsigned i; for (i = 0; i < n; i++) FREE (allocator, ((ProtobufCBinaryData*)arr)[i].data); } else if (desc->fields[f].type == PROTOBUF_C_TYPE_MESSAGE) { unsigned i; for (i = 0; i < n; i++) protobuf_c_message_free_unpacked (((ProtobufCMessage**)arr)[i], allocator); } if (arr != NULL) FREE (allocator, arr); } else if (desc->fields[f].type == PROTOBUF_C_TYPE_STRING) { char *str = STRUCT_MEMBER (char *, message, desc->fields[f].offset); if (str && str != desc->fields[f].default_value) FREE (allocator, str); } else if (desc->fields[f].type == PROTOBUF_C_TYPE_BYTES) { void *data = STRUCT_MEMBER (ProtobufCBinaryData, message, desc->fields[f].offset).data; const ProtobufCBinaryData *default_bd; default_bd = desc->fields[f].default_value; if (data != NULL && (default_bd == NULL || default_bd->data != data)) FREE (allocator, data); } else if (desc->fields[f].type == PROTOBUF_C_TYPE_MESSAGE) { ProtobufCMessage *sm; sm = STRUCT_MEMBER (ProtobufCMessage *, message,desc->fields[f].offset); if (sm && sm != desc->fields[f].default_value) protobuf_c_message_free_unpacked (sm, allocator); } } for (f = 0; f < message->n_unknown_fields; f++) FREE (allocator, message->unknown_fields[f].data); if (message->unknown_fields != NULL) FREE (allocator, message->unknown_fields); FREE (allocator, message); } /* === services === */ typedef void (*DestroyHandler)(void *service); typedef void (*GenericHandler)(void *service, const ProtobufCMessage *input, ProtobufCClosure closure, void *closure_data); void protobuf_c_service_invoke_internal(ProtobufCService *service, unsigned method_index, const ProtobufCMessage *input, ProtobufCClosure closure, void *closure_data) { GenericHandler *handlers; GenericHandler handler; /* Verify that method_index is within range. If this fails, you are likely invoking a newly added method on an old service. (Although other memory corruption bugs can cause this assertion too) */ PROTOBUF_C_ASSERT (method_index < service->descriptor->n_methods); /* Get the array of virtual methods (which are enumerated by the generated code) */ handlers = (GenericHandler *) (service + 1); /* get our method and invoke it */ /* TODO: seems like handler==NULL is a situation that needs handling */ handler = handlers[method_index]; (*handler) (service, input, closure, closure_data); } void protobuf_c_service_generated_init (ProtobufCService *service, const ProtobufCServiceDescriptor *descriptor, ProtobufCServiceDestroy destroy) { ASSERT_IS_SERVICE_DESCRIPTOR(descriptor); service->descriptor = descriptor; service->destroy = destroy; service->invoke = protobuf_c_service_invoke_internal; memset (service + 1, 0, descriptor->n_methods * sizeof (GenericHandler)); } void protobuf_c_service_destroy (ProtobufCService *service) { service->destroy (service); } /* --- querying the descriptors --- */ const ProtobufCEnumValue * protobuf_c_enum_descriptor_get_value_by_name (const ProtobufCEnumDescriptor *desc, const char *name) { unsigned start = 0, count = desc->n_value_names; while (count > 1) { unsigned mid = start + count / 2; int rv = strcmp (desc->values_by_name[mid].name, name); if (rv == 0) return desc->values + desc->values_by_name[mid].index; else if (rv < 0) { count = start + count - (mid + 1); start = mid + 1; } else count = mid - start; } if (count == 0) return NULL; if (strcmp (desc->values_by_name[start].name, name) == 0) return desc->values + desc->values_by_name[start].index; return NULL; } const ProtobufCEnumValue * protobuf_c_enum_descriptor_get_value (const ProtobufCEnumDescriptor *desc, int value) { int rv = int_range_lookup (desc->n_value_ranges, desc->value_ranges, value); if (rv < 0) return NULL; return desc->values + rv; } const ProtobufCFieldDescriptor * protobuf_c_message_descriptor_get_field_by_name (const ProtobufCMessageDescriptor *desc, const char *name) { unsigned start = 0, count = desc->n_fields; const ProtobufCFieldDescriptor *field; while (count > 1) { unsigned mid = start + count / 2; int rv; field = desc->fields + desc->fields_sorted_by_name[mid]; rv = strcmp (field->name, name); if (rv == 0) return field; else if (rv < 0) { count = start + count - (mid + 1); start = mid + 1; } else count = mid - start; } if (count == 0) return NULL; field = desc->fields + desc->fields_sorted_by_name[start]; if (strcmp (field->name, name) == 0) return field; return NULL; } const ProtobufCFieldDescriptor * protobuf_c_message_descriptor_get_field (const ProtobufCMessageDescriptor *desc, unsigned value) { int rv = int_range_lookup (desc->n_field_ranges, desc->field_ranges, value); if (rv < 0) return NULL; return desc->fields + rv; } const ProtobufCMethodDescriptor * protobuf_c_service_descriptor_get_method_by_name (const ProtobufCServiceDescriptor *desc, const char *name) { unsigned start = 0, count = desc->n_methods; while (count > 1) { unsigned mid = start + count / 2; unsigned mid_index = desc->method_indices_by_name[mid]; const char *mid_name = desc->methods[mid_index].name; int rv = strcmp (mid_name, name); if (rv == 0) return desc->methods + desc->method_indices_by_name[mid]; if (rv < 0) { count = start + count - (mid + 1); start = mid + 1; } else { count = mid - start; } } if (count == 0) return NULL; if (strcmp (desc->methods[desc->method_indices_by_name[start]].name, name) == 0) return desc->methods + desc->method_indices_by_name[start]; return NULL; } php-pinba-1.1.2/protobuf-c.h000066400000000000000000000333411374247224700156420ustar00rootroot00000000000000/* --- protobuf-c.h: public protobuf c runtime api --- */ /* * Copyright 2008, Dave Benson. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with * the License. You may obtain a copy of the License * at http://www.apache.org/licenses/LICENSE-2.0 Unless * required by applicable law or agreed to in writing, * software distributed under the License is distributed on * an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ #ifndef __PROTOBUF_C_RUNTIME_H_ #define __PROTOBUF_C_RUNTIME_H_ #include #include #include #ifdef __cplusplus # define PROTOBUF_C_BEGIN_DECLS extern "C" { # define PROTOBUF_C_END_DECLS } #else # define PROTOBUF_C_BEGIN_DECLS # define PROTOBUF_C_END_DECLS #endif PROTOBUF_C_BEGIN_DECLS typedef enum { PROTOBUF_C_LABEL_REQUIRED, PROTOBUF_C_LABEL_OPTIONAL, PROTOBUF_C_LABEL_REPEATED } ProtobufCLabel; typedef enum { PROTOBUF_C_TYPE_INT32, PROTOBUF_C_TYPE_SINT32, PROTOBUF_C_TYPE_SFIXED32, PROTOBUF_C_TYPE_INT64, PROTOBUF_C_TYPE_SINT64, PROTOBUF_C_TYPE_SFIXED64, PROTOBUF_C_TYPE_UINT32, PROTOBUF_C_TYPE_FIXED32, PROTOBUF_C_TYPE_UINT64, PROTOBUF_C_TYPE_FIXED64, PROTOBUF_C_TYPE_FLOAT, PROTOBUF_C_TYPE_DOUBLE, PROTOBUF_C_TYPE_BOOL, PROTOBUF_C_TYPE_ENUM, PROTOBUF_C_TYPE_STRING, PROTOBUF_C_TYPE_BYTES, //PROTOBUF_C_TYPE_GROUP, // NOT SUPPORTED PROTOBUF_C_TYPE_MESSAGE, } ProtobufCType; typedef int protobuf_c_boolean; #define PROTOBUF_C_OFFSETOF(struct, member) offsetof(struct, member) #define PROTOBUF_C_ASSERT(condition) assert(condition) #define PROTOBUF_C_ASSERT_NOT_REACHED() assert(0) typedef struct _ProtobufCBinaryData ProtobufCBinaryData; struct _ProtobufCBinaryData { size_t len; uint8_t *data; }; typedef struct _ProtobufCIntRange ProtobufCIntRange; /* private */ /* --- memory management --- */ typedef struct _ProtobufCAllocator ProtobufCAllocator; struct _ProtobufCAllocator { void *(*alloc)(void *allocator_data, size_t size); void (*free)(void *allocator_data, void *pointer); void *(*tmp_alloc)(void *allocator_data, size_t size); unsigned max_alloca; void *allocator_data; }; /* This is a configurable allocator. * By default, it uses the system allocator (meaning malloc() and free()). * This is typically done to incorporate into frameworks that provide * some nonstandard allocation functions. */ extern ProtobufCAllocator protobuf_c_default_allocator; /* settable */ /* This is the system allocator, meaning it uses malloc() and free() */ extern ProtobufCAllocator protobuf_c_system_allocator; /* use malloc, free etc */ /* This is the function that our default allocators call when they run out-of-memory. The default behavior of this function is to terminate your program. */ extern void (*protobuf_c_out_of_memory) (void); extern void (*protobuf_c_error_printer)(char *, ...); /* --- append-only data buffer --- */ typedef struct _ProtobufCBuffer ProtobufCBuffer; struct _ProtobufCBuffer { void (*append)(ProtobufCBuffer *buffer, size_t len, const uint8_t *data); }; /* --- enums --- */ typedef struct _ProtobufCEnumValue ProtobufCEnumValue; typedef struct _ProtobufCEnumValueIndex ProtobufCEnumValueIndex; typedef struct _ProtobufCEnumDescriptor ProtobufCEnumDescriptor; /* ProtobufCEnumValue: this represents a single value of * an enumeration. * 'name' is the string identifying this value, as given in the .proto file. * 'c_name' is the full name of the C enumeration value. * 'value' is the number assigned to this value, as given in the .proto file. */ struct _ProtobufCEnumValue { const char *name; const char *c_name; int value; }; /* ProtobufCEnumDescriptor: the represents the enum as a whole, * with all its values. * 'magic' is a code we check to ensure that the api is used correctly. * 'name' is the qualified name (e.g. "namespace.Type"). * 'short_name' is the unqualified name ("Type"), as given in the .proto file. * 'package_name' is the '.'-separated namespace * 'n_values' is the number of distinct values. * 'values' is the array of distinct values. * 'n_value_names' number of named values (including aliases). * 'value_names' are the named values (including aliases). * * The rest of the values are private essentially. * * see also: Use protobuf_c_enum_descriptor_get_value_by_name() * and protobuf_c_enum_descriptor_get_value() to efficiently * lookup values in the descriptor. */ struct _ProtobufCEnumDescriptor { uint32_t magic; const char *name; const char *short_name; const char *c_name; const char *package_name; /* sorted by value */ unsigned n_values; const ProtobufCEnumValue *values; /* sorted by name */ unsigned n_value_names; const ProtobufCEnumValueIndex *values_by_name; /* value-ranges, for faster lookups by number */ unsigned n_value_ranges; const ProtobufCIntRange *value_ranges; void *reserved1; void *reserved2; void *reserved3; void *reserved4; }; /* --- messages --- */ typedef struct _ProtobufCMessageDescriptor ProtobufCMessageDescriptor; typedef struct _ProtobufCFieldDescriptor ProtobufCFieldDescriptor; typedef struct _ProtobufCMessage ProtobufCMessage; typedef void (*ProtobufCMessageInit)(ProtobufCMessage *); /* ProtobufCFieldDescriptor: description of a single field * in a message. * 'name' is the name of the field, as given in the .proto file. * 'id' is the code representing the field, as given in the .proto file. * 'label' is one of PROTOBUF_C_LABEL_{REQUIRED,OPTIONAL,REPEATED} * 'type' is the type of field. * 'quantifier_offset' is the offset in bytes into the message's C structure * for this member's "has_MEMBER" field (for optional members) or * "n_MEMBER" field (for repeated members). * 'offset' is the offset in bytes into the message's C structure * for the member itself. * 'descriptor' is a pointer to a ProtobufC{Enum,Message}Descriptor * if type is PROTOBUF_C_TYPE_{ENUM,MESSAGE} respectively, * otherwise NULL. * 'default_value' is a pointer to a default value for this field, * where allowed. */ struct _ProtobufCFieldDescriptor { const char *name; uint32_t id; ProtobufCLabel label; ProtobufCType type; unsigned quantifier_offset; unsigned offset; const void *descriptor; /* for MESSAGE and ENUM types */ const void *default_value; /* or NULL if no default-value */ union { struct { void *reserved1; void *reserved2; }; unsigned deprecated:1; }; }; /* ProtobufCMessageDescriptor: description of a message. * * 'magic' is a code we check to ensure that the api is used correctly. * 'name' is the qualified name (e.g. "namespace.Type"). * 'short_name' is the unqualified name ("Type"), as given in the .proto file. * 'c_name' is the c-formatted name of the structure * 'package_name' is the '.'-separated namespace * 'sizeof_message' is the size in bytes of the C structure * representing an instance of this type of message. * 'n_fields' is the number of known fields in this message. * 'fields' is the fields sorted by id number. * 'fields_sorted_by_name', 'n_field_ranges' and 'field_ranges' * are used for looking up fields by name and id. (private) */ struct _ProtobufCMessageDescriptor { uint32_t magic; const char *name; const char *short_name; const char *c_name; const char *package_name; size_t sizeof_message; /* sorted by field-id */ unsigned n_fields; const ProtobufCFieldDescriptor *fields; const unsigned *fields_sorted_by_name; /* ranges, optimization for looking up fields */ unsigned n_field_ranges; const ProtobufCIntRange *field_ranges; ProtobufCMessageInit message_init; void *reserved1; void *reserved2; void *reserved3; }; /* ProtobufCMessage: an instance of a message. * * ProtobufCMessage is sort-of a lightweight * base-class for all messages. * * In particular, ProtobufCMessage doesn't have * any allocation policy associated with it. * That's because it is common to create ProtobufCMessage's * on the stack. In fact, we that's what we recommend * for sending messages (because if you just allocate from the * stack, then you can't really have a memory leak). * * This means that functions like protobuf_c_message_unpack() * which return a ProtobufCMessage must be paired * with a free function, like protobuf_c_message_free_unpacked(). * * 'descriptor' gives the locations and types of the members of message * 'n_unknown_fields' is the number of fields we didn't recognize. * 'unknown_fields' are fields we didn't recognize. */ typedef struct _ProtobufCMessageUnknownField ProtobufCMessageUnknownField; struct _ProtobufCMessage { const ProtobufCMessageDescriptor *descriptor; unsigned n_unknown_fields; ProtobufCMessageUnknownField *unknown_fields; }; #define PROTOBUF_C_MESSAGE_INIT(descriptor) { descriptor, 0, NULL } /* To pack a message: you have two options: (1) you can compute the size of the message using protobuf_c_message_get_packed_size() then pass protobuf_c_message_pack() a buffer of that length. (2) Provide a virtual buffer (a ProtobufCBuffer) to accept data as we scan through it. */ size_t protobuf_c_message_get_packed_size(const ProtobufCMessage *message); size_t protobuf_c_message_pack (const ProtobufCMessage *message, uint8_t *out); size_t protobuf_c_message_pack_to_buffer (const ProtobufCMessage *message, ProtobufCBuffer *buffer); ProtobufCMessage * protobuf_c_message_unpack (const ProtobufCMessageDescriptor *, ProtobufCAllocator *allocator, size_t len, const uint8_t *data); void protobuf_c_message_free_unpacked (ProtobufCMessage *message, ProtobufCAllocator *allocator); /* WARNING: 'to_init' must be a block of memory of size descriptor->sizeof_message. */ #define protobuf_c_message_init(descriptor, message) (descriptor)->message_init(message) /* --- services --- */ typedef struct _ProtobufCMethodDescriptor ProtobufCMethodDescriptor; typedef struct _ProtobufCServiceDescriptor ProtobufCServiceDescriptor; struct _ProtobufCMethodDescriptor { const char *name; const ProtobufCMessageDescriptor *input; const ProtobufCMessageDescriptor *output; }; struct _ProtobufCServiceDescriptor { uint32_t magic; const char *name; const char *short_name; const char *c_name; const char *package; unsigned n_methods; const ProtobufCMethodDescriptor *methods; /* in order from .proto file */ const unsigned *method_indices_by_name; }; typedef struct _ProtobufCService ProtobufCService; typedef void (*ProtobufCClosure)(const ProtobufCMessage *message, void *closure_data); struct _ProtobufCService { const ProtobufCServiceDescriptor *descriptor; void (*invoke)(ProtobufCService *service, unsigned method_index, const ProtobufCMessage *input, ProtobufCClosure closure, void *closure_data); void (*destroy) (ProtobufCService *service); }; void protobuf_c_service_destroy (ProtobufCService *); /* --- querying the descriptors --- */ const ProtobufCEnumValue * protobuf_c_enum_descriptor_get_value_by_name (const ProtobufCEnumDescriptor *desc, const char *name); const ProtobufCEnumValue * protobuf_c_enum_descriptor_get_value (const ProtobufCEnumDescriptor *desc, int value); const ProtobufCFieldDescriptor * protobuf_c_message_descriptor_get_field_by_name (const ProtobufCMessageDescriptor *desc, const char *name); const ProtobufCFieldDescriptor * protobuf_c_message_descriptor_get_field (const ProtobufCMessageDescriptor *desc, unsigned value); const ProtobufCMethodDescriptor * protobuf_c_service_descriptor_get_method_by_name (const ProtobufCServiceDescriptor *desc, const char *name); /* --- wire format enums --- */ typedef enum { PROTOBUF_C_WIRE_TYPE_VARINT, PROTOBUF_C_WIRE_TYPE_64BIT, PROTOBUF_C_WIRE_TYPE_LENGTH_PREFIXED, PROTOBUF_C_WIRE_TYPE_START_GROUP, /* unsupported */ PROTOBUF_C_WIRE_TYPE_END_GROUP, /* unsupported */ PROTOBUF_C_WIRE_TYPE_32BIT } ProtobufCWireType; /* --- unknown message fields --- */ struct _ProtobufCMessageUnknownField { uint32_t tag; ProtobufCWireType wire_type; size_t len; uint8_t *data; }; /* --- extra (superfluous) api: trivial buffer --- */ typedef struct _ProtobufCBufferSimple ProtobufCBufferSimple; struct _ProtobufCBufferSimple { ProtobufCBuffer base; size_t alloced; size_t len; uint8_t *data; protobuf_c_boolean must_free_data; }; #define PROTOBUF_C_BUFFER_SIMPLE_INIT(array_of_bytes) \ { { protobuf_c_buffer_simple_append }, \ sizeof(array_of_bytes), 0, (array_of_bytes), 0 } #define PROTOBUF_C_BUFFER_SIMPLE_CLEAR(simp_buf) \ do { if ((simp_buf)->must_free_data) \ protobuf_c_default_allocator.free (&protobuf_c_default_allocator.allocator_data, (simp_buf)->data); } while (0) /* ====== private ====== */ #include "protobuf-c-private.h" PROTOBUF_C_END_DECLS #endif /* __PROTOBUF_C_RUNTIME_H_ */ php-pinba-1.1.2/tests/000077500000000000000000000000001374247224700145475ustar00rootroot00000000000000php-pinba-1.1.2/tests/ini_set.phpt000066400000000000000000000012541374247224700171000ustar00rootroot00000000000000--TEST-- Check for ini_set("pinba.server", ...) --SKIPIF-- --FILE-- --EXPECT-- pinba extension is available '' '' 'one.server' 'one.server' 'one.server,two.server' 'one.server,two.server' ''