aboutsummaryrefslogtreecommitdiffhomepage
path: root/docs/fetch-tcp.example.c
blob: 3d3b60885a3a807ae18679a93ecfadaab0b5d762 (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
#include <arpa/inet.h>
#include <errno.h>
#include <libsparklepaw/transport.h>
#include <netinet/in.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/socket.h>

int main(int argc, char** argv) {
  if (argc != 3) {
    fprintf(stderr, "usage: %s <inet4-addr> <tcp-port>\n", argv[0]);
    return 1;
  }

  // key for my example zone, replace it with one you can test against
  uint8_t key[0x20] = {
    0xc5, 0x82, 0x1e, 0x05, 0x34, 0x80, 0x17, 0x25,
    0x3c, 0xfc, 0x80, 0x87, 0x0b, 0xca, 0x03, 0xed,
    0x0a, 0x8b, 0x93, 0xbc, 0x33, 0x58, 0x33, 0x9e,
    0x7e, 0xee, 0x44, 0x08, 0xff, 0xfd, 0x2c, 0x2d
  };

  struct sprkl_request* req = sprkl_request_make_fetchservice(
    SPRKL_SIGALGO_ED25519, key, 0
  );

  // horrible awful code practices ensue. don't write your code like this, i
  // just did this cause it's shorter for the example :3

  struct sockaddr_in saddr;
  saddr.sin_family = AF_INET;
  saddr.sin_addr.s_addr = inet_addr(argv[1]);
  saddr.sin_port = htons(atoi(argv[2]));
  
  int sock = socket(AF_INET, SOCK_STREAM, 6);
  errno = 0;
  if (connect(sock, (struct sockaddr*) &saddr, sizeof saddr)) {
    fprintf(stderr, "connect error: %s\n", strerror(errno));
    return errno;
  }
  
  FILE* stream = fdopen(sock, "r+");
  struct sprkl_transport t = sprkl_transport_make_stream(stream);

  int err = sprkl_transport_sendrequest(&t, req);
  if (err) {
    fprintf(stderr, "req error: %s\n", sprkl_transport_strerror(&t, err));
    return err;
  }

  struct sprkl_response resp;
  resp.verb = req->verb;
  err = sprkl_transport_recvresponse(&t, &resp);
  if (err) {
    fprintf(stderr, "resp error: %s\n", sprkl_transport_strerror(&t, err));
    return err;
  }

  fclose(stream);

  fprintf(stderr, "response status code is %x\n", resp.status);
  if (resp.status != SPRKL_STATUS_OK) {
    fprintf(stderr, "server said: %*s\n", resp.errmsgsz, resp.errmsg);
  } else {
    sprkl_service_printdebug(resp.fetchsvc.svc, stdout);
  }

  sprkl_response_freeparts(&resp, true);
  sprkl_request_freeall(req);
}