Debian Codegraph @

contrib/pgcrypto/pgp-pgsql.c

raw
1 /*
2 * pgp-pgsql.c
3 * PostgreSQL wrappers for pgp.
4 *
5 * Copyright (c) 2005 Marko Kreen
6 * All rights reserved.
7 *
8 * Redistribution and use in source and binary forms, with or without
9 * modification, are permitted provided that the following conditions
10 * are met:
11 * 1. Redistributions of source code must retain the above copyright
12 * notice, this list of conditions and the following disclaimer.
13 * 2. Redistributions in binary form must reproduce the above copyright
14 * notice, this list of conditions and the following disclaimer in the
15 * documentation and/or other materials provided with the distribution.
16 *
17 * THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND
18 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
19 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
20 * ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE
21 * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
22 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
23 * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
24 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
25 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
26 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
27 * SUCH DAMAGE.
28 *
29 * contrib/pgcrypto/pgp-pgsql.c
30 */
31
32 #include "postgres.h"
33
34 #include "catalog/pg_type.h"
35 #include "common/string.h"
36 #include "funcapi.h"
37 #include "lib/stringinfo.h"
38 #include "mb/pg_wchar.h"
39 #include "mbuf.h"
40 #include "pgp.h"
41 #include "px.h"
42 #include "utils/array.h"
43 #include "utils/builtins.h"
44
45 /*
46 * public functions
47 */
48 PG_FUNCTION_INFO_V1(pgp_sym_encrypt_bytea);
49 PG_FUNCTION_INFO_V1(pgp_sym_encrypt_text);
50 PG_FUNCTION_INFO_V1(pgp_sym_decrypt_bytea);
51 PG_FUNCTION_INFO_V1(pgp_sym_decrypt_text);
52
53 PG_FUNCTION_INFO_V1(pgp_pub_encrypt_bytea);
54 PG_FUNCTION_INFO_V1(pgp_pub_encrypt_text);
55 PG_FUNCTION_INFO_V1(pgp_pub_decrypt_bytea);
56 PG_FUNCTION_INFO_V1(pgp_pub_decrypt_text);
57
58 PG_FUNCTION_INFO_V1(pgp_key_id_w);
59
60 PG_FUNCTION_INFO_V1(pg_armor);
61 PG_FUNCTION_INFO_V1(pg_dearmor);
62 PG_FUNCTION_INFO_V1(pgp_armor_headers);
63
64 /*
65 * returns src in case of no conversion or error
66 */
67 static text *
68 convert_charset(text *src, int cset_from, int cset_to)
69 {
70 int src_len = VARSIZE_ANY_EXHDR(src);
71 unsigned char *dst;
72 unsigned char *csrc = (unsigned char *) VARDATA_ANY(src);
73 text *res;
74
75 dst = pg_do_encoding_conversion(csrc, src_len, cset_from, cset_to);
76 if (dst == csrc)
77 return src;
78
79 res = cstring_to_text((char *) dst);
80 pfree(dst);
81 return res;
82 }
83
84 static text *
85 convert_from_utf8(text *src)
86 {
87 return convert_charset(src, PG_UTF8, GetDatabaseEncoding());
88 }
89
90 static text *
91 convert_to_utf8(text *src)
92 {
93 return convert_charset(src, GetDatabaseEncoding(), PG_UTF8);
94 }
95
96 static void
97 clear_and_pfree(text *p)
98 {
99 px_memset(p, 0, VARSIZE_ANY(p));
100 pfree(p);
101 }
102
103 /*
104 * expect-* arguments storage
105 */
106 struct debug_expect
107 {
108 int debug;
109 int expect;
110 int cipher_algo;
111 int s2k_mode;
112 int s2k_count;
113 int s2k_cipher_algo;
114 int s2k_digest_algo;
115 int compress_algo;
116 int use_sess_key;
117 int disable_mdc;
118 int unicode_mode;
119 };
120
121 static void
122 fill_expect(struct debug_expect *ex, int text_mode)
123 {
124 ex->debug = 0;
125 ex->expect = 0;
126 ex->cipher_algo = -1;
127 ex->s2k_mode = -1;
128 ex->s2k_count = -1;
129 ex->s2k_cipher_algo = -1;
130 ex->s2k_digest_algo = -1;
131 ex->compress_algo = -1;
132 ex->use_sess_key = -1;
133 ex->disable_mdc = -1;
134 ex->unicode_mode = -1;
135 }
136
137 #define EX_MSG(arg) \
138 ereport(NOTICE, (errmsg( \
139 "pgp_decrypt: unexpected %s: expected %d got %d", \
140 CppAsString(arg), ex->arg, ctx->arg)))
141
142 #define EX_CHECK(arg) do { \
143 if (ex->arg >= 0 && ex->arg != ctx->arg) EX_MSG(arg); \
144 } while (0)
145
146 static void
147 check_expect(PGP_Context *ctx, struct debug_expect *ex)
148 {
149 EX_CHECK(cipher_algo);
150 EX_CHECK(s2k_mode);
151 EX_CHECK(s2k_count);
152 EX_CHECK(s2k_digest_algo);
153 EX_CHECK(use_sess_key);
154 if (ctx->use_sess_key)
155 EX_CHECK(s2k_cipher_algo);
156 EX_CHECK(disable_mdc);
157 EX_CHECK(compress_algo);
158 EX_CHECK(unicode_mode);
159 }
160
161 static void
162 show_debug(const char *msg)
163 {
164 ereport(NOTICE, (errmsg("dbg: %s", msg)));
165 }
166
167 static int
168 set_arg(PGP_Context *ctx, char *key, char *val,
169 struct debug_expect *ex)
170 {
171 int res = 0;
172
173 if (strcmp(key, "cipher-algo") == 0)
174 res = pgp_set_cipher_algo(ctx, val);
175 else if (strcmp(key, "disable-mdc") == 0)
176 res = pgp_disable_mdc(ctx, atoi(val));
177 else if (strcmp(key, "sess-key") == 0)
178 res = pgp_set_sess_key(ctx, atoi(val));
179 else if (strcmp(key, "s2k-mode") == 0)
180 res = pgp_set_s2k_mode(ctx, atoi(val));
181 else if (strcmp(key, "s2k-count") == 0)
182 res = pgp_set_s2k_count(ctx, atoi(val));
183 else if (strcmp(key, "s2k-digest-algo") == 0)
184 res = pgp_set_s2k_digest_algo(ctx, val);
185 else if (strcmp(key, "s2k-cipher-algo") == 0)
186 res = pgp_set_s2k_cipher_algo(ctx, val);
187 else if (strcmp(key, "compress-algo") == 0)
188 res = pgp_set_compress_algo(ctx, atoi(val));
189 else if (strcmp(key, "compress-level") == 0)
190 res = pgp_set_compress_level(ctx, atoi(val));
191 else if (strcmp(key, "convert-crlf") == 0)
192 res = pgp_set_convert_crlf(ctx, atoi(val));
193 else if (strcmp(key, "unicode-mode") == 0)
194 res = pgp_set_unicode_mode(ctx, atoi(val));
195 else if (strcmp(key, "ignore-cipher-failure") == 0)
196 res = pgp_set_ignore_cipher_failure(ctx, atoi(val));
197
198 /*
199 * The remaining options are for debugging/testing and are therefore not
200 * documented in the user-facing docs.
201 */
202 else if (ex != NULL && strcmp(key, "debug") == 0)
203 ex->debug = atoi(val);
204 else if (ex != NULL && strcmp(key, "expect-cipher-algo") == 0)
205 {
206 ex->expect = 1;
207 ex->cipher_algo = pgp_get_cipher_code(val);
208 }
209 else if (ex != NULL && strcmp(key, "expect-disable-mdc") == 0)
210 {
211 ex->expect = 1;
212 ex->disable_mdc = atoi(val);
213 }
214 else if (ex != NULL && strcmp(key, "expect-sess-key") == 0)
215 {
216 ex->expect = 1;
217 ex->use_sess_key = atoi(val);
218 }
219 else if (ex != NULL && strcmp(key, "expect-s2k-mode") == 0)
220 {
221 ex->expect = 1;
222 ex->s2k_mode = atoi(val);
223 }
224 else if (ex != NULL && strcmp(key, "expect-s2k-count") == 0)
225 {
226 ex->expect = 1;
227 ex->s2k_count = atoi(val);
228 }
229 else if (ex != NULL && strcmp(key, "expect-s2k-digest-algo") == 0)
230 {
231 ex->expect = 1;
232 ex->s2k_digest_algo = pgp_get_digest_code(val);
233 }
234 else if (ex != NULL && strcmp(key, "expect-s2k-cipher-algo") == 0)
235 {
236 ex->expect = 1;
237 ex->s2k_cipher_algo = pgp_get_cipher_code(val);
238 }
239 else if (ex != NULL && strcmp(key, "expect-compress-algo") == 0)
240 {
241 ex->expect = 1;
242 ex->compress_algo = atoi(val);
243 }
244 else if (ex != NULL && strcmp(key, "expect-unicode-mode") == 0)
245 {
246 ex->expect = 1;
247 ex->unicode_mode = atoi(val);
248 }
249 else
250 res = PXE_ARGUMENT_ERROR;
251
252 return res;
253 }
254
255 /*
256 * Find next word. Handle ',' and '=' as words. Skip whitespace.
257 * Put word info into res_p, res_len.
258 * Returns ptr to next word.
259 */
260 static char *
261 getword(char *p, char **res_p, int *res_len)
262 {
263 /* whitespace at start */
264 while (*p && (*p == ' ' || *p == '\t' || *p == '\n'))
265 p++;
266
267 /* word data */
268 *res_p = p;
269 if (*p == '=' || *p == ',')
270 p++;
271 else
272 while (*p && !(*p == ' ' || *p == '\t' || *p == '\n'
273 || *p == '=' || *p == ','))
274 p++;
275
276 /* word end */
277 *res_len = p - *res_p;
278
279 /* whitespace at end */
280 while (*p && (*p == ' ' || *p == '\t' || *p == '\n'))
281 p++;
282
283 return p;
284 }
285
286 /*
287 * Convert to lowercase asciiz string.
288 */
289 static char *
290 downcase_convert(const uint8 *s, int len)
291 {
292 int c,
293 i;
294 char *res = palloc(len + 1);
295
296 for (i = 0; i < len; i++)
297 {
298 c = s[i];
299 if (c >= 'A' && c <= 'Z')
300 c += 'a' - 'A';
301 res[i] = c;
302 }
303 res[len] = 0;
304 return res;
305 }
306
307 static int
308 parse_args(PGP_Context *ctx, uint8 *args, int arg_len,
309 struct debug_expect *ex)
310 {
311 char *str = downcase_convert(args, arg_len);
312 char *key,
313 *val;
314 int key_len,
315 val_len;
316 int res = 0;
317 char *p = str;
318
319 while (*p)
320 {
321 res = PXE_ARGUMENT_ERROR;
322 p = getword(p, &key, &key_len);
323 if (*p++ != '=')
324 break;
325 p = getword(p, &val, &val_len);
326 if (*p == '\0')
327 ;
328 else if (*p++ != ',')
329 break;
330
331 if (*key == 0 || *val == 0 || val_len == 0)
332 break;
333
334 key[key_len] = 0;
335 val[val_len] = 0;
336
337 res = set_arg(ctx, key, val, ex);
338 if (res < 0)
339 break;
340 }
341 pfree(str);
342 return res;
343 }
344
345 static MBuf *
346 create_mbuf_from_vardata(text *data)
347 {
348 return mbuf_create_from_data((uint8 *) VARDATA_ANY(data),
349 VARSIZE_ANY_EXHDR(data));
350 }
351
352 static void
353 init_work(PGP_Context **ctx_p, int is_text,
354 text *args, struct debug_expect *ex)
355 {
356 int err = pgp_init(ctx_p);
357
358 fill_expect(ex, is_text);
359
360 if (err == 0 && args != NULL)
361 err = parse_args(*ctx_p, (uint8 *) VARDATA_ANY(args),
362 VARSIZE_ANY_EXHDR(args), ex);
363
364 if (err)
365 px_THROW_ERROR(err);
366
367 if (ex->debug)
368 px_set_debug_handler(show_debug);
369
370 pgp_set_text_mode(*ctx_p, is_text);
371 }
372
373 static bytea *
374 encrypt_internal(int is_pubenc, int is_text,
375 text *data, text *key, text *args)
376 {
377 MBuf *src,
378 *dst;
379 uint8 tmp[VARHDRSZ];
380 uint8 *restmp;
381 bytea *res;
382 int res_len;
383 PGP_Context *ctx;
384 int err;
385 struct debug_expect ex;
386 text *tmp_data = NULL;
387
388 init_work(&ctx, is_text, args, &ex);
389
390 if (is_text && pgp_get_unicode_mode(ctx))
391 {
392 tmp_data = convert_to_utf8(data);
393 if (tmp_data == data)
394 tmp_data = NULL;
395 else
396 data = tmp_data;
397 }
398
399 src = create_mbuf_from_vardata(data);
400 dst = mbuf_create(VARSIZE_ANY(data) + 128);
401
402 /*
403 * reserve room for header
404 */
405 mbuf_append(dst, tmp, VARHDRSZ);
406
407 /*
408 * set key
409 */
410 if (is_pubenc)
411 {
412 MBuf *kbuf = create_mbuf_from_vardata(key);
413
414 err = pgp_set_pubkey(ctx, kbuf,
415 NULL, 0, 0);
416 mbuf_free(kbuf);
417 }
418 else
419 err = pgp_set_symkey(ctx, (uint8 *) VARDATA_ANY(key),
420 VARSIZE_ANY_EXHDR(key));
421
422 /*
423 * encrypt
424 */
425 if (err >= 0)
426 err = pgp_encrypt(ctx, src, dst);
427
428 /*
429 * check for error
430 */
431 if (err)
432 {
433 if (ex.debug)
434 px_set_debug_handler(NULL);
435 if (tmp_data)
436 clear_and_pfree(tmp_data);
437 pgp_free(ctx);
438 mbuf_free(src);
439 mbuf_free(dst);
440 px_THROW_ERROR(err);
441 }
442
443 /* res_len includes VARHDRSZ */
444 res_len = mbuf_steal_data(dst, &restmp);
445 res = (bytea *) restmp;
446 SET_VARSIZE(res, res_len);
447
448 if (tmp_data)
449 clear_and_pfree(tmp_data);
450 pgp_free(ctx);
451 mbuf_free(src);
452 mbuf_free(dst);
453
454 px_set_debug_handler(NULL);
455
456 return res;
457 }
458
459 static bytea *
460 decrypt_internal(int is_pubenc, int need_text, text *data,
461 text *key, text *keypsw, text *args)
462 {
463 int err;
464 MBuf *src = NULL,
465 *dst = NULL;
466 uint8 tmp[VARHDRSZ];
467 uint8 *restmp;
468 bytea *res;
469 int res_len;
470 PGP_Context *ctx = NULL;
471 struct debug_expect ex;
472 int got_unicode = 0;
473
474
475 init_work(&ctx, need_text, args, &ex);
476
477 src = mbuf_create_from_data((uint8 *) VARDATA_ANY(data),
478 VARSIZE_ANY_EXHDR(data));
479 dst = mbuf_create(VARSIZE_ANY(data) + 2048);
480
481 /*
482 * reserve room for header
483 */
484 mbuf_append(dst, tmp, VARHDRSZ);
485
486 /*
487 * set key
488 */
489 if (is_pubenc)
490 {
491 uint8 *psw = NULL;
492 int psw_len = 0;
493 MBuf *kbuf;
494
495 if (keypsw)
496 {
497 psw = (uint8 *) VARDATA_ANY(keypsw);
498 psw_len = VARSIZE_ANY_EXHDR(keypsw);
499 }
500 kbuf = create_mbuf_from_vardata(key);
501 err = pgp_set_pubkey(ctx, kbuf, psw, psw_len, 1);
502 mbuf_free(kbuf);
503 }
504 else
505 err = pgp_set_symkey(ctx, (uint8 *) VARDATA_ANY(key),
506 VARSIZE_ANY_EXHDR(key));
507
508 /* decrypt */
509 if (err >= 0)
510 {
511 err = pgp_decrypt(ctx, src, dst);
512
513 if (ex.expect)
514 check_expect(ctx, &ex);
515
516 /* remember the setting */
517 got_unicode = pgp_get_unicode_mode(ctx);
518 }
519
520 mbuf_free(src);
521 pgp_free(ctx);
522
523 if (err)
524 {
525 px_set_debug_handler(NULL);
526 mbuf_free(dst);
527 px_THROW_ERROR(err);
528 }
529
530 res_len = mbuf_steal_data(dst, &restmp);
531 mbuf_free(dst);
532
533 /* res_len includes VARHDRSZ */
534 res = (bytea *) restmp;
535 SET_VARSIZE(res, res_len);
536
537 if (need_text && got_unicode)
538 {
539 text *utf = convert_from_utf8(res);
540
541 if (utf != res)
542 {
543 clear_and_pfree(res);
544 res = utf;
545 }
546 }
547 px_set_debug_handler(NULL);
548
549 return res;
550 }
551
552 /*
553 * Wrappers for symmetric-key functions
554 */
555 Datum
556 pgp_sym_encrypt_bytea(PG_FUNCTION_ARGS)
557 {
558 bytea *data;
559 text *arg = NULL;
560 text *res,
561 *key;
562
563 data = PG_GETARG_BYTEA_PP(0);
564 key = PG_GETARG_TEXT_PP(1);
565 if (PG_NARGS() > 2)
566 arg = PG_GETARG_TEXT_PP(2);
567
568 res = encrypt_internal(0, 0, data, key, arg);
569
570 PG_FREE_IF_COPY(data, 0);
571 PG_FREE_IF_COPY(key, 1);
572 if (PG_NARGS() > 2)
573 PG_FREE_IF_COPY(arg, 2);
574 PG_RETURN_TEXT_P(res);
575 }
576
577 Datum
578 pgp_sym_encrypt_text(PG_FUNCTION_ARGS)
579 {
580 text *data,
581 *key;
582 text *arg = NULL;
583 text *res;
584
585 data = PG_GETARG_TEXT_PP(0);
586 key = PG_GETARG_TEXT_PP(1);
587 if (PG_NARGS() > 2)
588 arg = PG_GETARG_TEXT_PP(2);
589
590 res = encrypt_internal(0, 1, data, key, arg);
591
592 PG_FREE_IF_COPY(data, 0);
593 PG_FREE_IF_COPY(key, 1);
594 if (PG_NARGS() > 2)
595 PG_FREE_IF_COPY(arg, 2);
596 PG_RETURN_TEXT_P(res);
597 }
598
599
600 Datum
601 pgp_sym_decrypt_bytea(PG_FUNCTION_ARGS)
602 {
603 bytea *data;
604 text *arg = NULL;
605 text *res,
606 *key;
607
608 data = PG_GETARG_BYTEA_PP(0);
609 key = PG_GETARG_TEXT_PP(1);
610 if (PG_NARGS() > 2)
611 arg = PG_GETARG_TEXT_PP(2);
612
613 res = decrypt_internal(0, 0, data, key, NULL, arg);
614
615 PG_FREE_IF_COPY(data, 0);
616 PG_FREE_IF_COPY(key, 1);
617 if (PG_NARGS() > 2)
618 PG_FREE_IF_COPY(arg, 2);
619 PG_RETURN_TEXT_P(res);
620 }
621
622 Datum
623 pgp_sym_decrypt_text(PG_FUNCTION_ARGS)
624 {
625 bytea *data;
626 text *arg = NULL;
627 text *res,
628 *key;
629
630 data = PG_GETARG_BYTEA_PP(0);
631 key = PG_GETARG_TEXT_PP(1);
632 if (PG_NARGS() > 2)
633 arg = PG_GETARG_TEXT_PP(2);
634
635 res = decrypt_internal(0, 1, data, key, NULL, arg);
636 pg_verifymbstr(VARDATA_ANY(res), VARSIZE_ANY_EXHDR(res), false);
637
638 PG_FREE_IF_COPY(data, 0);
639 PG_FREE_IF_COPY(key, 1);
640 if (PG_NARGS() > 2)
641 PG_FREE_IF_COPY(arg, 2);
642 PG_RETURN_TEXT_P(res);
643 }
644
645 /*
646 * Wrappers for public-key functions
647 */
648
649 Datum
650 pgp_pub_encrypt_bytea(PG_FUNCTION_ARGS)
651 {
652 bytea *data,
653 *key;
654 text *arg = NULL;
655 text *res;
656
657 data = PG_GETARG_BYTEA_PP(0);
658 key = PG_GETARG_BYTEA_PP(1);
659 if (PG_NARGS() > 2)
660 arg = PG_GETARG_TEXT_PP(2);
661
662 res = encrypt_internal(1, 0, data, key, arg);
663
664 PG_FREE_IF_COPY(data, 0);
665 PG_FREE_IF_COPY(key, 1);
666 if (PG_NARGS() > 2)
667 PG_FREE_IF_COPY(arg, 2);
668 PG_RETURN_TEXT_P(res);
669 }
670
671 Datum
672 pgp_pub_encrypt_text(PG_FUNCTION_ARGS)
673 {
674 bytea *key;
675 text *arg = NULL;
676 text *res,
677 *data;
678
679 data = PG_GETARG_TEXT_PP(0);
680 key = PG_GETARG_BYTEA_PP(1);
681 if (PG_NARGS() > 2)
682 arg = PG_GETARG_TEXT_PP(2);
683
684 res = encrypt_internal(1, 1, data, key, arg);
685
686 PG_FREE_IF_COPY(data, 0);
687 PG_FREE_IF_COPY(key, 1);
688 if (PG_NARGS() > 2)
689 PG_FREE_IF_COPY(arg, 2);
690 PG_RETURN_TEXT_P(res);
691 }
692
693
694 Datum
695 pgp_pub_decrypt_bytea(PG_FUNCTION_ARGS)
696 {
697 bytea *data,
698 *key;
699 text *psw = NULL,
700 *arg = NULL;
701 text *res;
702
703 data = PG_GETARG_BYTEA_PP(0);
704 key = PG_GETARG_BYTEA_PP(1);
705 if (PG_NARGS() > 2)
706 psw = PG_GETARG_TEXT_PP(2);
707 if (PG_NARGS() > 3)
708 arg = PG_GETARG_TEXT_PP(3);
709
710 res = decrypt_internal(1, 0, data, key, psw, arg);
711
712 PG_FREE_IF_COPY(data, 0);
713 PG_FREE_IF_COPY(key, 1);
714 if (PG_NARGS() > 2)
715 PG_FREE_IF_COPY(psw, 2);
716 if (PG_NARGS() > 3)
717 PG_FREE_IF_COPY(arg, 3);
718 PG_RETURN_TEXT_P(res);
719 }
720
721 Datum
722 pgp_pub_decrypt_text(PG_FUNCTION_ARGS)
723 {
724 bytea *data,
725 *key;
726 text *psw = NULL,
727 *arg = NULL;
728 text *res;
729
730 data = PG_GETARG_BYTEA_PP(0);
731 key = PG_GETARG_BYTEA_PP(1);
732 if (PG_NARGS() > 2)
733 psw = PG_GETARG_TEXT_PP(2);
734 if (PG_NARGS() > 3)
735 arg = PG_GETARG_TEXT_PP(3);
736
737 res = decrypt_internal(1, 1, data, key, psw, arg);
738 pg_verifymbstr(VARDATA_ANY(res), VARSIZE_ANY_EXHDR(res), false);
739
740 PG_FREE_IF_COPY(data, 0);
741 PG_FREE_IF_COPY(key, 1);
742 if (PG_NARGS() > 2)
743 PG_FREE_IF_COPY(psw, 2);
744 if (PG_NARGS() > 3)
745 PG_FREE_IF_COPY(arg, 3);
746 PG_RETURN_TEXT_P(res);
747 }
748
749
750 /*
751 * Wrappers for PGP ascii armor
752 */
753
754 /*
755 * Helper function for pg_armor. Converts arrays of keys and values into
756 * plain C arrays, and checks that they don't contain invalid characters.
757 */
758 static int
759 parse_key_value_arrays(ArrayType *key_array, ArrayType *val_array,
760 char ***p_keys, char ***p_values)
761 {
762 int nkdims = ARR_NDIM(key_array);
763 int nvdims = ARR_NDIM(val_array);
764 char **keys,
765 **values;
766 Datum *key_datums,
767 *val_datums;
768 bool *key_nulls,
769 *val_nulls;
770 int key_count,
771 val_count;
772 int i;
773
774 if (nkdims > 1 || nkdims != nvdims)
775 ereport(ERROR,
776 (errcode(ERRCODE_ARRAY_SUBSCRIPT_ERROR),
777 errmsg("wrong number of array subscripts")));
778 if (nkdims == 0)
779 return 0;
780
781 deconstruct_array_builtin(key_array, TEXTOID, &key_datums, &key_nulls, &key_count);
782 deconstruct_array_builtin(val_array, TEXTOID, &val_datums, &val_nulls, &val_count);
783
784 if (key_count != val_count)
785 ereport(ERROR,
786 (errcode(ERRCODE_ARRAY_SUBSCRIPT_ERROR),
787 errmsg("mismatched array dimensions")));
788
789 keys = (char **) palloc(sizeof(char *) * key_count);
790 values = (char **) palloc(sizeof(char *) * val_count);
791
792 for (i = 0; i < key_count; i++)
793 {
794 char *v;
795
796 /* Check that the key doesn't contain anything funny */
797 if (key_nulls[i])
798 ereport(ERROR,
799 (errcode(ERRCODE_NULL_VALUE_NOT_ALLOWED),
800 errmsg("null value not allowed for header key")));
801
802 v = TextDatumGetCString(key_datums[i]);
803
804 if (!pg_is_ascii(v))
805 ereport(ERROR,
806 (errcode(ERRCODE_INVALID_PARAMETER_VALUE),
807 errmsg("header key must not contain non-ASCII characters")));
808 if (strstr(v, ": "))
809 ereport(ERROR,
810 (errcode(ERRCODE_INVALID_PARAMETER_VALUE),
811 errmsg("header key must not contain \": \"")));
812 if (strchr(v, '\n'))
813 ereport(ERROR,
814 (errcode(ERRCODE_INVALID_PARAMETER_VALUE),
815 errmsg("header key must not contain newlines")));
816 keys[i] = v;
817
818 /* And the same for the value */
819 if (val_nulls[i])
820 ereport(ERROR,
821 (errcode(ERRCODE_NULL_VALUE_NOT_ALLOWED),
822 errmsg("null value not allowed for header value")));
823
824 v = TextDatumGetCString(val_datums[i]);
825
826 if (!pg_is_ascii(v))
827 ereport(ERROR,
828 (errcode(ERRCODE_INVALID_PARAMETER_VALUE),
829 errmsg("header value must not contain non-ASCII characters")));
830 if (strchr(v, '\n'))
831 ereport(ERROR,
832 (errcode(ERRCODE_INVALID_PARAMETER_VALUE),
833 errmsg("header value must not contain newlines")));
834
835 values[i] = v;
836 }
837
838 *p_keys = keys;
839 *p_values = values;
840 return key_count;
841 }
842
843 Datum
844 pg_armor(PG_FUNCTION_ARGS)
845 {
846 bytea *data;
847 text *res;
848 int data_len;
849 StringInfoData buf;
850 int num_headers;
851 char **keys = NULL,
852 **values = NULL;
853
854 data = PG_GETARG_BYTEA_PP(0);
855 data_len = VARSIZE_ANY_EXHDR(data);
856 if (PG_NARGS() == 3)
857 {
858 num_headers = parse_key_value_arrays(PG_GETARG_ARRAYTYPE_P(1),
859 PG_GETARG_ARRAYTYPE_P(2),
860 &keys, &values);
861 }
862 else if (PG_NARGS() == 1)
863 num_headers = 0;
864 else
865 elog(ERROR, "unexpected number of arguments %d", PG_NARGS());
866
867 initStringInfo(&buf);
868
869 pgp_armor_encode((uint8 *) VARDATA_ANY(data), data_len, &buf,
870 num_headers, keys, values);
871
872 res = palloc(VARHDRSZ + buf.len);
873 SET_VARSIZE(res, VARHDRSZ + buf.len);
874 memcpy(VARDATA(res), buf.data, buf.len);
875 pfree(buf.data);
876
877 PG_FREE_IF_COPY(data, 0);
878 PG_RETURN_TEXT_P(res);
879 }
880
881 Datum
882 pg_dearmor(PG_FUNCTION_ARGS)
883 {
884 text *data;
885 bytea *res;
886 int data_len;
887 int ret;
888 StringInfoData buf;
889
890 data = PG_GETARG_TEXT_PP(0);
891 data_len = VARSIZE_ANY_EXHDR(data);
892
893 initStringInfo(&buf);
894
895 ret = pgp_armor_decode((uint8 *) VARDATA_ANY(data), data_len, &buf);
896 if (ret < 0)
897 px_THROW_ERROR(ret);
898 res = palloc(VARHDRSZ + buf.len);
899 SET_VARSIZE(res, VARHDRSZ + buf.len);
900 memcpy(VARDATA(res), buf.data, buf.len);
901 pfree(buf.data);
902
903 PG_FREE_IF_COPY(data, 0);
904 PG_RETURN_TEXT_P(res);
905 }
906
907 /* cross-call state for pgp_armor_headers */
908 typedef struct
909 {
910 int nheaders;
911 char **keys;
912 char **values;
913 } pgp_armor_headers_state;
914
915 Datum
916 pgp_armor_headers(PG_FUNCTION_ARGS)
917 {
918 FuncCallContext *funcctx;
919 pgp_armor_headers_state *state;
920 char *utf8key;
921 char *utf8val;
922 HeapTuple tuple;
923 TupleDesc tupdesc;
924 AttInMetadata *attinmeta;
925
926 if (SRF_IS_FIRSTCALL())
927 {
928 text *data = PG_GETARG_TEXT_PP(0);
929 int res;
930 MemoryContext oldcontext;
931
932 funcctx = SRF_FIRSTCALL_INIT();
933
934 /* we need the state allocated in the multi call context */
935 oldcontext = MemoryContextSwitchTo(funcctx->multi_call_memory_ctx);
936
937 /* Build a tuple descriptor for our result type */
938 if (get_call_result_type(fcinfo, NULL, &tupdesc) != TYPEFUNC_COMPOSITE)
939 elog(ERROR, "return type must be a row type");
940
941 attinmeta = TupleDescGetAttInMetadata(tupdesc);
942 funcctx->attinmeta = attinmeta;
943
944 state = (pgp_armor_headers_state *) palloc(sizeof(pgp_armor_headers_state));
945
946 res = pgp_extract_armor_headers((uint8 *) VARDATA_ANY(data),
947 VARSIZE_ANY_EXHDR(data),
948 &state->nheaders, &state->keys,
949 &state->values);
950 if (res < 0)
951 px_THROW_ERROR(res);
952
953 MemoryContextSwitchTo(oldcontext);
954 funcctx->user_fctx = state;
955 }
956
957 funcctx = SRF_PERCALL_SETUP();
958 state = (pgp_armor_headers_state *) funcctx->user_fctx;
959
960 if (funcctx->call_cntr >= state->nheaders)
961 SRF_RETURN_DONE(funcctx);
962 else
963 {
964 char *values[2];
965
966 /* we assume that the keys (and values) are in UTF-8. */
967 utf8key = state->keys[funcctx->call_cntr];
968 utf8val = state->values[funcctx->call_cntr];
969
970 values[0] = pg_any_to_server(utf8key, strlen(utf8key), PG_UTF8);
971 values[1] = pg_any_to_server(utf8val, strlen(utf8val), PG_UTF8);
972
973 /* build a tuple */
974 tuple = BuildTupleFromCStrings(funcctx->attinmeta, values);
975 SRF_RETURN_NEXT(funcctx, HeapTupleGetDatum(tuple));
976 }
977 }
978
979
980
981 /*
982 * Wrappers for PGP key id
983 */
984
985 Datum
986 pgp_key_id_w(PG_FUNCTION_ARGS)
987 {
988 bytea *data;
989 text *res;
990 int res_len;
991 MBuf *buf;
992
993 data = PG_GETARG_BYTEA_PP(0);
994 buf = create_mbuf_from_vardata(data);
995 res = palloc(VARHDRSZ + 17);
996
997 res_len = pgp_get_keyid(buf, VARDATA(res));
998 mbuf_free(buf);
999 if (res_len < 0)
1000 px_THROW_ERROR(res_len);
1001 SET_VARSIZE(res, VARHDRSZ + res_len);
1002
1003 PG_FREE_IF_COPY(data, 0);
1004 PG_RETURN_TEXT_P(res);
1005 }