1 // Copyright 2014 The Chromium Authors. All rights reserved.
2 // Use of this source code is governed by a BSD-style license that can be
3 // found in the LICENSE file.
4
5 #include "crypto/openssl_bio_string.h"
6
7 #include <openssl/bio.h>
8 #include <string.h>
9
10 namespace crypto {
11
12 namespace {
13
bio_string_write(BIO * bio,const char * data,int len)14 int bio_string_write(BIO* bio, const char* data, int len) {
15 reinterpret_cast<std::string*>(bio->ptr)->append(data, len);
16 return len;
17 }
18
bio_string_puts(BIO * bio,const char * data)19 int bio_string_puts(BIO* bio, const char* data) {
20 // Note: unlike puts(), BIO_puts does not add a newline.
21 return bio_string_write(bio, data, strlen(data));
22 }
23
bio_string_ctrl(BIO * bio,int cmd,long num,void * ptr)24 long bio_string_ctrl(BIO* bio, int cmd, long num, void* ptr) {
25 std::string* str = reinterpret_cast<std::string*>(bio->ptr);
26 switch (cmd) {
27 case BIO_CTRL_RESET:
28 str->clear();
29 return 1;
30 case BIO_C_FILE_SEEK:
31 return -1;
32 case BIO_C_FILE_TELL:
33 return str->size();
34 case BIO_CTRL_FLUSH:
35 return 1;
36 default:
37 return 0;
38 }
39 }
40
bio_string_new(BIO * bio)41 int bio_string_new(BIO* bio) {
42 bio->ptr = NULL;
43 bio->init = 0;
44 return 1;
45 }
46
bio_string_free(BIO * bio)47 int bio_string_free(BIO* bio) {
48 // The string is owned by the caller, so there's nothing to do here.
49 return bio != NULL;
50 }
51
52 BIO_METHOD bio_string_methods = {
53 // TODO(mattm): Should add some type number too? (bio.h uses 1-24)
54 BIO_TYPE_SOURCE_SINK,
55 "bio_string",
56 bio_string_write,
57 NULL, /* read */
58 bio_string_puts,
59 NULL, /* gets */
60 bio_string_ctrl,
61 bio_string_new,
62 bio_string_free,
63 NULL, /* callback_ctrl */
64 };
65
66 } // namespace
67
BIO_new_string(std::string * out)68 BIO* BIO_new_string(std::string* out) {
69 BIO* bio = BIO_new(&bio_string_methods);
70 if (!bio)
71 return bio;
72 bio->ptr = out;
73 bio->init = 1;
74 return bio;
75 }
76
77 } // namespace crypto
78