XRootD
Loading...
Searching...
No Matches
XrdSutAux.cc
Go to the documentation of this file.
1/******************************************************************************/
2/* */
3/* X r d S u t A u x . c c */
4/* */
5/* (c) 2004 by the Board of Trustees of the Leland Stanford, Jr., University */
6/* Produced by Gerri Ganis for CERN */
7/* */
8/* This file is part of the XRootD software suite. */
9/* */
10/* XRootD is free software: you can redistribute it and/or modify it under */
11/* the terms of the GNU Lesser General Public License as published by the */
12/* Free Software Foundation, either version 3 of the License, or (at your */
13/* option) any later version. */
14/* */
15/* XRootD is distributed in the hope that it will be useful, but WITHOUT */
16/* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or */
17/* FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public */
18/* License for more details. */
19/* */
20/* You should have received a copy of the GNU Lesser General Public License */
21/* along with XRootD in a file called COPYING.LESSER (LGPL license) and file */
22/* COPYING (GPL license). If not, see <http://www.gnu.org/licenses/>. */
23/* */
24/* The copyright holder's institutional names and contributor's names may not */
25/* be used to endorse or promote products derived from this software without */
26/* specific prior written permission of the institution or contributor. */
27/******************************************************************************/
28
29#include <cstdio>
30#include <cstdlib>
31#include <cstring>
32#include <unistd.h>
33#include <cerrno>
34#include <ctime>
35#include <pwd.h>
36#include <sys/types.h>
37#include <sys/stat.h>
38#include <fcntl.h>
39
41#include "XrdSys/XrdSysError.hh"
42#include "XrdSys/XrdSysPwd.hh"
44
45#include "XrdSut/XrdSutAux.hh"
46#include "XrdSut/XrdSutRndm.hh"
47#include "XrdSut/XrdSutTrace.hh"
48
49static const char *gXRSBucketTypes[] = {
50 "kXRS_none",
51 "kXRS_inactive",
52 "kXRS_cryptomod",
53 "kXRS_main",
54 "kXRS_srv_seal",
55 "kXRS_clnt_seal",
56 "kXRS_puk",
57 "kXRS_cipher",
58 "kXRS_rtag",
59 "kXRS_signed_rtag",
60 "kXRS_user",
61 "kXRS_host",
62 "kXRS_creds",
63 "kXRS_message",
64 "kXRS_srvID",
65 "kXRS_sessionID",
66 "kXRS_version",
67 "kXRS_status",
68 "kXRS_localstatus",
69 "kXRS_othercreds",
70 "kXRS_cache_idx",
71 "kXRS_clnt_opts",
72 "kXRS_error_code",
73 "kXRS_timestamp",
74 "kXRS_x509",
75 "kXRS_issuer_hash",
76 "kXRS_x509_req",
77 "kXRS_cipher_alg",
78 "kXRS_md_alg",
79 "kXRS_afsinfo",
80 "kXRS_reserved"
81};
82
83//
84// For error logging and tracing
86static XrdSysError eDest(0,"sut_");
88
89/******************************************************************************/
90/* X r d S u t S e t T r a c e */
91/******************************************************************************/
92//______________________________________________________________________________
94{
95 // Set trace flags according to 'trace'
96
97 //
98 // Initiate error logging and tracing
99 eDest.logger(&Logger);
100 if (!sutTrace)
101 sutTrace = new XrdOucTrace(&eDest);
102 if (sutTrace) {
103 // Set debug mask
104 sutTrace->What = 0;
105 // Low level only
106 if ((trace & sutTRACE_Notify))
107 sutTrace->What |= sutTRACE_Notify;
108 // Medium level
109 if ((trace & sutTRACE_Debug))
111 // High level
112 if ((trace & sutTRACE_Dump))
113 sutTrace->What |= sutTRACE_ALL;
114 }
115}
116
117/******************************************************************************/
118/* X r d S u t B u c k S t r */
119/******************************************************************************/
120//______________________________________________________________________________
121const char *XrdSutBuckStr(int kbck)
122{
123 // Return bucket string
124 static const char *ukn = "Unknown";
125
126 kbck = (kbck < 0) ? 0 : kbck;
127 kbck = (kbck > kXRS_reserved) ? 0 : kbck;
128 kbck = (kbck >= kXRS_cryptomod) ? (kbck - kXRS_cryptomod + 2) : kbck;
129
130 if (kbck < 0 || kbck > (kXRS_reserved - kXRS_cryptomod + 2))
131 return ukn;
132 else
133 return gXRSBucketTypes[kbck];
134}
135
136/******************************************************************************/
137/* X r d S u t M e m S e t */
138/******************************************************************************/
139//______________________________________________________________________________
140volatile void *XrdSutMemSet(volatile void *dst, int c, int len)
141{
142 return memset((void*)dst, c, len);
143}
144
145#ifndef USE_EXTERNAL_GETPASS
146/******************************************************************************/
147/* X r d S u t G e t P a s s */
148/******************************************************************************/
149//_____________________________________________________________________________
150int XrdSutGetPass(const char *prompt, XrdOucString &passwd)
151{
152 // Get password from command line using getpass
153 // *** Use only if you cannot provide a better alternative ***
154 // User will be prompted for 'prompt'; the entered password
155 // is returned in 'passwd'.
156 // Returns 0 if ok, -1 if any error occurs.
157 EPNAME("GetPass");
158
159 char *pw = getpass(prompt);
160 if (pw) {
161 // Get rid of special chars, if any
162 int k = 0, i = 0, len = strlen(pw);
163 for (; i<len ; i++)
164 if (pw[i] > 0x20) pw[k++] = pw[i];
165 pw[k] = 0;
166 passwd = pw;
167 XrdSutMemSet((void *)pw,0,len);
168 } else {
169 DEBUG("error from getpass");
170 return -1;
171 }
172 return 0;
173}
174#endif
175
176/******************************************************************************/
177/* X r d S u t G e t L i n e */
178/******************************************************************************/
179int XrdSutGetLine(XrdOucString &line, const char *prompt)
180{
181 // Get line from main input stream.
182 // Prompt 'prompt' if this is defined.
183 // Returns number of chars entered.
184 // NB: at most XrdSutMAXBUF-1 chars will be accepted
185 char bin[XrdSutMAXBUF] = {0};
186
187 // Print prompt, if requested
188 if (prompt)
189 std::cout << prompt;
190
191 // Get line
192 std::cin.getline(bin,XrdSutMAXBUF-1);
193
194 // Fill input
195 line = bin;
196
197 return line.length();
198}
199
200/******************************************************************************/
201/* X r d S u t A s k C o n f i r m */
202/******************************************************************************/
203bool XrdSutAskConfirm(const char *msg1, bool defact, const char *msg2)
204{
205 // Prompt for confirmation of action
206 // If defined, msg1 is printed as prompt, followed by the default action
207 // ( [y] == do-act, for defact = true;
208 // [n] == do-not-act, for defact = false)
209 // If defined, msg2 is printed before prompting.
210
211 bool rc = defact;
212
213 if (msg2)
214 std::cout << msg2;
215 XrdOucString ask;
216 XrdOucString prompt = defact ? " [y]: " : " [n]: ";
217 if (msg1)
218 prompt.insert(msg1,0);
219 XrdSutGetLine(ask,prompt.c_str());
220 ask.lower(0);
221 if (ask.length()) {
222 if (defact && (ask == 'n' || ask == "no")) {
223 rc = 0;
224 } else if (!defact && (ask == 'y' || ask == "yes")) {
225 rc = 1;
226 }
227 }
228 // we are done
229 return rc;
230}
231
232/******************************************************************************/
233/* X r d S u t T o H e x */
234/******************************************************************************/
235int XrdSutToHex(const char *in, int lin, char *out)
236{
237 // Content of lin bytes at in are transformed into an hexadecimal,
238 // null-terminated, string of length 2*lin; the result is returned
239 // in the buffer pointed by out, which must be allocated by the caller
240 // to contain at least 2*lin+1 bytes.
241 // Return 0 in case of success, -1 in case of error (errno set to EINVAL if
242 // any of in or out are not defined).
243
244 if (!in || !out) {
245 errno = EINVAL;
246 return -1;
247 }
248
249 int lbuf = 2*lin+1;
250 int i = 0;
251 out[0] = 0;
252 for ( ; i < lin; i++)
253 {
254 char buff[3];
255 sprintf(buff, "%02x", (0xFF & in[i]));
256 strncat(out, buff, 3);
257 }
258 // Null termination
259 out[lbuf-1] = 0;
260
261 // ok
262 return 0;
263}
264
265/******************************************************************************/
266/* X r d S u t F r o m H e x */
267/******************************************************************************/
268int XrdSutFromHex(const char *in, char *out, int &lout)
269{
270 // Content of the hexadecimal, null-terminated, string at in, is
271 // transformed into lout bytes returned in out.
272 // The output buffer should be allocated by the caller to contain
273 // at least lin/2 bytes if lin=strlen(in) is even, and lin/2+1 bytes
274 // if lin is odd (in this case an additional char equal 0 is appended
275 // to in).
276 // Return 0 in case of success, -1 in case of error (errno set to EINVAL if
277 // any of in or out are not defined).
278
279 lout = 0;
280 if (!in || !out) {
281 errno = EINVAL;
282 return -1;
283 }
284
285 int lin = strlen(in);
286 char st[3] = {0};
287 int i = 0, k = 0;
288 for ( ; i<lin; i += 2) {
289 st[0] = in[i];
290 st[1] = ((i+1) < lin) ? in[i+1] : 0;
291 unsigned int c;
292 sscanf(st,"%x",&c);
293 out[k++] = (char)(0x000000FF & c);
294 }
295
296 lout = k;
297
298 return 0;
299}
300
301/******************************************************************************/
302/* X r d S u t T i m e S t r i n g */
303/* */
304/******************************************************************************/
305int XrdSutTimeString(int t, char *st, int opt)
306{
307 // Trasform a time in secs since 1Jan1970 in a string of the format
308 // 24Apr2006:09:10:23 (opt = 0, default)
309 // 24Apr2006-091023 (opt = 1)
310 // The buffer st must be supplied by the caller to contain at least 20.
311 // This length is returned when calling the function with t=-1
312 static const char month[12][4] = {"Jan","Feb","Mar","Apr","May","Jun",
313 "Jul","Aug","Sep","Oct","Nov","Dec"};
314 static short flen = strlen("24Apr2006:09:10:23");
315
316 // Check if the length is required
317 if (t == -1)
318 return (flen+1);
319
320 // Now check inputs
321 if (t < 0 || !st)
322 return -1;
323
324 // Get the breakdown
325 struct tm tst;
326 time_t ttmp = t;
327 if (!localtime_r(&ttmp,&tst))
328 return -2;
329
330 // Now fill the output
331 if (opt == 1) {
332 sprintf(st,"%2d%3s%4d-%2d%2d%2d",tst.tm_mday,month[tst.tm_mon],
333 1900+tst.tm_year,
334 tst.tm_hour,tst.tm_min,tst.tm_sec);
335 // Make sure is null terminated at the right point
336 st[flen-2] = '\0';
337 } else {
338 sprintf(st,"%2d%3s%4d:%2d:%2d:%2d",tst.tm_mday,month[tst.tm_mon],
339 1900+tst.tm_year,
340 tst.tm_hour,tst.tm_min,tst.tm_sec);
341 }
342
343 // Make sure there are no empty spaces
344 if (st[0] == 0x20) st[0] = 0x30;
345 int i = 10;
346 for (; i <= 16; i++ )
347 if (st[i] == 0x20) st[i] = 0x30;
348
349
350 // Null termination
351 st[flen] = 0;
352
353 // Ok
354 return 0;
355}
356
357/******************************************************************************/
358/* X r d S u t E x p a n d */
359/******************************************************************************/
361{
362 // Expand '~' or $PWD for incomplete absolute path specification
363 // Returns 0 in case of success, -EINVAL if path is not defined;
364 // -errno if failure of the pwnam functions; -ENOENT if PWD is not
365 // defined
366 EPNAME("Expand");
367
368 // Path must be defined
369 if (!path.length())
370 return -EINVAL;
371
372 // If path is absolute, do nothing
373 if (path[0] == '/')
374 return 0;
375
376 if (path[0] == '~') {
377 XrdOucString unam, home;
378 XrdOucString sdir(path);
379 int iu = path.find('/');
380 if (iu != STR_NPOS) {
381 if (iu > 1)
382 unam.assign(path, 1, iu-1);
383 sdir.erase(0, iu);
384 } else
385 sdir = '/';
386 if (unam.length() > 0) {
387 struct passwd *pw;
388 XrdSysPwd thePwd(unam.c_str(), &pw);
389 if (!pw) {
390 DEBUG("cannot pwnam information for local user "<<
391 ((unam.length() > 0) ? unam : XrdOucString("")));
392 return -errno;
393 }
394 home = pw->pw_dir;
395 } else
396 home = XrdSutHome();
397 if (home.length() > 0) {
398 sdir.insert(home.c_str(),0);
399 path = sdir;
400 }
401 } else {
402 // relative path, add local dir
403 char *pwd = getenv("PWD");
404 if (pwd) {
405 path.insert('/',0);
406 path.insert(pwd,0);
407 path.erase("//");
408 } else {
409 DEBUG("PWD undefined ");
410 return -ENOENT;
411 }
412 }
413 return 0;
414}
415
416/******************************************************************************/
417/* X r d S u t R e s o l v e */
418/******************************************************************************/
420 const char *ho, const char *vo, const char *gr, const char *us)
421{
422 // Resolve templates <host>, <vo>, <group>, <user> (if any)
423 // Returns 0 in case of success, -EINVAL if path is not defined.
424
425 // Path must be defined
426 if (!path.length())
427 return -EINVAL;
428
429 // No templates, nothing to do
430 if (path.find("<") == STR_NPOS)
431 return 0;
432
433 // Replace <host>, if defined
434 if (ho && strlen(ho) > 0) path.replace("<host>", ho);
435
436 // Replace <vo>, if defined
437 if (vo && strlen(vo) > 0) path.replace("<vo>", vo);
438
439 // Replace <group>, if defined
440 if (gr && strlen(gr) > 0) path.replace("<group>", gr);
441
442 // Replace <user>, if defined
443 if (us && strlen(us) > 0) path.replace("<user>", us);
444
445 // Replace <rtag>, if defined
446 if (path.find("<rtag>") != STR_NPOS) {
447 XrdOucString rtag;
448 XrdSutRndm::GetString(2,6,rtag);
449 path.replace("<rtag>", rtag);
450 }
451
452 // Done
453 return 0;
454}
455
456/******************************************************************************/
457/* X r d S u t H o m e */
458/******************************************************************************/
459const char *XrdSutHome()
460{
461 // Gets the home directory preferentially from HOME or from pwd entry
462 EPNAME("Home");
463
464 // Use the save value, if any
465 static XrdOucString homedir;
466 if (homedir.length() <= 0) {
467 // Check the HOME environment variable
468 if (getenv("HOME"))
469 homedir = getenv("HOME");
470 if (homedir.length() <= 0) {
471 struct passwd *pw;
472 XrdSysPwd thePwd(getuid(), &pw);
473 if (pw) homedir = pw->pw_dir;
474 }
475 if (homedir.length() <= 0)
476 DEBUG("Warning: home directory undefined! ");
477 }
478
479 // Done
480 return homedir.c_str();
481}
482
483/******************************************************************************/
484/* X r d S u t M k d i r */
485/* */
486/******************************************************************************/
487int XrdSutMkdir(const char *dir, unsigned int mode, const char *opt)
488{
489 // Make directory dir
490 // mode specifies permissions
491 // opt == "-p" : make parent directories as needed
492
493 if (!dir) {
494 errno = EINVAL;
495 return -1;
496 }
497
498 if (!strncmp(opt,"-p",2)) {
499 //
500 // make also parent directories, if needed
501 XrdOucString dd(dir);
502 XrdSutExpand(dd);
503 if (dd[dd.length()-1] != '/')
504 dd.append('/');
505 int lsl = dd.find('/',1);
506 while (lsl > -1) {
507 XrdOucString pd(dd,0,lsl-1);
508 struct stat st;
509 if (stat(pd.c_str(),&st) == -1) {
510 if (errno == ENOENT) {
511 // path does not exists: create it
512 if (mkdir(pd.c_str(),mode) != 0)
513 return -1;
514 } else {
515 return -1;
516 }
517 }
518 // Go to next
519 lsl = dd.find('/',lsl+1);
520 }
521
522 } else {
523 return mkdir(dir,mode);
524 }
525
526 return 0;
527}
528
529/******************************************************************************/
530/* X r d S u t P a r s e T i m e */
531/* */
532/******************************************************************************/
533//______________________________________________________________________
534int XrdSutParseTime(const char *tstr, int opt)
535{
536 // Parse time string of the form "<val1><unit1>:<val2><unit2>:..."
537 // with <val> any integer and <unit> one of the following chars:
538 // 'y' for years
539 // 'd' for days
540 // 'h' for hours
541 // 'm' for minutes
542 // 's' for seconds
543 // (e.g. "34d:10h:20s")
544 // If opt == 1, assume a string in the form ".hh"[:<ss>[:<mm>]]"
545 // (e.g. "12:24:35" for 12 hours, 24 minutes and 35 secs)
546 // Return the corresponding number of seconds
547 EPNAME("ParseTime");
548
549 XrdOucString ts = tstr;
550 XrdOucString fr = "";
551 int i = 0;
552 int tsec = 0;
553 // Parse list
554 if (ts.length()) {
555 int ls = 0;
556 int ld = ts.find(':',1);
557 ld = (ld == -1) ? ts.length() - 1 : ld;
558 while (ld >= ls) {
559 fr.assign(ts, ls, ld);
560 fr.erase(":");
561 // Check this fraction
562 if (opt == 0) {
563 if (fr.length() > 1) {
564 // The unit must be known
565 char u = fr[fr.length()-1];
566 fr.erase(fr.length()-1);
567 if (u == 'y') {
568 tsec += atoi(fr.c_str())*31536000;
569 } else if (u == 'd') {
570 tsec += atoi(fr.c_str())*86400;
571 } else if (u == 'h') {
572 tsec += atoi(fr.c_str())*3600;
573 } else if (u == 'm') {
574 tsec += atoi(fr.c_str())*60;
575 } else if (u == 's') {
576 tsec += atoi(fr.c_str());
577 } else {
578 DEBUG("unknown unit: "<<u);
579 }
580 } else {
581 DEBUG("Incomplete fraction: "<<fr.c_str());
582 }
583 } else {
584 if (i == 0) {
585 tsec += atoi(fr.c_str())*3600;
586 } else if (i == 1) {
587 tsec += atoi(fr.c_str())*60;
588 } else if (i == 2) {
589 tsec += atoi(fr.c_str());
590 }
591 }
592 i++;
593 ls = ld + 1;
594 ld = ts.find(':',ls);
595 ld = (ld == -1) ? ts.length() - 1 : ld;
596 }
597 }
598 return tsec;
599}
600
601/******************************************************************************/
602/* X r d S u t F i l e L o c k e r */
603/* */
604/* Guard class for file locking */
605/* Usage: */
606/* { */
607/* XrdSutFileLocker fl(filename,1); */
608/* // File exclusively locked */
609/* ... */
610/* } // Unlocks file 'filename' */
611/* 's' for seconds */
612/* */
613/******************************************************************************/
614//______________________________________________________________________________
616{
617 // Constructor: locks the file in 'lock' mode.
618 // Use IsValid() to test success.
619
620 valid = 0;
621 fdesk = fd;
622
623 // Exclusive lock of the whole file
624 int lockmode = (lock == XrdSutFileLocker::kExcl) ? (F_WRLCK | F_RDLCK)
625 : F_RDLCK;
626 struct flock flck;
627 memset(&flck, 0, sizeof(flck));
628 flck.l_type = lockmode;
629 flck.l_whence = SEEK_SET;
630 if (fcntl(fdesk, F_SETLK, &flck) != 0)
631 // Failure
632 return;
633
634 // Success
635 valid = 1;
636}
637//______________________________________________________________________________
639{
640 // Destructor: unlocks the file if locked.
641
642 if (fdesk < 0 || !IsValid())
643 return;
644 //
645 // Unlock the file
646 struct flock flck = {F_UNLCK, SEEK_SET, 0, 0, 0};
647 memset(&flck, 0, sizeof(flck));
648 flck.l_type = F_UNLCK;
649 flck.l_whence = SEEK_SET;
650 fcntl(fdesk, F_SETLK, &flck);
651}
652
int kXR_int32
Definition XPtypes.hh:89
#define DEBUG(x)
#define EPNAME(x)
static std::string ts()
timestamp output for logging messages
Definition XrdCephOss.cc:53
static XrdSysLogger Logger
static XrdSysError eDest(0,"crypto_")
#define STR_NPOS
#define mkdir(a, b)
Definition XrdPosix.hh:74
#define stat(a, b)
Definition XrdPosix.hh:101
int XrdSutGetPass(const char *prompt, XrdOucString &passwd)
Definition XrdSutAux.cc:150
int XrdSutParseTime(const char *tstr, int opt)
Definition XrdSutAux.cc:534
static XrdSysError eDest(0,"sut_")
int XrdSutExpand(XrdOucString &path)
Definition XrdSutAux.cc:360
int XrdSutResolve(XrdOucString &path, const char *ho, const char *vo, const char *gr, const char *us)
Definition XrdSutAux.cc:419
bool XrdSutAskConfirm(const char *msg1, bool defact, const char *msg2)
Definition XrdSutAux.cc:203
volatile void * XrdSutMemSet(volatile void *dst, int c, int len)
Definition XrdSutAux.cc:140
static const char * gXRSBucketTypes[]
Definition XrdSutAux.cc:49
int XrdSutToHex(const char *in, int lin, char *out)
Definition XrdSutAux.cc:235
int XrdSutMkdir(const char *dir, unsigned int mode, const char *opt)
Definition XrdSutAux.cc:487
int XrdSutTimeString(int t, char *st, int opt)
Definition XrdSutAux.cc:305
XrdOucTrace * sutTrace
Definition XrdSutAux.cc:87
const char * XrdSutHome()
Definition XrdSutAux.cc:459
const char * XrdSutBuckStr(int kbck)
Definition XrdSutAux.cc:121
void XrdSutSetTrace(kXR_int32 trace)
Definition XrdSutAux.cc:93
int XrdSutFromHex(const char *in, char *out, int &lout)
Definition XrdSutAux.cc:268
int XrdSutGetLine(XrdOucString &line, const char *prompt)
Definition XrdSutAux.cc:179
@ kXRS_reserved
Definition XrdSutAux.hh:85
@ kXRS_cryptomod
Definition XrdSutAux.hh:57
#define sutTRACE_ALL
Definition XrdSutAux.hh:97
#define sutTRACE_Notify
Definition XrdSutAux.hh:100
#define XrdSutMAXBUF
Definition XrdSutAux.hh:48
#define sutTRACE_Debug
Definition XrdSutAux.hh:99
#define sutTRACE_Dump
Definition XrdSutAux.hh:98
void insert(const int i, int start=-1)
void assign(const char *s, int j, int k=-1)
int erase(int start=0, int size=0)
int replace(const char *s1, const char *s2, int from=0, int to=-1)
int find(const char c, int start=0, bool forward=1)
int length() const
void append(const int i)
void lower(int pos, int size=0)
const char * c_str() const
XrdSutFileLocker(int fd, ELockType lock)
Definition XrdSutAux.cc:615
bool IsValid() const
Definition XrdSutAux.hh:246
static int GetString(int opt, int len, XrdOucString &s)