a huge pile of changes :-)
[kai/samba.git] / source3 / client / clitar.c
1 /* 
2    Unix SMB/Netbios implementation.
3    Version 1.9.
4    Tar Extensions
5    Copyright (C) Ricky Poulten 1995
6    
7    This program is free software; you can redistribute it and/or modify
8    it under the terms of the GNU General Public License as published by
9    the Free Software Foundation; either version 2 of the License, or
10    (at your option) any later version.
11    
12    This program is distributed in the hope that it will be useful,
13    but WITHOUT ANY WARRANTY; without even the implied warranty of
14    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
15    GNU General Public License for more details.
16    
17    You should have received a copy of the GNU General Public License
18    along with this program; if not, write to the Free Software
19    Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
20 */
21
22
23 #include "includes.h"
24 #include "clitar.h"
25
26 extern BOOL recurse;
27
28 #define SEPARATORS " \t\n\r"
29 extern int DEBUGLEVEL;
30 extern int Client;
31
32 /* These defines are for the do_setrattr routine, to indicate
33  * setting and reseting of file attributes in the function call */
34 #define ATTRSET 1
35 #define ATTRRESET 0
36
37 static int attribute = aDIR | aSYSTEM | aHIDDEN;
38
39 #ifndef CLIENT_TIMEOUT
40 #define CLIENT_TIMEOUT (30*1000)
41 #endif
42
43 static char *tarbuf;
44 static int tp, ntarf, tbufsiz;
45 /* Incremental mode */
46 BOOL tar_inc=False;
47 /* Reset archive bit */
48 BOOL tar_reset=False;
49 /* Include / exclude mode (true=include, false=exclude) */
50 BOOL tar_excl=True;
51 char tar_type='\0';
52 static char **cliplist=NULL;
53 static int clipn=0;
54
55 extern file_info def_finfo;
56 extern BOOL lowercase;
57 extern int cnum;
58 extern BOOL readbraw_supported;
59 extern int max_xmit;
60 extern pstring cur_dir;
61 extern int get_total_time_ms;
62 extern int get_total_size;
63 extern int Protocol;
64
65 int blocksize=20;
66 int tarhandle;
67
68 static void writetarheader();
69 static void do_atar();
70 static void do_tar();
71 static void oct_it();
72 static void fixtarname();
73 static int dotarbuf();
74 static void dozerobuf();
75 static void dotareof();
76 static void initarbuf();
77 static int do_setrattr();
78 void cmd_tar();
79 int process_tar();
80 char **toktocliplist();
81 int clipfind();
82 /* restore functions */
83 static long readtarheader();
84 static long unoct();
85 static void do_tarput();
86 static void unfixtarname();
87
88 /*
89  * tar specific utitlities
90  */
91
92 /****************************************************************************
93 Write a tar header to buffer
94 ****************************************************************************/
95 static void writetarheader(int f,  char *aname, int size, time_t mtime,
96                     char *amode)
97 {
98   union hblock hb;
99   int i, chk, l;
100   char *jp;
101
102   memset(hb.dummy, 0, sizeof(hb.dummy));
103   
104   l=strlen(aname);
105   if (l >= NAMSIZ)
106     {
107       DEBUG(0, ("tar file %s name length exceeds NAMSIZ\n", aname));
108     }
109
110   /* use l + 1 to do the null too */
111   fixtarname(hb.dbuf.name, aname, (l >= NAMSIZ) ? NAMSIZ : l + 1);
112
113   if (lowercase)
114     strlower(hb.dbuf.name);
115
116   /* write out a "standard" tar format header */
117
118   hb.dbuf.name[NAMSIZ-1]='\0';
119   strcpy(hb.dbuf.mode, amode);
120   oct_it(0L, 8, hb.dbuf.uid);
121   oct_it(0L, 8, hb.dbuf.gid);
122   oct_it((long) size, 13, hb.dbuf.size);
123   oct_it((long) mtime, 13, hb.dbuf.mtime);
124   memcpy(hb.dbuf.chksum, "        ", sizeof(hb.dbuf.chksum));
125   hb.dbuf.linkflag='0';
126   memset(hb.dbuf.linkname, 0, NAMSIZ);
127   
128   for (chk=0, i=sizeof(hb.dummy), jp=hb.dummy; --i>=0;) chk+=(0xFF & *jp++);
129
130   oct_it((long) chk, 8, hb.dbuf.chksum);
131   hb.dbuf.chksum[6] = '\0';
132
133   (void) dotarbuf(f, hb.dummy, sizeof(hb.dummy));
134 }
135
136 /****************************************************************************
137 Read a tar header into a hblock structure, and validate
138 ***************************************************************************/
139 static long readtarheader(union hblock *hb, file_info *finfo, char *prefix)
140 {
141   long chk, fchk;
142   int i;
143   char *jp;
144
145   /*
146    * read in a "standard" tar format header - we're not that interested
147    * in that many fields, though
148    */
149
150   /* check the checksum */
151   for (chk=0, i=sizeof(hb->dummy), jp=hb->dummy; --i>=0;) chk+=(0xFF & *jp++);
152
153   if (chk == 0)
154     return chk;
155
156   /* compensate for blanks in chksum header */
157   for (i=sizeof(hb->dbuf.chksum), jp=hb->dbuf.chksum; --i>=0;)
158     chk-=(0xFF & *jp++);
159
160   chk += ' ' * sizeof(hb->dbuf.chksum);
161
162   fchk=unoct(hb->dbuf.chksum, sizeof(hb->dbuf.chksum));
163
164   DEBUG(5, ("checksum totals chk=%d fchk=%d chksum=%s\n",
165             chk, fchk, hb->dbuf.chksum));
166
167   if (fchk != chk)
168     {
169       DEBUG(0, ("checksums don't match %d %d\n", fchk, chk));
170       return -1;
171     }
172
173   strcpy(finfo->name, prefix);
174
175   /* use l + 1 to do the null too; do prefix - prefcnt to zap leading slash */
176   unfixtarname(finfo->name + strlen(prefix), hb->dbuf.name,
177                strlen(hb->dbuf.name) + 1);
178
179 /* can't handle links at present */
180   if (hb->dbuf.linkflag != '0') {
181     if (hb->dbuf.linkflag == 0) {
182       DEBUG(6, ("Warning: NULL link flag (gnu tar archive ?) %s\n",
183                 finfo->name));
184     } else { 
185       DEBUG(0, ("this tar file appears to contain some kind of link - ignoring\n"));
186       return -2;
187     }
188   }
189     
190   if ((unoct(hb->dbuf.mode, sizeof(hb->dbuf.mode)) & S_IFDIR)
191     || (*(finfo->name+strlen(finfo->name)-1) == '\\'))
192     {
193       finfo->mode=aDIR;
194     }
195   else
196     finfo->mode=0; /* we don't care about mode at the moment, we'll
197                     * just make it a regular file */
198   /*
199    * Bug fix by richard@sj.co.uk
200    *
201    * REC: restore times correctly (as does tar)
202    * We only get the modification time of the file; set the creation time
203    * from the mod. time, and the access time to current time
204    */
205   finfo->mtime = finfo->ctime = strtol(hb->dbuf.mtime, NULL, 8);
206   finfo->atime = time(NULL);
207   finfo->size = unoct(hb->dbuf.size, sizeof(hb->dbuf.size));
208
209   return True;
210 }
211
212 /****************************************************************************
213 Write out the tar buffer to tape or wherever
214 ****************************************************************************/
215 static int dotarbuf(int f, char *b, int n)
216 {
217   int fail=1, writ=n;
218
219   /* This routine and the next one should be the only ones that do write()s */
220   if (tp + n >= tbufsiz)
221     {
222       int diff;
223
224       diff=tbufsiz-tp;
225       memcpy(tarbuf + tp, b, diff);
226       fail=fail && (1+write(f, tarbuf, tbufsiz));
227       n-=diff;
228       b+=diff;
229       tp=0;
230
231       while (n >= tbufsiz)
232         {
233           fail=fail && (1 + write(f, b, tbufsiz));
234           n-=tbufsiz;
235           b+=tbufsiz;
236         }
237     }
238   if (n>0) {
239     memcpy(tarbuf+tp, b, n);
240     tp+=n;
241   }
242
243   return(fail ? writ : 0);
244 }
245
246 /****************************************************************************
247 Write a zeros to buffer / tape
248 ****************************************************************************/
249 static void dozerobuf(int f, int n)
250 {
251   /* short routine just to write out n zeros to buffer -
252    * used to round files to nearest block
253    * and to do tar EOFs */
254
255   if (n+tp >= tbufsiz)
256     {
257       memset(tarbuf+tp, 0, tbufsiz-tp);
258       write(f, tarbuf, tbufsiz);
259       memset(tarbuf, 0, (tp+=n-tbufsiz));
260     }
261   else
262     {
263       memset(tarbuf+tp, 0, n);
264       tp+=n;
265     }
266 }
267
268 /****************************************************************************
269 Malloc tape buffer
270 ****************************************************************************/
271 static void initarbuf()
272 {
273   /* initialize tar buffer */
274   tbufsiz=blocksize*TBLOCK;
275   tarbuf=malloc(tbufsiz);
276
277   /* reset tar buffer pointer and tar file counter */
278   tp=0; ntarf=0;
279 }
280
281 /****************************************************************************
282 Write two zero blocks at end of file
283 ****************************************************************************/
284 static void dotareof(int f)
285 {
286   struct stat stbuf;
287   /* Two zero blocks at end of file, write out full buffer */
288
289   (void) dozerobuf(f, TBLOCK);
290   (void) dozerobuf(f, TBLOCK);
291
292   if (fstat(f, &stbuf) == -1)
293     {
294       DEBUG(0, ("Couldn't stat file handle\n"));
295       return;
296     }
297
298   /* Could be a pipe, in which case S_ISREG should fail,
299    * and we should write out at full size */
300   if (tp > 0) write(f, tarbuf, S_ISREG(stbuf.st_mode) ? tp : tbufsiz);
301 }
302
303 /****************************************************************************
304 (Un)mangle DOS pathname, make nonabsolute
305 ****************************************************************************/
306 static void fixtarname(char *tptr, char *fp, int l)
307 {
308   /* add a '.' to start of file name, convert from ugly dos \'s in path
309    * to lovely unix /'s :-} */
310
311   *tptr++='.';
312 #ifdef KANJI
313   while (l > 0) {
314     if (is_shift_jis (*fp)) {
315       *tptr++ = *fp++;
316       *tptr++ = *fp++;
317       l -= 2;
318     } else if (is_kana (*fp)) {
319       *tptr++ = *fp++;
320       l--;
321     } else if (*fp == '\\') {
322       *tptr++ = '/';
323       fp++;
324       l--;
325     } else {
326       *tptr++ = *fp++;
327       l--;
328     }
329   }
330 #else
331   while (l--) { *tptr=(*fp == '\\') ? '/' : *fp; tptr++; fp++; }
332 #endif
333 }
334
335 /****************************************************************************
336 Convert from decimal to octal string
337 ****************************************************************************/
338 static void oct_it (register long value, register int ndgs, register char *p)
339 {
340   /* Converts long to octal string, pads with leading zeros */
341
342   /* skip final null, but do final space */
343   --ndgs;
344   p[--ndgs] = ' ';
345  
346   /* Loop does at least one digit */
347   do {
348       p[--ndgs] = '0' + (char) (value & 7);
349       value >>= 3;
350     }
351   while (ndgs > 0 && value != 0);
352  
353   /* Do leading zeros */
354   while (ndgs > 0)
355     p[--ndgs] = '0';
356 }
357
358 /****************************************************************************
359 Convert from octal string to long
360 ***************************************************************************/
361 static long unoct(char *p, int ndgs)
362 {
363   long value=0;
364   /* Converts octal string to long, ignoring any non-digit */
365
366   while (--ndgs)
367     {
368       if (isdigit(*p))
369         value = (value << 3) | (long) (*p - '0');
370
371       p++;
372     }
373
374   return value;
375 }
376
377 /****************************************************************************
378 Compare two strings in a slash insensitive way
379 ***************************************************************************/
380 int strslashcmp(const char *s1, const char *s2)
381 {
382   while(*s1 && *s2 &&
383         (*s1 == *s2
384          || tolower(*s1) == tolower(*s2)
385          || (*s1 == '\\' && *s2=='/')
386          || (*s1 == '/' && *s2=='\\'))) {
387           s1++; s2++;
388   }
389
390   return *s1-*s2;
391 }
392
393 /*
394  * general smb utility functions
395  */
396 /****************************************************************************
397 Set DOS file attributes
398 ***************************************************************************/
399 static int do_setrattr(char *fname, int attr, int setit)
400 {
401   /*
402    * First get the existing attribs from existing file
403    */
404   char *inbuf,*outbuf;
405   char *p;
406   pstring name;
407   int fattr;
408
409   strcpy(name,fname);
410   strcpy(fname,"\\");
411   strcat(fname,name);
412
413   inbuf = (char *)malloc(BUFFER_SIZE + SAFETY_MARGIN);
414   outbuf = (char *)malloc(BUFFER_SIZE + SAFETY_MARGIN);
415
416   if (!inbuf || !outbuf)
417     {
418       DEBUG(0,("out of memory\n"));
419       return False;
420     }
421
422   /* send an smb getatr message */
423
424   memset(outbuf,0,smb_size);
425   set_message(outbuf,0,2 + strlen(fname),True);
426   CVAL(outbuf,smb_com) = SMBgetatr;
427   SSVAL(outbuf,smb_tid,cnum);
428   setup_pkt(outbuf);
429
430   p = smb_buf(outbuf);
431   *p++ = 4;
432   strcpy(p,fname);
433   p += (strlen(fname)+1);
434   
435   *p++ = 4;
436   *p++ = 0;
437
438   send_smb(Client,outbuf);
439   receive_smb(Client,inbuf,CLIENT_TIMEOUT);
440
441   if (CVAL(inbuf,smb_rcls) != 0)
442     DEBUG(5,("getatr: %s\n",smb_errstr(inbuf)));
443   else
444     {
445       DEBUG(5,("\nattr 0x%X  time %d  size %d\n",
446                (int)CVAL(inbuf,smb_vwv0),
447                SVAL(inbuf,smb_vwv1),
448                SVAL(inbuf,smb_vwv3)));
449     }
450
451   fattr=CVAL(inbuf,smb_vwv0);
452
453   /* combine found attributes with bits to be set or reset */
454
455   attr=setit ? (fattr | attr) : (fattr & ~attr);
456
457   /* now try and set attributes by sending smb reset message */
458
459   /* clear out buffer and start again */
460   memset(outbuf,0,smb_size);
461   set_message(outbuf,8,4 + strlen(fname),True);
462   CVAL(outbuf,smb_com) = SMBsetatr;
463   SSVAL(outbuf,smb_tid,cnum);
464   setup_pkt(outbuf);
465
466   SSVAL(outbuf,smb_vwv0,attr);
467
468   p = smb_buf(outbuf);
469   *p++ = 4;      
470   strcpy(p,fname);
471   p += (strlen(fname)+1);
472   
473   *p++ = 4;
474   *p++ = 0;
475
476   send_smb(Client,outbuf);
477   receive_smb(Client,inbuf,CLIENT_TIMEOUT);
478   
479   if (CVAL(inbuf,smb_rcls) != 0)
480     {
481       DEBUG(0,("%s setting attributes on file %s\n",
482             smb_errstr(inbuf), fname));
483       free(inbuf);free(outbuf);
484       return(False);
485     }
486
487   free(inbuf);free(outbuf);
488   return(True);
489 }
490
491 /****************************************************************************
492 Create a file on a share
493 ***************************************************************************/
494 static BOOL smbcreat(file_info finfo, int *fnum, char *inbuf, char *outbuf)
495 {
496   char *p;
497   /* *must* be called with buffer ready malloc'ed */
498   /* open remote file */
499   
500   memset(outbuf,0,smb_size);
501   set_message(outbuf,3,2 + strlen(finfo.name),True);
502   CVAL(outbuf,smb_com) = SMBcreate;
503   SSVAL(outbuf,smb_tid,cnum);
504   setup_pkt(outbuf);
505   
506   SSVAL(outbuf,smb_vwv0,finfo.mode);
507   put_dos_date3(outbuf,smb_vwv1,finfo.mtime);
508   
509   p = smb_buf(outbuf);
510   *p++ = 4;      
511   strcpy(p,finfo.name);
512   
513   send_smb(Client,outbuf);
514   receive_smb(Client,inbuf,CLIENT_TIMEOUT);
515   
516   if (CVAL(inbuf,smb_rcls) != 0)
517     {
518       DEBUG(0,("%s opening remote file %s\n",smb_errstr(inbuf),
519                finfo.name));
520       return 0;
521     }
522   
523   *fnum = SVAL(inbuf,smb_vwv0);
524   return True;
525 }
526
527 /****************************************************************************
528 Write a file to a share
529 ***************************************************************************/
530 static BOOL smbwrite(int fnum, int n, int low, int high, int left,
531                      char *bufferp, char *inbuf, char *outbuf)
532 {
533   /* *must* be called with buffer ready malloc'ed */
534
535   memset(outbuf,0,smb_size);
536   set_message(outbuf,5,n + 3,True);
537   
538   memcpy(smb_buf(outbuf)+3, bufferp, n);
539   
540   set_message(outbuf,5,n + 3, False);
541   CVAL(outbuf,smb_com) = SMBwrite;
542   SSVAL(outbuf,smb_tid,cnum);
543   setup_pkt(outbuf);
544   
545   SSVAL(outbuf,smb_vwv0,fnum);
546   SSVAL(outbuf,smb_vwv1,n);
547   SIVAL(outbuf,smb_vwv2,low);
548   SSVAL(outbuf,smb_vwv4,left);
549   CVAL(smb_buf(outbuf),0) = 1;
550   SSVAL(smb_buf(outbuf),1,n);
551
552   send_smb(Client,outbuf); 
553   receive_smb(Client,inbuf,CLIENT_TIMEOUT);
554   
555   if (CVAL(inbuf,smb_rcls) != 0)
556     {
557       DEBUG(0,("%s writing remote file\n",smb_errstr(inbuf)));
558       return False;
559     }
560   
561   if (n != SVAL(inbuf,smb_vwv0))
562     {
563       DEBUG(0,("Error: only wrote %d bytes out of %d\n",
564                SVAL(inbuf,smb_vwv0), n));
565       return False;
566     }
567
568   return True;
569 }
570
571 /****************************************************************************
572 Close a file on a share
573 ***************************************************************************/
574 static BOOL smbshut(file_info finfo, int fnum, char *inbuf, char *outbuf)
575 {
576   /* *must* be called with buffer ready malloc'ed */
577
578   memset(outbuf,0,smb_size);
579   set_message(outbuf,3,0,True);
580   CVAL(outbuf,smb_com) = SMBclose;
581   SSVAL(outbuf,smb_tid,cnum);
582   setup_pkt(outbuf);
583   
584   SSVAL(outbuf,smb_vwv0,fnum);
585   put_dos_date3(outbuf,smb_vwv1,finfo.mtime);
586   
587   DEBUG(3,("Setting date to %s (0x%X)",
588            asctime(LocalTime(&finfo.mtime)),
589            finfo.mtime));
590   
591   send_smb(Client,outbuf);
592   receive_smb(Client,inbuf,CLIENT_TIMEOUT);
593   
594   if (CVAL(inbuf,smb_rcls) != 0)
595     {
596       DEBUG(0,("%s closing remote file %s\n",smb_errstr(inbuf),
597                finfo.name));
598       return False;
599     }
600
601   return True;
602 }
603
604 /****************************************************************************
605 Verify existence of path on share
606 ***************************************************************************/
607 static BOOL smbchkpath(char *fname, char *inbuf, char *outbuf)
608 {
609   char *p;
610
611   memset(outbuf,0,smb_size);
612   set_message(outbuf,0,4 + strlen(fname),True);
613   CVAL(outbuf,smb_com) = SMBchkpth;
614   SSVAL(outbuf,smb_tid,cnum);
615   setup_pkt(outbuf);
616
617   p = smb_buf(outbuf);
618   *p++ = 4;
619   strcpy(p,fname);
620
621   send_smb(Client,outbuf);
622   receive_smb(Client,inbuf,CLIENT_TIMEOUT);
623
624   DEBUG(5,("smbchkpath: %s\n",smb_errstr(inbuf)));
625
626   return(CVAL(inbuf,smb_rcls) == 0);
627 }
628
629 /****************************************************************************
630 Make a directory on share
631 ***************************************************************************/
632 static BOOL smbmkdir(char *fname, char *inbuf, char *outbuf)
633 {
634   /* *must* be called with buffer ready malloc'ed */
635   char *p;
636
637   memset(outbuf,0,smb_size);
638   set_message(outbuf,0,2 + strlen(fname),True);
639   
640   CVAL(outbuf,smb_com) = SMBmkdir;
641   SSVAL(outbuf,smb_tid,cnum);
642   setup_pkt(outbuf);
643   
644   p = smb_buf(outbuf);
645   *p++ = 4;      
646   strcpy(p,fname);
647   
648   send_smb(Client,outbuf);
649   receive_smb(Client,inbuf,CLIENT_TIMEOUT);
650   
651   if (CVAL(inbuf,smb_rcls) != 0)
652     {
653       DEBUG(0,("%s making remote directory %s\n",
654                smb_errstr(inbuf),fname));
655       return(False);
656     }
657
658   return(True);
659 }
660
661 /****************************************************************************
662 Ensure a remote path exists (make if necessary)
663 ***************************************************************************/
664 static BOOL ensurepath(char *fname, char *inbuf, char *outbuf)
665 {
666   /* *must* be called with buffer ready malloc'ed */
667   /* ensures path exists */
668
669   pstring partpath, ffname;
670   char *p=fname, *basehack;
671
672   *partpath = 0;
673
674   /* fname copied to ffname so can strtok */
675
676   strcpy(ffname, fname);
677
678   /* do a `basename' on ffname, so don't try and make file name directory */
679   if ((basehack=strrchr(ffname, '\\')) == NULL)
680     return True;
681   else
682     *basehack='\0';
683
684   p=strtok(ffname, "\\");
685
686   while (p)
687     {
688       strcat(partpath, p);
689
690       if (!smbchkpath(partpath, inbuf, outbuf)) {
691         if (!smbmkdir(partpath, inbuf, outbuf))
692           {
693             DEBUG(0, ("Error mkdirhiering\n"));
694             return False;
695           }
696         else
697           DEBUG(3, ("mkdirhiering %s\n", partpath));
698
699       }
700
701       strcat(partpath, "\\");
702       p = strtok(NULL,"/\\");
703     }
704
705     return True;
706 }
707
708 /*
709  * smbclient functions
710  */
711 /****************************************************************************
712 append one remote file to the tar file
713 ***************************************************************************/
714 static void do_atar(char *rname,char *lname,file_info *finfo1)
715 {
716   int fnum;
717   uint32 nread=0;
718   char *p;
719   char *inbuf,*outbuf;
720   file_info finfo;
721   BOOL close_done = False;
722   BOOL shallitime=True;
723   BOOL ignore_close_error = False;
724   char *dataptr=NULL;
725   int datalen=0;
726
727   struct timeval tp_start;
728   GetTimeOfDay(&tp_start);
729
730   if (finfo1) 
731     finfo = *finfo1;
732   else
733     finfo = def_finfo;
734
735   inbuf = (char *)malloc(BUFFER_SIZE + SAFETY_MARGIN);
736   outbuf = (char *)malloc(BUFFER_SIZE + SAFETY_MARGIN);
737
738   if (!inbuf || !outbuf)
739     {
740       DEBUG(0,("out of memory\n"));
741       return;
742     }
743
744   memset(outbuf,0,smb_size);
745   set_message(outbuf,15,1 + strlen(rname),True);
746
747   CVAL(outbuf,smb_com) = SMBopenX;
748   SSVAL(outbuf,smb_tid,cnum);
749   setup_pkt(outbuf);
750
751   SSVAL(outbuf,smb_vwv0,0xFF);
752   SSVAL(outbuf,smb_vwv2,1);
753   SSVAL(outbuf,smb_vwv3,(DENY_NONE<<4));
754   SSVAL(outbuf,smb_vwv4,aSYSTEM | aHIDDEN);
755   SSVAL(outbuf,smb_vwv5,aSYSTEM | aHIDDEN);
756   SSVAL(outbuf,smb_vwv8,1);
757
758   p = smb_buf(outbuf);
759   strcpy(p,rname);
760   p = skip_string(p,1);
761
762   dos_clean_name(rname);
763
764   /* do a chained openX with a readX? */  
765   if (finfo.size > 0)
766     {
767       SSVAL(outbuf,smb_vwv0,SMBreadX);
768       SSVAL(outbuf,smb_vwv1,PTR_DIFF(p,outbuf) - 4);
769       memset(p,0,200);
770       p -= smb_wct;
771       SSVAL(p,smb_wct,10);
772       SSVAL(p,smb_vwv0,0xFF);
773       SSVAL(p,smb_vwv5,MIN(max_xmit-500,finfo.size));
774       SSVAL(p,smb_vwv9,MIN(0xFFFF,finfo.size));
775       smb_setlen(outbuf,smb_len(outbuf)+11*2+1);  
776     }
777   
778   send_smb(Client,outbuf);
779   receive_smb(Client,inbuf,CLIENT_TIMEOUT);
780
781   if (CVAL(inbuf,smb_rcls) != 0)
782     {
783       if (CVAL(inbuf,smb_rcls) == ERRSRV &&
784           SVAL(inbuf,smb_err) == ERRnoresource &&
785           reopen_connection(inbuf,outbuf))
786         {
787           do_atar(rname,lname,finfo1);
788           free(inbuf);free(outbuf);
789           return;
790         }
791
792       DEBUG(0,("%s opening remote file %s\n",smb_errstr(inbuf),rname));
793       free(inbuf);free(outbuf);
794       return;
795     }
796
797   strcpy(finfo.name,rname);
798   if (!finfo1)
799     {
800       finfo.mode = SVAL(inbuf,smb_vwv3);
801       finfo.size = IVAL(inbuf,smb_vwv4);
802       finfo.mtime = make_unix_date3(inbuf+smb_vwv6);
803       finfo.atime = finfo.ctime = finfo.mtime;
804     }
805
806   DEBUG(3,("file %s attrib 0x%X\n",finfo.name,finfo.mode));
807
808   fnum = SVAL(inbuf,smb_vwv2);
809
810   if (tar_inc && !(finfo.mode & aARCH))
811     {
812       DEBUG(4, ("skipping %s - archive bit not set\n", finfo.name));
813       shallitime=0;
814     }
815   else
816     {
817       if (SVAL(inbuf,smb_vwv0) == SMBreadX)
818         {
819           p = (inbuf+4+SVAL(inbuf,smb_vwv1)) - smb_wct;
820           datalen = SVAL(p,smb_vwv5);
821           dataptr = inbuf + 4 + SVAL(p,smb_vwv6);
822         }
823       else
824         {
825           dataptr = NULL;
826           datalen = 0;
827         }
828
829       DEBUG(2,("getting file %s of size %d bytes as a tar file %s",
830                finfo.name,
831                finfo.size,
832                lname));
833       
834       /* write a tar header, don't bother with mode - just set to 100644 */
835       writetarheader(tarhandle, rname, finfo.size, finfo.mtime, "100644 \0");
836       
837       while (nread < finfo.size && !close_done)
838         {
839           int method = -1;
840           static BOOL can_chain_close=True;
841
842           p=NULL;
843           
844           DEBUG(3,("nread=%d\n",nread));
845           
846           /* 3 possible read types. readbraw if a large block is required.
847              readX + close if not much left and read if neither is supported */
848
849           /* we might have already read some data from a chained readX */
850           if (dataptr && datalen>0)
851             method=3;
852           
853           /* if we can finish now then readX+close */
854           if (method<0 && can_chain_close && (Protocol >= PROTOCOL_LANMAN1) && 
855               ((finfo.size - nread) < 
856                (max_xmit - (2*smb_size + 13*SIZEOFWORD + 300))))
857             method = 0;
858           
859           /* if we support readraw then use that */
860           if (method<0 && readbraw_supported)
861             method = 1;
862           
863           /* if we can then use readX */
864           if (method<0 && (Protocol >= PROTOCOL_LANMAN1))
865             method = 2;
866           
867           
868           switch (method)
869             {
870               /* use readX */
871             case 0:
872             case 2:
873               if (method == 0)
874                 close_done = True;
875               
876               /* use readX + close */
877               memset(outbuf,0,smb_size);
878               set_message(outbuf,10,0,True);
879               CVAL(outbuf,smb_com) = SMBreadX;
880               SSVAL(outbuf,smb_tid,cnum);
881               setup_pkt(outbuf);
882               
883               if (close_done)
884                 {
885                   CVAL(outbuf,smb_vwv0) = SMBclose;
886                   SSVAL(outbuf,smb_vwv1,PTR_DIFF(smb_buf(outbuf),outbuf) - 4);
887                 }
888               else
889                 CVAL(outbuf,smb_vwv0) = 0xFF;         
890               
891               
892               SSVAL(outbuf,smb_vwv2,fnum);
893               SIVAL(outbuf,smb_vwv3,nread);
894               SSVAL(outbuf,smb_vwv5,MIN(max_xmit-200,finfo.size - nread));
895               SSVAL(outbuf,smb_vwv6,0);
896               SIVAL(outbuf,smb_vwv7,0);
897               SSVAL(outbuf,smb_vwv9,MIN(0xFFFF,finfo.size-nread));
898               
899               if (close_done)
900                 {
901                   p = smb_buf(outbuf);
902                   memset(p,0,9);
903                   
904                   CVAL(p,0) = 3;
905                   SSVAL(p,1,fnum);
906                   SIVALS(p,3,-1);
907                   
908                   /* now set the total packet length */
909                   smb_setlen(outbuf,smb_len(outbuf)+9);
910                 }
911               
912               send_smb(Client,outbuf);
913               receive_smb(Client,inbuf,CLIENT_TIMEOUT);
914               
915               if (CVAL(inbuf,smb_rcls) != 0)
916                 {
917                   DEBUG(0,("Error %s reading remote file\n",smb_errstr(inbuf)));
918                   break;
919                 }
920               
921               if (close_done &&
922                   SVAL(inbuf,smb_vwv0) != SMBclose)
923                 {
924                   /* NOTE: WfWg sometimes just ignores the chained
925                      command! This seems to break the spec? */
926                   DEBUG(3,("Rejected chained close?\n"));
927                   close_done = False;
928                   can_chain_close = False;
929                   ignore_close_error = True;
930                 }
931               
932               datalen = SVAL(inbuf,smb_vwv5);
933               dataptr = inbuf + 4 + SVAL(inbuf,smb_vwv6);
934               break;
935               
936               
937               /* use readbraw */
938             case 1:
939               {
940                 static int readbraw_size = 0xFFFF;
941                 
942                 extern int Client;
943                 memset(outbuf,0,smb_size);
944                 set_message(outbuf,8,0,True);
945                 CVAL(outbuf,smb_com) = SMBreadbraw;
946                 SSVAL(outbuf,smb_tid,cnum);
947                 setup_pkt(outbuf);
948                 SSVAL(outbuf,smb_vwv0,fnum);
949                 SIVAL(outbuf,smb_vwv1,nread);
950                 SSVAL(outbuf,smb_vwv3,MIN(finfo.size-nread,readbraw_size));
951                 SSVAL(outbuf,smb_vwv4,0);
952                 SIVALS(outbuf,smb_vwv5,-1);
953                 send_smb(Client,outbuf);
954                 
955                 /* Now read the raw data into the buffer and write it */          
956                 if(read_smb_length(Client,inbuf,0) == -1) {
957                   DEBUG(0,("Failed to read length in readbraw\n"));         
958                   exit(1);
959                 }
960                 
961                 /* Even though this is not an smb message, smb_len
962                    returns the generic length of an smb message */
963                 datalen = smb_len(inbuf);
964                 
965                 if (datalen == 0)
966                   {
967                     /* we got a readbraw error */
968                     DEBUG(4,("readbraw error - reducing size\n"));
969                     readbraw_size = (readbraw_size * 9) / 10;
970                     
971                     if (readbraw_size < max_xmit)
972                       {
973                         DEBUG(0,("disabling readbraw\n"));
974                         readbraw_supported = False;
975                       }
976
977                     dataptr=NULL;
978                     continue;
979                   }
980
981                 if(read_data(Client,inbuf,datalen) != datalen) {
982                   DEBUG(0,("Failed to read data in readbraw\n"));
983                   exit(1);
984                 }
985                 dataptr = inbuf;
986               }
987               break;
988
989             case 3:
990               /* we've already read some data with a chained readX */
991               break;
992               
993             default:
994               /* use plain read */
995               memset(outbuf,0,smb_size);
996               set_message(outbuf,5,0,True);
997               CVAL(outbuf,smb_com) = SMBread;
998               SSVAL(outbuf,smb_tid,cnum);
999               setup_pkt(outbuf);
1000               
1001               SSVAL(outbuf,smb_vwv0,fnum);
1002               SSVAL(outbuf,smb_vwv1,MIN(max_xmit-200,finfo.size - nread));
1003               SIVAL(outbuf,smb_vwv2,nread);
1004               SSVAL(outbuf,smb_vwv4,finfo.size - nread);
1005               
1006               send_smb(Client,outbuf);
1007               receive_smb(Client,inbuf,CLIENT_TIMEOUT);
1008               
1009               if (CVAL(inbuf,smb_rcls) != 0)
1010                 {
1011                   DEBUG(0,("Error %s reading remote file\n",smb_errstr(inbuf)));
1012                   break;
1013                 }
1014               
1015               datalen = SVAL(inbuf,smb_vwv0);
1016               dataptr = smb_buf(inbuf) + 3;
1017               break;
1018             }
1019           
1020           
1021           /* add received bits of file to buffer - dotarbuf will
1022            * write out in 512 byte intervals */
1023           if (dotarbuf(tarhandle,dataptr,datalen) != datalen)
1024             {
1025               DEBUG(0,("Error writing local file\n"));
1026               break;
1027             }
1028           
1029           nread += datalen;
1030           if (datalen == 0) 
1031             {
1032               DEBUG(0,("Error reading file %s. Got 0 bytes\n", rname));
1033               break;
1034             }
1035
1036           dataptr=NULL;
1037           datalen=0;
1038         }
1039       
1040       /* round tar file to nearest block */
1041       if (finfo.size % TBLOCK)
1042         dozerobuf(tarhandle, TBLOCK - (finfo.size % TBLOCK));
1043       
1044       ntarf++;
1045     }
1046   
1047   if (!close_done)
1048     {
1049       memset(outbuf,0,smb_size);
1050       set_message(outbuf,3,0,True);
1051       CVAL(outbuf,smb_com) = SMBclose;
1052       SSVAL(outbuf,smb_tid,cnum);
1053       setup_pkt(outbuf);
1054       
1055       SSVAL(outbuf,smb_vwv0,fnum);
1056       SIVALS(outbuf,smb_vwv1,-1);
1057       
1058       send_smb(Client,outbuf);
1059       receive_smb(Client,inbuf,CLIENT_TIMEOUT);
1060       
1061       if (!ignore_close_error && CVAL(inbuf,smb_rcls) != 0)
1062         {
1063           DEBUG(0,("Error %s closing remote file\n",smb_errstr(inbuf)));
1064           free(inbuf);free(outbuf);
1065           return;
1066         }
1067     }
1068
1069   if (shallitime)
1070     {
1071       struct timeval tp_end;
1072       int this_time;
1073
1074       /* if shallitime is true then we didn't skip */
1075       if (tar_reset) (void) do_setrattr(finfo.name, aARCH, ATTRRESET);
1076       
1077       GetTimeOfDay(&tp_end);
1078       this_time = 
1079         (tp_end.tv_sec - tp_start.tv_sec)*1000 +
1080           (tp_end.tv_usec - tp_start.tv_usec)/1000;
1081       get_total_time_ms += this_time;
1082       get_total_size += finfo.size;
1083
1084       /* Thanks to Carel-Jan Engel (ease@mail.wirehub.nl) for this one */
1085       DEBUG(2,("(%g kb/s) (average %g kb/s)\n",
1086                finfo.size / MAX(0.001, (1.024*this_time)),
1087                get_total_size / MAX(0.001, (1.024*get_total_time_ms))));
1088     }
1089   
1090   free(inbuf);free(outbuf);
1091 }
1092
1093 /****************************************************************************
1094 Append single file to tar file (or not)
1095 ***************************************************************************/
1096 static void do_tar(file_info *finfo)
1097 {
1098   pstring rname;
1099
1100   if (strequal(finfo->name,".") || strequal(finfo->name,".."))
1101     return;
1102
1103   /* Is it on the exclude list ? */
1104   if (!tar_excl && clipn) {
1105     pstring exclaim;
1106
1107     strcpy(exclaim, cur_dir);
1108     *(exclaim+strlen(exclaim)-1)='\0';
1109
1110     if (clipfind(cliplist, clipn, exclaim)) {
1111       DEBUG(3,("Skipping directory %s\n", exclaim));
1112       return;
1113     }
1114
1115     strcat(exclaim, "\\");
1116     strcat(exclaim, finfo->name);
1117
1118     if (clipfind(cliplist, clipn, exclaim)) {
1119       DEBUG(3,("Skipping file %s\n", exclaim));
1120       return;
1121     }
1122   }
1123
1124   if (finfo->mode & aDIR)
1125     {
1126       pstring saved_curdir;
1127       pstring mtar_mask;
1128       char *inbuf,*outbuf;
1129
1130       inbuf = (char *)malloc(BUFFER_SIZE + SAFETY_MARGIN);
1131       outbuf = (char *)malloc(BUFFER_SIZE + SAFETY_MARGIN);
1132
1133       if (!inbuf || !outbuf)
1134         {
1135           DEBUG(0,("out of memory\n"));
1136           return;
1137         }
1138
1139       strcpy(saved_curdir,cur_dir);
1140
1141       strcat(cur_dir,finfo->name);
1142       strcat(cur_dir,"\\");
1143
1144       /* write a tar directory, don't bother with mode - just set it to
1145        * 40755 */
1146       writetarheader(tarhandle, cur_dir, 0, finfo->mtime, "040755 \0");
1147       strcpy(mtar_mask,cur_dir);
1148       strcat(mtar_mask,"*");
1149       
1150       do_dir((char *)inbuf,(char *)outbuf,mtar_mask,attribute,do_tar,recurse);
1151       strcpy(cur_dir,saved_curdir);
1152       free(inbuf);free(outbuf);
1153     }
1154   else
1155     {
1156       strcpy(rname,cur_dir);
1157       strcat(rname,finfo->name);
1158       do_atar(rname,finfo->name,finfo);
1159     }
1160 }
1161
1162 /****************************************************************************
1163 Convert from UNIX to DOS file names
1164 ***************************************************************************/
1165 static void unfixtarname(char *tptr, char *fp, int l)
1166 {
1167   /* remove '.' from start of file name, convert from unix /'s to
1168    * dos \'s in path. Kill any absolute path names.
1169    */
1170
1171   if (*fp == '.') fp++;
1172   if (*fp == '\\' || *fp == '/') fp++;
1173
1174 #ifdef KANJI
1175   while (l > 0) {
1176     if (is_shift_jis (*fp)) {
1177       *tptr++ = *fp++;
1178       *tptr++ = *fp++;
1179       l -= 2;
1180     } else if (is_kana (*fp)) {
1181       *tptr++ = *fp++;
1182       l--;
1183     } else if (*fp == '/') {
1184       *tptr++ = '\\';
1185       fp++;
1186       l--;
1187     } else {
1188       *tptr++ = *fp++;
1189       l--;
1190     }
1191   }
1192 #else
1193   while (l--) { *tptr=(*fp == '/') ? '\\' : *fp; tptr++; fp++; }
1194 #endif
1195 }
1196
1197 static void do_tarput()
1198 {
1199   file_info finfo;
1200   int nread=0, bufread;
1201   char *inbuf,*outbuf; 
1202   int fsize=0;
1203   int fnum;
1204   struct timeval tp_start;
1205   BOOL tskip=False;       /* We'll take each file as it comes */
1206
1207   GetTimeOfDay(&tp_start);
1208   
1209   inbuf = (char *)malloc(BUFFER_SIZE + SAFETY_MARGIN);
1210   outbuf = (char *)malloc(BUFFER_SIZE + SAFETY_MARGIN);
1211   
1212   if (!inbuf || !outbuf)
1213     {
1214       DEBUG(0,("out of memory\n"));
1215       return;
1216     }
1217   
1218   /*
1219    * Must read in tbufsiz dollops
1220    */
1221
1222   /* These should be the only reads in clitar.c */
1223   while ((bufread=read(tarhandle, tarbuf, tbufsiz))>0) {
1224     char *bufferp, *endofbuffer;
1225     int chunk;
1226
1227     /* Code to handle a short read.
1228      * We always need a TBLOCK full of stuff
1229      */
1230     if (bufread % TBLOCK) {
1231       int lchunk=TBLOCK-(bufread % TBLOCK);
1232       int lread;
1233
1234       /* It's a shorty - a short read that is */
1235       DEBUG(3, ("Short read, read %d so far (need %d)\n", bufread, lchunk));
1236
1237       while ((lread=read(tarhandle, tarbuf+bufread, lchunk))>0) {
1238         bufread+=lread;
1239         if (!(lchunk-=lread)) break;
1240       }
1241
1242       /* If we've reached EOF then that must be a short file */
1243       if (lread<=0) break;
1244     }
1245
1246     bufferp=tarbuf; 
1247     endofbuffer=tarbuf+bufread;
1248
1249     if (tskip) {
1250       if (fsize<bufread) {
1251         tskip=False;
1252         bufferp+=fsize;
1253         fsize=0;
1254       } else {
1255         if (fsize==bufread) tskip=False;
1256         fsize-=bufread;
1257         continue;
1258       }
1259     }
1260
1261     do {
1262       if (!fsize)
1263         {
1264           switch (readtarheader((union hblock *) bufferp, &finfo, cur_dir))
1265             {
1266             case -2:             /* something dodgy but not fatal about this */
1267               DEBUG(0, ("skipping %s...\n", finfo.name));
1268               bufferp+=TBLOCK;   /* header - like a link */
1269               continue;
1270             case -1:
1271               DEBUG(0, ("abandoning restore\n"));
1272               free(inbuf); free(outbuf);
1273               return;
1274             case 0: /* chksum is zero - we assume that one all zero
1275                      *header block will do for eof */
1276               DEBUG(0,
1277                     ("total of %d tar files restored to share\n", ntarf));
1278               free(inbuf); free(outbuf);
1279               return;
1280             default:
1281               break;
1282             }
1283
1284           tskip=clipn
1285             && (clipfind(cliplist, clipn, finfo.name) ^ tar_excl);
1286           if (tskip) {
1287             bufferp+=TBLOCK;
1288             if (finfo.mode & aDIR)
1289               continue;
1290             else if ((fsize=finfo.size) % TBLOCK) {
1291               fsize+=TBLOCK-(fsize%TBLOCK);
1292             }
1293             if (fsize<endofbuffer-bufferp) {
1294               bufferp+=fsize;
1295               fsize=0;
1296               continue;
1297             } else {
1298               fsize-=endofbuffer-bufferp;
1299               break;
1300             }
1301           }
1302
1303           if (finfo.mode & aDIR)
1304             {
1305               if (!smbchkpath(finfo.name, inbuf, outbuf)
1306                   && !smbmkdir(finfo.name, inbuf, outbuf))
1307                 {
1308                   DEBUG(0, ("abandoning restore\n"));
1309                   free(inbuf); free(outbuf);
1310                   return;
1311               }
1312               else
1313                 {
1314                   bufferp+=TBLOCK;
1315                   continue;
1316                 }
1317             }
1318           
1319           fsize=finfo.size;
1320
1321           if (ensurepath(finfo.name, inbuf, outbuf)
1322               && !smbcreat(finfo, &fnum, inbuf, outbuf))
1323             {
1324               DEBUG(0, ("abandoning restore\n"));
1325               free(inbuf);free(outbuf);
1326               return;
1327             }
1328
1329           DEBUG(0,("restore tar file %s of size %d bytes\n",
1330                    finfo.name,finfo.size));
1331
1332           nread=0;
1333           if ((bufferp+=TBLOCK) >= endofbuffer) break;    
1334         } /* if (!fsize) */
1335         
1336       /* write out the file in chunk sized chunks - don't
1337        * go past end of buffer though */
1338       chunk=(fsize-nread < endofbuffer - bufferp)
1339         ? fsize - nread : endofbuffer - bufferp;
1340       
1341       while (chunk > 0) {
1342         int minichunk=MIN(chunk, max_xmit-200);
1343         
1344         if (!smbwrite(fnum, /* file descriptor */
1345                       minichunk, /* n */
1346                       nread, /* offset low */
1347                       0, /* offset high - not implemented */
1348                       fsize-nread, /* left - only hint to server */
1349                       bufferp,
1350                       inbuf,
1351                       outbuf))
1352           {
1353             DEBUG(0, ("Error writing remote file\n"));
1354             free(inbuf); free(outbuf);
1355             return;
1356           }
1357         DEBUG(5, ("chunk writing fname=%s fnum=%d nread=%d minichunk=%d chunk=%d size=%d\n", finfo.name, fnum, nread, minichunk, chunk, fsize));
1358         
1359         bufferp+=minichunk; nread+=minichunk;
1360         chunk-=minichunk;
1361       }
1362       
1363       if (nread>=fsize)
1364         {
1365           if (!smbshut(finfo, fnum, inbuf, outbuf))
1366             {
1367               DEBUG(0, ("Error closing remote file\n"));
1368               free(inbuf);free(outbuf);
1369               return;
1370             }
1371           if (fsize % TBLOCK) bufferp+=TBLOCK - (fsize % TBLOCK);
1372           DEBUG(5, ("bufferp is now %d (psn=%d)\n",
1373                     (long) bufferp, (long)(bufferp - tarbuf)));
1374           ntarf++;
1375           fsize=0;
1376         }
1377     } while (bufferp < endofbuffer);
1378   }
1379
1380   DEBUG(0, ("premature eof on tar file ?\n"));
1381   DEBUG(0,("total of %d tar files restored to share\n", ntarf));
1382
1383   free(inbuf); free(outbuf);
1384 }
1385
1386 /*
1387  * samba interactive commands
1388  */
1389
1390 /****************************************************************************
1391 Blocksize command
1392 ***************************************************************************/
1393 void cmd_block(void)
1394 {
1395   fstring buf;
1396   int block;
1397
1398   if (!next_token(NULL,buf,NULL))
1399     {
1400       DEBUG(0, ("blocksize <n>\n"));
1401       return;
1402     }
1403
1404   block=atoi(buf);
1405   if (block < 0 || block > 65535)
1406     {
1407       DEBUG(0, ("blocksize out of range"));
1408       return;
1409     }
1410
1411   blocksize=block;
1412   DEBUG(2,("blocksize is now %d\n", blocksize));
1413 }
1414
1415 /****************************************************************************
1416 command to set incremental / reset mode
1417 ***************************************************************************/
1418 void cmd_tarmode(void)
1419 {
1420   fstring buf;
1421
1422   while (next_token(NULL,buf,NULL)) {
1423     if (strequal(buf, "full"))
1424       tar_inc=False;
1425     else if (strequal(buf, "inc"))
1426       tar_inc=True;
1427     else if (strequal(buf, "reset"))
1428       tar_reset=True;
1429     else if (strequal(buf, "noreset"))
1430       tar_reset=False;
1431     else DEBUG(0, ("tarmode: unrecognised option %s\n", buf));
1432   }
1433
1434   DEBUG(0, ("tarmode is now %s, %s\n",
1435             tar_inc ? "incremental" : "full",
1436             tar_reset ? "reset" : "noreset"));
1437 }
1438
1439 /****************************************************************************
1440 Feeble attrib command
1441 ***************************************************************************/
1442 void cmd_setmode(void)
1443 {
1444   char *q;
1445   fstring buf;
1446   pstring fname;
1447   int attra[2];
1448   int direct=1;
1449
1450   attra[0] = attra[1] = 0;
1451
1452   if (!next_token(NULL,buf,NULL))
1453     {
1454       DEBUG(0, ("setmode <filename> <perm=[+|-]rsha>\n"));
1455       return;
1456     }
1457
1458   strcpy(fname, cur_dir);
1459   strcat(fname, buf);
1460
1461   while (next_token(NULL,buf,NULL)) {
1462     q=buf;
1463
1464     while(*q)
1465       switch (*q++) {
1466       case '+': direct=1;
1467         break;
1468       case '-': direct=0;
1469         break;
1470       case 'r': attra[direct]|=aRONLY;
1471         break;
1472       case 'h': attra[direct]|=aHIDDEN;
1473         break;
1474       case 's': attra[direct]|=aSYSTEM;
1475         break;
1476       case 'a': attra[direct]|=aARCH;
1477         break;
1478       default: DEBUG(0, ("setmode <filename> <perm=[+|-]rsha>\n"));
1479         return;
1480       }
1481   }
1482
1483   if (attra[ATTRSET]==0 && attra[ATTRRESET]==0)
1484     {
1485       DEBUG(0, ("setmode <filename> <perm=[+|-]rsha>\n"));
1486       return;
1487     }
1488
1489 DEBUG(2, ("\nperm set %d %d\n", attra[ATTRSET], attra[ATTRRESET]));
1490   (void) do_setrattr(fname, attra[ATTRSET], ATTRSET);
1491   (void) do_setrattr(fname, attra[ATTRRESET], ATTRRESET);
1492 }
1493
1494 /****************************************************************************
1495 Principal command for creating / extracting
1496 ***************************************************************************/
1497 void cmd_tar(char *inbuf, char *outbuf)
1498 {
1499   fstring buf;
1500   char **argl;
1501   int argcl;
1502
1503   if (!next_token(NULL,buf,NULL))
1504     {
1505       DEBUG(0,("tar <c|x>[IXbga] <filename>\n"));
1506       return;
1507     }
1508
1509   argl=toktocliplist(&argcl, NULL);
1510   if (!tar_parseargs(argcl, argl, buf, 0))
1511     return;
1512
1513   process_tar(inbuf, outbuf);
1514
1515   free(argl);
1516 }
1517
1518 /****************************************************************************
1519 Command line (option) version
1520 ***************************************************************************/
1521 int process_tar(char *inbuf, char *outbuf)
1522 {
1523   initarbuf();
1524   switch(tar_type) {
1525   case 'x':
1526     do_tarput();
1527     free(tarbuf);
1528     close(tarhandle);
1529     break;
1530   case 'r':
1531   case 'c':
1532     if (clipn && tar_excl) {
1533       int i;
1534       pstring tarmac;
1535
1536       for (i=0; i<clipn; i++) {
1537         DEBUG(0,("arg %d = %s\n", i, cliplist[i]));
1538
1539         if (*(cliplist[i]+strlen(cliplist[i])-1)=='\\') {
1540           *(cliplist[i]+strlen(cliplist[i])-1)='\0';
1541         }
1542         
1543         if (strrchr(cliplist[i], '\\')) {
1544           pstring saved_dir;
1545           
1546           strcpy(saved_dir, cur_dir);
1547           
1548           if (*cliplist[i]=='\\') {
1549             strcpy(tarmac, cliplist[i]);
1550           } else {
1551             strcpy(tarmac, cur_dir);
1552             strcat(tarmac, cliplist[i]);
1553           }
1554           strcpy(cur_dir, tarmac);
1555           *(strrchr(cur_dir, '\\')+1)='\0';
1556
1557           do_dir((char *)inbuf,(char *)outbuf,tarmac,attribute,do_tar,recurse);
1558           strcpy(cur_dir,saved_dir);
1559         } else {
1560           strcpy(tarmac, cur_dir);
1561           strcat(tarmac, cliplist[i]);
1562           do_dir((char *)inbuf,(char *)outbuf,tarmac,attribute,do_tar,recurse);
1563         }
1564       }
1565     } else {
1566       pstring mask;
1567       strcpy(mask,cur_dir);
1568       strcat(mask,"\\*");
1569       do_dir((char *)inbuf,(char *)outbuf,mask,attribute,do_tar,recurse);
1570     }
1571     
1572     if (ntarf) dotareof(tarhandle);
1573     close(tarhandle);
1574     free(tarbuf);
1575     
1576     DEBUG(0, ("tar: dumped %d tar files\n", ntarf));
1577     break;
1578   }
1579
1580   return(0);
1581 }
1582
1583 /****************************************************************************
1584 Find a token (filename) in a clip list
1585 ***************************************************************************/
1586 int clipfind(char **aret, int ret, char *tok)
1587 {
1588   if (aret==NULL) return 0;
1589
1590   /* ignore leading slashes or dots in token */
1591   while(strchr("/\\.", *tok)) tok++;
1592
1593   while(ret--) {
1594     char *pkey=*aret++;
1595
1596     /* ignore leading slashes or dots in list */
1597     while(strchr("/\\.", *pkey)) pkey++;
1598
1599     if (!strslashcmp(pkey, tok)) return 1;
1600   }
1601
1602   return 0;
1603 }
1604
1605 /****************************************************************************
1606 Parse tar arguments. Sets tar_type, tar_excl, etc.
1607 ***************************************************************************/
1608 int tar_parseargs(int argc, char *argv[], char *Optarg, int Optind)
1609 {
1610   char tar_clipfl='\0';
1611
1612   /* Reset back to defaults - could be from interactive version 
1613    * reset mode and archive mode left as they are though
1614    */
1615   tar_type='\0';
1616   tar_excl=True;
1617
1618   while (*Optarg) 
1619     switch(*Optarg++) {
1620     case 'c':
1621       tar_type='c';
1622       break;
1623     case 'x':
1624       if (tar_type=='c') {
1625         printf("Tar must be followed by only one of c or x.\n");
1626         return 0;
1627       }
1628       tar_type='x';
1629       break;
1630     case 'b':
1631       if (Optind>=argc || !(blocksize=atoi(argv[Optind]))) {
1632         DEBUG(0,("Option b must be followed by valid blocksize\n"));
1633         return 0;
1634       } else {
1635         Optind++;
1636       }
1637       break;
1638     case 'g':
1639       tar_inc=True;
1640       break;
1641     case 'N':
1642       if (Optind>=argc) {
1643         DEBUG(0,("Option N must be followed by valid file name\n"));
1644         return 0;
1645       } else {
1646         struct stat stbuf;
1647         extern time_t newer_than;
1648         
1649         if (sys_stat(argv[Optind], &stbuf) == 0) {
1650           newer_than = stbuf.st_mtime;
1651           DEBUG(1,("Getting files newer than %s",
1652                    asctime(LocalTime(&newer_than))));
1653           Optind++;
1654         } else {
1655           DEBUG(0,("Error setting newer-than time\n"));
1656           return 0;
1657         }
1658       }
1659       break;
1660     case 'a':
1661       tar_reset=True;
1662       break;
1663     case 'I':
1664       if (tar_clipfl) {
1665         DEBUG(0,("Only one of I,X must be specified\n"));
1666         return 0;
1667       }
1668       tar_clipfl='I';
1669       break;
1670     case 'X':
1671       if (tar_clipfl) {
1672         DEBUG(0,("Only one of I,X must be specified\n"));
1673         return 0;
1674       }
1675       tar_clipfl='X';
1676       break;
1677     default:
1678       DEBUG(0,("Unknown tar option\n"));
1679       return 0;
1680     }
1681
1682   if (!tar_type) {
1683     printf("Option T must be followed by one of c or x.\n");
1684     return 0;
1685   }
1686
1687   if (Optind>=argc || !strcmp(argv[Optind], "-")) {
1688     /* Sets tar handle to either 0 or 1, as appropriate */
1689     tarhandle=(tar_type=='c');
1690   } else {
1691     tar_excl=tar_clipfl!='X';
1692     
1693     if (Optind+1<argc) {
1694       cliplist=argv+Optind+1;
1695       clipn=argc-Optind-1;
1696     }
1697
1698     if ((tar_type=='x' && (tarhandle = open(argv[Optind], O_RDONLY)) == -1)
1699         || (tar_type=='c' && (tarhandle=creat(argv[Optind], 0644)) < 0))
1700       {
1701         DEBUG(0,("Error opening local file %s\n",argv[Optind]));
1702         return(0);
1703       }
1704   }
1705
1706   return 1;
1707 }