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