forked from ka9q/ka9q-radio
-
Notifications
You must be signed in to change notification settings - Fork 0
/
attr.c
75 lines (68 loc) · 1.85 KB
/
attr.c
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
// Low-level extended file attribute routines
// These are in a separate file mainly because they are so OS-dependent. And gratuitously so.
// 29 July 2017 Phil Karn
// Copyright 2017-2023 Phil Karn, KA9Q
#define _GNU_SOURCE 1
#include <stdio.h>
#include <stdlib.h>
#include <stdarg.h>
#include <alloca.h>
#include <string.h>
#include <assert.h>
#include <sys/types.h>
#include <sys/xattr.h>
#include "misc.h"
#include "attr.h"
// Look for external attribute "name" on an open file and perform scanf on its value
int attrscanf(int fd,char const *name,char const *format, ...){
int attrlen;
char *value = NULL;
#ifdef __linux__ // Grrrrr.....
char *fullname = NULL;
if(asprintf(&fullname,"user.%s",name) >= 0){
if((attrlen = fgetxattr(fd,fullname,NULL,0)) >= 0){ // Length of attribute value
value = alloca(attrlen+1);
fgetxattr(fd,fullname,value,attrlen);
value[attrlen] = '\0';
}
FREE(fullname);
}
#else // mainly OSX, probably BSD
if((attrlen = fgetxattr(fd,name,NULL,0,0,0)) >= 0){
value = alloca(attrlen+1);
fgetxattr(fd,name,value,attrlen,0,0);
value[attrlen] = '\0';
}
#endif
int r = -1;
if(value != NULL){
va_list ap;
va_start(ap,format);
r = vsscanf(value,format,ap);
va_end(ap);
// no need to free value, it's on the stack
}
return r;
}
// Format an extended attribute and attach it to an open file
int attrprintf(int fd,char const *attr,char const *format, ...){
va_list ap;
va_start(ap,format);
int r = -1;
char *args = NULL;
int argslen;
if((argslen = vasprintf(&args,format,ap)) >= 0){
#ifdef __linux__ // Grrrrrrr....
char *prefix = NULL;
if(asprintf(&prefix,"user.%s",attr) >= 0){
r = fsetxattr(fd,prefix,args,argslen,0);
FREE(prefix);
}
#else
r = fsetxattr(fd,attr,args,argslen,0,0);
#endif
FREE(args);
}
va_end(ap);
return r;
}