1 // Protocol Buffers - Google's data interchange format
2 // Copyright 2008 Google Inc. All rights reserved.
3 // https://developers.google.com/protocol-buffers/
4 //
5 // Redistribution and use in source and binary forms, with or without
6 // modification, are permitted provided that the following conditions are
7 // met:
8 //
9 // * Redistributions of source code must retain the above copyright
10 // notice, this list of conditions and the following disclaimer.
11 // * Redistributions in binary form must reproduce the above
12 // copyright notice, this list of conditions and the following disclaimer
13 // in the documentation and/or other materials provided with the
14 // distribution.
15 // * Neither the name of Google Inc. nor the names of its
16 // contributors may be used to endorse or promote products derived from
17 // this software without specific prior written permission.
18 //
19 // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
20 // "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
21 // LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
22 // A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
23 // OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
24 // SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
25 // LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
26 // DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
27 // THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
28 // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
29 // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
30
31 #include "convert.h"
32
33 #include <php.h>
34
35 // This is not self-contained: it must be after other Zend includes.
36 #include <Zend/zend_exceptions.h>
37
38 #include "array.h"
39 #include "map.h"
40 #include "message.h"
41 #include "php-upb.h"
42 #include "protobuf.h"
43
44 // -----------------------------------------------------------------------------
45 // GPBUtil
46 // -----------------------------------------------------------------------------
47
48 static zend_class_entry* GPBUtil_class_entry;
49
50 // The implementation of type checking for primitive fields is empty. This is
51 // because type checking is done when direct assigning message fields (e.g.,
52 // foo->a = 1). Functions defined here are place holders in generated code for
53 // pure PHP implementation (c extension and pure PHP share the same generated
54 // code).
55
PHP_METHOD(Util,checkInt32)56 PHP_METHOD(Util, checkInt32) {}
PHP_METHOD(Util,checkUint32)57 PHP_METHOD(Util, checkUint32) {}
PHP_METHOD(Util,checkInt64)58 PHP_METHOD(Util, checkInt64) {}
PHP_METHOD(Util,checkUint64)59 PHP_METHOD(Util, checkUint64) {}
PHP_METHOD(Util,checkEnum)60 PHP_METHOD(Util, checkEnum) {}
PHP_METHOD(Util,checkFloat)61 PHP_METHOD(Util, checkFloat) {}
PHP_METHOD(Util,checkDouble)62 PHP_METHOD(Util, checkDouble) {}
PHP_METHOD(Util,checkBool)63 PHP_METHOD(Util, checkBool) {}
PHP_METHOD(Util,checkString)64 PHP_METHOD(Util, checkString) {}
PHP_METHOD(Util,checkBytes)65 PHP_METHOD(Util, checkBytes) {}
PHP_METHOD(Util,checkMessage)66 PHP_METHOD(Util, checkMessage) {}
67
68 // The result of checkMapField() is assigned, so we need to return the first
69 // param:
70 // $arr = GPBUtil::checkMapField($var,
71 // \Google\Protobuf\Internal\GPBType::INT64,
72 // \Google\Protobuf\Internal\GPBType::INT32);
PHP_METHOD(Util,checkMapField)73 PHP_METHOD(Util, checkMapField) {
74 zval *val, *key_type, *val_type, *klass;
75 if (zend_parse_parameters(ZEND_NUM_ARGS(), "zzz|z", &val, &key_type,
76 &val_type, &klass) == FAILURE) {
77 return;
78 }
79 RETURN_ZVAL(val, 1, 0);
80 }
81
82 // The result of checkRepeatedField() is assigned, so we need to return the
83 // first param:
84 // $arr = GPBUtil::checkRepeatedField(
85 // $var, \Google\Protobuf\Internal\GPBType::STRING);
PHP_METHOD(Util,checkRepeatedField)86 PHP_METHOD(Util, checkRepeatedField) {
87 zval *val, *type, *klass;
88 if (zend_parse_parameters(ZEND_NUM_ARGS(), "zz|z", &val, &type, &klass) ==
89 FAILURE) {
90 return;
91 }
92 RETURN_ZVAL(val, 1, 0);
93 }
94
95 ZEND_BEGIN_ARG_INFO_EX(arginfo_checkPrimitive, 0, 0, 1)
96 ZEND_ARG_INFO(0, value)
97 ZEND_END_ARG_INFO()
98
99 ZEND_BEGIN_ARG_INFO_EX(arginfo_checkMessage, 0, 0, 2)
100 ZEND_ARG_INFO(0, value)
101 ZEND_ARG_INFO(0, class)
102 ZEND_END_ARG_INFO()
103
104 ZEND_BEGIN_ARG_INFO_EX(arginfo_checkMapField, 0, 0, 3)
105 ZEND_ARG_INFO(0, value)
106 ZEND_ARG_INFO(0, key_type)
107 ZEND_ARG_INFO(0, value_type)
108 ZEND_ARG_INFO(0, value_class)
109 ZEND_END_ARG_INFO()
110
111 ZEND_BEGIN_ARG_INFO_EX(arginfo_checkRepeatedField, 0, 0, 2)
112 ZEND_ARG_INFO(0, value)
113 ZEND_ARG_INFO(0, type)
114 ZEND_ARG_INFO(0, class)
115 ZEND_END_ARG_INFO()
116
117 static zend_function_entry util_methods[] = {
118 PHP_ME(Util, checkInt32, arginfo_checkPrimitive,
119 ZEND_ACC_PUBLIC|ZEND_ACC_STATIC)
120 PHP_ME(Util, checkUint32, arginfo_checkPrimitive,
121 ZEND_ACC_PUBLIC|ZEND_ACC_STATIC)
122 PHP_ME(Util, checkInt64, arginfo_checkPrimitive,
123 ZEND_ACC_PUBLIC|ZEND_ACC_STATIC)
124 PHP_ME(Util, checkUint64, arginfo_checkPrimitive,
125 ZEND_ACC_PUBLIC|ZEND_ACC_STATIC)
126 PHP_ME(Util, checkEnum, arginfo_checkPrimitive,
127 ZEND_ACC_PUBLIC|ZEND_ACC_STATIC)
128 PHP_ME(Util, checkFloat, arginfo_checkPrimitive,
129 ZEND_ACC_PUBLIC|ZEND_ACC_STATIC)
130 PHP_ME(Util, checkDouble, arginfo_checkPrimitive,
131 ZEND_ACC_PUBLIC|ZEND_ACC_STATIC)
132 PHP_ME(Util, checkBool, arginfo_checkPrimitive,
133 ZEND_ACC_PUBLIC|ZEND_ACC_STATIC)
134 PHP_ME(Util, checkString, arginfo_checkPrimitive,
135 ZEND_ACC_PUBLIC|ZEND_ACC_STATIC)
136 PHP_ME(Util, checkBytes, arginfo_checkPrimitive,
137 ZEND_ACC_PUBLIC|ZEND_ACC_STATIC)
138 PHP_ME(Util, checkMessage, arginfo_checkMessage,
139 ZEND_ACC_PUBLIC|ZEND_ACC_STATIC)
140 PHP_ME(Util, checkMapField, arginfo_checkMapField,
141 ZEND_ACC_PUBLIC|ZEND_ACC_STATIC)
142 PHP_ME(Util, checkRepeatedField, arginfo_checkRepeatedField,
143 ZEND_ACC_PUBLIC|ZEND_ACC_STATIC)
144 ZEND_FE_END
145 };
146
147 // -----------------------------------------------------------------------------
148 // Conversion functions used from C
149 // -----------------------------------------------------------------------------
150
pbphp_dtype_to_type(upb_descriptortype_t type)151 upb_fieldtype_t pbphp_dtype_to_type(upb_descriptortype_t type) {
152 switch (type) {
153 #define CASE(descriptor_type, type) \
154 case UPB_DESCRIPTOR_TYPE_##descriptor_type: \
155 return UPB_TYPE_##type;
156
157 CASE(FLOAT, FLOAT);
158 CASE(DOUBLE, DOUBLE);
159 CASE(BOOL, BOOL);
160 CASE(STRING, STRING);
161 CASE(BYTES, BYTES);
162 CASE(MESSAGE, MESSAGE);
163 CASE(GROUP, MESSAGE);
164 CASE(ENUM, ENUM);
165 CASE(INT32, INT32);
166 CASE(INT64, INT64);
167 CASE(UINT32, UINT32);
168 CASE(UINT64, UINT64);
169 CASE(SINT32, INT32);
170 CASE(SINT64, INT64);
171 CASE(FIXED32, UINT32);
172 CASE(FIXED64, UINT64);
173 CASE(SFIXED32, INT32);
174 CASE(SFIXED64, INT64);
175
176 #undef CASE
177
178 }
179
180 zend_error(E_ERROR, "Unknown field type.");
181 return 0;
182 }
183
buftouint64(const char * ptr,const char * end,uint64_t * val)184 static bool buftouint64(const char *ptr, const char *end, uint64_t *val) {
185 uint64_t u64 = 0;
186 while (ptr < end) {
187 unsigned ch = (unsigned)(*ptr - '0');
188 if (ch >= 10) break;
189 if (u64 > UINT64_MAX / 10 || u64 * 10 > UINT64_MAX - ch) {
190 return false;
191 }
192 u64 *= 10;
193 u64 += ch;
194 ptr++;
195 }
196
197 if (ptr != end) {
198 // In PHP tradition, we allow truncation: "1.1" -> 1.
199 // But we don't allow 'e', eg. '1.1e2' or any other non-numeric chars.
200 if (*ptr++ != '.') return false;
201
202 for (;ptr < end; ptr++) {
203 if (*ptr < '0' || *ptr > '9') {
204 return false;
205 }
206 }
207 }
208
209 *val = u64;
210 return true;
211 }
212
buftoint64(const char * ptr,const char * end,int64_t * val)213 static bool buftoint64(const char *ptr, const char *end, int64_t *val) {
214 bool neg = false;
215 uint64_t u64;
216
217 if (ptr != end && *ptr == '-') {
218 ptr++;
219 neg = true;
220 }
221
222 if (!buftouint64(ptr, end, &u64) ||
223 u64 > (uint64_t)INT64_MAX + neg) {
224 return false;
225 }
226
227 *val = neg ? -u64 : u64;
228 return true;
229 }
230
throw_conversion_exception(const char * to,const zval * zv)231 static void throw_conversion_exception(const char *to, const zval *zv) {
232 zval tmp;
233 ZVAL_COPY(&tmp, zv);
234 convert_to_string(&tmp);
235
236 zend_throw_exception_ex(NULL, 0, "Cannot convert '%s' to %s",
237 Z_STRVAL_P(&tmp), to);
238
239 zval_ptr_dtor(&tmp);
240 }
241
Convert_PhpToInt64(const zval * php_val,int64_t * i64)242 bool Convert_PhpToInt64(const zval *php_val, int64_t *i64) {
243 switch (Z_TYPE_P(php_val)) {
244 case IS_LONG:
245 *i64 = Z_LVAL_P(php_val);
246 return true;
247 case IS_DOUBLE: {
248 double dbl = Z_DVAL_P(php_val);
249 if (dbl > 9223372036854774784.0 || dbl < -9223372036854775808.0) {
250 zend_throw_exception_ex(NULL, 0, "Out of range");
251 return false;
252 }
253 *i64 = dbl; /* must be guarded, overflow here is UB */
254 return true;
255 }
256 case IS_STRING: {
257 const char *buf = Z_STRVAL_P(php_val);
258 // PHP would accept scientific notation here, but we're going to be a
259 // little more discerning and only accept pure integers.
260 bool ok = buftoint64(buf, buf + Z_STRLEN_P(php_val), i64);
261 if (!ok) {
262 throw_conversion_exception("integer", php_val);
263 }
264 return ok;
265 }
266 default:
267 throw_conversion_exception("integer", php_val);
268 return false;
269 }
270 }
271
to_double(zval * php_val,double * dbl)272 static bool to_double(zval *php_val, double *dbl) {
273 switch (Z_TYPE_P(php_val)) {
274 case IS_LONG:
275 *dbl = Z_LVAL_P(php_val);
276 return true;
277 case IS_DOUBLE:
278 *dbl = Z_DVAL_P(php_val);
279 return true;
280 case IS_STRING: {
281 zend_long lval;
282 switch (is_numeric_string(Z_STRVAL_P(php_val), Z_STRLEN_P(php_val), &lval,
283 dbl, false)) {
284 case IS_LONG:
285 *dbl = lval;
286 return true;
287 case IS_DOUBLE:
288 return true;
289 default:
290 goto fail;
291 }
292 }
293 default:
294 fail:
295 throw_conversion_exception("double", php_val);
296 return false;
297 }
298 }
299
to_bool(zval * from,bool * to)300 static bool to_bool(zval* from, bool* to) {
301 switch (Z_TYPE_P(from)) {
302 case IS_TRUE:
303 *to = true;
304 return true;
305 case IS_FALSE:
306 *to = false;
307 return true;
308 case IS_LONG:
309 *to = (Z_LVAL_P(from) != 0);
310 return true;
311 case IS_DOUBLE:
312 *to = (Z_LVAL_P(from) != 0);
313 return true;
314 case IS_STRING:
315 if (Z_STRLEN_P(from) == 0 ||
316 (Z_STRLEN_P(from) == 1 && Z_STRVAL_P(from)[0] == '0')) {
317 *to = false;
318 } else {
319 *to = true;
320 }
321 return true;
322 default:
323 throw_conversion_exception("bool", from);
324 return false;
325 }
326 }
327
to_string(zval * from)328 static bool to_string(zval* from) {
329 if (Z_ISREF_P(from)) {
330 ZVAL_DEREF(from);
331 }
332
333 switch (Z_TYPE_P(from)) {
334 case IS_STRING:
335 return true;
336 case IS_TRUE:
337 case IS_FALSE:
338 case IS_LONG:
339 case IS_DOUBLE: {
340 zval tmp;
341 zend_make_printable_zval(from, &tmp);
342 ZVAL_COPY_VALUE(from, &tmp);
343 return true;
344 }
345 default:
346 throw_conversion_exception("string", from);
347 return false;
348 }
349 }
350
Convert_PhpToUpb(zval * php_val,upb_msgval * upb_val,upb_fieldtype_t type,const Descriptor * desc,upb_arena * arena)351 bool Convert_PhpToUpb(zval *php_val, upb_msgval *upb_val, upb_fieldtype_t type,
352 const Descriptor *desc, upb_arena *arena) {
353 int64_t i64;
354
355 if (Z_ISREF_P(php_val)) {
356 ZVAL_DEREF(php_val);
357 }
358
359 switch (type) {
360 case UPB_TYPE_INT64:
361 return Convert_PhpToInt64(php_val, &upb_val->int64_val);
362 case UPB_TYPE_INT32:
363 case UPB_TYPE_ENUM:
364 if (!Convert_PhpToInt64(php_val, &i64)) {
365 return false;
366 }
367 upb_val->int32_val = i64;
368 return true;
369 case UPB_TYPE_UINT64:
370 if (!Convert_PhpToInt64(php_val, &i64)) {
371 return false;
372 }
373 upb_val->uint64_val = i64;
374 return true;
375 case UPB_TYPE_UINT32:
376 if (!Convert_PhpToInt64(php_val, &i64)) {
377 return false;
378 }
379 upb_val->uint32_val = i64;
380 return true;
381 case UPB_TYPE_DOUBLE:
382 return to_double(php_val, &upb_val->double_val);
383 case UPB_TYPE_FLOAT:
384 if (!to_double(php_val, &upb_val->double_val)) return false;
385 upb_val->float_val = upb_val->double_val;
386 return true;
387 case UPB_TYPE_BOOL:
388 return to_bool(php_val, &upb_val->bool_val);
389 case UPB_TYPE_STRING:
390 case UPB_TYPE_BYTES: {
391 char *ptr;
392 size_t size;
393
394 if (!to_string(php_val)) return false;
395
396 size = Z_STRLEN_P(php_val);
397
398 // If arena is NULL we reference the input zval.
399 // The resulting upb_strview will only be value while the zval is alive.
400 if (arena) {
401 ptr = upb_arena_malloc(arena, size);
402 memcpy(ptr, Z_STRVAL_P(php_val), size);
403 } else {
404 ptr = Z_STRVAL_P(php_val);
405 }
406
407 upb_val->str_val = upb_strview_make(ptr, size);
408 return true;
409 }
410 case UPB_TYPE_MESSAGE:
411 PBPHP_ASSERT(desc);
412 return Message_GetUpbMessage(php_val, desc, arena,
413 (upb_msg **)&upb_val->msg_val);
414 }
415
416 return false;
417 }
418
Convert_UpbToPhp(upb_msgval upb_val,zval * php_val,upb_fieldtype_t type,const Descriptor * desc,zval * arena)419 void Convert_UpbToPhp(upb_msgval upb_val, zval *php_val, upb_fieldtype_t type,
420 const Descriptor *desc, zval *arena) {
421 switch (type) {
422 case UPB_TYPE_INT64:
423 #if SIZEOF_ZEND_LONG == 8
424 ZVAL_LONG(php_val, upb_val.int64_val);
425 #else
426 {
427 char buf[20];
428 int size = sprintf(buf, "%lld", upb_val.int64_val);
429 ZVAL_NEW_STR(php_val, zend_string_init(buf, size, 0));
430 }
431 #endif
432 break;
433 case UPB_TYPE_UINT64:
434 #if SIZEOF_ZEND_LONG == 8
435 ZVAL_LONG(php_val, upb_val.uint64_val);
436 #else
437 {
438 char buf[20];
439 int size = sprintf(buf, "%lld", (int64_t)upb_val.uint64_val);
440 ZVAL_NEW_STR(php_val, zend_string_init(buf, size, 0));
441 }
442 #endif
443 break;
444 case UPB_TYPE_INT32:
445 case UPB_TYPE_ENUM:
446 ZVAL_LONG(php_val, upb_val.int32_val);
447 break;
448 case UPB_TYPE_UINT32: {
449 // Sign-extend for consistency between 32/64-bit builds.
450 zend_long val = (int32_t)upb_val.uint32_val;
451 ZVAL_LONG(php_val, val);
452 break;
453 }
454 case UPB_TYPE_DOUBLE:
455 ZVAL_DOUBLE(php_val, upb_val.double_val);
456 break;
457 case UPB_TYPE_FLOAT:
458 ZVAL_DOUBLE(php_val, upb_val.float_val);
459 break;
460 case UPB_TYPE_BOOL:
461 ZVAL_BOOL(php_val, upb_val.bool_val);
462 break;
463 case UPB_TYPE_STRING:
464 case UPB_TYPE_BYTES: {
465 upb_strview str = upb_val.str_val;
466 ZVAL_NEW_STR(php_val, zend_string_init(str.data, str.size, 0));
467 break;
468 }
469 case UPB_TYPE_MESSAGE:
470 PBPHP_ASSERT(desc);
471 Message_GetPhpWrapper(php_val, desc, (upb_msg*)upb_val.msg_val, arena);
472 break;
473 }
474 }
475
Convert_PhpToUpbAutoWrap(zval * val,upb_msgval * upb_val,upb_fieldtype_t type,const Descriptor * desc,upb_arena * arena)476 bool Convert_PhpToUpbAutoWrap(zval *val, upb_msgval *upb_val,
477 upb_fieldtype_t type, const Descriptor *desc,
478 upb_arena *arena) {
479 const upb_msgdef *subm = desc ? desc->msgdef : NULL;
480 if (subm && upb_msgdef_iswrapper(subm) && Z_TYPE_P(val) != IS_OBJECT) {
481 // Assigning a scalar to a wrapper-typed value. We will automatically wrap
482 // the value, so the user doesn't need to create a FooWrapper(['value': X])
483 // message manually.
484 upb_msg *wrapper = upb_msg_new(subm, arena);
485 const upb_fielddef *val_f = upb_msgdef_itof(subm, 1);
486 upb_fieldtype_t type_f = upb_fielddef_type(val_f);
487 upb_msgval msgval;
488 if (!Convert_PhpToUpb(val, &msgval, type_f, NULL, arena)) return false;
489 upb_msg_set(wrapper, val_f, msgval, arena);
490 upb_val->msg_val = wrapper;
491 return true;
492 } else {
493 // Convert_PhpToUpb doesn't auto-construct messages. This means that we only
494 // allow:
495 // ['foo_submsg': new Foo(['a' => 1])]
496 // not:
497 // ['foo_submsg': ['a' => 1]]
498 return Convert_PhpToUpb(val, upb_val, type, desc, arena);
499 }
500 }
501
Convert_ModuleInit(void)502 void Convert_ModuleInit(void) {
503 const char *prefix_name = "TYPE_URL_PREFIX";
504 zend_class_entry class_type;
505
506 INIT_CLASS_ENTRY(class_type, "Google\\Protobuf\\Internal\\GPBUtil",
507 util_methods);
508 GPBUtil_class_entry = zend_register_internal_class(&class_type);
509
510 zend_declare_class_constant_string(GPBUtil_class_entry, prefix_name,
511 strlen(prefix_name),
512 "type.googleapis.com/");
513 }
514