blob: eb531a5850f2dec12df01897cb8eb5c3845ee612 [file] [log] [blame]
Gilles Peskined50177f2017-05-16 17:53:03 +02001#!/usr/bin/env perl
2
3# A simple TCP client that sends some data and expects a response.
4# Usage: tcp_client.pl HOSTNAME PORT DATA1 RESPONSE1
5# DATA: hex-encoded data to send to the server
6# RESPONSE: regexp that must match the server's response
Bence Szépkúti700ee442020-05-26 00:33:31 +02007#
8# Copyright (C) 2017, Arm Limited, All Rights Reserved
9#
10# This file is part of Mbed TLS (https://tls.mbed.org)
Gilles Peskined50177f2017-05-16 17:53:03 +020011
12use warnings;
13use strict;
14use IO::Socket::INET;
15
16# Pack hex digits into a binary string, ignoring whitespace.
17sub parse_hex {
18 my ($hex) = @_;
19 $hex =~ s/\s+//g;
20 return pack('H*', $hex);
21}
22
23## Open a TCP connection to the specified host and port.
24sub open_connection {
25 my ($host, $port) = @_;
26 my $socket = IO::Socket::INET->new(PeerAddr => $host,
27 PeerPort => $port,
28 Proto => 'tcp',
29 Timeout => 1);
30 die "Cannot connect to $host:$port: $!" unless $socket;
31 return $socket;
32}
33
34## Close the TCP connection.
35sub close_connection {
36 my ($connection) = @_;
37 $connection->shutdown(2);
38 # Ignore shutdown failures (at least for now)
39 return 1;
40}
41
42## Write the given data, expressed as hexadecimal
43sub write_data {
44 my ($connection, $hexdata) = @_;
45 my $data = parse_hex($hexdata);
46 my $total_sent = 0;
47 while ($total_sent < length($data)) {
48 my $sent = $connection->send($data, 0);
49 if (!defined $sent) {
50 die "Unable to send data: $!";
51 }
52 $total_sent += $sent;
53 }
54 return 1;
55}
56
57## Read a response and check it against an expected prefix
58sub read_response {
59 my ($connection, $expected_hex) = @_;
60 my $expected_data = parse_hex($expected_hex);
61 my $start_offset = 0;
62 while ($start_offset < length($expected_data)) {
63 my $actual_data;
64 my $ok = $connection->recv($actual_data, length($expected_data));
65 if (!defined $ok) {
66 die "Unable to receive data: $!";
67 }
68 if (($actual_data ^ substr($expected_data, $start_offset)) =~ /[^\000]/) {
69 printf STDERR ("Received \\x%02x instead of \\x%02x at offset %d\n",
70 ord(substr($actual_data, $-[0], 1)),
71 ord(substr($expected_data, $start_offset + $-[0], 1)),
72 $start_offset + $-[0]);
73 return 0;
74 }
75 $start_offset += length($actual_data);
76 }
77 return 1;
78}
79
80if (@ARGV != 4) {
81 print STDERR "Usage: $0 HOSTNAME PORT DATA1 RESPONSE1\n";
82 exit(3);
83}
84my ($host, $port, $data1, $response1) = @ARGV;
85my $connection = open_connection($host, $port);
86write_data($connection, $data1);
87if (!read_response($connection, $response1)) {
88 exit(1);
89}
90close_connection($connection);