├── LICENSE
├── Makefile
├── README.md
├── async-ssl-cli.cc
├── async-ssl-svr.cc
├── server.pem
├── sync-ssl-cli.cc
└── sync-ssl-svr.cc
/LICENSE:
--------------------------------------------------------------------------------
1 | GNU GENERAL PUBLIC LICENSE
2 | Version 2, June 1991
3 |
4 | Copyright (C) 1989, 1991 Free Software Foundation, Inc.,
5 | 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
6 | Everyone is permitted to copy and distribute verbatim copies
7 | of this license document, but changing it is not allowed.
8 |
9 | Preamble
10 |
11 | The licenses for most software are designed to take away your
12 | freedom to share and change it. By contrast, the GNU General Public
13 | License is intended to guarantee your freedom to share and change free
14 | software--to make sure the software is free for all its users. This
15 | General Public License applies to most of the Free Software
16 | Foundation's software and to any other program whose authors commit to
17 | using it. (Some other Free Software Foundation software is covered by
18 | the GNU Lesser General Public License instead.) You can apply it to
19 | your programs, too.
20 |
21 | When we speak of free software, we are referring to freedom, not
22 | price. Our General Public Licenses are designed to make sure that you
23 | have the freedom to distribute copies of free software (and charge for
24 | this service if you wish), that you receive source code or can get it
25 | if you want it, that you can change the software or use pieces of it
26 | in new free programs; and that you know you can do these things.
27 |
28 | To protect your rights, we need to make restrictions that forbid
29 | anyone to deny you these rights or to ask you to surrender the rights.
30 | These restrictions translate to certain responsibilities for you if you
31 | distribute copies of the software, or if you modify it.
32 |
33 | For example, if you distribute copies of such a program, whether
34 | gratis or for a fee, you must give the recipients all the rights that
35 | you have. You must make sure that they, too, receive or can get the
36 | source code. And you must show them these terms so they know their
37 | rights.
38 |
39 | We protect your rights with two steps: (1) copyright the software, and
40 | (2) offer you this license which gives you legal permission to copy,
41 | distribute and/or modify the software.
42 |
43 | Also, for each author's protection and ours, we want to make certain
44 | that everyone understands that there is no warranty for this free
45 | software. If the software is modified by someone else and passed on, we
46 | want its recipients to know that what they have is not the original, so
47 | that any problems introduced by others will not reflect on the original
48 | authors' reputations.
49 |
50 | Finally, any free program is threatened constantly by software
51 | patents. We wish to avoid the danger that redistributors of a free
52 | program will individually obtain patent licenses, in effect making the
53 | program proprietary. To prevent this, we have made it clear that any
54 | patent must be licensed for everyone's free use or not licensed at all.
55 |
56 | The precise terms and conditions for copying, distribution and
57 | modification follow.
58 |
59 | GNU GENERAL PUBLIC LICENSE
60 | TERMS AND CONDITIONS FOR COPYING, DISTRIBUTION AND MODIFICATION
61 |
62 | 0. This License applies to any program or other work which contains
63 | a notice placed by the copyright holder saying it may be distributed
64 | under the terms of this General Public License. The "Program", below,
65 | refers to any such program or work, and a "work based on the Program"
66 | means either the Program or any derivative work under copyright law:
67 | that is to say, a work containing the Program or a portion of it,
68 | either verbatim or with modifications and/or translated into another
69 | language. (Hereinafter, translation is included without limitation in
70 | the term "modification".) Each licensee is addressed as "you".
71 |
72 | Activities other than copying, distribution and modification are not
73 | covered by this License; they are outside its scope. The act of
74 | running the Program is not restricted, and the output from the Program
75 | is covered only if its contents constitute a work based on the
76 | Program (independent of having been made by running the Program).
77 | Whether that is true depends on what the Program does.
78 |
79 | 1. You may copy and distribute verbatim copies of the Program's
80 | source code as you receive it, in any medium, provided that you
81 | conspicuously and appropriately publish on each copy an appropriate
82 | copyright notice and disclaimer of warranty; keep intact all the
83 | notices that refer to this License and to the absence of any warranty;
84 | and give any other recipients of the Program a copy of this License
85 | along with the Program.
86 |
87 | You may charge a fee for the physical act of transferring a copy, and
88 | you may at your option offer warranty protection in exchange for a fee.
89 |
90 | 2. You may modify your copy or copies of the Program or any portion
91 | of it, thus forming a work based on the Program, and copy and
92 | distribute such modifications or work under the terms of Section 1
93 | above, provided that you also meet all of these conditions:
94 |
95 | a) You must cause the modified files to carry prominent notices
96 | stating that you changed the files and the date of any change.
97 |
98 | b) You must cause any work that you distribute or publish, that in
99 | whole or in part contains or is derived from the Program or any
100 | part thereof, to be licensed as a whole at no charge to all third
101 | parties under the terms of this License.
102 |
103 | c) If the modified program normally reads commands interactively
104 | when run, you must cause it, when started running for such
105 | interactive use in the most ordinary way, to print or display an
106 | announcement including an appropriate copyright notice and a
107 | notice that there is no warranty (or else, saying that you provide
108 | a warranty) and that users may redistribute the program under
109 | these conditions, and telling the user how to view a copy of this
110 | License. (Exception: if the Program itself is interactive but
111 | does not normally print such an announcement, your work based on
112 | the Program is not required to print an announcement.)
113 |
114 | These requirements apply to the modified work as a whole. If
115 | identifiable sections of that work are not derived from the Program,
116 | and can be reasonably considered independent and separate works in
117 | themselves, then this License, and its terms, do not apply to those
118 | sections when you distribute them as separate works. But when you
119 | distribute the same sections as part of a whole which is a work based
120 | on the Program, the distribution of the whole must be on the terms of
121 | this License, whose permissions for other licensees extend to the
122 | entire whole, and thus to each and every part regardless of who wrote it.
123 |
124 | Thus, it is not the intent of this section to claim rights or contest
125 | your rights to work written entirely by you; rather, the intent is to
126 | exercise the right to control the distribution of derivative or
127 | collective works based on the Program.
128 |
129 | In addition, mere aggregation of another work not based on the Program
130 | with the Program (or with a work based on the Program) on a volume of
131 | a storage or distribution medium does not bring the other work under
132 | the scope of this License.
133 |
134 | 3. You may copy and distribute the Program (or a work based on it,
135 | under Section 2) in object code or executable form under the terms of
136 | Sections 1 and 2 above provided that you also do one of the following:
137 |
138 | a) Accompany it with the complete corresponding machine-readable
139 | source code, which must be distributed under the terms of Sections
140 | 1 and 2 above on a medium customarily used for software interchange; or,
141 |
142 | b) Accompany it with a written offer, valid for at least three
143 | years, to give any third party, for a charge no more than your
144 | cost of physically performing source distribution, a complete
145 | machine-readable copy of the corresponding source code, to be
146 | distributed under the terms of Sections 1 and 2 above on a medium
147 | customarily used for software interchange; or,
148 |
149 | c) Accompany it with the information you received as to the offer
150 | to distribute corresponding source code. (This alternative is
151 | allowed only for noncommercial distribution and only if you
152 | received the program in object code or executable form with such
153 | an offer, in accord with Subsection b above.)
154 |
155 | The source code for a work means the preferred form of the work for
156 | making modifications to it. For an executable work, complete source
157 | code means all the source code for all modules it contains, plus any
158 | associated interface definition files, plus the scripts used to
159 | control compilation and installation of the executable. However, as a
160 | special exception, the source code distributed need not include
161 | anything that is normally distributed (in either source or binary
162 | form) with the major components (compiler, kernel, and so on) of the
163 | operating system on which the executable runs, unless that component
164 | itself accompanies the executable.
165 |
166 | If distribution of executable or object code is made by offering
167 | access to copy from a designated place, then offering equivalent
168 | access to copy the source code from the same place counts as
169 | distribution of the source code, even though third parties are not
170 | compelled to copy the source along with the object code.
171 |
172 | 4. You may not copy, modify, sublicense, or distribute the Program
173 | except as expressly provided under this License. Any attempt
174 | otherwise to copy, modify, sublicense or distribute the Program is
175 | void, and will automatically terminate your rights under this License.
176 | However, parties who have received copies, or rights, from you under
177 | this License will not have their licenses terminated so long as such
178 | parties remain in full compliance.
179 |
180 | 5. You are not required to accept this License, since you have not
181 | signed it. However, nothing else grants you permission to modify or
182 | distribute the Program or its derivative works. These actions are
183 | prohibited by law if you do not accept this License. Therefore, by
184 | modifying or distributing the Program (or any work based on the
185 | Program), you indicate your acceptance of this License to do so, and
186 | all its terms and conditions for copying, distributing or modifying
187 | the Program or works based on it.
188 |
189 | 6. Each time you redistribute the Program (or any work based on the
190 | Program), the recipient automatically receives a license from the
191 | original licensor to copy, distribute or modify the Program subject to
192 | these terms and conditions. You may not impose any further
193 | restrictions on the recipients' exercise of the rights granted herein.
194 | You are not responsible for enforcing compliance by third parties to
195 | this License.
196 |
197 | 7. If, as a consequence of a court judgment or allegation of patent
198 | infringement or for any other reason (not limited to patent issues),
199 | conditions are imposed on you (whether by court order, agreement or
200 | otherwise) that contradict the conditions of this License, they do not
201 | excuse you from the conditions of this License. If you cannot
202 | distribute so as to satisfy simultaneously your obligations under this
203 | License and any other pertinent obligations, then as a consequence you
204 | may not distribute the Program at all. For example, if a patent
205 | license would not permit royalty-free redistribution of the Program by
206 | all those who receive copies directly or indirectly through you, then
207 | the only way you could satisfy both it and this License would be to
208 | refrain entirely from distribution of the Program.
209 |
210 | If any portion of this section is held invalid or unenforceable under
211 | any particular circumstance, the balance of the section is intended to
212 | apply and the section as a whole is intended to apply in other
213 | circumstances.
214 |
215 | It is not the purpose of this section to induce you to infringe any
216 | patents or other property right claims or to contest validity of any
217 | such claims; this section has the sole purpose of protecting the
218 | integrity of the free software distribution system, which is
219 | implemented by public license practices. Many people have made
220 | generous contributions to the wide range of software distributed
221 | through that system in reliance on consistent application of that
222 | system; it is up to the author/donor to decide if he or she is willing
223 | to distribute software through any other system and a licensee cannot
224 | impose that choice.
225 |
226 | This section is intended to make thoroughly clear what is believed to
227 | be a consequence of the rest of this License.
228 |
229 | 8. If the distribution and/or use of the Program is restricted in
230 | certain countries either by patents or by copyrighted interfaces, the
231 | original copyright holder who places the Program under this License
232 | may add an explicit geographical distribution limitation excluding
233 | those countries, so that distribution is permitted only in or among
234 | countries not thus excluded. In such case, this License incorporates
235 | the limitation as if written in the body of this License.
236 |
237 | 9. The Free Software Foundation may publish revised and/or new versions
238 | of the General Public License from time to time. Such new versions will
239 | be similar in spirit to the present version, but may differ in detail to
240 | address new problems or concerns.
241 |
242 | Each version is given a distinguishing version number. If the Program
243 | specifies a version number of this License which applies to it and "any
244 | later version", you have the option of following the terms and conditions
245 | either of that version or of any later version published by the Free
246 | Software Foundation. If the Program does not specify a version number of
247 | this License, you may choose any version ever published by the Free Software
248 | Foundation.
249 |
250 | 10. If you wish to incorporate parts of the Program into other free
251 | programs whose distribution conditions are different, write to the author
252 | to ask for permission. For software which is copyrighted by the Free
253 | Software Foundation, write to the Free Software Foundation; we sometimes
254 | make exceptions for this. Our decision will be guided by the two goals
255 | of preserving the free status of all derivatives of our free software and
256 | of promoting the sharing and reuse of software generally.
257 |
258 | NO WARRANTY
259 |
260 | 11. BECAUSE THE PROGRAM IS LICENSED FREE OF CHARGE, THERE IS NO WARRANTY
261 | FOR THE PROGRAM, TO THE EXTENT PERMITTED BY APPLICABLE LAW. EXCEPT WHEN
262 | OTHERWISE STATED IN WRITING THE COPYRIGHT HOLDERS AND/OR OTHER PARTIES
263 | PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED
264 | OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
265 | MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. THE ENTIRE RISK AS
266 | TO THE QUALITY AND PERFORMANCE OF THE PROGRAM IS WITH YOU. SHOULD THE
267 | PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF ALL NECESSARY SERVICING,
268 | REPAIR OR CORRECTION.
269 |
270 | 12. IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING
271 | WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MAY MODIFY AND/OR
272 | REDISTRIBUTE THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES,
273 | INCLUDING ANY GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING
274 | OUT OF THE USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED
275 | TO LOSS OF DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY
276 | YOU OR THIRD PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER
277 | PROGRAMS), EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE
278 | POSSIBILITY OF SUCH DAMAGES.
279 |
280 | END OF TERMS AND CONDITIONS
281 |
282 | How to Apply These Terms to Your New Programs
283 |
284 | If you develop a new program, and you want it to be of the greatest
285 | possible use to the public, the best way to achieve this is to make it
286 | free software which everyone can redistribute and change under these terms.
287 |
288 | To do so, attach the following notices to the program. It is safest
289 | to attach them to the start of each source file to most effectively
290 | convey the exclusion of warranty; and each file should have at least
291 | the "copyright" line and a pointer to where the full notice is found.
292 |
293 | {description}
294 | Copyright (C) {year} {fullname}
295 |
296 | This program is free software; you can redistribute it and/or modify
297 | it under the terms of the GNU General Public License as published by
298 | the Free Software Foundation; either version 2 of the License, or
299 | (at your option) any later version.
300 |
301 | This program is distributed in the hope that it will be useful,
302 | but WITHOUT ANY WARRANTY; without even the implied warranty of
303 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
304 | GNU General Public License for more details.
305 |
306 | You should have received a copy of the GNU General Public License along
307 | with this program; if not, write to the Free Software Foundation, Inc.,
308 | 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
309 |
310 | Also add information on how to contact you by electronic and paper mail.
311 |
312 | If the program is interactive, make it output a short notice like this
313 | when it starts in an interactive mode:
314 |
315 | Gnomovision version 69, Copyright (C) year name of author
316 | Gnomovision comes with ABSOLUTELY NO WARRANTY; for details type `show w'.
317 | This is free software, and you are welcome to redistribute it
318 | under certain conditions; type `show c' for details.
319 |
320 | The hypothetical commands `show w' and `show c' should show the appropriate
321 | parts of the General Public License. Of course, the commands you use may
322 | be called something other than `show w' and `show c'; they could even be
323 | mouse-clicks or menu items--whatever suits your program.
324 |
325 | You should also get your employer (if you work as a programmer) or your
326 | school, if any, to sign a "copyright disclaimer" for the program, if
327 | necessary. Here is a sample; alter the names:
328 |
329 | Yoyodyne, Inc., hereby disclaims all copyright interest in the program
330 | `Gnomovision' (which makes passes at compilers) written by James Hacker.
331 |
332 | {signature of Ty Coon}, 1 April 1989
333 | Ty Coon, President of Vice
334 |
335 | This General Public License does not permit incorporating your program into
336 | proprietary programs. If your program is a subroutine library, you may
337 | consider it more useful to permit linking proprietary applications with the
338 | library. If this is what you want to do, use the GNU Lesser General
339 | Public License instead of this License.
340 |
341 |
--------------------------------------------------------------------------------
/Makefile:
--------------------------------------------------------------------------------
1 | SOURCES=async-ssl-svr.cc sync-ssl-svr.cc async-ssl-cli.cc sync-ssl-cli.cc
2 | PROGRAMS = $(SOURCES:.cc=)
3 |
4 | default: $(PROGRAMS)
5 |
6 | clean:
7 | rm *.o $(PROGRAMS) -f
8 |
9 | .cc:
10 | g++ -Wall -g $< -o $@ -lssl -lcrypto
11 |
12 |
--------------------------------------------------------------------------------
/README.md:
--------------------------------------------------------------------------------
1 | install
2 | ====
3 |
4 | make
5 |
6 | usage
7 | ====
8 |
9 | ./async-ssl-svr 443
10 |
11 | ./async-ssl-cli www.openssl.com 443
12 |
13 | ./sync-ssl-svr 443
14 |
15 | ./sync-ssl-cli www.openssl.com 443
16 |
17 | openssl的代码解释
18 | ====
19 | 1. 初始化SSL库
20 | ```c
21 | SSL_load_error_strings ();
22 | SSL_library_init ();
23 | sslContext = SSL_CTX_new (SSLv23_method ());
24 |
25 | //server端需要初始化证书与私钥
26 | string cert = "server.pem", key = "server.pem";
27 | r = SSL_CTX_use_certificate_file(g_sslCtx, cert.c_str(), SSL_FILETYPE_PEM);
28 | r = SSL_CTX_use_PrivateKey_file(g_sslCtx, key.c_str(), SSL_FILETYPE_PEM);
29 | r = SSL_CTX_check_private_key(g_sslCtx);
30 | ```
31 |
32 | 2. 非阻塞方式建立tcp连接(网上有很多epoll相关例子)
33 |
34 | 3. 使用已建立连接的socket初始化ssl
35 | ```c
36 | ch->ssl_ = SSL_new (g_sslCtx);
37 | int r = SSL_set_fd(ch->ssl_, ch->fd_);
38 | //服务器端 SSL_set_accept_state(ch->ssl_);
39 | //客户端 SSL_set_connect_state(ch->ssl_);
40 | ```
41 | 4. epoll_wait后,如果SSL相关的socket有读写事件需要处理则进行SSL握手,直到握手完成
42 | ```c
43 | int r = SSL_do_handshake(ch->ssl_);
44 | if (r == 1) { // 若返回值为1,则SSL握手已完成
45 | ch->sslConnected_ = true;
46 | return;
47 | }
48 | int err = SSL_get_error(ch->ssl_, r);
49 | if (err == SSL_ERROR_WANT_WRITE) { //SSL需要在非阻塞socket可写时写入数据
50 | ch->events_ |= EPOLLOUT;
51 | ch->events_ &= ~EPOLLIN;
52 | } else if (err == SSL_ERROR_WANT_READ) { //SSL需要在非阻塞socket可读时读入数据
53 | ch->events_ |= EPOLLIN; //等待socket可读
54 | ch->events_ &= ~EPOLLOUT; //暂时不关注socket可写状态
55 | } else { //错误
56 | ERR_print_errors(errBio);
57 | }
58 | ```
59 |
60 | 5. 握手完成后,进行SSL数据的读写
61 | ```c
62 | SSL_write(con->sslHandle, text, len);
63 | SSL_read(con->sslHandle, buf, sizeof buf);
64 | ```
65 | comments
66 | ====
67 |
68 | those examples demostrate how to write sync/async openssl programs
69 |
70 | email
71 | ====
72 |
73 | dongfuye@163.com
74 |
--------------------------------------------------------------------------------
/async-ssl-cli.cc:
--------------------------------------------------------------------------------
1 | #include
2 | #include
3 | #include
4 | #include
5 | #include
6 | #include
7 | #include
8 | #include
9 | #include
10 | #include
11 | #include
12 | #include
13 | #include
14 | #include
15 | #include
16 | #include
17 | #include
18 | #include
19 | #include
20 | #include
21 |
22 | #define log(...) do { printf(__VA_ARGS__); fflush(stdout); } while(0)
23 | #define check0(x, ...) if(x) do { log( __VA_ARGS__); exit(1); } while(0)
24 | #define check1(x, ...) if(!(x)) do { log( __VA_ARGS__); exit(1); } while(0)
25 | SSL_CTX *sslContext;
26 |
27 | struct SSLCon{
28 | int socket;
29 | SSL *sslHandle;
30 | ~SSLCon() {
31 | SSL_shutdown (sslHandle);
32 | SSL_free (sslHandle);
33 | close(socket);
34 | }
35 | };
36 |
37 | int setNonBlock(int fd, bool value) {
38 | int flags = fcntl(fd, F_GETFL, 0);
39 | if (flags < 0) {
40 | return errno;
41 | }
42 | if (value) {
43 | return fcntl(fd, F_SETFL, flags | O_NONBLOCK);
44 | }
45 | return fcntl(fd, F_SETFL, flags & ~O_NONBLOCK);
46 | }
47 |
48 | // Establish a regular tcp connection
49 | int tcpConnect (const char* svr, short port)
50 | {
51 | struct hostent *host = gethostbyname (svr);
52 | int handle = socket (AF_INET, SOCK_STREAM, 0);
53 | check1(handle >= 0, "socket return error");
54 | setNonBlock(handle, true);
55 | struct sockaddr_in server;
56 | bzero (&server, sizeof server);
57 | server.sin_family = AF_INET;
58 | server.sin_port = htons (port);
59 | server.sin_addr = *((struct in_addr *) host->h_addr);
60 |
61 | log("connecting to %s %d\n", svr, port);
62 | int r = connect (handle, (struct sockaddr *) &server,
63 | sizeof (struct sockaddr));
64 | if (r < 0 && (errno == EWOULDBLOCK || errno == EAGAIN)) {
65 | struct pollfd pfd;
66 | pfd.fd = handle;
67 | pfd.events = POLLOUT | POLLERR;
68 | while (r == 0) {
69 | r = poll(&pfd, 1, 100);
70 | }
71 | check1(pfd.revents == POLLOUT, "poll return error events: %d", pfd.revents);
72 | }
73 | check1(r, "connect to %s %d failed\n", svr, port);
74 | log("connected to %s %d\n", svr, port);
75 | return handle;
76 | }
77 |
78 | void sslConnect (SSLCon* con, const char* host, short port)
79 | {
80 | bzero(con, sizeof *con);
81 | con->socket = tcpConnect (host, port);
82 |
83 | con->sslHandle = SSL_new (sslContext);
84 | if (con->sslHandle == NULL) {
85 | ERR_print_errors_fp (stderr);
86 | check1(0, "SSL_new failed");
87 | }
88 |
89 | if (!SSL_set_fd (con->sslHandle, con->socket)) {
90 | ERR_print_errors_fp (stderr);
91 | check1(0, "SSL_set_fd failed");
92 | }
93 |
94 | SSL_set_connect_state (con->sslHandle);
95 | int r = 0;
96 | int events = POLLIN | POLLOUT | POLLERR;
97 | while ((r = SSL_do_handshake(con->sslHandle)) != 1) {
98 | int err = SSL_get_error(con->sslHandle, r);
99 | if (err == SSL_ERROR_WANT_WRITE) {
100 | events |= POLLOUT;
101 | events &= ~POLLIN;
102 | log("return want write set events %d\n", events);
103 | } else if (err == SSL_ERROR_WANT_READ) {
104 | events |= EPOLLIN;
105 | events &= ~EPOLLOUT;
106 | log("return want read set events %d\n", events);
107 | } else {
108 | log("SSL_do_handshake return %d error %d errno %d msg %s\n", r, err, errno, strerror(errno));
109 | ERR_print_errors_fp(stderr);
110 | check1(0, "do handshake error");
111 | }
112 | struct pollfd pfd;
113 | pfd.fd = con->socket;
114 | pfd.events = events;
115 | do {
116 | r = poll(&pfd, 1, 100);
117 | } while (r == 0);
118 | check1(r == 1, "poll return %d error events: %d errno %d %s\n", r, pfd.revents, errno, strerror(errno));
119 | }
120 | log("ssl connected \n");
121 | }
122 |
123 | void sslRead (SSLCon* con)
124 | {
125 | char buf[256];
126 | int rd = 0;
127 | int r = 1;
128 | while (rd < int(sizeof buf) && r) {
129 | log("reading\n");
130 |
131 | struct pollfd pfd;
132 | pfd.fd = con->socket;
133 | pfd.events = POLLIN;
134 | do {
135 | r = poll(&pfd, 1, 100);
136 | }while (r == 0);
137 |
138 | r = SSL_read(con->sslHandle, buf+rd, sizeof buf - rd);
139 | if (r < 0) {
140 | int err = SSL_get_error(con->sslHandle, r);
141 | if (err == SSL_ERROR_WANT_READ) {
142 | continue;
143 | }
144 | ERR_print_errors_fp (stderr);
145 | }
146 | check1(r >= 0, "SSL_read error return %d errno %d msg %s", r, errno, strerror(errno));
147 | log("read %d bytes\n", r);
148 | rd += r;
149 | }
150 | log("read %d bytes contents:\n%.*s\n", rd, rd, buf);
151 | }
152 |
153 | void sslWrite (SSLCon* con, const char *text)
154 | {
155 | int len = strlen(text);
156 | int wd = SSL_write (con->sslHandle, text, len);
157 | check1(wd == len, "SSL_write error. return %d errno %d msg %s", wd, errno, strerror(errno));
158 | log("sslWrite %d bytes\n", len);
159 | }
160 |
161 | int main (int argc, char **argv)
162 | {
163 | if (argc < 3) {
164 | printf("usage %s \n", argv[0]);
165 | return 0;
166 | }
167 | SSL_load_error_strings ();
168 | SSL_library_init ();
169 | sslContext = SSL_CTX_new (SSLv23_client_method ());
170 | if (sslContext == NULL)
171 | ERR_print_errors_fp (stderr);
172 | {
173 | SSLCon con;
174 | sslConnect(&con, argv[1], atoi(argv[2]));
175 | sslWrite (&con, "GET /\r\n\r\n");
176 | sslRead (&con);
177 | }
178 | SSL_CTX_free (sslContext);
179 | return 0;
180 | }
181 |
--------------------------------------------------------------------------------
/async-ssl-svr.cc:
--------------------------------------------------------------------------------
1 | #include
2 | #include
3 | #include
4 | #include
5 | #include
6 | #include
7 | #include
8 | #include
9 | #include
10 | #include
11 | #include
12 | #include
13 | #include
14 | #include
15 | #include
16 | #include
17 | #include
18 | #include
19 | #include
20 | #include
21 |
22 | using namespace std;
23 |
24 | #define log(...) do { printf(__VA_ARGS__); fflush(stdout); } while(0)
25 | #define check0(x, ...) if(x) do { log( __VA_ARGS__); exit(1); } while(0)
26 | #define check1(x, ...) if(!x) do { log( __VA_ARGS__); exit(1); } while(0)
27 |
28 | BIO* errBio;
29 | SSL_CTX* g_sslCtx;
30 |
31 | int epollfd, listenfd;
32 |
33 | struct Channel {
34 | int fd_;
35 | SSL *ssl_;
36 | bool tcpConnected_;
37 | bool sslConnected_;
38 | int events_;
39 | Channel(int fd, int events) {
40 | memset(this, 0, sizeof *this);
41 | fd_ = fd;
42 | events_ = events;
43 | }
44 | void update() {
45 | struct epoll_event ev;
46 | memset(&ev, 0, sizeof(ev));
47 | ev.events = events_;
48 | ev.data.ptr = this;
49 | log("modifying fd %d events read %d write %d\n",
50 | fd_, ev.events & EPOLLIN, ev.events & EPOLLOUT);
51 | int r = epoll_ctl(epollfd, EPOLL_CTL_MOD, fd_, &ev);
52 | check0(r, "epoll_ctl mod failed %d %s", errno, strerror(errno));
53 | }
54 | ~Channel() {
55 | log("deleting fd %d\n", fd_);
56 | close(fd_);
57 | if (ssl_) {
58 | SSL_shutdown (ssl_);
59 | SSL_free(ssl_);
60 | }
61 | }
62 | };
63 |
64 | int setNonBlock(int fd, bool value) {
65 | int flags = fcntl(fd, F_GETFL, 0);
66 | if (flags < 0) {
67 | return errno;
68 | }
69 | if (value) {
70 | return fcntl(fd, F_SETFL, flags | O_NONBLOCK);
71 | }
72 | return fcntl(fd, F_SETFL, flags & ~O_NONBLOCK);
73 | }
74 |
75 |
76 | void addEpollFd(int epollfd, Channel* ch) {
77 | struct epoll_event ev;
78 | memset(&ev, 0, sizeof(ev));
79 | ev.events = ch->events_;
80 | ev.data.ptr = ch;
81 | log("adding fd %d events %d\n", ch->fd_, ev.events);
82 | int r = epoll_ctl(epollfd, EPOLL_CTL_ADD, ch->fd_, &ev);
83 | check0(r, "epoll_ctl add failed %d %s", errno, strerror(errno));
84 | }
85 |
86 | int createServer(short port) {
87 | int fd = socket(AF_INET, SOCK_STREAM|SOCK_CLOEXEC, 0);
88 | setNonBlock(fd, 1);
89 | struct sockaddr_in addr;
90 | memset(&addr, 0, sizeof addr);
91 | addr.sin_family = AF_INET;
92 | addr.sin_port = htons(port);
93 | addr.sin_addr.s_addr = INADDR_ANY;
94 | int r = ::bind(fd,(struct sockaddr *)&addr, sizeof(struct sockaddr));
95 | check0(r, "bind to 0.0.0.0:%d failed %d %s", port, errno, strerror(errno));
96 | r = listen(fd, 20);
97 | check0(r, "listen failed %d %s", errno, strerror(errno));
98 | log("fd %d listening at %d\n", fd, port);
99 | return fd;
100 | }
101 |
102 | void handleAccept() {
103 | struct sockaddr_in raddr;
104 | socklen_t rsz = sizeof(raddr);
105 | int cfd;
106 | while ((cfd = accept4(listenfd,(struct sockaddr *)&raddr,&rsz, SOCK_CLOEXEC))>=0) {
107 | sockaddr_in peer, local;
108 | socklen_t alen = sizeof(peer);
109 | int r = getpeername(cfd, (sockaddr*)&peer, &alen);
110 | if (r < 0) {
111 | log("get peer name failed %d %s\n", errno, strerror(errno));
112 | continue;
113 | }
114 | r = getsockname(cfd, (sockaddr*)&local, &alen);
115 | if (r < 0) {
116 | log("getsockname failed %d %s\n", errno, strerror(errno));
117 | continue;
118 | }
119 | setNonBlock(cfd, 1);
120 | Channel* ch = new Channel(cfd, EPOLLIN | EPOLLOUT);
121 | addEpollFd(epollfd, ch);
122 | }
123 | }
124 |
125 | void handleHandshake(Channel* ch) {
126 | if (!ch->tcpConnected_) {
127 | struct pollfd pfd;
128 | pfd.fd = ch->fd_;
129 | pfd.events = POLLOUT | POLLERR;
130 | int r = poll(&pfd, 1, 0);
131 | if (r == 1 && pfd.revents == POLLOUT) {
132 | log("tcp connected fd %d\n", ch->fd_);
133 | ch->tcpConnected_ = true;
134 | ch->events_ = EPOLLIN | EPOLLOUT | EPOLLERR;
135 | ch->update();
136 | } else {
137 | log("poll fd %d return %d revents %d\n", ch->fd_, r, pfd.revents);
138 | delete ch;
139 | return;
140 | }
141 | }
142 | if (ch->ssl_ == NULL) {
143 | ch->ssl_ = SSL_new (g_sslCtx);
144 | check0(ch->ssl_ == NULL, "SSL_new failed");
145 | int r = SSL_set_fd(ch->ssl_, ch->fd_);
146 | check0(!r, "SSL_set_fd failed");
147 | log("SSL_set_accept_state for fd %d\n", ch->fd_);
148 | SSL_set_accept_state(ch->ssl_);
149 | }
150 | int r = SSL_do_handshake(ch->ssl_);
151 | if (r == 1) {
152 | ch->sslConnected_ = true;
153 | log("ssl connected fd %d\n", ch->fd_);
154 | return;
155 | }
156 | int err = SSL_get_error(ch->ssl_, r);
157 | int oldev = ch->events_;
158 | if (err == SSL_ERROR_WANT_WRITE) {
159 | ch->events_ |= EPOLLOUT;
160 | ch->events_ &= ~EPOLLIN;
161 | log("return want write set events %d\n", ch->events_);
162 | if (oldev == ch->events_) return;
163 | ch->update();
164 | } else if (err == SSL_ERROR_WANT_READ) {
165 | ch->events_ |= EPOLLIN;
166 | ch->events_ &= ~EPOLLOUT;
167 | log("return want read set events %d\n", ch->events_);
168 | if (oldev == ch->events_) return;
169 | ch->update();
170 | } else {
171 | log("SSL_do_handshake return %d error %d errno %d msg %s\n", r, err, errno, strerror(errno));
172 | ERR_print_errors(errBio);
173 | delete ch;
174 | }
175 | }
176 |
177 | void handleDataRead(Channel* ch) {
178 | char buf[4096];
179 | int rd = SSL_read(ch->ssl_, buf, sizeof buf);
180 | int ssle = SSL_get_error(ch->ssl_, rd);
181 | if (rd > 0) {
182 | const char* cont = "HTTP/1.1 200 OK\r\nConnection: Close\r\n\r\n";
183 | int len1 = strlen(cont);
184 | int wd = SSL_write(ch->ssl_, cont, len1);
185 | log("SSL_write %d bytes\n", wd);
186 | delete ch;
187 | }
188 | if (rd < 0 && ssle != SSL_ERROR_WANT_READ) {
189 | log("SSL_read return %d error %d errno %d msg %s", rd, ssle, errno, strerror(errno));
190 | delete ch;
191 | return;
192 | }
193 | if (rd == 0) {
194 | if (ssle == SSL_ERROR_ZERO_RETURN)
195 | log("SSL has been shutdown.\n");
196 | else
197 | log("Connection has been aborted.\n");
198 | delete ch;
199 | }
200 | }
201 |
202 | void handleRead(Channel* ch) {
203 | if (ch->fd_ == listenfd) {
204 | return handleAccept();
205 | }
206 | if (ch->sslConnected_) {
207 | return handleDataRead(ch);
208 | }
209 | handleHandshake(ch);
210 | }
211 |
212 | void handleWrite(Channel* ch) {
213 | if (!ch->sslConnected_) {
214 | return handleHandshake(ch);
215 | }
216 | log("handle write fd %d\n", ch->fd_);
217 | ch->events_ &= ~EPOLLOUT;
218 | ch->update();
219 | }
220 |
221 | void initSSL() {
222 | SSL_load_error_strings ();
223 | int r = SSL_library_init ();
224 | check0(!r, "SSL_library_init failed");
225 | g_sslCtx = SSL_CTX_new (SSLv23_method ());
226 | check0(g_sslCtx == NULL, "SSL_CTX_new failed");
227 | errBio = BIO_new_fd(2, BIO_NOCLOSE);
228 | string cert = "server.pem", key = "server.pem";
229 | r = SSL_CTX_use_certificate_file(g_sslCtx, cert.c_str(), SSL_FILETYPE_PEM);
230 | check0(r<=0, "SSL_CTX_use_certificate_file %s failed", cert.c_str());
231 | r = SSL_CTX_use_PrivateKey_file(g_sslCtx, key.c_str(), SSL_FILETYPE_PEM);
232 | check0(r<=0, "SSL_CTX_use_PrivateKey_file %s failed", key.c_str());
233 | r = SSL_CTX_check_private_key(g_sslCtx);
234 | check0(!r, "SSL_CTX_check_private_key failed");
235 | log("SSL inited\n");
236 | }
237 |
238 | int g_stop = 0;
239 |
240 | void loop_once(int epollfd, int waitms) {
241 | const int kMaxEvents = 20;
242 | struct epoll_event activeEvs[kMaxEvents];
243 | int n = epoll_wait(epollfd, activeEvs, kMaxEvents, waitms);
244 | for (int i = n-1; i >= 0; i --) {
245 | Channel* ch = (Channel*)activeEvs[i].data.ptr;
246 | int events = activeEvs[i].events;
247 | if (events & (EPOLLIN | EPOLLERR)) {
248 | log("fd %d handle read\n", ch->fd_);
249 | handleRead(ch);
250 | } else if (events & EPOLLOUT) {
251 | log("fd %d handle write\n", ch->fd_);
252 | handleWrite(ch);
253 | } else {
254 | log("unknown event %d\n", events);
255 | }
256 | }
257 | }
258 |
259 | void handleInterrupt(int sig) {
260 | g_stop = true;
261 | }
262 |
263 | int main(int argc, char **argv)
264 | {
265 | signal(SIGINT, handleInterrupt);
266 | initSSL();
267 | epollfd = epoll_create1(EPOLL_CLOEXEC);
268 | listenfd = createServer(443);
269 | Channel* li = new Channel(listenfd, EPOLLIN);
270 | addEpollFd(epollfd, li);
271 | while (!g_stop) {
272 | loop_once(epollfd, 100);
273 | }
274 | delete li;
275 | ::close(epollfd);
276 | BIO_free(errBio);
277 | SSL_CTX_free(g_sslCtx);
278 | ERR_free_strings();
279 | log("program exited\n");
280 | return 0;
281 | }
282 |
--------------------------------------------------------------------------------
/server.pem:
--------------------------------------------------------------------------------
1 | -----BEGIN PRIVATE KEY-----
2 | MIIEvgIBADANBgkqhkiG9w0BAQEFAASCBKgwggSkAgEAAoIBAQC+Z2mi8shZ3T0c
3 | 5ItI4KwLfYFXxNr3dmIY+2DS9boD18T46Ccow3wW/15SCcI1BdD/pPBmOTpUWP0b
4 | B22l4gAOUIWfk/CAHuaD+pHAGMlolAMdscwDZPdaM3XEdu839y2gy6RL4Pxls8No
5 | sI5h2BTGl3YgjSxA+vKJE+/IXzjajfiKfGHuywPjwPpGl1juOgSaU6zqLf4MlUnq
6 | Daq7r5V9KtJh8dz46PB6c8ALGNM+dxMJSLMyDvT1/7d9aYBkBvpb3mxOu9agIDNn
7 | 2AZ3AxYwA0ykBLmc5R6V0toqRIjfruvBHqQfcjsFaoKS6O+QjtA/eBTIzGajnyis
8 | 1TfeJxURAgMBAAECggEARANIlq5GpuMCW3m/zy6CBjC0rRdiaBbff7D7qx+fbJP8
9 | hjTXGBaMEuLxXDikKLCFMWxHexxiG5MWBjunDSQnhPV6ZcBAnmNrUCWHPqkb+ME2
10 | Q7so9uVv/cZ4AM/DL6iZoeBcNcaOIf4OhSzcD1NSSIX96i7Dagq57AE1G8v30Qlb
11 | CDybxrkbW8D9TkPh57oH/VNuhGLsFp62BjleYtNqo+aknlnHCj09mFQ+N5cA8DuK
12 | 0CcNFCy4C8oZvg9kVsfdypBr4IR0kXTArqMyjUgXe9KqOzf/GdHR9anWhOzHsy/b
13 | T1Nb+vF6fDm0o6WHWhfODoF4iklrdwRibAnme+zegQKBgQDzvt4KQLnG5jWxeCLn
14 | P+QR9q63H98oL3kKToyXPaJVL+I71GtZm4yhYP8KB+bTgrMHPhR5se63cySX2lMJ
15 | RRKkieeEFuDVKVHulRH39g9fMvvl/f97qwv2mAJhdNuIaIjLSVFjQ8WZ6UWvJczp
16 | sTAyhIxDGiOV00HaUp3BFFnEOQKBgQDH+gLGIsLlPAwuMpbSyuDJucMk0Jzo3+at
17 | 6h19pu5JpfTWn71Zs0RL45x9BLwbx8oi+vjECjMiaE2OyKC6uObxpXRl5okWQ63E
18 | XBpbONB+fx2v2h1cuB7iJCJxJ6DPTL70torWtwCp+I7CcIT+J/2SqPhiKipWo0Sk
19 | R2dxeb1HmQKBgEU8mmXfLOZKzkWzEncNtwNDRy3NZ95KXd+HoHf1kf8Qsvq7xCKY
20 | BMJygv+ebvr1zVTpVXecC2sg0ewwoBWqATmr0o+6z/K84gEbZxdAVe181gDmvYOr
21 | eqJ5W3PDdfixeOoF0ZCY17B4isrNuf9HzaEL9au56RHOCI6zmQwXc8hBAoGBAMaI
22 | h0h+Kk+7FbynrOUJVbHwIrTiB2WLJFF1JGIi4F9ty21omWv8dcmB51KW6MoLx7qC
23 | v4ahObLnKlifBjNabq1pPe4MufzIpDNV3TTDavqq6KY1PQFYKhEJHsiINzaXUt1Q
24 | fPY+KQKWKeUQIHjS6wQ3jKCoi/AHl5Yg7anS2v/BAoGBAIi309nwDFJG/2UFSObA
25 | WC+V6T7qy62UlwFlBwsFCbxf9FmFQfoP6wwbQef35Wx2aDnZaSzoXKn/1jvG5e1e
26 | TFW7K9oC8JkeA//mnTAVrgkvkaHGZmd27zQYB1U3DsO3fLvEt62PZn8fyEwaczeM
27 | vOOkHciP4pIhAObg/uiO0V9I
28 | -----END PRIVATE KEY-----
29 | -----BEGIN CERTIFICATE-----
30 | MIIDXTCCAkWgAwIBAgIJAM9HYUREwVxFMA0GCSqGSIb3DQEBCwUAMEUxCzAJBgNV
31 | BAYTAkNOMRMwEQYDVQQIDApTb21lLVN0YXRlMSEwHwYDVQQKDBhJbnRlcm5ldCBX
32 | aWRnaXRzIFB0eSBMdGQwHhcNMTQxMTAxMDY1OTE2WhcNMjQxMDI5MDY1OTE2WjBF
33 | MQswCQYDVQQGEwJDTjETMBEGA1UECAwKU29tZS1TdGF0ZTEhMB8GA1UECgwYSW50
34 | ZXJuZXQgV2lkZ2l0cyBQdHkgTHRkMIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIB
35 | CgKCAQEAvmdpovLIWd09HOSLSOCsC32BV8Ta93ZiGPtg0vW6A9fE+OgnKMN8Fv9e
36 | UgnCNQXQ/6TwZjk6VFj9GwdtpeIADlCFn5PwgB7mg/qRwBjJaJQDHbHMA2T3WjN1
37 | xHbvN/ctoMukS+D8ZbPDaLCOYdgUxpd2II0sQPryiRPvyF842o34inxh7ssD48D6
38 | RpdY7joEmlOs6i3+DJVJ6g2qu6+VfSrSYfHc+OjwenPACxjTPncTCUizMg709f+3
39 | fWmAZAb6W95sTrvWoCAzZ9gGdwMWMANMpAS5nOUeldLaKkSI367rwR6kH3I7BWqC
40 | kujvkI7QP3gUyMxmo58orNU33icVEQIDAQABo1AwTjAdBgNVHQ4EFgQUJS1vm+Z3
41 | dm8z29qqdzeI94ZmoqwwHwYDVR0jBBgwFoAUJS1vm+Z3dm8z29qqdzeI94Zmoqww
42 | DAYDVR0TBAUwAwEB/zANBgkqhkiG9w0BAQsFAAOCAQEAl/6TWgvtFCcxue+YmpLz
43 | gcPckabL2dbgC7uxbIMgFEJUjtmHRpY1Tih8pKqqbdkPWhK2IBvyCqp7L1P5A4ib
44 | FTKRGogJSaWMjnh/w644yrmsjjo5uoAueqygwha+OAC3gtt6p844hb9KJTjaoMHC
45 | caaZ6jCAnfjAp2O/3bBpgXCy69UNlWizx8aXajn5a9ah/DrY8wZfI+ESRH3oMd/f
46 | hecgZLhdTPSkUJi/l6WK9wBuI8mVl+/Gesi8zgz8u+/BRZsxQoP9tBWUjOG396fm
47 | PCpapHzlchV1N1s0k+poxmoO/GI0GTPcIY3RhU6QJIQ0dtGCLZFVWchJms5u9GBg
48 | xw==
49 | -----END CERTIFICATE-----
50 |
--------------------------------------------------------------------------------
/sync-ssl-cli.cc:
--------------------------------------------------------------------------------
1 | #include
2 | #include
3 | #include
4 | #include
5 | #include
6 | #include
7 | #include
8 | #include
9 | #include
10 |
11 | #include
12 | #include
13 | #include
14 |
15 | #define log(...) do { printf(__VA_ARGS__); fflush(stdout); } while(0)
16 | #define check0(x, ...) if(x) do { log( __VA_ARGS__); exit(1); } while(0)
17 | #define check1(x, ...) if(!(x)) do { log( __VA_ARGS__); exit(1); } while(0)
18 | SSL_CTX *sslContext;
19 |
20 | struct SSLCon{
21 | int socket;
22 | SSL *sslHandle;
23 | ~SSLCon() {
24 | close(socket);
25 | SSL_shutdown (sslHandle);
26 | SSL_free (sslHandle);
27 | }
28 | };
29 |
30 | // Establish a regular tcp connection
31 | int tcpConnect (const char* svr, short port)
32 | {
33 | struct hostent *host = gethostbyname (svr);
34 | int handle = socket (AF_INET, SOCK_STREAM, 0);
35 | check1(handle >= 0, "socket return error");
36 | struct sockaddr_in server;
37 | bzero (&server, sizeof server);
38 | server.sin_family = AF_INET;
39 | server.sin_port = htons (port);
40 | server.sin_addr = *((struct in_addr *) host->h_addr);
41 |
42 | log("connecting to %s %d\n", svr, port);
43 | int r = connect (handle, (struct sockaddr *) &server,
44 | sizeof (struct sockaddr));
45 | check0(r, "connect to %s %d failed\n", svr, port);
46 | log("connected to %s %d\n", svr, port);
47 | return handle;
48 | }
49 |
50 | void sslConnect (SSLCon* con, const char* host, short port)
51 | {
52 | bzero(con, sizeof *con);
53 | con->socket = tcpConnect (host, port);
54 |
55 | con->sslHandle = SSL_new (sslContext);
56 | if (con->sslHandle == NULL) {
57 | ERR_print_errors_fp (stderr);
58 | check1(0, "SSL_new failed");
59 | }
60 |
61 | if (!SSL_set_fd (con->sslHandle, con->socket)) {
62 | ERR_print_errors_fp (stderr);
63 | check1(0, "SSL_set_fd failed");
64 | }
65 |
66 | if (SSL_connect (con->sslHandle) != 1) {
67 | ERR_print_errors_fp (stderr);
68 | check1(0, "SSL_connect failed");
69 | }
70 | }
71 |
72 | void sslRead (SSLCon* con)
73 | {
74 | char buf[256];
75 | int rd = 0;
76 | int r = 1;
77 | while (rd < int(sizeof buf) && r) {
78 | log("reading\n");
79 | r = SSL_read(con->sslHandle, buf+rd, sizeof buf - rd);
80 | if (r < 0) {
81 | ERR_print_errors_fp (stderr);
82 | }
83 | check1(r >= 0, "SSL_read error return %d errno %d msg %s", r, errno, strerror(errno));
84 | log("read %d bytes\n", r);
85 | rd += r;
86 | }
87 | log("read %d bytes contents:\n%.*s\n", rd, rd, buf);
88 | }
89 |
90 | void sslWrite (SSLCon* con, const char *text)
91 | {
92 | int len = strlen(text);
93 | int wd = SSL_write (con->sslHandle, text, len);
94 | check1(wd == len, "SSL_write error. return %d errno %d msg %s", wd, errno, strerror(errno));
95 | log("sslWrite %d bytes\n", len);
96 | }
97 |
98 | int main (int argc, char **argv)
99 | {
100 | if (argc < 3) {
101 | printf("usage %s \n", argv[0]);
102 | return 0;
103 | }
104 | SSL_load_error_strings ();
105 | SSL_library_init ();
106 | sslContext = SSL_CTX_new (SSLv23_client_method ());
107 | if (sslContext == NULL)
108 | ERR_print_errors_fp (stderr);
109 | {
110 | SSLCon con;
111 | sslConnect(&con, argv[1], atoi(argv[2]));
112 | sslWrite (&con, "GET /\r\n\r\n");
113 | sslRead (&con);
114 | }
115 | SSL_CTX_free (sslContext);
116 | return 0;
117 | }
118 |
--------------------------------------------------------------------------------
/sync-ssl-svr.cc:
--------------------------------------------------------------------------------
1 | //gcc -Wall -o ssl-svr-demo ssl-svr-demo.c -lssl -lcrypto
2 | #include
3 | #include
4 | #include
5 | #include
6 | #include
7 | #include
8 | #include
9 | #include
10 | #include
11 | #include
12 | #include
13 | #include
14 |
15 | #include "openssl/bio.h"
16 | #include "openssl/ssl.h"
17 | #include "openssl/err.h"
18 |
19 | #define log(...) do { printf(__VA_ARGS__); fflush(stdout); } while(0)
20 | #define check0(x, ...) if(x) do { log( __VA_ARGS__); exit(1); } while(0)
21 | #define check1(x, ...) if(!(x)) do { log( __VA_ARGS__); exit(1); } while(0)
22 |
23 | int main(int argc, char **argv)
24 | {
25 | if (argc < 2) {
26 | printf("usage %s \n", argv[0]);
27 | exit(1);
28 | }
29 | struct sockaddr_in addr;
30 |
31 | SSL_library_init();
32 | SSL_load_error_strings();
33 | ERR_load_BIO_strings();
34 |
35 | SSL_CTX* ctx = SSL_CTX_new (SSLv23_method());
36 | check1(ctx, "SSL_CTX_new failed\n");
37 |
38 | // 要求校验对方证书
39 | //SSL_CTX_set_verify(ctx, SSL_VERIFY_PEER, NULL);
40 |
41 | // 加载CA的证书
42 | //!SSL_CTX_load_verify_locations(ctx, "cacert.cer", NULL);
43 |
44 | // 加载自己的证书
45 | int r = SSL_CTX_use_certificate_file(ctx, "server.pem", SSL_FILETYPE_PEM);
46 | check1(r>0, "SSL_CTX_use_certificate_file failed");
47 |
48 | // 加载自己的私钥
49 | r = SSL_CTX_use_PrivateKey_file(ctx, "server.pem", SSL_FILETYPE_PEM);
50 | check1(r>0, "SSL_CTX_use_PrivateKey_file failed");
51 |
52 | // 判定私钥是否正确
53 | r = SSL_CTX_check_private_key(ctx);
54 | check1(r, "SSL_CTX_check_private_key failed");
55 |
56 | log("ssl inited\n");
57 | // 创建并等待连接
58 | int nListenFd = socket(AF_INET, SOCK_STREAM|SOCK_CLOEXEC, 0);
59 | memset(&addr, 0, sizeof addr);
60 | addr.sin_family = AF_INET;
61 | addr.sin_port = htons(atoi(argv[1]));
62 | int len = sizeof(addr);
63 | addr.sin_addr.s_addr = INADDR_ANY;
64 | r = bind(nListenFd, (struct sockaddr *)&addr, len);
65 | check0(r, "bind error errno %d %s", errno, strerror(errno));
66 | r = listen(nListenFd, 20);
67 | check0(r, "listen error errno %d %s", errno, strerror(errno));
68 | log("listen at %d\n", atoi(argv[1]));
69 | for(;;) {
70 | memset(&addr, 0, sizeof(addr));
71 | int len = sizeof(addr);
72 | int nAcceptFd = accept(nListenFd, (struct sockaddr *)&addr, (socklen_t *)&len);
73 | log("Accept a connect from [%s:%d]\n",
74 | inet_ntoa(addr.sin_addr), ntohs(addr.sin_port));
75 |
76 | // 将连接付给SSL
77 | SSL* ssl = SSL_new (ctx);
78 | check1(ssl, "SSL_new failed");
79 | SSL_set_fd (ssl, nAcceptFd);
80 |
81 | SSL_set_accept_state(ssl);
82 | r = SSL_do_handshake(ssl);
83 | check1(r, "SSL_do_handshake failed");
84 | // 进行操作
85 | char szBuffer[1024];
86 | memset(szBuffer, 0, sizeof(szBuffer));
87 | SSL_read(ssl,szBuffer, sizeof(szBuffer));
88 | const char* resp = "HTTP/1.1 200 OK\r\nConnection: Close\r\n\r\n";
89 | SSL_write(ssl, resp, strlen(resp));
90 | log("send response %ld bytes to client\n", strlen(resp));
91 | // 释放资源
92 | SSL_free (ssl);
93 | close(nAcceptFd);
94 | }
95 | SSL_CTX_free (ctx);
96 | close(nListenFd);
97 | return 0;
98 | }
99 |
--------------------------------------------------------------------------------