]> git.sur5r.net Git - bacula/bacula/blob - bacula/src/findlib/attribs.c
Implement class template for automatic casting uint64_t to stat packet fields
[bacula/bacula] / bacula / src / findlib / attribs.c
1 /*
2  *  Encode and decode standard Unix attributes and
3  *   Extended attributes for Win32 and
4  *   other non-Unix systems, or Unix systems with ACLs, ...
5  *
6  *    Kern Sibbald, October MMII
7  *
8  *   Version $Id$
9  *
10  */
11 /*
12    Copyright (C) 2002-2004 Kern Sibbald and John Walker
13
14    This program is free software; you can redistribute it and/or
15    modify it under the terms of the GNU General Public License as
16    published by the Free Software Foundation; either version 2 of
17    the License, or (at your option) any later version.
18
19    This program is distributed in the hope that it will be useful,
20    but WITHOUT ANY WARRANTY; without even the implied warranty of
21    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
22    General Public License for more details.
23
24    You should have received a copy of the GNU General Public
25    License along with this program; if not, write to the Free
26    Software Foundation, Inc., 59 Temple Place - Suite 330, Boston,
27    MA 02111-1307, USA.
28
29  */
30
31 #include "bacula.h"
32 #include "find.h"
33
34 #if defined(HAVE_CYGWIN) || defined(HAVE_WIN32)
35
36 /* Forward referenced subroutines */
37 static bool set_win32_attributes(JCR *jcr, ATTR *attr, BFILE *ofd);
38 void unix_name_to_win32(POOLMEM **win32_name, char *name);
39 void win_error(JCR *jcr, char *prefix, POOLMEM *ofile);
40 HANDLE bget_handle(BFILE *bfd);
41 #endif
42
43 /* For old systems that don't have lchown() use chown() */
44 #ifndef HAVE_LCHOWN
45 #define lchown chown
46 #endif
47
48 /*=============================================================*/
49 /*                                                             */
50 /*             ***  A l l  S y s t e m s ***                   */
51 /*                                                             */
52 /*=============================================================*/
53
54 /*
55  * Return the data stream that will be used 
56  */
57 int select_data_stream(FF_PKT *ff_pkt)
58 {
59    int stream;
60
61    /* Note, no sparse option for win32_data */
62    if (!is_portable_backup(&ff_pkt->bfd)) {
63       stream = STREAM_WIN32_DATA;
64       ff_pkt->flags &= ~FO_SPARSE;
65    } else if (ff_pkt->flags & FO_SPARSE) {
66       stream = STREAM_SPARSE_DATA;
67    } else {
68       stream = STREAM_FILE_DATA;
69    }
70 #ifdef HAVE_LIBZ
71    if (ff_pkt->flags & FO_GZIP) {
72       if (stream == STREAM_WIN32_DATA) {
73          stream = STREAM_WIN32_GZIP_DATA;
74       } else if (stream == STREAM_FILE_DATA) {
75          stream = STREAM_GZIP_DATA;
76       } else {
77          stream = STREAM_SPARSE_GZIP_DATA;
78       }
79    }
80 #endif
81    return stream;
82 }
83
84
85 /* 
86  * Encode a stat structure into a base64 character string   
87  *   All systems must create such a structure.
88  *   In addition, we tack on the LinkFI, which is non-zero in
89  *   the case of a hard linked file that has no data.  This
90  *   is a File Index pointing to the link that does have the
91  *   data (always the first one encountered in a save).
92  * You may piggyback attributes on this packet by encoding
93  *   them in the encode_attribsEx() subroutine, but this is
94  *   not recommended.
95  */
96 void encode_stat(char *buf, FF_PKT *ff_pkt, int data_stream)
97 {
98    char *p = buf;
99    struct stat *statp = &ff_pkt->statp;
100    /*
101     *  Encode a stat packet.  I should have done this more intelligently
102     *   with a length so that it could be easily expanded.
103     */
104    p += to_base64((int64_t)statp->st_dev, p);
105    *p++ = ' ';                        /* separate fields with a space */
106    p += to_base64((int64_t)statp->st_ino, p);
107    *p++ = ' ';
108    p += to_base64((int64_t)statp->st_mode, p);
109    *p++ = ' ';
110    p += to_base64((int64_t)statp->st_nlink, p);
111    *p++ = ' ';
112    p += to_base64((int64_t)statp->st_uid, p);
113    *p++ = ' ';
114    p += to_base64((int64_t)statp->st_gid, p);
115    *p++ = ' ';
116    p += to_base64((int64_t)statp->st_rdev, p);
117    *p++ = ' ';
118    p += to_base64((int64_t)statp->st_size, p);
119    *p++ = ' ';
120 #ifndef HAVE_MINGW
121    p += to_base64((int64_t)statp->st_blksize, p);
122    *p++ = ' ';
123    p += to_base64((int64_t)statp->st_blocks, p);
124    *p++ = ' ';
125 #else
126    p += to_base64((int64_t)0, p); /* output place holder */
127    *p++ = ' ';
128    p += to_base64((int64_t)0, p); /* output place holder */
129    *p++ = ' ';
130 #endif
131    p += to_base64((int64_t)statp->st_atime, p);
132    *p++ = ' ';
133    p += to_base64((int64_t)statp->st_mtime, p);
134    *p++ = ' ';
135    p += to_base64((int64_t)statp->st_ctime, p);
136    *p++ = ' ';
137    p += to_base64((int64_t)ff_pkt->LinkFI, p);
138    *p++ = ' ';
139
140 #ifdef HAVE_CHFLAGS
141    /* FreeBSD function */
142    p += to_base64((int64_t)statp->st_flags, p);  /* output st_flags */
143 #else
144    p += to_base64((int64_t)0, p);     /* output place holder */
145 #endif
146    *p++ = ' ';
147    p += to_base64((int64_t)data_stream, p);
148    *p = 0;
149    return;
150 }
151
152
153 /* Do casting according to unknown type to keep compiler happy */
154 class castit {
155 public:
156   template <class T> void plug(T &st, uint64_t val)
157     { st = (T)val; }
158 };
159
160
161 /* Decode a stat packet from base64 characters */
162 int decode_stat(char *buf, struct stat *statp, int32_t *LinkFI) 
163 {
164    char *p = buf;
165    int64_t val;
166    castit plugger;
167      
168
169    p += from_base64(&val, p);
170    plugger.plug(statp->st_dev, val);
171    p++;
172    p += from_base64(&val, p);
173    plugger.plug(statp->st_ino, val);
174    p++;
175    p += from_base64(&val, p);
176    plugger.plug(statp->st_mode, val);
177    p++;
178    p += from_base64(&val, p);
179    plugger.plug(statp->st_nlink, val);
180    p++;
181    p += from_base64(&val, p);
182    plugger.plug(statp->st_uid, val);
183    p++;
184    p += from_base64(&val, p);
185    plugger.plug(statp->st_gid, val);
186    p++;
187    p += from_base64(&val, p);
188    plugger.plug(statp->st_rdev, val);
189    p++;
190    p += from_base64(&val, p);
191    plugger.plug(statp->st_size, val);
192    p++;
193 #ifndef HAVE_MINGW
194    p += from_base64(&val, p);
195    plugger.plug(statp->st_blksize, val);
196    p++;
197    p += from_base64(&val, p);
198    plugger.plug(statp->st_blocks, val);
199    p++;
200 #else
201    p += from_base64(&val, p);
202 //   plugger.plug(statp->st_blksize, val);
203    p++;
204    p += from_base64(&val, p);
205 //   plugger.plug(statp->st_blocks, val);
206    p++;
207 #endif
208    p += from_base64(&val, p);
209    plugger.plug(statp->st_atime, val);
210    p++;
211    p += from_base64(&val, p);
212    plugger.plug(statp->st_mtime, val);
213    p++;
214    p += from_base64(&val, p);
215    plugger.plug(statp->st_ctime, val);
216
217    /* Optional FileIndex of hard linked file data */
218    if (*p == ' ' || (*p != 0 && *(p+1) == ' ')) {
219       p++;
220       p += from_base64(&val, p);
221       *LinkFI = (uint32_t)val;
222    } else {
223       *LinkFI = 0;
224       return 0;
225    }
226
227    /* FreeBSD user flags */
228    if (*p == ' ' || (*p != 0 && *(p+1) == ' ')) {
229       p++;
230       p += from_base64(&val, p);
231 #ifdef HAVE_CHFLAGS
232       plugger.plug(statp->st_flags, val);
233    } else {
234       statp->st_flags  = 0;
235 #endif
236    }
237     
238    /* Look for data stream id */
239    if (*p == ' ' || (*p != 0 && *(p+1) == ' ')) {
240       p++;
241       p += from_base64(&val, p);
242    } else {
243       val = 0;
244    }
245    return (int)val;
246 }
247
248 /* Decode a LinkFI field of encoded stat packet */
249 int32_t decode_LinkFI(char *buf, struct stat *statp)
250 {
251    char *p = buf;
252    int64_t val;
253
254    skip_nonspaces(&p);                /* st_dev */
255    p++;                               /* skip space */
256    skip_nonspaces(&p);                /* st_ino */
257    p++;
258    p += from_base64(&val, p);
259    statp->st_mode = val;              /* st_mode */
260    p++;
261    skip_nonspaces(&p);                /* st_nlink */
262    p++;
263    skip_nonspaces(&p);                /* st_uid */
264    p++;
265    skip_nonspaces(&p);                /* st_gid */
266    p++;
267    skip_nonspaces(&p);                /* st_rdev */
268    p++;
269    skip_nonspaces(&p);                /* st_size */
270    p++;
271    skip_nonspaces(&p);                /* st_blksize */
272    p++;
273    skip_nonspaces(&p);                /* st_blocks */
274    p++;
275    skip_nonspaces(&p);                /* st_atime */
276    p++;
277    skip_nonspaces(&p);                /* st_mtime */
278    p++;
279    skip_nonspaces(&p);                /* st_ctime */
280
281    /* Optional FileIndex of hard linked file data */
282    if (*p == ' ' || (*p != 0 && *(p+1) == ' ')) {
283       p++;
284       p += from_base64(&val, p);
285       return (int32_t)val;
286    }
287    return 0;
288 }
289
290 /*
291  * Set file modes, permissions and times
292  *
293  *  fname is the original filename  
294  *  ofile is the output filename (may be in a different directory)
295  *
296  * Returns:  true  on success
297  *           false on failure
298  */
299 bool set_attributes(JCR *jcr, ATTR *attr, BFILE *ofd)
300 {
301    struct utimbuf ut;    
302    mode_t old_mask;
303    bool ok = true;
304
305 #if defined(HAVE_CYGWIN) || defined(HAVE_WIN32)
306    if (attr->stream == STREAM_UNIX_ATTRIBUTES_EX &&
307        set_win32_attributes(jcr, attr, ofd)) {
308        if (is_bopen(ofd)) {
309            bclose(ofd); 
310        }
311        pm_strcpy(&attr->ofname, "*none*");
312        return true;
313    }
314    if (attr->data_stream == STREAM_WIN32_DATA ||
315        attr->data_stream == STREAM_WIN32_GZIP_DATA) {
316       if (is_bopen(ofd)) {
317          bclose(ofd); 
318       }
319       pm_strcpy(&attr->ofname, "*none*");
320       return true;
321    }
322
323
324    /*
325     * If Windows stuff failed, e.g. attempt to restore Unix file
326     *  to Windows, simply fall through and we will do it the     
327     *  universal way.
328     */
329 #endif
330
331    old_mask = umask(0);
332    if (is_bopen(ofd)) {
333       bclose(ofd);                    /* first close file */
334    }
335
336    ut.actime = attr->statp.st_atime;
337    ut.modtime = attr->statp.st_mtime;
338
339    /* ***FIXME**** optimize -- don't do if already correct */
340    /* 
341     * For link, change owner of link using lchown, but don't
342     *   try to do a chmod as that will update the file behind it.
343     */
344    if (attr->type == FT_LNK) {
345       /* Change owner of link, not of real file */
346       if (lchown(attr->ofname, attr->statp.st_uid, attr->statp.st_gid) < 0) {
347          berrno be;
348          Jmsg2(jcr, M_ERROR, 0, _("Unable to set file owner %s: ERR=%s\n"),
349             attr->ofname, be.strerror());
350          ok = false;
351       }
352    } else {
353       if (chown(attr->ofname, attr->statp.st_uid, attr->statp.st_gid) < 0) {
354          berrno be;
355          Jmsg2(jcr, M_ERROR, 0, _("Unable to set file owner %s: ERR=%s\n"),
356             attr->ofname, be.strerror());
357          ok = false;
358       }
359       if (chmod(attr->ofname, attr->statp.st_mode) < 0) {
360          berrno be;
361          Jmsg2(jcr, M_ERROR, 0, _("Unable to set file modes %s: ERR=%s\n"),
362             attr->ofname, be.strerror());
363          ok = false;
364       }
365
366       /*
367        * Reset file times.
368        */
369       if (utime(attr->ofname, &ut) < 0) {
370          berrno be;
371          Jmsg2(jcr, M_ERROR, 0, _("Unable to set file times %s: ERR=%s\n"),
372             attr->ofname, be.strerror());
373          ok = false;
374       }
375 #ifdef HAVE_CHFLAGS
376       /*
377        * FreeBSD user flags
378        *
379        * Note, this should really be done before the utime() above,
380        *  but if the immutable bit is set, it will make the utimes()
381        *  fail.
382        */
383       if (chflags(attr->ofname, attr->statp.st_flags) < 0) {
384          berrno be;
385          Jmsg2(jcr, M_ERROR, 0, _("Unable to set file flags %s: ERR=%s\n"),
386             attr->ofname, be.strerror());
387          ok = false;
388       }
389 #endif
390    }
391    pm_strcpy(&attr->ofname, "*none*");
392    umask(old_mask);
393    return ok;
394 }
395
396
397 /*=============================================================*/
398 /*                                                             */
399 /*                 * * *  U n i x * * * *                      */
400 /*                                                             */
401 /*=============================================================*/
402
403 #if !defined(HAVE_CYGWIN) && !defined(HAVE_WIN32)
404     
405 /*
406  * It is possible to piggyback additional data e.g. ACLs on
407  *   the encode_stat() data by returning the extended attributes
408  *   here.  They must be "self-contained" (i.e. you keep track
409  *   of your own length), and they must be in ASCII string
410  *   format. Using this feature is not recommended.
411  * The code below shows how to return nothing.  See the Win32
412  *   code below for returning something in the attributes.
413  */
414 int encode_attribsEx(JCR *jcr, char *attribsEx, FF_PKT *ff_pkt)
415 {
416    *attribsEx = 0;                    /* no extended attributes */
417    return STREAM_UNIX_ATTRIBUTES;
418 }
419
420 #endif
421
422
423
424 /*=============================================================*/
425 /*                                                             */
426 /*                 * * *  W i n 3 2 * * * *                    */
427 /*                                                             */
428 /*=============================================================*/
429
430 #if defined(HAVE_CYGWIN) || defined(HAVE_WIN32)
431
432 int encode_attribsEx(JCR *jcr, char *attribsEx, FF_PKT *ff_pkt)
433 {
434    char *p = attribsEx;
435    WIN32_FILE_ATTRIBUTE_DATA atts;
436    ULARGE_INTEGER li;
437
438    attribsEx[0] = 0;                  /* no extended attributes */
439
440    if (!p_GetFileAttributesEx) {                                 
441       return STREAM_UNIX_ATTRIBUTES;
442    }
443
444    unix_name_to_win32(&ff_pkt->sys_fname, ff_pkt->fname);
445    if (!p_GetFileAttributesEx(ff_pkt->sys_fname, GetFileExInfoStandard,
446                             (LPVOID)&atts)) {
447       win_error(jcr, "GetFileAttributesEx:", ff_pkt->sys_fname);
448       return STREAM_UNIX_ATTRIBUTES;
449    }
450
451    p += to_base64((uint64_t)atts.dwFileAttributes, p);
452    *p++ = ' ';                        /* separate fields with a space */
453    li.LowPart = atts.ftCreationTime.dwLowDateTime;
454    li.HighPart = atts.ftCreationTime.dwHighDateTime;
455    p += to_base64((uint64_t)li.QuadPart, p);
456    *p++ = ' ';
457    li.LowPart = atts.ftLastAccessTime.dwLowDateTime;
458    li.HighPart = atts.ftLastAccessTime.dwHighDateTime;
459    p += to_base64((uint64_t)li.QuadPart, p);
460    *p++ = ' ';
461    li.LowPart = atts.ftLastWriteTime.dwLowDateTime;
462    li.HighPart = atts.ftLastWriteTime.dwHighDateTime;
463    p += to_base64((uint64_t)li.QuadPart, p);
464    *p++ = ' ';
465    p += to_base64((uint64_t)atts.nFileSizeHigh, p);
466    *p++ = ' ';
467    p += to_base64((uint64_t)atts.nFileSizeLow, p);
468    *p = 0;
469    return STREAM_UNIX_ATTRIBUTES_EX;
470 }
471
472 /* Define attributes that are legal to set with SetFileAttributes() */
473 #define SET_ATTRS ( \
474          FILE_ATTRIBUTE_ARCHIVE| \
475          FILE_ATTRIBUTE_HIDDEN| \
476          FILE_ATTRIBUTE_NORMAL| \
477          FILE_ATTRIBUTE_NOT_CONTENT_INDEXED| \
478          FILE_ATTRIBUTE_OFFLINE| \
479          FILE_ATTRIBUTE_READONLY| \
480          FILE_ATTRIBUTE_SYSTEM| \
481          FILE_ATTRIBUTE_TEMPORARY)
482
483
484 /*
485  * Set Extended File Attributes for Win32
486  *
487  *  fname is the original filename  
488  *  ofile is the output filename (may be in a different directory)
489  *
490  * Returns:  true  on success
491  *           false on failure
492  */
493 static bool set_win32_attributes(JCR *jcr, ATTR *attr, BFILE *ofd)
494 {
495    char *p = attr->attrEx;
496    int64_t val;
497    WIN32_FILE_ATTRIBUTE_DATA atts;
498    ULARGE_INTEGER li;
499    POOLMEM *win32_ofile;
500
501    if (!p_GetFileAttributesEx) {                                 
502       return false;
503    }
504
505    if (!p || !*p) {                   /* we should have attributes */
506       Dmsg2(100, "Attributes missing. of=%s ofd=%d\n", attr->ofname, ofd->fid);
507       if (is_bopen(ofd)) {
508          bclose(ofd);
509       }
510       return false;
511    } else {
512       Dmsg2(100, "Attribs %s = %s\n", attr->ofname, attr->attrEx);
513    }
514
515    p += from_base64(&val, p);
516    atts.dwFileAttributes = val;
517    p++;                               /* skip space */
518    p += from_base64(&val, p);
519    li.QuadPart = val;
520    atts.ftCreationTime.dwLowDateTime = li.LowPart;
521    atts.ftCreationTime.dwHighDateTime = li.HighPart;
522    p++;                               /* skip space */
523    p += from_base64(&val, p);
524    li.QuadPart = val;
525    atts.ftLastAccessTime.dwLowDateTime = li.LowPart;
526    atts.ftLastAccessTime.dwHighDateTime = li.HighPart;
527    p++;                               /* skip space */
528    p += from_base64(&val, p);
529    li.QuadPart = val;
530    atts.ftLastWriteTime.dwLowDateTime = li.LowPart;
531    atts.ftLastWriteTime.dwHighDateTime = li.HighPart;
532    p++;   
533    p += from_base64(&val, p);
534    atts.nFileSizeHigh = val;
535    p++;
536    p += from_base64(&val, p);
537    atts.nFileSizeLow = val;
538
539    /* Convert to Windows path format */
540    win32_ofile = get_pool_memory(PM_FNAME);
541    unix_name_to_win32(&win32_ofile, attr->ofname);
542
543
544
545    /* At this point, we have reconstructed the WIN32_FILE_ATTRIBUTE_DATA pkt */
546
547    if (!is_bopen(ofd)) {
548       Dmsg1(100, "File not open: %s\n", attr->ofname);
549       bopen(ofd, attr->ofname, O_WRONLY|O_BINARY, 0);   /* attempt to open the file */
550    }
551
552    if (is_bopen(ofd)) {
553       Dmsg1(100, "SetFileTime %s\n", attr->ofname);
554       if (!SetFileTime(bget_handle(ofd),
555                          &atts.ftCreationTime,
556                          &atts.ftLastAccessTime,
557                          &atts.ftLastWriteTime)) {
558          win_error(jcr, "SetFileTime:", win32_ofile);
559       }
560       bclose(ofd);
561    }
562
563    Dmsg1(100, "SetFileAtts %s\n", attr->ofname);
564    if (!(atts.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY)) {
565       if (!SetFileAttributes(win32_ofile, atts.dwFileAttributes & SET_ATTRS)) {
566          win_error(jcr, "SetFileAttributes:", win32_ofile);
567       }
568    }
569    free_pool_memory(win32_ofile);
570    return true;
571 }
572
573 void win_error(JCR *jcr, char *prefix, POOLMEM *win32_ofile)
574 {
575    DWORD lerror = GetLastError();
576    LPTSTR msg;
577    FormatMessage(FORMAT_MESSAGE_ALLOCATE_BUFFER|
578                  FORMAT_MESSAGE_FROM_SYSTEM,
579                  NULL,
580                  lerror,
581                  0,
582                  (LPTSTR)&msg,
583                  0,
584                  NULL);
585    Dmsg3(100, "Error in %s on file %s: ERR=%s\n", prefix, win32_ofile, msg);
586    strip_trailing_junk(msg);
587    Jmsg(jcr, M_ERROR, 0, _("Error in %s file %s: ERR=%s\n"), prefix, win32_ofile, msg);
588    LocalFree(msg);
589 }
590
591 void win_error(JCR *jcr, char *prefix, DWORD lerror)
592 {
593    LPTSTR msg;
594    FormatMessage(FORMAT_MESSAGE_ALLOCATE_BUFFER|
595                  FORMAT_MESSAGE_FROM_SYSTEM,
596                  NULL,
597                  lerror,
598                  0,
599                  (LPTSTR)&msg,
600                  0,
601                  NULL);
602    strip_trailing_junk(msg);
603    if (jcr) {
604       Jmsg2(jcr, M_ERROR, 0, _("Error in %s: ERR=%s\n"), prefix, msg);
605    } else {
606       MessageBox(NULL, msg, prefix, MB_OK);
607    }
608    LocalFree(msg);
609 }
610
611
612 /* Cygwin API definition */
613 extern "C" void cygwin_conv_to_win32_path(const char *path, char *win32_path);
614
615 void unix_name_to_win32(POOLMEM **win32_name, char *name)
616 {
617    /* One extra byte should suffice, but we double it */
618    *win32_name = check_pool_memory_size(*win32_name, 2*strlen(name)+1);
619    cygwin_conv_to_win32_path(name, *win32_name);
620 }
621
622 #endif  /* HAVE_CYGWIN */