aboutsummaryrefslogtreecommitdiffstats
path: root/doc/examples/tls_client.cpp
blob: 9e9fce9c2f0c3db1a0cae764aaf505c604d69224 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
/*
* (C) 2008 Jack Lloyd
*
* Distributed under the terms of the Botan license
*/

#include <botan/init.h>
#include <botan/tls_client.h>
#include <botan/unx_sock.h>

using namespace Botan;

#include <stdio.h>
#include <string>
#include <iostream>
#include <memory>

int main(int argc, char* argv[])
   {
   if(argc != 2 && argc != 3)
      {
      printf("Usage: %s host [port]\n", argv[0]);
      return 1;
      }

   try
      {
      LibraryInitializer init;

      std::string host = argv[1];
      u32bit port = argc == 3 ? Botan::to_u32bit(argv[2]) : 443;

      printf("Connecting to %s:%d...\n", host.c_str(), port);

      Unix_Socket sock(argv[1], port);

      std::auto_ptr<Botan::RandomNumberGenerator> rng(
         Botan::RandomNumberGenerator::make_rng());

      TLS_Client tls(*rng, sock);

      printf("Handshake extablished...\n");

      std::string http_command = "GET / HTTP/1.1\r\n"
                                 "Server: " + host + ':' + to_string(port) + "\r\n\r\n";

      tls.write((const byte*)http_command.c_str(), http_command.length());

      u32bit total_got = 0;

      while(true)
         {
         if(tls.is_closed())
            break;

         byte buf[16+1] = { 0 };
         u32bit got = tls.read(buf, sizeof(buf)-1);
         printf("%s", buf);
         fflush(0);

         total_got += got;
         }

      printf("Retrieved %d bytes total\n", total_got);
   }
   catch(std::exception& e)
      {
      printf("%s\n", e.what());
      return 1;
      }
   return 0;
   }