Initial revision
[l2tpns.git] / control.c
1 #include <stdio.h>
2 #include <arpa/inet.h>
3 #include <errno.h>
4 #include <fcntl.h>
5 #include <malloc.h>
6 #include <netdb.h>
7 #include <string.h>
8 #include <sys/time.h>
9 #include <sys/types.h>
10 #include <sys/socket.h>
11 #include <netinet/in.h>
12 #include <signal.h>
13 #include <stdarg.h>
14 #include <stdlib.h>
15 #include <unistd.h>
16 #include <time.h>
17 #include "control.h"
18
19 int new_packet(short type, char *packet)
20 {
21 int id = (time(NULL) ^ (rand() * 1024*1024));
22
23 *(short *)(packet + 0) = ntohs(0x9012);
24 *(short *)(packet + 2) = ntohs(type);
25 *(int *)(packet + 6) = ntohl(id);
26
27 return 10;
28 }
29
30 int send_packet(int sockfd, int dest_ip, int dest_port, char *packet, int len)
31 {
32 struct sockaddr_in addr;
33
34 *(short *)(packet + 4) = ntohs(len);
35
36 memset(&addr, 0, sizeof(addr));
37 addr.sin_family = AF_INET;
38 *(int*)&addr.sin_addr = htonl(dest_ip);
39 addr.sin_port = htons(dest_port);
40 if (sendto(sockfd, packet, len, 0, (void *) &addr, sizeof(addr)) < 0)
41 {
42 perror("sendto");
43 return 0;
44 }
45 return 1;
46 }
47
48 int read_packet(int sockfd, char *packet)
49 {
50 struct sockaddr_in addr;
51 int alen = sizeof(addr);
52 memset(&addr, 0, sizeof(addr));
53 return recvfrom(sockfd, packet, 1400, 0, (void *) &addr, &alen);
54 }
55
56 void dump_packet(char *packet, FILE *stream)
57 {
58 if (htons(*(short *)(packet + 0)) != 0x9012)
59 {
60 fprintf(stream, "Invalid packet identifier %x\n", htons(*(short *)(packet + 0)));
61 return;
62 }
63 fprintf(stream, "Control packet:\n");
64 fprintf(stream, " Type: %d\n", htons(*(short *)(packet + 2)));
65 fprintf(stream, " Length: %d\n", htons(*(short *)(packet + 4)));
66 fprintf(stream, " Identifier: %x\n", htonl(*(int *)(packet + 6)));
67 fprintf(stream, "\n");
68 }
69
70