d2e1207f695e5187c0b63cb9e85e9972e289503f
[openafs.git] / src / vol / daemon_com.c
1 /*
2  * Copyright 2006-2008, Sine Nomine Associates and others.
3  * All Rights Reserved.
4  *
5  * This software has been released under the terms of the IBM Public
6  * License.  For details, see the LICENSE file in the top-level source
7  * directory or online at http://www.openafs.org/dl/license10.html
8  */
9
10 /*
11  * localhost interprocess communication for servers
12  *
13  * currently handled by a localhost socket
14  * (yes, this needs to be replaced someday)
15  */
16
17 #ifndef _WIN32
18 #define FD_SETSIZE 65536
19 #endif
20
21 #include <afsconfig.h>
22 #include <afs/param.h>
23
24 #include <roken.h>
25 #include <afs/opr.h>
26
27 #include <rx/xdr.h>
28 #include <afs/afsint.h>
29 #include <afs/errors.h>
30
31 #include "nfs.h"
32 #include "daemon_com.h"
33 #include "lwp.h"
34 #include "lock.h"
35 #include <afs/afssyscalls.h>
36 #include "ihandle.h"
37 #include "vnode.h"
38 #include "volume.h"
39 #include "partition.h"
40 #include "common.h"
41 #include <rx/rx_queue.h>
42
43 #ifdef USE_UNIX_SOCKETS
44 #include <afs/afsutil.h>
45 #include <sys/un.h>
46 #endif
47
48 int (*V_BreakVolumeCallbacks) (VolumeId);
49
50 #define MAXHANDLERS     4       /* Up to 4 clients; must be at least 2, so that
51                                  * move = dump+restore can run on single server */
52
53 #define MAX_BIND_TRIES  5       /* Number of times to retry socket bind */
54
55 static int SYNC_ask_internal(SYNC_client_state * state, SYNC_command * com, SYNC_response * res);
56
57
58 /*
59  * On AIX, connect() and bind() require use of SUN_LEN() macro;
60  * sizeof(struct sockaddr_un) will not suffice.
61  */
62 #if defined(AFS_AIX_ENV) && defined(USE_UNIX_SOCKETS)
63 #define AFS_SOCKADDR_LEN(sa)  SUN_LEN(sa)
64 #else
65 #define AFS_SOCKADDR_LEN(sa)  sizeof(*sa)
66 #endif
67
68
69 /* daemon com SYNC general interfaces */
70
71 /**
72  * fill in sockaddr structure.
73  *
74  * @param[in]  endpoint pointer to sync endpoint object
75  * @param[out] addr     pointer to sockaddr structure
76  *
77  * @post sockaddr structure populated using information from
78  *       endpoint structure.
79  */
80 void
81 SYNC_getAddr(SYNC_endpoint_t * endpoint, SYNC_sockaddr_t * addr)
82 {
83 #ifdef USE_UNIX_SOCKETS
84     char tbuffer[AFSDIR_PATH_MAX];
85 #endif /* USE_UNIX_SOCKETS */
86
87     memset(addr, 0, sizeof(*addr));
88
89 #ifdef USE_UNIX_SOCKETS
90     strcompose(tbuffer, AFSDIR_PATH_MAX, AFSDIR_SERVER_LOCAL_DIRPATH, "/",
91                endpoint->un, (char *)NULL);
92     addr->sun_family = AF_UNIX;
93     strncpy(addr->sun_path, tbuffer, (sizeof(struct sockaddr_un) - sizeof(short)));
94 #else  /* !USE_UNIX_SOCKETS */
95 #ifdef STRUCT_SOCKADDR_HAS_SA_LEN
96     addr->sin_len = sizeof(struct sockaddr_in);
97 #endif
98     addr->sin_addr.s_addr = htonl(0x7f000001);
99     addr->sin_family = AF_INET; /* was localhost->h_addrtype */
100     addr->sin_port = htons(endpoint->in);       /* XXXX htons not _really_ neccessary */
101 #endif /* !USE_UNIX_SOCKETS */
102 }
103
104 /**
105  * get a socket descriptor of the appropriate domain.
106  *
107  * @param[in]  endpoint pointer to sync endpoint object
108  *
109  * @return socket descriptor
110  *
111  * @post socket of domain specified in endpoint structure is created and
112  *       returned to caller.
113  */
114 osi_socket
115 SYNC_getSock(SYNC_endpoint_t * endpoint)
116 {
117     osi_socket sd;
118     opr_Verify((sd = socket(endpoint->domain, SOCK_STREAM, 0)) >= 0);
119     return sd;
120 }
121
122 /* daemon com SYNC client interface */
123
124 /**
125  * open a client connection to a sync server
126  *
127  * @param[in] state  pointer to sync client handle
128  *
129  * @return operation status
130  *    @retval 1 success
131  *
132  * @note at present, this routine aborts rather than returning an error code
133  */
134 int
135 SYNC_connect(SYNC_client_state * state)
136 {
137     SYNC_sockaddr_t addr;
138     /* I can't believe the following is needed for localhost connections!! */
139     static time_t backoff[] =
140         { 3, 3, 3, 5, 5, 5, 7, 15, 16, 24, 32, 40, 48, 0 };
141     time_t *timeout = &backoff[0];
142
143     if (state->fd != OSI_NULLSOCKET) {
144         return 1;
145     }
146
147     SYNC_getAddr(&state->endpoint, &addr);
148
149     for (;;) {
150         state->fd = SYNC_getSock(&state->endpoint);
151         if (connect(state->fd, (struct sockaddr *)&addr, AFS_SOCKADDR_LEN(&addr)) >= 0)
152             return 1;
153         if (!*timeout)
154             break;
155         if (!(*timeout & 1))
156             Log("SYNC_connect: temporary failure on circuit '%s' (will retry)\n",
157                 state->proto_name);
158         SYNC_disconnect(state);
159         sleep(*timeout++);
160     }
161     perror("SYNC_connect failed (giving up!)");
162     return 0;
163 }
164
165 /**
166  * forcibly disconnect a sync client handle.
167  *
168  * @param[in] state  pointer to sync client handle
169  *
170  * @retval operation status
171  *    @retval 0 success
172  */
173 int
174 SYNC_disconnect(SYNC_client_state * state)
175 {
176     rk_closesocket(state->fd);
177     state->fd = OSI_NULLSOCKET;
178     return 0;
179 }
180
181 /**
182  * gracefully disconnect a sync client handle.
183  *
184  * @param[in] state  pointer to sync client handle
185  *
186  * @return operation status
187  *    @retval SYNC_OK success
188  */
189 afs_int32
190 SYNC_closeChannel(SYNC_client_state * state)
191 {
192     SYNC_command com;
193     SYNC_response res;
194     SYNC_PROTO_BUF_DECL(ores);
195
196     if (state->fd == OSI_NULLSOCKET)
197         return SYNC_OK;
198
199     memset(&com, 0, sizeof(com));
200     memset(&res, 0, sizeof(res));
201
202     res.payload.len = SYNC_PROTO_MAX_LEN;
203     res.payload.buf = ores;
204
205     com.hdr.command = SYNC_COM_CHANNEL_CLOSE;
206     com.hdr.command_len = sizeof(SYNC_command_hdr);
207     com.hdr.flags |= SYNC_FLAG_CHANNEL_SHUTDOWN;
208
209     /* in case the other end dropped, don't do any retries */
210     state->retry_limit = 0;
211     state->hard_timeout = 0;
212
213     SYNC_ask(state, &com, &res);
214     SYNC_disconnect(state);
215
216     return SYNC_OK;
217 }
218
219 /**
220  * forcibly break a client connection, and then create a new connection.
221  *
222  * @param[in] state  pointer to sync client handle
223  *
224  * @post old connection dropped; new connection established
225  *
226  * @return @see SYNC_connect()
227  */
228 int
229 SYNC_reconnect(SYNC_client_state * state)
230 {
231     SYNC_disconnect(state);
232     return SYNC_connect(state);
233 }
234
235 /**
236  * send a command to a sync server and wait for a response.
237  *
238  * @param[in]  state  pointer to sync client handle
239  * @param[in]  com    command object
240  * @param[out] res    response object
241  *
242  * @return operation status
243  *    @retval SYNC_OK success
244  *    @retval SYNC_COM_ERROR communications error
245  *    @retval SYNC_BAD_COMMAND server did not recognize command code
246  *
247  * @note this routine merely handles error processing; SYNC_ask_internal()
248  *       handles the low-level details of communicating with the SYNC server.
249  *
250  * @see SYNC_ask_internal
251  */
252 afs_int32
253 SYNC_ask(SYNC_client_state * state, SYNC_command * com, SYNC_response * res)
254 {
255     int tries;
256     afs_uint32 now, timeout, code=SYNC_OK;
257
258     if (state->fd == OSI_NULLSOCKET) {
259         SYNC_connect(state);
260     }
261
262     if (state->fd == OSI_NULLSOCKET) {
263         return SYNC_COM_ERROR;
264     }
265
266 #ifdef AFS_DEMAND_ATTACH_FS
267     com->hdr.flags |= SYNC_FLAG_DAFS_EXTENSIONS;
268 #endif
269
270     now = FT_ApproxTime();
271     timeout = now + state->hard_timeout;
272     for (tries = 0;
273          (tries <= state->retry_limit) && (now <= timeout);
274          tries++, now = FT_ApproxTime()) {
275         code = SYNC_ask_internal(state, com, res);
276         if (code == SYNC_OK) {
277             break;
278         } else if (code == SYNC_BAD_COMMAND) {
279             Log("SYNC_ask: protocol mismatch on circuit '%s'; make sure "
280                 "fileserver, volserver, salvageserver and salvager are same "
281                 "version\n", state->proto_name);
282             break;
283         } else if ((code == SYNC_COM_ERROR) && (tries < state->retry_limit)) {
284             Log("SYNC_ask: protocol communications failure on circuit '%s'; "
285                 "attempting reconnect to server\n", state->proto_name);
286             SYNC_reconnect(state);
287             /* try again */
288         } else {
289             /*
290              * unknown (probably protocol-specific) response code, pass it up to
291              * the caller, and let them deal with it
292              */
293             break;
294         }
295     }
296
297     if (code == SYNC_COM_ERROR) {
298         Log("SYNC_ask: too many / too latent fatal protocol errors on circuit "
299             "'%s'; giving up (tries %d timeout %d)\n",
300             state->proto_name, tries, timeout);
301     }
302
303     return code;
304 }
305
306 /**
307  * send a command to a sync server and wait for a response.
308  *
309  * @param[in]  state  pointer to sync client handle
310  * @param[in]  com    command object
311  * @param[out] res    response object
312  *
313  * @return operation status
314  *    @retval SYNC_OK success
315  *    @retval SYNC_COM_ERROR communications error
316  *
317  * @internal
318  */
319 static afs_int32
320 SYNC_ask_internal(SYNC_client_state * state, SYNC_command * com, SYNC_response * res)
321 {
322     int n;
323     SYNC_PROTO_BUF_DECL(buf);
324 #ifndef AFS_NT40_ENV
325     int iovcnt;
326     struct iovec iov[2];
327 #endif
328
329     if (state->fd == OSI_NULLSOCKET) {
330         Log("SYNC_ask:  invalid sync file descriptor on circuit '%s'\n",
331             state->proto_name);
332         res->hdr.response = SYNC_COM_ERROR;
333         goto done;
334     }
335
336     if (com->hdr.command_len > SYNC_PROTO_MAX_LEN) {
337         Log("SYNC_ask:  internal SYNC buffer too small on circuit '%s'; "
338             "please file a bug\n", state->proto_name);
339         res->hdr.response = SYNC_COM_ERROR;
340         goto done;
341     }
342
343     /*
344      * fill in some common header fields
345      */
346     com->hdr.proto_version = state->proto_version;
347     com->hdr.pkt_seq = ++state->pkt_seq;
348     com->hdr.com_seq = ++state->com_seq;
349 #ifdef AFS_NT40_ENV
350     com->hdr.pid = 0;
351     com->hdr.tid = 0;
352 #else
353     com->hdr.pid = getpid();
354 #ifdef AFS_PTHREAD_ENV
355     com->hdr.tid = afs_pointer_to_int(pthread_self());
356 #else
357     {
358         PROCESS handle = LWP_ThreadId();
359         com->hdr.tid = (handle) ? handle->index : 0;
360     }
361 #endif /* !AFS_PTHREAD_ENV */
362 #endif /* !AFS_NT40_ENV */
363
364     memcpy(buf, &com->hdr, sizeof(com->hdr));
365     if (com->payload.len) {
366         memcpy(buf + sizeof(com->hdr), com->payload.buf,
367                com->hdr.command_len - sizeof(com->hdr));
368     }
369
370 #ifdef AFS_NT40_ENV
371     n = send(state->fd, buf, com->hdr.command_len, 0);
372     if (n != com->hdr.command_len) {
373         Log("SYNC_ask:  write failed on circuit '%s'\n", state->proto_name);
374         res->hdr.response = SYNC_COM_ERROR;
375         goto done;
376     }
377
378     if (com->hdr.command == SYNC_COM_CHANNEL_CLOSE) {
379         /* short circuit close channel requests */
380         res->hdr.response = SYNC_OK;
381         goto done;
382     }
383
384     n = recv(state->fd, buf, SYNC_PROTO_MAX_LEN, 0);
385     if (n == 0 || (n < 0 && WSAEINTR != WSAGetLastError())) {
386         Log("SYNC_ask:  No response on circuit '%s'\n", state->proto_name);
387         res->hdr.response = SYNC_COM_ERROR;
388         goto done;
389     }
390 #else /* !AFS_NT40_ENV */
391     n = write(state->fd, buf, com->hdr.command_len);
392     if (com->hdr.command_len != n) {
393         Log("SYNC_ask: write failed on circuit '%s'\n", state->proto_name);
394         res->hdr.response = SYNC_COM_ERROR;
395         goto done;
396     }
397
398     if (com->hdr.command == SYNC_COM_CHANNEL_CLOSE) {
399         /* short circuit close channel requests */
400         res->hdr.response = SYNC_OK;
401         goto done;
402     }
403
404     /* receive the response */
405     iov[0].iov_base = (char *)&res->hdr;
406     iov[0].iov_len = sizeof(res->hdr);
407     if (res->payload.len) {
408         iov[1].iov_base = (char *)res->payload.buf;
409         iov[1].iov_len = res->payload.len;
410         iovcnt = 2;
411     } else {
412         iovcnt = 1;
413     }
414     n = readv(state->fd, iov, iovcnt);
415     if (n == 0 || (n < 0 && errno != EINTR)) {
416         Log("SYNC_ask: No response on circuit '%s'\n", state->proto_name);
417         res->hdr.response = SYNC_COM_ERROR;
418         goto done;
419     }
420 #endif /* !AFS_NT40_ENV */
421
422     res->recv_len = n;
423
424     if (n < sizeof(res->hdr)) {
425         Log("SYNC_ask:  response too short on circuit '%s'\n",
426             state->proto_name);
427         res->hdr.response = SYNC_COM_ERROR;
428         goto done;
429     }
430 #ifdef AFS_NT40_ENV
431     memcpy(&res->hdr, buf, sizeof(res->hdr));
432 #endif
433
434     if ((n - sizeof(res->hdr)) > res->payload.len) {
435         Log("SYNC_ask:  response too long on circuit '%s'\n",
436             state->proto_name);
437         res->hdr.response = SYNC_COM_ERROR;
438         goto done;
439     }
440 #ifdef AFS_NT40_ENV
441     memcpy(res->payload.buf, buf + sizeof(res->hdr), n - sizeof(res->hdr));
442 #endif
443
444     if (res->hdr.response_len != n) {
445         Log("SYNC_ask:  length field in response inconsistent "
446             "on circuit '%s'\n", state->proto_name);
447         res->hdr.response = SYNC_COM_ERROR;
448         goto done;
449     }
450     if (res->hdr.response == SYNC_DENIED) {
451         Log("SYNC_ask: negative response on circuit '%s'\n", state->proto_name);
452     }
453
454   done:
455     return res->hdr.response;
456 }
457
458
459 /*
460  * daemon com SYNC server-side interfaces
461  */
462
463 /**
464  * receive a command structure off a sync socket.
465  *
466  * @param[in]  state  pointer to server-side state object
467  * @param[in]  fd     file descriptor on which to perform i/o
468  * @param[out] com    sync command object to be populated
469  *
470  * @return operation status
471  *    @retval SYNC_OK command received
472  *    @retval SYNC_COM_ERROR there was a socket communications error
473  */
474 afs_int32
475 SYNC_getCom(SYNC_server_state_t * state,
476             osi_socket fd,
477             SYNC_command * com)
478 {
479     int n;
480     afs_int32 code = SYNC_OK;
481 #ifdef AFS_NT40_ENV
482     SYNC_PROTO_BUF_DECL(buf);
483 #else
484     struct iovec iov[2];
485     int iovcnt;
486 #endif
487
488 #ifdef AFS_NT40_ENV
489     n = recv(fd, buf, SYNC_PROTO_MAX_LEN, 0);
490
491     if (n == 0 || (n < 0 && WSAEINTR != WSAGetLastError())) {
492         Log("SYNC_getCom:  error receiving command\n");
493         code = SYNC_COM_ERROR;
494         goto done;
495     }
496 #else /* !AFS_NT40_ENV */
497     iov[0].iov_base = (char *)&com->hdr;
498     iov[0].iov_len = sizeof(com->hdr);
499     if (com->payload.len) {
500         iov[1].iov_base = (char *)com->payload.buf;
501         iov[1].iov_len = com->payload.len;
502         iovcnt = 2;
503     } else {
504         iovcnt = 1;
505     }
506
507     n = readv(fd, iov, iovcnt);
508     if (n == 0 || (n < 0 && errno != EINTR)) {
509         Log("SYNC_getCom:  error receiving command\n");
510         code = SYNC_COM_ERROR;
511         goto done;
512     }
513 #endif /* !AFS_NT40_ENV */
514
515     com->recv_len = n;
516
517     if (n < sizeof(com->hdr)) {
518         Log("SYNC_getCom:  command too short\n");
519         code = SYNC_COM_ERROR;
520         goto done;
521     }
522 #ifdef AFS_NT40_ENV
523     memcpy(&com->hdr, buf, sizeof(com->hdr));
524 #endif
525
526     if ((n - sizeof(com->hdr)) > com->payload.len) {
527         Log("SYNC_getCom:  command too long\n");
528         code = SYNC_COM_ERROR;
529         goto done;
530     }
531 #ifdef AFS_NT40_ENV
532     memcpy(com->payload.buf, buf + sizeof(com->hdr), n - sizeof(com->hdr));
533 #endif
534
535  done:
536     return code;
537 }
538
539 /**
540  * write a response structure to a sync socket.
541  *
542  * @param[in] state  handle to server-side state object
543  * @param[in] fd     file descriptor on which to perform i/o
544  * @param[in] res    handle to response packet
545  *
546  * @return operation status
547  *    @retval SYNC_OK
548  *    @retval SYNC_COM_ERROR
549  */
550 afs_int32
551 SYNC_putRes(SYNC_server_state_t * state,
552             osi_socket fd,
553             SYNC_response * res)
554 {
555     int n;
556     afs_int32 code = SYNC_OK;
557     SYNC_PROTO_BUF_DECL(buf);
558
559     if (res->hdr.response_len > (sizeof(res->hdr) + res->payload.len)) {
560         Log("SYNC_putRes:  response_len field in response header inconsistent\n");
561         code = SYNC_COM_ERROR;
562         goto done;
563     }
564
565     if (res->hdr.response_len > SYNC_PROTO_MAX_LEN) {
566         Log("SYNC_putRes:  internal SYNC buffer too small; please file a bug\n");
567         code = SYNC_COM_ERROR;
568         goto done;
569     }
570
571 #ifdef AFS_DEMAND_ATTACH_FS
572     res->hdr.flags |= SYNC_FLAG_DAFS_EXTENSIONS;
573 #endif
574     res->hdr.proto_version = state->proto_version;
575     res->hdr.pkt_seq = ++state->pkt_seq;
576     res->hdr.res_seq = ++state->res_seq;
577
578     memcpy(buf, &res->hdr, sizeof(res->hdr));
579     if (res->payload.len) {
580         memcpy(buf + sizeof(res->hdr), res->payload.buf,
581                res->hdr.response_len - sizeof(res->hdr));
582     }
583
584 #ifdef AFS_NT40_ENV
585     n = send(fd, buf, res->hdr.response_len, 0);
586 #else /* !AFS_NT40_ENV */
587     n = write(fd, buf, res->hdr.response_len);
588 #endif /* !AFS_NT40_ENV */
589
590     if (res->hdr.response_len != n) {
591         Log("SYNC_putRes: write failed\n");
592         res->hdr.response = SYNC_COM_ERROR;
593         goto done;
594     }
595
596  done:
597     return code;
598 }
599
600 /* return 0 for legal (null-terminated) string,
601  * 1 for illegal (unterminated) string */
602 int
603 SYNC_verifyProtocolString(char * buf, size_t len)
604 {
605     size_t s_len;
606
607     s_len = strnlen(buf, len);
608
609     return (s_len == len) ? 1 : 0;
610 }
611
612 /**
613  * clean up old sockets.
614  *
615  * @param[in]  state  server state object
616  *
617  * @post unix domain sockets are cleaned up
618  */
619 void
620 SYNC_cleanupSock(SYNC_server_state_t * state)
621 {
622 #ifdef USE_UNIX_SOCKETS
623     remove(state->addr.sun_path);
624 #endif
625 }
626
627 /**
628  * bind socket and set it to listen state.
629  *
630  * @param[in] state  server state object
631  *
632  * @return operation status
633  *    @retval 0 success
634  *    @retval nonzero failure
635  *
636  * @post socket bound and set to listen state
637  */
638 int
639 SYNC_bindSock(SYNC_server_state_t * state)
640 {
641     int code;
642     int on = 1;
643     int numTries;
644
645     /* Reuseaddr needed because system inexplicably leaves crud lying around */
646     code =
647         setsockopt(state->fd, SOL_SOCKET, SO_REUSEADDR, (char *)&on,
648                    sizeof(on));
649     if (code)
650         Log("SYNC_bindSock: setsockopt failed with (%d)\n", errno);
651
652     for (numTries = 0; numTries < state->bind_retry_limit; numTries++) {
653         code = bind(state->fd,
654                     (struct sockaddr *)&state->addr,
655                     AFS_SOCKADDR_LEN(&state->addr));
656         if (code == 0)
657             break;
658         Log("SYNC_bindSock: bind failed with (%d), will sleep and retry\n",
659             errno);
660         sleep(5);
661     }
662     listen(state->fd, state->listen_depth);
663
664     return code;
665 }