e32b08aec2e108dfcb3d191aebe733ac3fe3b84a
[openafs.git] / src / venus / afsio.c
1 /*
2  * Copyright (c) 2007, Hartmut Reuter,
3  * RZG, Max-Planck-Institut f. Plasmaphysik.
4  * All Rights Reserved.
5  *
6  * Redistribution and use in source and binary forms, with or without
7  * modification, are permitted provided that the following conditions are met:
8  *
9  *   1. Redistributions of source code must retain the above copyright
10  *      notice, this list of conditions and the following disclaimer.
11  *   2. Redistributions in binary form must reproduce the above copyright
12  *      notice, this list of conditions and the following disclaimer in
13  *      the documentation and/or other materials provided with the
14  *      distribution.
15  *
16  * THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES,
17  * INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY
18  * AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
19  * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
20  * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
21  * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
22  * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
23  * OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
24  * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
25  * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
26  */
27 /*
28  * Revised in 2010 by Chaz Chandler to enhance clientless operations.
29  * Now utilizes libafscp by Chaskiel Grundman.
30  * Work funded in part by Sine Nomine Associates (http://www.sinenomine.net/)
31  */
32
33 #include <afsconfig.h>
34 #include <afs/param.h>
35 #include <afs/stds.h>
36
37 #include <roken.h>
38
39 #ifdef AFS_NT40_ENV
40 #include <windows.h>
41 #define _CRT_RAND_S
42 #include <afs/smb_iocons.h>
43 #include <afs/afsd.h>
44 #include <afs/cm_ioctl.h>
45 #include <afs/pioctl_nt.h>
46 #include <WINNT/syscfg.h>
47 #else
48 #include <afs/afsint.h>
49 #define FSINT_COMMON_XG 1
50 #endif
51
52 #include <afs/opr.h>
53 #include <afs/cmd.h>
54 #include <afs/auth.h>
55 #include <afs/vlserver.h>
56 #include <afs/ihandle.h>
57 #include <afs/com_err.h>
58 #include <afs/afscp.h>
59
60 #ifdef HAVE_DIRECT_H
61 #include <direct.h>
62 #endif
63 #include <hcrypto/md5.h>
64 #ifdef AFS_PTHREAD_ENV
65 pthread_key_t uclient_key;
66 #endif
67
68 static int lockFile(struct cmd_syndesc *, void *);
69 static int readFile(struct cmd_syndesc *, void *);
70 static int writeFile(struct cmd_syndesc *, void *);
71 static void printDatarate(void);
72 static void summarizeDatarate(struct timeval *, const char *);
73 static int CmdProlog(struct cmd_syndesc *, char **, char **,
74                      char **, char **);
75 static int ScanFid(char *, struct AFSFid *);
76 static afs_int32 GetVenusFidByFid(char *, char *, int, struct afscp_venusfid **);
77 static afs_int32 GetVenusFidByPath(char *, char *, struct afscp_venusfid **);
78 static int BreakUpPath(char *, char *, char *, size_t);
79
80 static char pnp[AFSPATHMAX];    /* filename of this program when called */
81 static int verbose = 0;         /* Set if -verbose option given */
82 static int clear = 0;           /* Set if -clear option given,
83                                    Unset if -crypt given; default is -crypt */
84 static int cellGiven = 0;       /* Set if -cell option given */
85 static int force = 0;           /* Set if -force option given */
86 static int readlock = 0;        /* Set if -readlock option given */
87 static int waittime = 0;        /* Set if -waittime option given */
88 static int useFid = 0;          /* Set if fidwrite/fidread/fidappend invoked */
89 static int append = 0;          /* Set if append/fidappend invoked */
90 static struct timeval starttime, opentime, readtime, writetime;
91 static afs_uint64 xfered = 0;
92 static struct timeval now;
93 #ifdef AFS_NT40_ENV
94 static int Timezone;            /* Roken gettimeofday ignores the timezone */
95 #else
96 static struct timezone Timezone;
97 #endif
98
99 #define BUFFLEN 65536
100 #define WRITEBUFLEN (BUFFLEN * 1024)
101 #define MEGABYTE_F 1048576.0f
102
103 static MD5_CTX md5;
104 static int md5sum = 0;          /* Set if -md5 option given */
105
106 struct wbuf {
107     struct wbuf *next;
108     afs_uint32 offset;          /* offset inside the buffer */
109     afs_uint32 buflen;          /* total length == BUFFLEN */
110     afs_uint32 used;            /* bytes used inside buffer */
111     char buf[BUFFLEN];
112 };
113
114 /*!
115  *  returns difference in seconds between two times
116  *
117  *  \param[in]  from    start time
118  *  \param[in]  to      end time
119  *
120  *  \post returns "to" minus "from" in seconds
121  *
122  */
123 static_inline float
124 time_elapsed(struct timeval *from, struct timeval *to)
125 {
126     return (float)(to->tv_sec + (to->tv_usec * 0.000001) - from->tv_sec -
127                    (from->tv_usec * 0.000001));
128 } /* time_elapsed */
129
130 /*!
131  * prints current average data transfer rate at no less than 30-second intervals
132  */
133 static void
134 printDatarate(void)
135 {
136     static float oldseconds = 0.0;
137     static afs_uint64 oldxfered = 0;
138     float seconds;
139
140     gettimeofday(&now, &Timezone);
141     seconds = time_elapsed(&opentime, &now);
142     if ((seconds - oldseconds) > 30) {
143         fprintf(stderr, "%llu MB transferred, present data rate = %.3f MB/sec.\n", xfered >> 20,        /* total bytes transferred, in MB */
144                 (xfered - oldxfered) / (seconds - oldseconds) / MEGABYTE_F);
145         oldxfered = xfered;
146         oldseconds = seconds;
147     }
148 } /* printDatarate */
149
150 /*!
151  * prints overall average data transfer rate and elapsed time
152  *
153  * \param[in]   tvp             current time (to compare with file open time)
154  * \param[in]   xfer_type       string identify transfer type ("read" or "write")
155  */
156 static void
157 summarizeDatarate(struct timeval *tvp, const char *xfer_type)
158 {
159     float seconds = time_elapsed(&opentime, tvp);
160
161     fprintf(stderr, "Transfer of %llu bytes took %.3f sec.\n",
162             xfered, seconds);
163     fprintf(stderr, "Total data rate = %.03f MB/sec. for %s\n",
164             xfered / seconds / MEGABYTE_F, xfer_type);
165 } /* summarizeDatarate */
166
167 /*!
168  * prints final MD5 sum of all file data transferred
169  *
170  * \param[in]   fname   file name or FID
171  */
172 static void
173 summarizeMD5(char *fname)
174 {
175     afs_uint32 md5int[4];
176     char *p;
177
178     MD5_Final((char *) &md5int[0], &md5);
179     p = fname + strlen(fname);
180     while (p > fname) {
181         if (*(--p) == '/') {
182             ++p;
183             break;
184         }
185     }
186     fprintf(stderr, "%08x%08x%08x%08x  %s\n", htonl(md5int[0]),
187             htonl(md5int[1]), htonl(md5int[2]), htonl(md5int[3]), p);
188 } /* summarizeMD5 */
189
190 #ifdef AFS_NT40_ENV
191 static void
192 ConvertAFSPath(char **fnp)
193 {
194     char *p;
195
196     for (p = *fnp; *p; p++) {
197         if (*p == '\\')
198            *p = '/';
199     }
200
201     p = *fnp;
202     if (p[0] == '/' && p[1] == '/')
203         *fnp = p+1;
204 }
205 #endif /* AFS_NT40_ENV */
206
207 /*!
208  * parses all command-line arguments
209  *
210  * \param[in]  as       arguments list
211  * \param[out] cellp    cell name
212  * \param[out] realmp   realm name
213  * \param[out] fnp      filename (either fid or path)
214  * \param[out] slp      "synthesized" (made up) data given
215  *
216  * \post returns 0 on success or -1 on error
217  *
218  */
219 static int
220 CmdProlog(struct cmd_syndesc *as, char **cellp, char **realmp,
221           char **fnp, char **slp)
222 {
223     int i;
224     struct cmd_parmdesc *pdp;
225
226     if (as == NULL) {
227         afs_com_err(pnp, EINVAL, "(syndesc is null)");
228         return -1;
229     }
230
231     /* determine which command was requested */
232     if (strncmp(as->name, "fid", 3) == 0) /* fidread/fidwrite/fidappend */
233         useFid = 1;
234     if ( (strcmp(as->name, "append") == 0) ||
235          (strcmp(as->name, "fidappend") == 0) )
236         append = 1;             /* global */
237
238     /* attempts to ensure loop is bounded: */
239     for (pdp = as->parms, i = 0; pdp && (i < as->nParms); i++, pdp++) {
240         if (pdp->items != NULL) {
241             if (strcmp(pdp->name, "-verbose") == 0)
242                 verbose = 1;
243             if (strcmp(pdp->name, "-clear") == 0)
244                 clear = 1;
245             if (strcmp(pdp->name, "-crypt") == 0)
246                 clear = 0;
247             else if (strcmp(pdp->name, "-md5") == 0)
248                 md5sum = 1;     /* global */
249             else if (strcmp(pdp->name, "-cell") == 0) {
250                 cellGiven = 1;  /* global */
251                 *cellp = pdp->items->data;
252             } else if ( strcmp(pdp->name, "-file") == 0) {
253                 *fnp = pdp->items->data;
254 #ifdef AFS_NT40_ENV
255                 ConvertAFSPath(fnp);
256 #endif /* AFS_NT40_ENV */
257             } else if ( (strcmp(pdp->name, "-fid") == 0) ||
258                         (strcmp(pdp->name, "-vnode") == 0) ) {
259                 *fnp = pdp->items->data;
260             } else if (strcmp(pdp->name, "-force") == 0)
261                 force = 1;      /* global */
262             else if (strcmp(pdp->name, "-synthesize") == 0)
263                 *slp = pdp->items->data;
264             else if (strcmp(pdp->name, "-realm") == 0)
265                 *realmp = pdp->items->data;
266             else if (strcmp(pdp->name, "-wait") == 0)
267                 waittime = atoi(pdp->items->data);
268             else if (strcmp(pdp->name, "-readlock") == 0)
269                 readlock = 1;
270         }
271     }
272     return 0;
273 }                               /* CmdProlog */
274
275 int
276 main(int argc, char **argv)
277 {
278     struct cmd_syndesc *ts;
279     char baseName[AFSNAMEMAX];
280     int code;
281
282     /* try to get only the base name of this executable for use in logs */
283 #ifdef AFS_NT40_ENV
284     char *p = strdup(argv[0]);
285     ConvertAFSPath(&p);
286     code = BreakUpPath(p, NULL, baseName, AFSNAMEMAX);
287     free(p);
288 #else
289     code = BreakUpPath(argv[0], NULL, baseName, AFSNAMEMAX);
290 #endif
291     if (code > 0)
292         strlcpy(pnp, baseName, AFSNAMEMAX);
293     else
294         strlcpy(pnp, argv[0], AFSPATHMAX);
295
296 #ifdef AFS_PTHREAD_ENV
297     opr_Verify(pthread_key_create(&uclient_key, NULL) == 0);
298 #endif
299
300     ts = cmd_CreateSyntax("lock", lockFile, (void *)LockWrite, 0,
301                           "lock a file in AFS");
302     cmd_AddParm(ts, "-file", CMD_SINGLE, CMD_REQUIRED, "AFS-filename");
303     cmd_AddParm(ts, "-cell", CMD_SINGLE, CMD_OPTIONAL, "cellname");
304     cmd_AddParm(ts, "-verbose", CMD_FLAG, CMD_OPTIONAL, (char *)0);
305     cmd_AddParm(ts, "-clear", CMD_FLAG, CMD_OPTIONAL, (char *)0);
306     cmd_AddParm(ts, "-crypt", CMD_FLAG, CMD_OPTIONAL, (char *)0);
307     cmd_Seek(ts, 4);
308     cmd_AddParm(ts, "-realm", CMD_SINGLE, CMD_OPTIONAL, "REALMNAME");
309     cmd_AddParm(ts, "-waitseconds", CMD_SINGLE, CMD_OPTIONAL, "seconds to wait before giving up");
310     cmd_AddParm(ts, "-readlock", CMD_FLAG, CMD_OPTIONAL, "read lock only");
311
312     ts = cmd_CreateSyntax("fidlock", lockFile, (void *)LockWrite, 0,
313                           "lock by FID a file from AFS");
314     cmd_AddParm(ts, "-fid", CMD_SINGLE, CMD_REQUIRED,
315                 "volume.vnode.uniquifier");
316     cmd_AddParm(ts, "-cell", CMD_SINGLE, CMD_OPTIONAL, "cellname");
317     cmd_AddParm(ts, "-verbose", CMD_FLAG, CMD_OPTIONAL, (char *)0);
318     cmd_AddParm(ts, "-clear", CMD_FLAG, CMD_OPTIONAL, (char *)0);
319     cmd_AddParm(ts, "-crypt", CMD_FLAG, CMD_OPTIONAL, (char *)0);
320     cmd_Seek(ts, 4);
321     cmd_AddParm(ts, "-realm", CMD_SINGLE, CMD_OPTIONAL, "REALMNAME");
322     cmd_AddParm(ts, "-waitseconds", CMD_SINGLE, CMD_OPTIONAL, "seconds to wait before giving up");
323     cmd_AddParm(ts, "-readlock", CMD_FLAG, CMD_OPTIONAL, "read lock only");
324
325     ts = cmd_CreateSyntax("unlock", lockFile, (void *)LockRelease, 0,
326                           "unlock a file in AFS");
327     cmd_AddParm(ts, "-file", CMD_SINGLE, CMD_REQUIRED, "AFS-filename");
328     cmd_AddParm(ts, "-cell", CMD_SINGLE, CMD_OPTIONAL, "cellname");
329     cmd_AddParm(ts, "-verbose", CMD_FLAG, CMD_OPTIONAL, (char *)0);
330     cmd_AddParm(ts, "-clear", CMD_FLAG, CMD_OPTIONAL, (char *)0);
331     cmd_AddParm(ts, "-crypt", CMD_FLAG, CMD_OPTIONAL, (char *)0);
332     cmd_Seek(ts, 4);
333     cmd_AddParm(ts, "-realm", CMD_SINGLE, CMD_OPTIONAL, "REALMNAME");
334     cmd_AddParm(ts, "-waitseconds", CMD_SINGLE, CMD_OPTIONAL, "seconds to wait before giving up");
335
336     ts = cmd_CreateSyntax("fidunlock", lockFile, (void *)LockRelease, 0,
337                           "unlock by FID a file from AFS");
338     cmd_AddParm(ts, "-fid", CMD_SINGLE, CMD_REQUIRED,
339                 "volume.vnode.uniquifier");
340     cmd_AddParm(ts, "-cell", CMD_SINGLE, CMD_OPTIONAL, "cellname");
341     cmd_AddParm(ts, "-verbose", CMD_FLAG, CMD_OPTIONAL, (char *)0);
342     cmd_AddParm(ts, "-clear", CMD_FLAG, CMD_OPTIONAL, (char *)0);
343     cmd_AddParm(ts, "-crypt", CMD_FLAG, CMD_OPTIONAL, (char *)0);
344     cmd_Seek(ts, 4);
345     cmd_AddParm(ts, "-realm", CMD_SINGLE, CMD_OPTIONAL, "REALMNAME");
346     cmd_AddParm(ts, "-waitseconds", CMD_SINGLE, CMD_OPTIONAL, "seconds to wait before giving up");
347
348     ts = cmd_CreateSyntax("read", readFile, NULL, 0,
349                           "read a file from AFS");
350     cmd_AddParm(ts, "-file", CMD_SINGLE, CMD_REQUIRED, "AFS-filename");
351     cmd_AddParm(ts, "-cell", CMD_SINGLE, CMD_OPTIONAL, "cellname");
352     cmd_AddParm(ts, "-verbose", CMD_FLAG, CMD_OPTIONAL, (char *)0);
353     cmd_AddParm(ts, "-clear", CMD_FLAG, CMD_OPTIONAL, (char *)0);
354     cmd_AddParm(ts, "-crypt", CMD_FLAG, CMD_OPTIONAL, (char *)0);
355     cmd_AddParm(ts, "-md5", CMD_FLAG, CMD_OPTIONAL, "calculate md5 checksum");
356     cmd_AddParm(ts, "-realm", CMD_SINGLE, CMD_OPTIONAL, "REALMNAME");
357
358     ts = cmd_CreateSyntax("fidread", readFile, CMD_REQUIRED, 0,
359                           "read on a non AFS-client a file from AFS");
360     cmd_AddParm(ts, "-fid", CMD_SINGLE, CMD_REQUIRED,
361                 "volume.vnode.uniquifier");
362     cmd_AddParm(ts, "-cell", CMD_SINGLE, CMD_OPTIONAL, "cellname");
363     cmd_AddParm(ts, "-verbose", CMD_FLAG, CMD_OPTIONAL, (char *)0);
364     cmd_AddParm(ts, "-clear", CMD_FLAG, CMD_OPTIONAL, (char *)0);
365     cmd_AddParm(ts, "-md5", CMD_FLAG, CMD_OPTIONAL, "calculate md5 checksum");
366     cmd_AddParm(ts, "-realm", CMD_SINGLE, CMD_OPTIONAL, "REALMNAME");
367
368     ts = cmd_CreateSyntax("write", writeFile, NULL, 0,
369                           "write a file into AFS");
370     cmd_AddParm(ts, "-file", CMD_SINGLE, CMD_REQUIRED, "AFS-filename");
371     cmd_AddParm(ts, "-cell", CMD_SINGLE, CMD_OPTIONAL, "cellname");
372     cmd_AddParm(ts, "-verbose", CMD_FLAG, CMD_OPTIONAL, (char *)0);
373     cmd_AddParm(ts, "-clear", CMD_FLAG, CMD_OPTIONAL, (char *)0);
374     cmd_AddParm(ts, "-crypt", CMD_FLAG, CMD_OPTIONAL, (char *)0);
375     cmd_AddParm(ts, "-md5", CMD_FLAG, CMD_OPTIONAL, "calculate md5 checksum");
376     cmd_AddParm(ts, "-force", CMD_FLAG, CMD_OPTIONAL,
377                 "overwrite existing file");
378     cmd_AddParm(ts, "-synthesize", CMD_SINGLE, CMD_OPTIONAL,
379                 "create data pattern of specified length instead reading from stdin");
380     cmd_AddParm(ts, "-realm", CMD_SINGLE, CMD_OPTIONAL, "REALMNAME");
381
382     ts = cmd_CreateSyntax("fidwrite", writeFile, CMD_REQUIRED, 0,
383                           "write a file into AFS");
384     cmd_AddParm(ts, "-vnode", CMD_SINGLE, CMD_REQUIRED,
385                 "volume.vnode.uniquifier");
386     cmd_AddParm(ts, "-cell", CMD_SINGLE, CMD_OPTIONAL, "cellname");
387     cmd_AddParm(ts, "-verbose", CMD_FLAG, CMD_OPTIONAL, (char *)0);
388     cmd_AddParm(ts, "-clear", CMD_FLAG, CMD_OPTIONAL, (char *)0);
389     cmd_AddParm(ts, "-crypt", CMD_FLAG, CMD_OPTIONAL, (char *)0);
390     cmd_AddParm(ts, "-md5", CMD_FLAG, CMD_OPTIONAL, "calculate md5 checksum");
391     cmd_AddParm(ts, "-force", CMD_FLAG, CMD_OPTIONAL,
392                 "overwrite existing file");
393     cmd_AddParm(ts, "-realm", CMD_SINGLE, CMD_OPTIONAL, "REALMNAME");
394
395     ts = cmd_CreateSyntax("append", writeFile, NULL, 0,
396                           "append to a file in AFS");
397     cmd_AddParm(ts, "-file", CMD_SINGLE, CMD_REQUIRED, "AFS-filename");
398     cmd_AddParm(ts, "-cell", CMD_SINGLE, CMD_OPTIONAL, "cellname");
399     cmd_AddParm(ts, "-verbose", CMD_FLAG, CMD_OPTIONAL, (char *)0);
400     cmd_AddParm(ts, "-clear", CMD_FLAG, CMD_OPTIONAL, (char *)0);
401     cmd_AddParm(ts, "-crypt", CMD_FLAG, CMD_OPTIONAL, (char *)0);
402     cmd_AddParm(ts, "-realm", CMD_SINGLE, CMD_OPTIONAL, "REALMNAME");
403
404     ts = cmd_CreateSyntax("fidappend", writeFile, NULL, 0,
405                           "append to a file in AFS");
406     cmd_AddParm(ts, "-vnode", CMD_SINGLE, CMD_REQUIRED,
407                 "volume.vnode.uniquifier");
408     cmd_AddParm(ts, "-cell", CMD_SINGLE, CMD_OPTIONAL, "cellname");
409     cmd_AddParm(ts, "-verbose", CMD_FLAG, CMD_OPTIONAL, (char *)0);
410     cmd_AddParm(ts, "-clear", CMD_FLAG, CMD_OPTIONAL, (char *)0);
411     cmd_AddParm(ts, "-crypt", CMD_FLAG, CMD_OPTIONAL, (char *)0);
412     cmd_AddParm(ts, "-realm", CMD_SINGLE, CMD_OPTIONAL, "REALMNAME");
413
414     if (afscp_Init(NULL) != 0)
415         exit(1);
416
417     cmd_Dispatch(argc, argv);
418
419     afscp_Finalize();
420     exit(0);
421 } /* main */
422
423 /*!
424  * standardized way of parsing a File ID (FID) from command line input
425  *
426  * \param[in]   fidString       dot-delimited FID triple
427  * \param[out]  fid             pointer to the AFSFid to fill in
428  *
429  * \post The FID pointed to by "fid" is filled in which the parsed Volume,
430  *       Vnode, and Uniquifier data.  The string should be in the format
431  *       of three numbers separated by dot (.) delimiters, representing
432  *       (in order) the volume id, vnode number, and uniquifier.
433  *       Example: "576821346.1.1"
434  */
435 static int
436 ScanFid(char *fidString, struct AFSFid *fid)
437 {
438     int i = 0, code = 0;
439     long unsigned int f1, f2, f3;
440
441     if (fidString) {
442         i = sscanf(fidString, "%lu.%lu.%lu", &f1, &f2, &f3);
443         fid->Volume = (afs_uint32) f1;
444         fid->Vnode = (afs_uint32) f2;
445         fid->Unique = (afs_uint32) f3;
446     }
447     if (i != 3) {
448         fid->Volume = 0;
449         fid->Vnode = 0;
450         fid->Unique = 0;
451         code = EINVAL;
452         afs_com_err(pnp, code, "(invalid FID triple: %s)", fidString);
453     }
454
455     return code;
456 } /* ScanFid */
457
458 /*!
459  * look up cell info and verify FID info from user input
460  *
461  * \param[in]   fidString       string containing FID info
462  * \param[in]   cellName        cell name string
463  * \param[in]   onlyRW          bool: 1 = RW vol only, 0 = any vol type
464  * \param[out]  avfpp           pointer to venusfid info
465  *
466  * \post *avfpp will contain the VenusFid info found for the FID
467  *       given by the used in the string fidString and zero is
468  *       returned.  If not found, an appropriate afs error code
469  *       is returned and *avfpp will be NULL.
470  *
471  * \note Any non-NULL avfpp returned should later be freed with
472  *       afscp_FreeFid() when no longer needed.
473  */
474 static afs_int32
475 GetVenusFidByFid(char *fidString, char *cellName, int onlyRW,
476                  struct afscp_venusfid **avfpp)
477 {
478     afs_int32 code = 0;
479     struct stat sbuf;
480     struct afscp_volume *avolp;
481
482     if (*avfpp == NULL) {
483         *avfpp = calloc(1, sizeof(struct afscp_venusfid));
484         if ( *avfpp == NULL ) {
485             code = ENOMEM;
486             return code;
487         }
488     }
489
490     if (cellName == NULL) {
491         (*avfpp)->cell = afscp_DefaultCell();
492     } else {
493         (*avfpp)->cell = afscp_CellByName(cellName, NULL);
494     }
495     if ((*avfpp)->cell == NULL) {
496         if (afscp_errno == 0)
497             code = EINVAL;
498         else
499             code = afscp_errno;
500         return code;
501     }
502
503     code = ScanFid(fidString, &((*avfpp)->fid));
504     if (code != 0) {
505         code = EINVAL;
506         return code;
507     }
508
509     avolp = afscp_VolumeById((*avfpp)->cell, (*avfpp)->fid.Volume);
510     if (avolp == NULL) {
511         if (afscp_errno == 0)
512             code = ENOENT;
513         else
514             code = afscp_errno;
515         afs_com_err(pnp, code, "(finding volume %lu)",
516                     afs_printable_uint32_lu((*avfpp)->fid.Volume));
517         return code;
518     }
519
520     if ( onlyRW && (avolp->voltype != RWVOL) ) {
521         avolp = afscp_VolumeByName((*avfpp)->cell, avolp->name, RWVOL);
522         if (avolp == NULL) {
523             if (afscp_errno == 0)
524                 code = ENOENT;
525             else
526                 code = afscp_errno;
527             afs_com_err(pnp, code, "(finding volume %lu)",
528                         afs_printable_uint32_lu((*avfpp)->fid.Volume));
529             return code;
530         }
531         (*avfpp)->fid.Volume = avolp->id; /* is this safe? */
532     }
533
534     code = afscp_Stat((*avfpp), &sbuf);
535     if (code != 0) {
536         afs_com_err(pnp, code, "(stat failed with code %d)", code);
537         return code;
538     }
539     return 0;
540 } /* GetVenusFidByFid */
541
542 /*!
543  * Split a full path up into dirName and baseName components
544  *
545  * \param[in]   fullPath        can be absolute, relative, or local
546  * \param[out]  dirName         pointer to allocated char buffer or NULL
547  * \param[out]  baseName        pointer to allocated char buffer or NULL
548  *
549  * \post To the fulleset extent possible, the rightmost full path
550  *       component will be copied into baseName and all other
551  *       components into dirName (minus the trailing path separator).
552  *       If either dirName or baseName are NULL, only the non-NULL
553  *       pointer will be filled in (but both can't be null or it would
554  *       be pointless) -- so the caller can retrieve, say, only baseName
555  *       if desired.  The return code is the number of strings copied:
556  *       0 if neither dirName nor baseName could be filled in
557  *       1 if either dirName or baseName were filled in
558  *       2 if both dirName and baseName were filled in
559  */
560 static int
561 BreakUpPath(char *fullPath, char *dirName, char *baseName, size_t baseNameSize)
562 {
563     char *lastSlash;
564     size_t dirNameLen = 0;
565     int code = 0, useDirName = 1, useBaseName = 1;
566
567     if (fullPath == NULL) {
568         return code;
569     }
570
571     if (dirName == NULL)
572         useDirName = 0;
573     if (baseName == NULL)
574         useBaseName = 0;
575     if (!useBaseName && !useDirName) {
576         /* would be pointless to continue -- must be error in call */
577         return code;
578     }
579     lastSlash = strrchr(fullPath, '/');
580     if (lastSlash != NULL) {
581         /* then lastSlash points to the last path separator in fullPath */
582         if (useDirName) {
583             dirNameLen = strlen(fullPath) - strlen(lastSlash);
584             strlcpy(dirName, fullPath, min(dirNameLen + 1, baseNameSize));
585             code++;
586         }
587         if (useBaseName) {
588             lastSlash++;
589             strlcpy(baseName, lastSlash, min(strlen(lastSlash) + 1, baseNameSize));
590             code++;
591         }
592     } else {
593         /* there are no path separators in fullPath -- it's just a baseName */
594         if (useBaseName) {
595             strlcpy(baseName, fullPath, min(strlen(fullPath) + 1, baseNameSize));
596             code++;
597         }
598     }
599     return code;
600 } /* BreakUpPath */
601
602 /*!
603  * Get the VenusFid info available for the file at AFS path 'fullPath'.
604  * Works without pioctls/afsd by using libafscp.  Analogous to
605  * get_file_cell() in the previous iteration of afsio.
606  *
607  * \param[in]   fullPath        the file name
608  * \param[in]   cellName        the cell name to look up
609  * \param[out]  avfpp           pointer to Venus FID info to be filled in
610  *
611  * \post If the path resolves successfully (using afscp_ResolvePath),
612  *       then vfpp will contain the Venus FID info (cell info plus
613  *       AFSFid) of the last path segment in fullPath.
614  */
615 static afs_int32
616 GetVenusFidByPath(char *fullPath, char *cellName,
617                   struct afscp_venusfid **avfpp)
618 {
619     afs_int32 code = 0;
620
621     if (fullPath == NULL) {
622         return -1;
623     }
624
625     if (cellName != NULL) {
626         code = (afs_int32) afscp_SetDefaultCell(cellName);
627         if (code != 0) {
628             return code;
629         }
630     }
631
632     *avfpp = afscp_ResolvePath(fullPath);
633     if (*avfpp == NULL) {
634         if (afscp_errno == 0)
635             code = ENOENT;
636         else
637             code = afscp_errno;
638     }
639
640     return code;
641 } /* GetVenusFidByPath */
642
643 static int
644 lockFile(struct cmd_syndesc *as, void *arock)
645 {
646     char *fname = NULL;
647     char *cell = NULL;
648     char *realm = NULL;
649     afs_int32 code = 0;
650     struct AFSFetchStatus OutStatus;
651     struct afscp_venusfid *avfp = NULL;
652     char *buf = 0;
653     char ipv4_addr[16];
654     int locktype = (int)(intptr_t) arock;
655
656 #ifdef AFS_NT40_ENV
657     /* stdout on Windows defaults to _O_TEXT mode */
658     _setmode(1, _O_BINARY);
659 #endif
660
661     gettimeofday(&starttime, &Timezone);
662
663     CmdProlog(as, &cell, &realm, &fname, NULL);
664     afscp_AnonymousAuth(1);
665     if (clear)
666         afscp_Insecure();
667
668     if ((locktype == LockWrite) && readlock)
669         locktype = LockRead;
670
671     if (realm != NULL)
672         afscp_SetDefaultRealm(realm);
673
674     if (cell != NULL)
675         afscp_SetDefaultCell(cell);
676
677     if (useFid)
678         code = GetVenusFidByFid(fname, cell, 0, &avfp);
679     else
680         code = GetVenusFidByPath(fname, cell, &avfp);
681     if (code != 0) {
682         afs_com_err(pnp, code, "(file not found: %s)", fname);
683         afscp_FreeFid(avfp);
684         return code;
685     }
686
687 retry:
688     code = afscp_GetStatus(avfp, &OutStatus);
689     if (code != 0) {
690         afs_inet_ntoa_r(avfp->cell->fsservers[0]->addrs[0], ipv4_addr);
691         afs_com_err(pnp, code, "(failed to get status of file %s from"
692                     "server %s, code = %d)", fname, ipv4_addr, code);
693         afscp_FreeFid(avfp);
694         return code;
695     }
696
697     if (locktype != LockRelease) {
698         while (OutStatus.lockCount != 0) {
699             code = afscp_WaitForCallback(avfp, waittime);
700             if ((code == -1) && (afscp_errno == ETIMEDOUT))
701                 break;
702             if ((code = afscp_GetStatus(avfp, &OutStatus)) != 0)
703                 break;
704         }
705     } else {
706         if (OutStatus.lockCount == 0) {
707             code = -1;
708         }
709     }
710
711     if (!code) {
712         code = afscp_Lock(avfp, locktype);
713         if ((code == -1) && (afscp_errno == EWOULDBLOCK))
714             goto retry;
715     }
716     afscp_FreeFid(avfp);
717
718     if (buf != NULL)
719         free(buf);
720
721     if (code != 0)
722         afs_com_err(pnp, code, "(failed to change lock status: %d)", afscp_errno);
723
724     return code;
725 } /* lockFile */
726
727 static int
728 readFile(struct cmd_syndesc *as, void *unused)
729 {
730     char *fname = NULL;
731     char *cell = NULL;
732     char *realm = NULL;
733     afs_int32 code = 0;
734     struct AFSFetchStatus OutStatus;
735     struct afscp_venusfid *avfp = NULL;
736     afs_int64 Pos;
737     afs_int32 len;
738     afs_int64 length = 0, Len;
739     int bytes;
740     int worstCode = 0;
741     char *buf = 0;
742     char ipv4_addr[16];
743     int bufflen = BUFFLEN;
744
745 #ifdef AFS_NT40_ENV
746     /* stdout on Windows defaults to _O_TEXT mode */
747     _setmode(1, _O_BINARY);
748 #endif
749
750     gettimeofday(&starttime, &Timezone);
751
752     CmdProlog(as, &cell, &realm, &fname, NULL);
753     afscp_AnonymousAuth(1);
754     if (clear)
755         afscp_Insecure();
756
757     if (md5sum)
758         MD5_Init(&md5);
759
760     if (realm != NULL)
761         afscp_SetDefaultRealm(realm);
762
763     if (cell != NULL)
764         afscp_SetDefaultCell(cell);
765
766     if (useFid)
767         code = GetVenusFidByFid(fname, cell, 0, &avfp);
768     else
769         code = GetVenusFidByPath(fname, cell, &avfp);
770     if (code != 0) {
771         afscp_FreeFid(avfp);
772         afs_com_err(pnp, code, "(file not found: %s)", fname);
773         return code;
774     }
775
776     if (avfp->fid.Vnode & 1) {
777         code = ENOENT;
778         afs_com_err(pnp, code, "(%s is a directory, not a file)", fname);
779         afscp_FreeFid(avfp);
780         return code;
781     }
782
783     code = afscp_GetStatus(avfp, &OutStatus);
784     if (code != 0) {
785         afs_inet_ntoa_r(avfp->cell->fsservers[0]->addrs[0], ipv4_addr);
786         afs_com_err(pnp, code, "(failed to get status of file %s from"
787                     "server %s, code = %d)", fname, ipv4_addr, code);
788         afscp_FreeFid(avfp);
789         return code;
790     }
791
792     gettimeofday(&opentime, &Timezone);
793     if (verbose)
794         fprintf(stderr, "Startup to find the file took %.3f sec.\n",
795                 time_elapsed(&starttime, &opentime));
796     Len = OutStatus.Length_hi;
797     Len <<= 32;
798     Len += OutStatus.Length;
799     ZeroInt64(Pos);
800     buf = calloc(bufflen, sizeof(char));
801     if (buf == NULL) {
802         code = ENOMEM;
803         afs_com_err(pnp, code, "(cannot allocate buffer)");
804         afscp_FreeFid(avfp);
805         return code;
806     }
807     length = Len;
808     while (!code && NonZeroInt64(length)) {
809         if (length > bufflen)
810             len = bufflen;
811         else
812             len = (afs_int32) length;
813         bytes = afscp_PRead(avfp, buf, len, Pos);
814         if (bytes != len)
815             code = -3; /* what error name should we use here? */
816         if (md5sum)
817             MD5_Update(&md5, buf, len);
818         if (code == 0) {
819             len = write(1, buf, len); /* to stdout */
820             if (len == 0)
821                 code = errno;
822         }
823         length -= len;
824         xfered += len;
825         if (verbose)
826             printDatarate();
827         Pos += len;
828         worstCode = code;
829     }
830     afscp_FreeFid(avfp);
831
832     gettimeofday(&readtime, &Timezone);
833     if (md5sum)
834         summarizeMD5(fname);
835     if (verbose)
836         summarizeDatarate(&readtime, "read");
837     if (buf != NULL)
838         free(buf);
839
840     return worstCode;
841 } /* readFile */
842
843 static int
844 writeFile(struct cmd_syndesc *as, void *unused)
845 {
846     char *fname = NULL;
847     char *cell = NULL;
848     char *sSynthLen = NULL;
849     char *realm = NULL;
850     afs_int32 code = 0;
851     afs_int32 byteswritten;
852     struct AFSFetchStatus OutStatus;
853     struct AFSStoreStatus InStatus;
854     struct afscp_venusfid *dirvfp = NULL, *newvfp = NULL;
855     afs_int64 Pos;
856     afs_int64 length, Len, synthlength = 0, offset = 0;
857     afs_int64 bytes;
858     int worstCode = 0;
859     int synthesize = 0;
860     int overWrite = 0;
861     struct wbuf *bufchain = 0;
862     struct wbuf *previous, *tbuf;
863     char dirName[AFSPATHMAX];
864     char baseName[AFSNAMEMAX];
865     char ipv4_addr[16];
866
867 #ifdef AFS_NT40_ENV
868     /* stdin on Windows defaults to _O_TEXT mode */
869     _setmode(0, _O_BINARY);
870 #endif
871
872     CmdProlog(as, &cell, &realm, &fname, &sSynthLen);
873     afscp_AnonymousAuth(1);
874     if (clear)
875         afscp_Insecure();
876
877     if (realm != NULL)
878         afscp_SetDefaultRealm(realm);
879
880     if (cell != NULL)
881         afscp_SetDefaultCell(cell);
882
883     if (sSynthLen) {
884         code = util_GetInt64(sSynthLen, &synthlength);
885         if (code != 0) {
886             afs_com_err(pnp, code, "(invalid value for synthesize length %s)",
887                         sSynthLen);
888             return code;
889         }
890         synthesize = 1;
891     }
892
893     if (useFid) {
894         code = GetVenusFidByFid(fname, cell, 1, &newvfp);
895         if (code != 0) {
896             afscp_FreeFid(newvfp);
897             afs_com_err(pnp, code, "(GetVenusFidByFid returned code %d)", code);
898             return code;
899         }
900     } else {
901         code = GetVenusFidByPath(fname, cell, &newvfp);
902         if (code == 0) { /* file was found */
903             if (force)
904                 overWrite = 1;
905             else if (!append) {
906                 /*
907                  * file cannot already exist if specified by path and not
908                  * appending to it unless user forces overwrite
909                  */
910                 code = EEXIST;
911                 afscp_FreeFid(newvfp);
912                 afs_com_err(pnp, code, "(use -force to overwrite)");
913                 return code;
914             }
915         } else { /* file not found */
916             if (append) {
917                 code = ENOENT;
918                 afs_com_err(pnp, code, "(cannot append to non-existent file)");
919                 return code;
920             }
921         }
922         if (!append && !overWrite) { /* must create a new file in this case */
923             if ( BreakUpPath(fname, dirName, baseName, AFSNAMEMAX) != 2 ) {
924                 code = EINVAL;
925                 afs_com_err(pnp, code, "(must provide full AFS path)");
926                 afscp_FreeFid(newvfp);
927                 return code;
928             }
929
930             code = GetVenusFidByPath(dirName, cell, &dirvfp);
931             afscp_FreeFid(newvfp); /* release now-unneeded fid */
932             newvfp = NULL;
933             if (code != 0) {
934                 afs_com_err(pnp, code, "(is dir %s in AFS?)", dirName);
935                 return code;
936             }
937         }
938     }
939
940     if ( (newvfp != NULL) && (newvfp->fid.Vnode & 1) ) {
941         code = EISDIR;
942         afs_com_err(pnp, code, "(%s is a directory, not a file)", fname);
943         afscp_FreeFid(newvfp);
944         afscp_FreeFid(dirvfp);
945         return code;
946     }
947     gettimeofday(&starttime, &Timezone);
948
949     InStatus.UnixModeBits = 0644;
950     InStatus.Mask = AFS_SETMODE + AFS_FSYNC;
951     if (newvfp == NULL) {
952         code = afscp_CreateFile(dirvfp, baseName, &InStatus, &newvfp);
953         if (code != 0) {
954             afs_com_err(pnp, code,
955                         "(could not create file %s in directory %lu.%lu.%lu)",
956                         baseName, afs_printable_uint32_lu(dirvfp->fid.Volume),
957                         afs_printable_uint32_lu(dirvfp->fid.Vnode),
958                         afs_printable_uint32_lu(dirvfp->fid.Unique));
959             return code;
960         }
961     }
962     code = afscp_GetStatus(newvfp, &OutStatus);
963     if (code != 0) {
964         afs_inet_ntoa_r(newvfp->cell->fsservers[0]->addrs[0], ipv4_addr);
965         afs_com_err(pnp, code, "(failed to get status of file %s from"
966                     "server %s, code = %d)", fname, ipv4_addr, code);
967         afscp_FreeFid(newvfp);
968         afscp_FreeFid(dirvfp);
969         return code;
970     }
971
972     if ( !append && !force &&
973          (OutStatus.Length != 0 || OutStatus.Length_hi !=0 ) ) {
974         /*
975          * file exists, is of non-zero length, and we're not appending
976          * to it: user must force overwrite
977          * (covers fidwrite edge case)
978          */
979         code = EEXIST;
980         afscp_FreeFid(newvfp);
981         afscp_FreeFid(dirvfp);
982         afs_com_err(pnp, code, "(use -force to overwrite)");
983         return code;
984     }
985
986     if (append) {
987         Pos = OutStatus.Length_hi;
988         Pos = (Pos << 32) | OutStatus.Length;
989     } else
990         Pos = 0;
991     previous = (struct wbuf *)&bufchain;
992     if (md5sum)
993         MD5_Init(&md5);
994
995     /*
996      * currently, these two while loops (1) read the whole source file in
997      * before (2) writing any of it out, meaning that afsio can't deal with
998      * files larger than the maximum amount of memory designated for
999      * reading a file in (WRITEBUFLEN).
1000      * Consider going to a single loop, like in readFile(), though will
1001      * have implications on timing statistics (such as the "Startup to
1002      * find the file" time, below).
1003      */
1004     Len = 0;
1005     while (Len < WRITEBUFLEN) {
1006         tbuf = calloc(1, sizeof(struct wbuf));
1007         if (tbuf == NULL) {
1008             if (!bufchain) {
1009                 code = ENOMEM;
1010                 afscp_FreeFid(newvfp);
1011                 afscp_FreeFid(dirvfp);
1012                 afs_com_err(pnp, code, "(cannot allocate buffer)");
1013                 return code;
1014             }
1015             break;
1016         }
1017         tbuf->buflen = BUFFLEN;
1018         if (synthesize) {
1019             afs_int64 ll, l = tbuf->buflen;
1020             if (l > synthlength)
1021                 l = synthlength;
1022             for (ll = 0; ll < l; ll += 4096) {
1023                 sprintf(&tbuf->buf[ll], "Offset (0x%x, 0x%x)\n",
1024                         (unsigned int)((offset + ll) >> 32),
1025                         (unsigned int)((offset + ll) & 0xffffffff));
1026             }
1027             offset += l;
1028             synthlength -= l;
1029             tbuf->used = (afs_int32) l;
1030         } else
1031             tbuf->used = read(0, &tbuf->buf, tbuf->buflen); /* from stdin */
1032         if (tbuf->used == 0) {
1033             free(tbuf);
1034             break;
1035         }
1036         if (md5sum)
1037             MD5_Update(&md5, &tbuf->buf, tbuf->used);
1038         previous->next = tbuf;
1039         previous = tbuf;
1040         Len += tbuf->used;
1041     }
1042     gettimeofday(&opentime, &Timezone);
1043     if (verbose)
1044         fprintf(stderr, "Startup to find the file took %.3f sec.\n",
1045                 time_elapsed(&starttime, &opentime));
1046     bytes = Len;
1047     while (!code && bytes) {
1048         Len = bytes;
1049         length = Len;
1050         if (Len) {
1051             for (tbuf = bufchain; tbuf; tbuf = tbuf->next) {
1052                 if (tbuf->used == 0)
1053                     break;
1054                 byteswritten = afscp_PWrite(newvfp, tbuf->buf,
1055                                             tbuf->used, Pos + xfered);
1056                 if (byteswritten != tbuf->used) {
1057                     fprintf(stderr,"Only %d instead of %" AFS_INT64_FMT " bytes transferred by rx_Write()\n", byteswritten, length);
1058                     fprintf(stderr, "At %" AFS_UINT64_FMT " bytes from the end\n", length);
1059                     code = -4;
1060                     break;
1061                 }
1062                 xfered += tbuf->used;
1063                 if (verbose)
1064                     printDatarate();
1065                 length -= tbuf->used;
1066             }
1067         }
1068         Pos += Len;
1069         bytes = 0;
1070         if (!code) {
1071             for (tbuf = bufchain; tbuf; tbuf = tbuf->next) {
1072                 tbuf->offset = 0;
1073                 if (synthesize) {
1074                     afs_int64 ll, l = tbuf->buflen;
1075                     if (l > synthlength)
1076                         l = synthlength;
1077                     for (ll = 0; ll < l; ll += 4096) {
1078                         sprintf(&tbuf->buf[ll], "Offset (0x%x, 0x%x)\n",
1079                                 (unsigned int)((offset + ll) >> 32),
1080                                 (unsigned int)((offset + ll) & 0xffffffff));
1081                     }
1082                     offset += l;
1083                     synthlength -= l;
1084                     tbuf->used = (afs_int32) l;
1085                 } else
1086                     tbuf->used = read(0, &tbuf->buf, tbuf->buflen); /* from stdin */
1087                 if (!tbuf->used)
1088                     break;
1089                 if (md5sum)
1090                     MD5_Update(&md5, &tbuf->buf, tbuf->used);
1091                 Len += tbuf->used;
1092                 bytes += tbuf->used;
1093             }
1094         }
1095     }
1096     afscp_FreeFid(newvfp);
1097     afscp_FreeFid(dirvfp);
1098
1099     gettimeofday(&writetime, &Timezone);
1100     if (code) {
1101         afs_com_err(pnp, code, "(%s failed with code %d)", as->name,
1102                     code);
1103     } else if (verbose) {
1104         summarizeDatarate(&writetime, "write");
1105     }
1106     while (bufchain) {
1107         tbuf = bufchain;
1108         bufchain = tbuf->next;
1109         free(tbuf);
1110     }
1111
1112     if (md5sum)
1113         summarizeMD5(fname);
1114
1115     return worstCode;
1116 } /* writeFile */