amended the draft
[swift-upb.git] / datagram.cpp
1 /*
2  *  datagram.cpp
3  *  serp++
4  *
5  *  Created by Victor Grishchenko, Arno Bakker on 3/9/09.
6  *  Copyright 2009 Delft University of Technology. All rights reserved.
7  *
8  */
9 #include <iostream>
10
11 #ifdef _WIN32
12     #include <winsock2.h>
13     typedef int socklen_t;
14 #else
15     #include <arpa/inet.h>
16     #include <netdb.h>
17 #endif
18
19 #include "datagram.h"
20 #include "compat.h"
21
22 namespace swift {
23
24 tint Datagram::now = Datagram::Time();
25 tint Datagram::start = now;
26 tint Datagram::epoch = now/360000000LL*360000000LL; // make logs mergeable
27 uint32_t Address::LOCALHOST = INADDR_LOOPBACK;
28 uint64_t Datagram::dgrams_up=0, Datagram::dgrams_down=0,
29          Datagram::bytes_up=0, Datagram::bytes_down=0;
30
31 const char* tintstr (tint time) {
32     if (time==0)
33         time = Datagram::now;
34     static char ret_str[4][32]; // wow
35     static int i;
36     i = (i+1) & 3;
37     if (time==TINT_NEVER)
38         return "NEVER";
39     time -= Datagram::epoch;
40     assert(time>=0);
41     int hours = time/TINT_HOUR;
42     time %= TINT_HOUR;
43     int mins = time/TINT_MIN;
44     time %= TINT_MIN;
45     int secs = time/TINT_SEC;
46     time %= TINT_SEC;
47     int msecs = time/TINT_MSEC;
48     time %= TINT_MSEC;
49     int usecs = time/TINT_uSEC;
50     sprintf(ret_str[i],"%i_%02i_%02i_%03i_%03i",hours,mins,secs,msecs,usecs);
51     return ret_str[i];
52 }
53
54 void Address::set_ipv4 (const char* ip_str) {
55     struct hostent *h = gethostbyname(ip_str);
56     if (h == NULL) {
57         print_error("cannot lookup address");
58         return;
59     } else {
60         addr.sin_addr.s_addr = *(u_long *) h->h_addr_list[0];
61     }
62 }
63
64
65 Address::Address(const char* ip_port) {
66     clear();
67     if (strlen(ip_port)>=1024)
68         return;
69     char ipp[1024];
70     strncpy(ipp,ip_port,1024);
71     char* semi = strchr(ipp,':');
72     if (semi) {
73         *semi = 0;
74         set_ipv4(ipp);
75         set_port(semi+1);
76     } else {
77         if (strchr(ipp, '.')) {
78             set_ipv4(ipp);
79             set_port((uint16_t)0);
80         } else {
81             set_ipv4(INADDR_LOOPBACK);
82             set_port(ipp);
83         }
84     }
85 }
86
87
88 int Datagram::Send () {
89     int r = sendto(sock,(const char *)buf+offset,length-offset,0,
90                    (struct sockaddr*)&(addr.addr),sizeof(struct sockaddr_in));
91     if (r<0)
92         perror("can't send");
93     dgrams_up++;
94     bytes_up+=size();
95     offset=0;
96     length=0;
97     Time();
98     return r;
99 }
100
101 int Datagram::Recv () {
102     socklen_t addrlen = sizeof(struct sockaddr_in);
103     offset = 0;
104     length = recvfrom (sock, (char *)buf, MAXDGRAMSZ*2, 0,
105                        (struct sockaddr*)&(addr.addr), &addrlen);
106     if (length<0) {
107         length = 0;
108         print_error("error on recv");
109     }
110     dgrams_down++;
111     bytes_down+=length;
112     Time();
113     return length;
114 }
115
116
117 void Datagram::Wait (int sockcnt, socket_callbacks_t* sockets, tint usec) {
118     struct timeval timeout;
119     timeout.tv_sec = usec/TINT_SEC;
120     timeout.tv_usec = usec%TINT_SEC;
121     int max_sock_fd = 0;
122     fd_set rdfd, wrfd, errfd;
123     FD_ZERO(&rdfd);
124     FD_ZERO(&wrfd);
125     FD_ZERO(&errfd);
126     for(int i=0; i<sockcnt; i++) {
127         if (sockets[i].may_read!=0)
128             FD_SET(sockets[i].sock,&rdfd);
129         if (sockets[i].may_write!=0)
130             FD_SET(sockets[i].sock,&wrfd);
131         if (sockets[i].on_error!=0)
132             FD_SET(sockets[i].sock,&errfd);
133         if (sockets[i].sock>max_sock_fd)
134             max_sock_fd = sockets[i].sock;
135     }
136     int sel = select(max_sock_fd+1, &rdfd, &wrfd, &errfd, &timeout);
137     Time();
138     if (sel>0) {
139         for (int i=0; i<=sockcnt; i++) {
140             socket_callbacks_t& sct = sockets[i];
141             if (sct.may_read && FD_ISSET(sct.sock,&rdfd))
142                 (*(sct.may_read))(sct.sock);
143             if (sct.may_write && FD_ISSET(sockets[i].sock,&wrfd))
144                 (*(sct.may_write))(sct.sock);
145             if (sct.on_error && FD_ISSET(sockets[i].sock,&errfd))
146                 (*(sct.on_error))(sct.sock);
147         }
148     } else if (sel<0) {
149         print_error("select fails");
150     }
151 }
152
153 tint Datagram::Time () {
154     //HiResTimeOfDay* tod = HiResTimeOfDay::Instance();
155     //tint ret = tod->getTimeUSec();
156     //DLOG(INFO)<<"now is "<<ret;
157     return now = usec_time();
158 }
159
160 SOCKET Datagram::Bind (Address addr_) {
161     struct sockaddr_in addr = addr_;
162     SOCKET fd;
163     int len = sizeof(struct sockaddr_in), sndbuf=1<<20, rcvbuf=1<<20;
164     #define dbnd_ensure(x) { if (!(x)) { print_error("binding fails"); close_socket(fd); return INVALID_SOCKET; } }
165     dbnd_ensure ( (fd = socket(AF_INET, SOCK_DGRAM, 0)) >= 0 );
166     dbnd_ensure( make_socket_nonblocking(fd) );  // FIXME may remove this
167     int enable = true;
168     dbnd_ensure ( setsockopt(fd, SOL_SOCKET, SO_SNDBUF, (setsockoptptr_t)&sndbuf, sizeof(int)) == 0 );
169     dbnd_ensure ( setsockopt(fd, SOL_SOCKET, SO_RCVBUF, (setsockoptptr_t)&rcvbuf, sizeof(int)) == 0 );
170     setsockopt(fd, SOL_SOCKET, SO_REUSEADDR, (setsockoptptr_t)&enable, sizeof(int));
171     dbnd_ensure ( ::bind(fd, (sockaddr*)&addr, len) == 0 );
172     return fd;
173 }
174
175 void Datagram::Close (SOCKET sock) {
176     if (!close_socket(sock))
177         print_error("on closing a socket");
178 }
179
180
181 std::string sock2str (struct sockaddr_in addr) {
182     char ipch[32];
183 #ifdef _WIN32
184     //Vista only: InetNtop(AF_INET,&(addr.sin_addr),ipch,32);
185     // IPv4 only:
186     struct in_addr inaddr;
187     memcpy(&inaddr, &(addr.sin_addr), sizeof(inaddr));
188     strncpy(ipch, inet_ntoa(inaddr),32);
189 #else
190     inet_ntop(AF_INET,&(addr.sin_addr),ipch,32);
191 #endif
192     sprintf(ipch+strlen(ipch),":%i",ntohs(addr.sin_port));
193     return std::string(ipch);
194 }
195
196 /*
197 std::string Datagram::to_string () const { // TODO: pretty-print swift
198     std::string addrs = sock2str(addr);
199     char hex[MAXDGRAMSZ*2];
200     for(int i=offset; i<length; i++)
201         sprintf(hex+i*2,"%02x",buf[i]);
202     std::string hexs(hex+offset*2,(length-offset)*2);
203     return addrs + '\t' + hexs;
204 }*/
205
206 }