From 42ff12d487f8bb5dfe123b493451e9d339793b1f Mon Sep 17 00:00:00 2001 From: zwkylkx <51225320+zwkylkx@users.noreply.github.com> Date: Tue, 14 Mar 2023 22:06:24 +0800 Subject: [PATCH] Create demo_tls12_get.c (#1433) demo_tls12_get --- demos/src/demo_tls12_get.c | 100 +++++++++++++++++++++++++++++++++++++ 1 file changed, 100 insertions(+) create mode 100644 demos/src/demo_tls12_get.c diff --git a/demos/src/demo_tls12_get.c b/demos/src/demo_tls12_get.c new file mode 100644 index 00000000..5e13245a --- /dev/null +++ b/demos/src/demo_tls12_get.c @@ -0,0 +1,100 @@ +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include "url_parser.h" + + +int main(int argc, char *argv[]) +{ + int ret = -1; + char *prog = argv[0]; + const int cipher = TLS_cipher_ecc_sm4_cbc_sm3; + URL_COMPONENTS *url; + struct hostent *hp; + int port = 4430; + struct sockaddr_in server; + int sock; + TLS_CTX ctx; + TLS_CONNECT conn; + char request[1024]; + uint8_t buf[16800]; + char *p; + size_t len; + + if (argc != 2) { + fprintf(stderr, "example: https://sm2only.ovssl.cn\n"); + return 1; + } + + if (!(url = parse_url(argv[1]))) { + fprintf(stderr, "parse url '%s' failure\n", argv[1]); + return 1; + } + if (!(hp = gethostbyname(url->host))) { + herror("tls12_client: '-host' invalid"); + goto end; + } + if (url->port != -1) { + port = url->port; + } + + server.sin_addr = *((struct in_addr *)hp->h_addr_list[0]); + server.sin_family = AF_INET; + server.sin_port = htons(port); + + if ((sock = socket(AF_INET, SOCK_STREAM, 0)) < 0) { + perror("socket"); + goto end; + } + if (connect(sock, (struct sockaddr *)&server , sizeof(server)) < 0) { + perror("connect"); + goto end; + } + + memset(&ctx, 0, sizeof(ctx)); + memset(&conn, 0, sizeof(conn)); + + tls_ctx_init(&ctx, TLS_protocol_tls12, TLS_client_mode); + tls_ctx_set_cipher_suites(&ctx, &cipher, 1); + tls_init(&conn, &ctx); + tls_set_socket(&conn, sock); + + if (tls_do_handshake(&conn) != 1) { + fprintf(stderr, "%s: error\n", prog); + goto end; + } + + snprintf(request, sizeof(request)-1, "GET %s HTTP/1.1\r\nHost: %s\r\n\r\n", + url->path ? url->path : "/", + url->host); + + tls_send(&conn, (uint8_t *)request, strlen(request), &len); + + if (tls_recv(&conn, buf, sizeof(buf), &len) != 1) { + fprintf(stderr, "recv failure\n"); + goto end; + } + buf[len] = 0; + + p = strstr((char *)buf, "\r\n\r\n"); + if (p) { + printf("%s", p + 4); + fflush(stdout); + } + +end: + free_url_components(url); + close(sock); + tls_ctx_cleanup(&ctx); + tls_cleanup(&conn); + return 0; +}