]> git.sur5r.net Git - bacula/bacula/blob - bacula/src/findlib/attribs.c
First cut berrno unified Unix/Win32 errno handling
[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
154 /* Decode a stat packet from base64 characters */
155 int decode_stat(char *buf, struct stat *statp, int32_t *LinkFI) 
156 {
157    char *p = buf;
158    int64_t val;
159
160    p += from_base64(&val, p);
161    statp->st_dev = val;
162    p++;                               /* skip space */
163    p += from_base64(&val, p);
164    statp->st_ino = val;
165    p++;
166    p += from_base64(&val, p);
167    statp->st_mode = val;
168    p++;
169    p += from_base64(&val, p);
170    statp->st_nlink = val;
171    p++;
172    p += from_base64(&val, p);
173    statp->st_uid = val;
174    p++;
175    p += from_base64(&val, p);
176    statp->st_gid = val;
177    p++;
178    p += from_base64(&val, p);
179    statp->st_rdev = val;
180    p++;
181    p += from_base64(&val, p);
182    statp->st_size = val;
183    p++;
184 #ifndef HAVE_MINGW
185    p += from_base64(&val, p);
186    statp->st_blksize = val;
187    p++;
188    p += from_base64(&val, p);
189    statp->st_blocks = val;
190    p++;
191 #else
192    p += from_base64(&val, p);
193 //   statp->st_blksize = val;
194    p++;
195    p += from_base64(&val, p);
196 //   statp->st_blocks = val;
197    p++;
198 #endif
199    p += from_base64(&val, p);
200    statp->st_atime = val;
201    p++;
202    p += from_base64(&val, p);
203    statp->st_mtime = val;
204    p++;
205    p += from_base64(&val, p);
206    statp->st_ctime = val;
207
208    /* Optional FileIndex of hard linked file data */
209    if (*p == ' ' || (*p != 0 && *(p+1) == ' ')) {
210       p++;
211       p += from_base64(&val, p);
212       *LinkFI = (uint32_t)val;
213    } else {
214       *LinkFI = 0;
215       return 0;
216    }
217
218    /* FreeBSD user flags */
219    if (*p == ' ' || (*p != 0 && *(p+1) == ' ')) {
220       p++;
221       p += from_base64(&val, p);
222 #ifdef HAVE_CHFLAGS
223       statp->st_flags = (uint32_t)val;
224    } else {
225       statp->st_flags  = 0;
226 #endif
227    }
228     
229    /* Look for data stream id */
230    if (*p == ' ' || (*p != 0 && *(p+1) == ' ')) {
231       p++;
232       p += from_base64(&val, p);
233    } else {
234       val = 0;
235    }
236    return (int)val;
237 }
238
239 /* Decode a LinkFI field of encoded stat packet */
240 int32_t decode_LinkFI(char *buf, struct stat *statp)
241 {
242    char *p = buf;
243    int64_t val;
244
245    skip_nonspaces(&p);                /* st_dev */
246    p++;                               /* skip space */
247    skip_nonspaces(&p);                /* st_ino */
248    p++;
249    p += from_base64(&val, p);
250    statp->st_mode = val;              /* st_mode */
251    p++;
252    skip_nonspaces(&p);                /* st_nlink */
253    p++;
254    skip_nonspaces(&p);                /* st_uid */
255    p++;
256    skip_nonspaces(&p);                /* st_gid */
257    p++;
258    skip_nonspaces(&p);                /* st_rdev */
259    p++;
260    skip_nonspaces(&p);                /* st_size */
261    p++;
262    skip_nonspaces(&p);                /* st_blksize */
263    p++;
264    skip_nonspaces(&p);                /* st_blocks */
265    p++;
266    skip_nonspaces(&p);                /* st_atime */
267    p++;
268    skip_nonspaces(&p);                /* st_mtime */
269    p++;
270    skip_nonspaces(&p);                /* st_ctime */
271
272    /* Optional FileIndex of hard linked file data */
273    if (*p == ' ' || (*p != 0 && *(p+1) == ' ')) {
274       p++;
275       p += from_base64(&val, p);
276       return (int32_t)val;
277    }
278    return 0;
279 }
280
281 /*
282  * Set file modes, permissions and times
283  *
284  *  fname is the original filename  
285  *  ofile is the output filename (may be in a different directory)
286  *
287  * Returns:  true  on success
288  *           false on failure
289  */
290 bool set_attributes(JCR *jcr, ATTR *attr, BFILE *ofd)
291 {
292    struct utimbuf ut;    
293    mode_t old_mask;
294    bool ok = true;
295
296 #if defined(HAVE_CYGWIN) || defined(HAVE_WIN32)
297    if (attr->stream == STREAM_UNIX_ATTRIBUTES_EX &&
298        set_win32_attributes(jcr, attr, ofd)) {
299        if (is_bopen(ofd)) {
300            bclose(ofd); 
301        }
302        pm_strcpy(&attr->ofname, "*none*");
303        return true;
304    }
305    if (attr->data_stream == STREAM_WIN32_DATA ||
306        attr->data_stream == STREAM_WIN32_GZIP_DATA) {
307       if (is_bopen(ofd)) {
308          bclose(ofd); 
309       }
310       pm_strcpy(&attr->ofname, "*none*");
311       return true;
312    }
313
314
315    /*
316     * If Windows stuff failed, e.g. attempt to restore Unix file
317     *  to Windows, simply fall through and we will do it the     
318     *  universal way.
319     */
320 #endif
321
322    old_mask = umask(0);
323    if (is_bopen(ofd)) {
324       bclose(ofd);                    /* first close file */
325    }
326
327    ut.actime = attr->statp.st_atime;
328    ut.modtime = attr->statp.st_mtime;
329
330    /* ***FIXME**** optimize -- don't do if already correct */
331    /* 
332     * For link, change owner of link using lchown, but don't
333     *   try to do a chmod as that will update the file behind it.
334     */
335    if (attr->type == FT_LNK) {
336       /* Change owner of link, not of real file */
337       if (lchown(attr->ofname, attr->statp.st_uid, attr->statp.st_gid) < 0) {
338          berrno be;
339          Jmsg2(jcr, M_ERROR, 0, _("Unable to set file owner %s: ERR=%s\n"),
340             attr->ofname, be.strerror());
341          ok = false;
342       }
343    } else {
344       if (chown(attr->ofname, attr->statp.st_uid, attr->statp.st_gid) < 0) {
345          berrno be;
346          Jmsg2(jcr, M_ERROR, 0, _("Unable to set file owner %s: ERR=%s\n"),
347             attr->ofname, be.strerror());
348          ok = false;
349       }
350       if (chmod(attr->ofname, attr->statp.st_mode) < 0) {
351          berrno be;
352          Jmsg2(jcr, M_ERROR, 0, _("Unable to set file modes %s: ERR=%s\n"),
353             attr->ofname, be.strerror());
354          ok = false;
355       }
356
357       /*
358        * Reset file times.
359        */
360       if (utime(attr->ofname, &ut) < 0) {
361          berrno be;
362          Jmsg2(jcr, M_ERROR, 0, _("Unable to set file times %s: ERR=%s\n"),
363             attr->ofname, be.strerror());
364          ok = false;
365       }
366 #ifdef HAVE_CHFLAGS
367       /*
368        * FreeBSD user flags
369        *
370        * Note, this should really be done before the utime() above,
371        *  but if the immutable bit is set, it will make the utimes()
372        *  fail.
373        */
374       if (chflags(attr->ofname, attr->statp.st_flags) < 0) {
375          berrno be;
376          Jmsg2(jcr, M_ERROR, 0, _("Unable to set file flags %s: ERR=%s\n"),
377             attr->ofname, be.strerror());
378          ok = false;
379       }
380 #endif
381    }
382    pm_strcpy(&attr->ofname, "*none*");
383    umask(old_mask);
384    return ok;
385 }
386
387
388 /*=============================================================*/
389 /*                                                             */
390 /*                 * * *  U n i x * * * *                      */
391 /*                                                             */
392 /*=============================================================*/
393
394 #if !defined(HAVE_CYGWIN) && !defined(HAVE_WIN32)
395     
396 /*
397  * It is possible to piggyback additional data e.g. ACLs on
398  *   the encode_stat() data by returning the extended attributes
399  *   here.  They must be "self-contained" (i.e. you keep track
400  *   of your own length), and they must be in ASCII string
401  *   format. Using this feature is not recommended.
402  * The code below shows how to return nothing.  See the Win32
403  *   code below for returning something in the attributes.
404  */
405 int encode_attribsEx(JCR *jcr, char *attribsEx, FF_PKT *ff_pkt)
406 {
407    *attribsEx = 0;                    /* no extended attributes */
408    return STREAM_UNIX_ATTRIBUTES;
409 }
410
411 #endif
412
413
414
415 /*=============================================================*/
416 /*                                                             */
417 /*                 * * *  W i n 3 2 * * * *                    */
418 /*                                                             */
419 /*=============================================================*/
420
421 #if defined(HAVE_CYGWIN) || defined(HAVE_WIN32)
422
423 int encode_attribsEx(JCR *jcr, char *attribsEx, FF_PKT *ff_pkt)
424 {
425    char *p = attribsEx;
426    WIN32_FILE_ATTRIBUTE_DATA atts;
427    ULARGE_INTEGER li;
428
429    attribsEx[0] = 0;                  /* no extended attributes */
430
431    if (!p_GetFileAttributesEx) {                                 
432       return STREAM_UNIX_ATTRIBUTES;
433    }
434
435    unix_name_to_win32(&ff_pkt->sys_fname, ff_pkt->fname);
436    if (!p_GetFileAttributesEx(ff_pkt->sys_fname, GetFileExInfoStandard,
437                             (LPVOID)&atts)) {
438       win_error(jcr, "GetFileAttributesEx:", ff_pkt->sys_fname);
439       return STREAM_UNIX_ATTRIBUTES;
440    }
441
442    p += to_base64((uint64_t)atts.dwFileAttributes, p);
443    *p++ = ' ';                        /* separate fields with a space */
444    li.LowPart = atts.ftCreationTime.dwLowDateTime;
445    li.HighPart = atts.ftCreationTime.dwHighDateTime;
446    p += to_base64((uint64_t)li.QuadPart, p);
447    *p++ = ' ';
448    li.LowPart = atts.ftLastAccessTime.dwLowDateTime;
449    li.HighPart = atts.ftLastAccessTime.dwHighDateTime;
450    p += to_base64((uint64_t)li.QuadPart, p);
451    *p++ = ' ';
452    li.LowPart = atts.ftLastWriteTime.dwLowDateTime;
453    li.HighPart = atts.ftLastWriteTime.dwHighDateTime;
454    p += to_base64((uint64_t)li.QuadPart, p);
455    *p++ = ' ';
456    p += to_base64((uint64_t)atts.nFileSizeHigh, p);
457    *p++ = ' ';
458    p += to_base64((uint64_t)atts.nFileSizeLow, p);
459    *p = 0;
460    return STREAM_UNIX_ATTRIBUTES_EX;
461 }
462
463 /* Define attributes that are legal to set with SetFileAttributes() */
464 #define SET_ATTRS ( \
465          FILE_ATTRIBUTE_ARCHIVE| \
466          FILE_ATTRIBUTE_HIDDEN| \
467          FILE_ATTRIBUTE_NORMAL| \
468          FILE_ATTRIBUTE_NOT_CONTENT_INDEXED| \
469          FILE_ATTRIBUTE_OFFLINE| \
470          FILE_ATTRIBUTE_READONLY| \
471          FILE_ATTRIBUTE_SYSTEM| \
472          FILE_ATTRIBUTE_TEMPORARY)
473
474
475 /*
476  * Set Extended File Attributes for Win32
477  *
478  *  fname is the original filename  
479  *  ofile is the output filename (may be in a different directory)
480  *
481  * Returns:  true  on success
482  *           false on failure
483  */
484 static bool set_win32_attributes(JCR *jcr, ATTR *attr, BFILE *ofd)
485 {
486    char *p = attr->attrEx;
487    int64_t val;
488    WIN32_FILE_ATTRIBUTE_DATA atts;
489    ULARGE_INTEGER li;
490    POOLMEM *win32_ofile;
491
492    if (!p_GetFileAttributesEx) {                                 
493       return false;
494    }
495
496    if (!p || !*p) {                   /* we should have attributes */
497       Dmsg2(100, "Attributes missing. of=%s ofd=%d\n", attr->ofname, ofd->fid);
498       if (is_bopen(ofd)) {
499          bclose(ofd);
500       }
501       return false;
502    } else {
503       Dmsg2(100, "Attribs %s = %s\n", attr->ofname, attr->attrEx);
504    }
505
506    p += from_base64(&val, p);
507    atts.dwFileAttributes = val;
508    p++;                               /* skip space */
509    p += from_base64(&val, p);
510    li.QuadPart = val;
511    atts.ftCreationTime.dwLowDateTime = li.LowPart;
512    atts.ftCreationTime.dwHighDateTime = li.HighPart;
513    p++;                               /* skip space */
514    p += from_base64(&val, p);
515    li.QuadPart = val;
516    atts.ftLastAccessTime.dwLowDateTime = li.LowPart;
517    atts.ftLastAccessTime.dwHighDateTime = li.HighPart;
518    p++;                               /* skip space */
519    p += from_base64(&val, p);
520    li.QuadPart = val;
521    atts.ftLastWriteTime.dwLowDateTime = li.LowPart;
522    atts.ftLastWriteTime.dwHighDateTime = li.HighPart;
523    p++;   
524    p += from_base64(&val, p);
525    atts.nFileSizeHigh = val;
526    p++;
527    p += from_base64(&val, p);
528    atts.nFileSizeLow = val;
529
530    /* Convert to Windows path format */
531    win32_ofile = get_pool_memory(PM_FNAME);
532    unix_name_to_win32(&win32_ofile, attr->ofname);
533
534
535
536    /* At this point, we have reconstructed the WIN32_FILE_ATTRIBUTE_DATA pkt */
537
538    if (!is_bopen(ofd)) {
539       Dmsg1(100, "File not open: %s\n", attr->ofname);
540       bopen(ofd, attr->ofname, O_WRONLY|O_BINARY, 0);   /* attempt to open the file */
541    }
542
543    if (is_bopen(ofd)) {
544       Dmsg1(100, "SetFileTime %s\n", attr->ofname);
545       if (!SetFileTime(bget_handle(ofd),
546                          &atts.ftCreationTime,
547                          &atts.ftLastAccessTime,
548                          &atts.ftLastWriteTime)) {
549          win_error(jcr, "SetFileTime:", win32_ofile);
550       }
551       bclose(ofd);
552    }
553
554    Dmsg1(100, "SetFileAtts %s\n", attr->ofname);
555    if (!(atts.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY)) {
556       if (!SetFileAttributes(win32_ofile, atts.dwFileAttributes & SET_ATTRS)) {
557          win_error(jcr, "SetFileAttributes:", win32_ofile);
558       }
559    }
560    free_pool_memory(win32_ofile);
561    return true;
562 }
563
564 void win_error(JCR *jcr, char *prefix, POOLMEM *win32_ofile)
565 {
566    DWORD lerror = GetLastError();
567    LPTSTR msg;
568    FormatMessage(FORMAT_MESSAGE_ALLOCATE_BUFFER|
569                  FORMAT_MESSAGE_FROM_SYSTEM,
570                  NULL,
571                  lerror,
572                  0,
573                  (LPTSTR)&msg,
574                  0,
575                  NULL);
576    Dmsg3(100, "Error in %s on file %s: ERR=%s\n", prefix, win32_ofile, msg);
577    strip_trailing_junk(msg);
578    Jmsg(jcr, M_ERROR, 0, _("Error in %s file %s: ERR=%s\n"), prefix, win32_ofile, msg);
579    LocalFree(msg);
580 }
581
582 void win_error(JCR *jcr, char *prefix, DWORD lerror)
583 {
584    LPTSTR msg;
585    FormatMessage(FORMAT_MESSAGE_ALLOCATE_BUFFER|
586                  FORMAT_MESSAGE_FROM_SYSTEM,
587                  NULL,
588                  lerror,
589                  0,
590                  (LPTSTR)&msg,
591                  0,
592                  NULL);
593    strip_trailing_junk(msg);
594    if (jcr) {
595       Jmsg2(jcr, M_ERROR, 0, _("Error in %s: ERR=%s\n"), prefix, msg);
596    } else {
597       MessageBox(NULL, msg, prefix, MB_OK);
598    }
599    LocalFree(msg);
600 }
601
602
603 /* Cygwin API definition */
604 extern "C" void cygwin_conv_to_win32_path(const char *path, char *win32_path);
605
606 void unix_name_to_win32(POOLMEM **win32_name, char *name)
607 {
608    /* One extra byte should suffice, but we double it */
609    *win32_name = check_pool_memory_size(*win32_name, 2*strlen(name)+1);
610    cygwin_conv_to_win32_path(name, *win32_name);
611 }
612
613 #endif  /* HAVE_CYGWIN */