Handle failed negotiation on modern socket
[nbd.git] / nbd-tester-client.c
1 /*
2  * Test client to test the NBD server. Doesn't do anything useful, except
3  * checking that the server does, actually, work.
4  *
5  * Note that the only 'real' test is to check the client against a kernel. If
6  * it works here but does not work in the kernel, then that's most likely a bug
7  * in this program and/or in nbd-server.
8  *
9  * Copyright(c) 2006  Wouter Verhelst
10  *
11  * This program is Free Software; you can redistribute it and/or modify it
12  * under the terms of the GNU General Public License as published by the Free
13  * Software Foundation, in version 2.
14  *
15  * This program is distributed in the hope that it will be useful, but WITHOUT
16  * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
17  * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
18  * more details.
19  *
20  * You should have received a copy of the GNU General Public License along with
21  * this program; if not, write to the Free Software Foundation, Inc., 51
22  * Franklin St, Fifth Floor, Boston, MA  02110-1301 USA
23  */
24 #include <stdlib.h>
25 #include <stdio.h>
26 #include <stdbool.h>
27 #include <string.h>
28 #include <sys/time.h>
29 #include <sys/types.h>
30 #include <sys/socket.h>
31 #include <syslog.h>
32 #include <unistd.h>
33 #include "config.h"
34 #include "lfs.h"
35 #define MY_NAME "nbd-tester-client"
36 #include "cliserv.h"
37
38 #include <netinet/in.h>
39 #include <glib.h>
40
41 static gchar errstr[1024];
42 const static int errstr_len=1024;
43
44 static uint64_t size;
45
46 typedef enum {
47         CONNECTION_TYPE_NONE,
48         CONNECTION_TYPE_CONNECT,
49         CONNECTION_TYPE_INIT_PASSWD,
50         CONNECTION_TYPE_CLISERV,
51         CONNECTION_TYPE_FULL,
52 } CONNECTION_TYPE;
53
54 typedef enum {
55         CONNECTION_CLOSE_PROPERLY,
56         CONNECTION_CLOSE_FAST,
57 } CLOSE_TYPE;
58
59 static inline int read_all(int f, void *buf, size_t len) {
60         ssize_t res;
61         size_t retval=0;
62
63         while(len>0) {
64                 if((res=read(f, buf, len)) <=0) {
65                         snprintf(errstr, errstr_len, "Read failed: %s", strerror(errno));
66                         return -1;
67                 }
68                 len-=res;
69                 buf+=res;
70                 retval+=res;
71         }
72         return retval;
73 }
74
75 #define READ_ALL_ERRCHK(f, buf, len, whereto, errmsg...) if((read_all(f, buf, len))<=0) { snprintf(errstr, errstr_len, ##errmsg); goto whereto; }
76 #define READ_ALL_ERR_RT(f, buf, len, whereto, rval, errmsg...) if((read_all(f, buf, len))<=0) { snprintf(errstr, errstr_len, ##errmsg); retval = rval; goto whereto; }
77
78 int setup_connection(gchar *hostname, int port, gchar* name, CONNECTION_TYPE ctype) {
79         int sock;
80         struct hostent *host;
81         struct sockaddr_in addr;
82         char buf[256];
83         uint64_t mymagic = (name ? opts_magic : cliserv_magic);
84         u64 tmp64;
85         uint32_t tmp32 = 0;
86
87         sock=0;
88         if(ctype<CONNECTION_TYPE_CONNECT)
89                 goto end;
90         if((sock=socket(PF_INET, SOCK_STREAM, IPPROTO_TCP))<0) {
91                 strncpy(errstr, strerror(errno), errstr_len);
92                 goto err;
93         }
94         setmysockopt(sock);
95         if(!(host=gethostbyname(hostname))) {
96                 strncpy(errstr, strerror(errno), errstr_len);
97                 goto err_open;
98         }
99         addr.sin_family=AF_INET;
100         addr.sin_port=htons(port);
101         addr.sin_addr.s_addr=*((int *) host->h_addr);
102         if((connect(sock, (struct sockaddr *)&addr, sizeof(addr))<0)) {
103                 strncpy(errstr, strerror(errno), errstr_len);
104                 goto err_open;
105         }
106         if(ctype<CONNECTION_TYPE_INIT_PASSWD)
107                 goto end;
108         READ_ALL_ERRCHK(sock, buf, strlen(INIT_PASSWD), err_open, "Could not read INIT_PASSWD: %s", strerror(errno));
109         if(strlen(buf)==0) {
110                 snprintf(errstr, errstr_len, "Server closed connection");
111                 goto err_open;
112         }
113         if(strncmp(buf, INIT_PASSWD, strlen(INIT_PASSWD))) {
114                 snprintf(errstr, errstr_len, "INIT_PASSWD does not match");
115                 goto err_open;
116         }
117         if(ctype<CONNECTION_TYPE_CLISERV)
118                 goto end;
119         READ_ALL_ERRCHK(sock, &tmp64, sizeof(tmp64), err_open, "Could not read cliserv_magic: %s", strerror(errno));
120         tmp64=ntohll(tmp64);
121         if(tmp64 != mymagic) {
122                 strncpy(errstr, "mymagic does not match", errstr_len);
123                 goto err_open;
124         }
125         if(ctype<CONNECTION_TYPE_FULL)
126                 goto end;
127         if(!name) {
128                 READ_ALL_ERRCHK(sock, &size, sizeof(size), err_open, "Could not read size: %s", strerror(errno));
129                 size=ntohll(size);
130                 READ_ALL_ERRCHK(sock, buf, 128, err_open, "Could not read data: %s", strerror(errno));
131                 goto end;
132         }
133         /* flags */
134         READ_ALL_ERRCHK(sock, buf, sizeof(uint16_t), err_open, "Could not read flags: %s", strerror(errno));
135         /* reserved field */
136         write(sock, &tmp32, sizeof(tmp32));
137         /* magic */
138         tmp64 = htonll(opts_magic);
139         write(sock, &tmp64, sizeof(tmp64));
140         /* name */
141         tmp32 = htonl(NBD_OPT_EXPORT_NAME);
142         write(sock, &tmp32, sizeof(tmp32));
143         tmp32 = htonl((uint32_t)strlen(name));
144         write(sock, &tmp32, sizeof(tmp32));
145         write(sock, name, strlen(name));
146         READ_ALL_ERRCHK(sock, &size, sizeof(size), err_open, "Could not read size: %s", strerror(errno));
147         size = ntohll(size);
148         READ_ALL_ERRCHK(sock, buf, sizeof(uint16_t)+124, err_open, "Could not read reserved zeroes: %s", strerror(errno));
149         goto end;
150 err_open:
151         close(sock);
152 err:
153         sock=-1;
154 end:
155         return sock;
156 }
157
158 int close_connection(int sock, CLOSE_TYPE type) {
159         struct nbd_request req;
160         u64 counter=0;
161
162         switch(type) {
163                 case CONNECTION_CLOSE_PROPERLY:
164                         req.magic=htonl(NBD_REQUEST_MAGIC);
165                         req.type=htonl(NBD_CMD_DISC);
166                         memcpy(&(req.handle), &(counter), sizeof(counter));
167                         counter++;
168                         req.from=0;
169                         req.len=0;
170                         if(write(sock, &req, sizeof(req))<0) {
171                                 snprintf(errstr, errstr_len, "Could not write to socket: %s", strerror(errno));
172                                 return -1;
173                         }
174                 case CONNECTION_CLOSE_FAST:
175                         if(close(sock)<0) {
176                                 snprintf(errstr, errstr_len, "Could not close socket: %s", strerror(errno));
177                                 return -1;
178                         }
179                         break;
180                 default:
181                         g_critical("Your compiler is on crack!"); /* or I am buggy */
182                         return -1;
183         }
184         return 0;
185 }
186
187 int read_packet_check_header(int sock, size_t datasize, long long int curhandle) {
188         struct nbd_reply rep;
189         int retval=0;
190         char buf[datasize];
191
192         READ_ALL_ERR_RT(sock, &rep, sizeof(rep), end, -1, "Could not read reply header: %s", strerror(errno));
193         rep.magic=ntohl(rep.magic);
194         rep.error=ntohl(rep.error);
195         if(rep.magic!=NBD_REPLY_MAGIC) {
196                 snprintf(errstr, errstr_len, "Received package with incorrect reply_magic. Index of sent packages is %lld (0x%llX), received handle is %lld (0x%llX). Received magic 0x%lX, expected 0x%lX", curhandle, curhandle, *((u64*)rep.handle), *((u64*)rep.handle), (long unsigned int)rep.magic, (long unsigned int)NBD_REPLY_MAGIC);
197                 retval=-1;
198                 goto end;
199         }
200         if(rep.error) {
201                 snprintf(errstr, errstr_len, "Received error from server: %ld (0x%lX). Handle is %lld (0x%llX).", (long int)rep.error, (long unsigned int)rep.error, (long long int)(*((u64*)rep.handle)), *((u64*)rep.handle));
202                 retval=-1;
203                 goto end;
204         }
205         READ_ALL_ERR_RT(sock, &buf, datasize, end, -1, "Could not read data: %s", strerror(errno));
206
207 end:
208         return retval;
209 }
210
211 int oversize_test(gchar* hostname, int port, char* name, int sock, char sock_is_open, char close_sock) {
212         int retval=0;
213         struct nbd_request req;
214         struct nbd_reply rep;
215         int request=0;
216         int i=0;
217         pid_t mypid = getpid();
218         char buf[((1024*1024)+sizeof(struct nbd_request)/2)<<1];
219         bool got_err;
220
221         /* This should work */
222         if(!sock_is_open) {
223                 if((sock=setup_connection(hostname, port, name, CONNECTION_TYPE_FULL))<0) {
224                         g_warning("Could not open socket: %s", errstr);
225                         retval=-1;
226                         goto err;
227                 }
228         }
229         req.magic=htonl(NBD_REQUEST_MAGIC);
230         req.type=htonl(NBD_CMD_READ);
231         req.len=htonl(1024*1024);
232         memcpy(&(req.handle),&i,sizeof(i));
233         req.from=htonll(i);
234         write(sock, &req, sizeof(req));
235         printf("%d: testing oversized request: %d: ", getpid(), ntohl(req.len));
236         READ_ALL_ERR_RT(sock, &rep, sizeof(struct nbd_reply), err, -1, "Could not read reply header: %s", strerror(errno));
237         READ_ALL_ERR_RT(sock, &buf, ntohl(req.len), err, -1, "Could not read data: %s", strerror(errno));
238         if(rep.error) {
239                 snprintf(errstr, errstr_len, "Received unexpected error: %d", rep.error);
240                 retval=-1;
241                 goto err;
242         } else {
243                 printf("OK\n");
244         }
245         /* This probably should not work */
246         i++; req.from=htonll(i);
247         req.len = htonl(ntohl(req.len) + sizeof(struct nbd_request) / 2);
248         write(sock, &req, sizeof(req));
249         printf("%d: testing oversized request: %d: ", getpid(), ntohl(req.len));
250         READ_ALL_ERR_RT(sock, &rep, sizeof(struct nbd_reply), err, -1, "Could not read reply header: %s", strerror(errno));
251         READ_ALL_ERR_RT(sock, &buf, ntohl(req.len), err, -1, "Could not read data: %s", strerror(errno));
252         if(rep.error) {
253                 printf("Received expected error\n");
254                 got_err=true;
255         } else {
256                 printf("OK\n");
257                 got_err=false;
258         }
259         /* ... unless this works, too */
260         i++; req.from=htonll(i);
261         req.len = htonl(ntohl(req.len) << 1);
262         write(sock, &req, sizeof(req));
263         printf("%d: testing oversized request: %d: ", getpid(), ntohl(req.len));
264         READ_ALL_ERR_RT(sock, &rep, sizeof(struct nbd_reply), err, -1, "Could not read reply header: %s", strerror(errno));
265         READ_ALL_ERR_RT(sock, &buf, ntohl(req.len), err, -1, "Could not read data: %s", strerror(errno));
266         if(rep.error) {
267                 printf("error\n");
268         } else {
269                 printf("OK\n");
270         }
271         if((rep.error && !got_err) || (!rep.error && got_err)) {
272                 printf("Received unexpected error\n");
273                 retval=-1;
274         }
275   err:
276         return retval;
277 }
278
279 int throughput_test(gchar* hostname, int port, char* name, int sock, char sock_is_open, char close_sock) {
280         long long int i;
281         char buf[1024];
282         struct nbd_request req;
283         int requests=0;
284         fd_set set;
285         struct timeval tv;
286         struct timeval start;
287         struct timeval stop;
288         float timespan;
289         int speed;
290         char speedchar[2] = { '\0', '\0' };
291         int retval=0;
292         size_t tmp;
293         signed int do_write=TRUE;
294         pid_t mypid = getpid();
295
296         size=0;
297         if(!sock_is_open) {
298                 if((sock=setup_connection(hostname, port, name, CONNECTION_TYPE_FULL))<0) {
299                         g_warning("Could not open socket: %s", errstr);
300                         retval=-1;
301                         goto err;
302                 }
303         }
304         req.magic=htonl(NBD_REQUEST_MAGIC);
305         req.type=htonl(NBD_CMD_READ);
306         req.len=htonl(1024);
307         if(gettimeofday(&start, NULL)<0) {
308                 retval=-1;
309                 snprintf(errstr, errstr_len, "Could not measure start time: %s", strerror(errno));
310                 goto err_open;
311         }
312         for(i=0;i+1024<=size;i+=1024) {
313                 if(do_write) {
314                         memcpy(&(req.handle),&i,sizeof(i));
315                         req.from=htonll(i);
316                         write(sock, &req, sizeof(req));
317                         printf("%d: Requests(+): %d\n", (int)mypid, ++requests);
318                 }
319                 do {
320                         FD_ZERO(&set);
321                         FD_SET(sock, &set);
322                         tv.tv_sec=0;
323                         tv.tv_usec=0;
324                         select(sock+1, &set, NULL, NULL, &tv);
325                         if(FD_ISSET(sock, &set)) {
326                                 /* Okay, there's something ready for
327                                  * reading here */
328                                 if(read_packet_check_header(sock, 1024, i)<0) {
329                                         retval=-1;
330                                         goto err_open;
331                                 }
332                                 printf("%d: Requests(-): %d\n", (int)mypid, --requests);
333                         }
334                 } while FD_ISSET(sock, &set);
335                 /* Now wait until we can write again or until a second have
336                  * passed, whichever comes first*/
337                 FD_ZERO(&set);
338                 FD_SET(sock, &set);
339                 tv.tv_sec=1;
340                 tv.tv_usec=0;
341                 do_write=select(sock+1,NULL,&set,NULL,&tv);
342                 if(!do_write) printf("Select finished\n");
343                 if(do_write<0) {
344                         snprintf(errstr, errstr_len, "select: %s", strerror(errno));
345                         retval=-1;
346                         goto err_open;
347                 }
348         }
349         /* Now empty the read buffer */
350         do {
351                 FD_ZERO(&set);
352                 FD_SET(sock, &set);
353                 tv.tv_sec=0;
354                 tv.tv_usec=0;
355                 select(sock+1, &set, NULL, NULL, &tv);
356                 if(FD_ISSET(sock, &set)) {
357                         /* Okay, there's something ready for
358                          * reading here */
359                         read_packet_check_header(sock, 1024, i);
360                         printf("%d: Requests(-): %d\n", (int)mypid, --requests);
361                 }
362         } while (requests);
363         if(gettimeofday(&stop, NULL)<0) {
364                 retval=-1;
365                 snprintf(errstr, errstr_len, "Could not measure end time: %s", strerror(errno));
366                 goto err_open;
367         }
368         timespan=(float)(stop.tv_sec-start.tv_sec+(stop.tv_usec-start.tv_usec))/(float)1000000;
369         speed=(int)(size/timespan);
370         if(speed>1024) {
371                 speed>>=10;
372                 speedchar[0]='K';
373         }
374         if(speed>1024) {
375                 speed>>=10;
376                 speedchar[0]='M';
377         }
378         if(speed>1024) {
379                 speed>>=10;
380                 speedchar[0]='G';
381         }
382         g_message("%d: Throughput test complete. Took %.3f seconds to complete, %d%siB/s", (int)getpid(), timespan,speed,speedchar);
383
384 err_open:
385         if(close_sock) {
386                 close_connection(sock, CONNECTION_CLOSE_PROPERLY);
387         }
388 err:
389         return retval;
390 }
391
392 typedef int (*testfunc)(gchar*, int, char*, int, char, char);
393
394 int main(int argc, char**argv) {
395         gchar *hostname;
396         long int p = 0;
397         char* name = NULL;
398         int sock=0;
399         int c;
400         bool want_port = TRUE;
401         int nonopt=0;
402         testfunc test = throughput_test;
403
404         if(argc<3) {
405                 g_message("%d: Not enough arguments", (int)getpid());
406                 g_message("%d: Usage: %s <hostname> <port>", (int)getpid(), argv[0]);
407                 g_message("%d: Or: %s <hostname> -N <exportname>", (int)getpid(), argv[0]);
408                 exit(EXIT_FAILURE);
409         }
410         logging();
411         while((c=getopt(argc, argv, "-N:o"))>=0) {
412                 switch(c) {
413                         case 1:
414                                 switch(nonopt) {
415                                         case 0:
416                                                 hostname=g_strdup(optarg);
417                                                 nonopt++;
418                                                 break;
419                                         case 1:
420                                                 if(want_port)
421                                                 p=(strtol(argv[2], NULL, 0));
422                                                 if(p==LONG_MIN||p==LONG_MAX) {
423                                                         g_critical("Could not parse port number: %s", strerror(errno));
424                                                         exit(EXIT_FAILURE);
425                                                 }
426                                                 break;
427                                 }
428                                 break;
429                         case 'N':
430                                 name=g_strdup(optarg);
431                                 p = 10809;
432                                 want_port = false;
433                                 break;
434                         case 'o':
435                                 test=oversize_test;
436                                 break;
437                 }
438         }
439
440         if(test(hostname, (int)p, name, sock, FALSE, TRUE)<0) {
441                 g_warning("Could not run test: %s", errstr);
442                 exit(EXIT_FAILURE);
443         }
444
445         return 0;
446 }