httpgw needs polishing, MIME types
[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             if (FD_ISSET(sockets[i].sock,&rdfd))
141                 (*(sockets[i].may_read))(sockets[i].sock);
142             if (FD_ISSET(sockets[i].sock,&wrfd))
143                 (*(sockets[i].may_write))(sockets[i].sock);
144             if (FD_ISSET(sockets[i].sock,&errfd))
145                 (*(sockets[i].on_error))(sockets[i].sock);
146         }
147     } else if (sel<0) {
148         print_error("select fails");
149     }
150 }
151
152 tint Datagram::Time () {
153     //HiResTimeOfDay* tod = HiResTimeOfDay::Instance();
154     //tint ret = tod->getTimeUSec();
155     //DLOG(INFO)<<"now is "<<ret;
156     return now = usec_time();
157 }
158
159 SOCKET Datagram::Bind (Address addr_) {
160     struct sockaddr_in addr = addr_;
161     SOCKET fd;
162     int len = sizeof(struct sockaddr_in), sndbuf=1<<20, rcvbuf=1<<20;
163     #define dbnd_ensure(x) { if (!(x)) { print_error("binding fails"); close_socket(fd); return INVALID_SOCKET; } }
164     dbnd_ensure ( (fd = socket(AF_INET, SOCK_DGRAM, 0)) >= 0 );
165     dbnd_ensure( make_socket_nonblocking(fd) );  // FIXME may remove this
166     int enable = true;
167     dbnd_ensure ( setsockopt(fd, SOL_SOCKET, SO_SNDBUF, (setsockoptptr_t)&sndbuf, sizeof(int)) == 0 );
168     dbnd_ensure ( setsockopt(fd, SOL_SOCKET, SO_RCVBUF, (setsockoptptr_t)&rcvbuf, sizeof(int)) == 0 );
169     setsockopt(fd, SOL_SOCKET, SO_REUSEADDR, (setsockoptptr_t)&enable, sizeof(int));
170     dbnd_ensure ( ::bind(fd, (sockaddr*)&addr, len) == 0 );
171     return fd;
172 }
173
174 void Datagram::Close (SOCKET sock) {
175     if (!close_socket(sock))
176         print_error("on closing a socket");
177 }
178
179
180 std::string sock2str (struct sockaddr_in addr) {
181     char ipch[32];
182 #ifdef _WIN32
183     //Vista only: InetNtop(AF_INET,&(addr.sin_addr),ipch,32);
184     // IPv4 only:
185     struct in_addr inaddr;
186     memcpy(&inaddr, &(addr.sin_addr), sizeof(inaddr));
187     strncpy(ipch, inet_ntoa(inaddr),32);
188 #else
189     inet_ntop(AF_INET,&(addr.sin_addr),ipch,32);
190 #endif
191     sprintf(ipch+strlen(ipch),":%i",ntohs(addr.sin_port));
192     return std::string(ipch);
193 }
194
195 /*
196 std::string Datagram::to_string () const { // TODO: pretty-print swift
197     std::string addrs = sock2str(addr);
198     char hex[MAXDGRAMSZ*2];
199     for(int i=offset; i<length; i++)
200         sprintf(hex+i*2,"%02x",buf[i]);
201     std::string hexs(hex+offset*2,(length-offset)*2);
202     return addrs + '\t' + hexs;
203 }*/
204
205 }