XRootD
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 
40 #include "XrdSys/XrdSysLogger.hh"
41 #include "XrdSys/XrdSysError.hh"
42 #include "XrdSys/XrdSysPwd.hh"
43 #include "XrdOuc/XrdOucString.hh"
44 
45 #include "XrdSut/XrdSutAux.hh"
46 #include "XrdSut/XrdSutRndm.hh"
47 #include "XrdSut/XrdSutTrace.hh"
48 
49 static 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
86 static 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
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))
108  // Medium level
109  if ((trace & sutTRACE_Debug))
111  // High level
112  if ((trace & sutTRACE_Dump))
114  }
115 }
116 
117 /******************************************************************************/
118 /* X r d S u t B u c k S t r */
119 /******************************************************************************/
120 //______________________________________________________________________________
121 const 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 //______________________________________________________________________________
140 volatile void *XrdSutMemSet(volatile void *dst, int c, int len)
141 {
142  // To avoid problems due to compiler optmization
143  // Taken from Viega&Messier, "Secure Programming Cookbook", O'Really, #13.2
144  // (see discussion there)
145  volatile char *buf;
146 
147  for (buf = (volatile char *)dst; len; buf[--len] = c) {}
148  return dst;
149 }
150 
151 #ifndef USE_EXTERNAL_GETPASS
152 /******************************************************************************/
153 /* X r d S u t G e t P a s s */
154 /******************************************************************************/
155 //_____________________________________________________________________________
156 int XrdSutGetPass(const char *prompt, XrdOucString &passwd)
157 {
158  // Get password from command line using getpass
159  // *** Use only if you cannot provide a better alternative ***
160  // User will be prompted for 'prompt'; the entered password
161  // is returned in 'passwd'.
162  // Returns 0 if ok, -1 if any error occurs.
163  EPNAME("GetPass");
164 
165  char *pw = getpass(prompt);
166  if (pw) {
167  // Get rid of special chars, if any
168  int k = 0, i = 0, len = strlen(pw);
169  for (; i<len ; i++)
170  if (pw[i] > 0x20) pw[k++] = pw[i];
171  pw[k] = 0;
172  passwd = pw;
173  XrdSutMemSet((volatile void *)pw,0,len);
174  } else {
175  DEBUG("error from getpass");
176  return -1;
177  }
178  return 0;
179 }
180 #endif
181 
182 /******************************************************************************/
183 /* X r d S u t G e t L i n e */
184 /******************************************************************************/
185 int XrdSutGetLine(XrdOucString &line, const char *prompt)
186 {
187  // Get line from main input stream.
188  // Prompt 'prompt' if this is defined.
189  // Returns number of chars entered.
190  // NB: at most XrdSutMAXBUF-1 chars will be accepted
191  char bin[XrdSutMAXBUF] = {0};
192 
193  // Print prompt, if requested
194  if (prompt)
195  std::cout << prompt;
196 
197  // Get line
198  std::cin.getline(bin,XrdSutMAXBUF-1);
199 
200  // Fill input
201  line = bin;
202 
203  return line.length();
204 }
205 
206 /******************************************************************************/
207 /* X r d S u t A s k C o n f i r m */
208 /******************************************************************************/
209 bool XrdSutAskConfirm(const char *msg1, bool defact, const char *msg2)
210 {
211  // Prompt for confirmation of action
212  // If defined, msg1 is printed as prompt, followed by the default action
213  // ( [y] == do-act, for defact = true;
214  // [n] == do-not-act, for defact = false)
215  // If defined, msg2 is printed before prompting.
216 
217  bool rc = defact;
218 
219  if (msg2)
220  std::cout << msg2;
221  XrdOucString ask;
222  XrdOucString prompt = defact ? " [y]: " : " [n]: ";
223  if (msg1)
224  prompt.insert(msg1,0);
225  XrdSutGetLine(ask,prompt.c_str());
226  ask.lower(0);
227  if (ask.length()) {
228  if (defact && (ask == 'n' || ask == "no")) {
229  rc = 0;
230  } else if (!defact && (ask == 'y' || ask == "yes")) {
231  rc = 1;
232  }
233  }
234  // we are done
235  return rc;
236 }
237 
238 /******************************************************************************/
239 /* X r d S u t T o H e x */
240 /******************************************************************************/
241 int XrdSutToHex(const char *in, int lin, char *out)
242 {
243  // Content of lin bytes at in are transformed into an hexadecimal,
244  // null-terminated, string of length 2*lin; the result is returned
245  // in the buffer pointed by out, which must be allocated by the caller
246  // to contain at least 2*lin+1 bytes.
247  // Return 0 in case of success, -1 in case of error (errno set to EINVAL if
248  // any of in or out are not defined).
249 
250  if (!in || !out) {
251  errno = EINVAL;
252  return -1;
253  }
254 
255  int lbuf = 2*lin+1;
256  int i = 0;
257  out[0] = 0;
258  for ( ; i < lin; i++)
259  {
260  char buff[3];
261  sprintf(buff, "%02x", (0xFF & in[i]));
262  strncat(out, buff, 3);
263  }
264  // Null termination
265  out[lbuf-1] = 0;
266 
267  // ok
268  return 0;
269 }
270 
271 /******************************************************************************/
272 /* X r d S u t F r o m H e x */
273 /******************************************************************************/
274 int XrdSutFromHex(const char *in, char *out, int &lout)
275 {
276  // Content of the hexadecimal, null-terminated, string at in, is
277  // transformed into lout bytes returned in out.
278  // The output buffer should be allocated by the caller to contain
279  // at least lin/2 bytes if lin=strlen(in) is even, and lin/2+1 bytes
280  // if lin is odd (in this case an additional char equal 0 is appended
281  // to in).
282  // Return 0 in case of success, -1 in case of error (errno set to EINVAL if
283  // any of in or out are not defined).
284 
285  lout = 0;
286  if (!in || !out) {
287  errno = EINVAL;
288  return -1;
289  }
290 
291  int lin = strlen(in);
292  char st[3] = {0};
293  int i = 0, k = 0;
294  for ( ; i<lin; i += 2) {
295  st[0] = in[i];
296  st[1] = ((i+1) < lin) ? in[i+1] : 0;
297  unsigned int c;
298  sscanf(st,"%x",&c);
299  out[k++] = (char)(0x000000FF & c);
300  }
301 
302  lout = k;
303 
304  return 0;
305 }
306 
307 /******************************************************************************/
308 /* X r d S u t T i m e S t r i n g */
309 /* */
310 /******************************************************************************/
311 int XrdSutTimeString(int t, char *st, int opt)
312 {
313  // Trasform a time in secs since 1Jan1970 in a string of the format
314  // 24Apr2006:09:10:23 (opt = 0, default)
315  // 24Apr2006-091023 (opt = 1)
316  // The buffer st must be supplied by the caller to contain at least 20.
317  // This length is returned when calling the function with t=-1
318  static char month[12][4] = {"Jan","Feb","Mar","Apr","May","Jun",
319  "Jul","Aug","Sep","Oct","Nov","Dec"};
320  static short flen = strlen("24Apr2006:09:10:23");
321 
322  // Check if the length is required
323  if (t == -1)
324  return (flen+1);
325 
326  // Now check inputs
327  if (t < 0 || !st)
328  return -1;
329 
330  // Get the breakdown
331  struct tm tst;
332  time_t ttmp = t;
333  if (!localtime_r(&ttmp,&tst))
334  return -2;
335 
336  // Now fill the output
337  if (opt == 1) {
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  // Make sure is null terminated at the right point
342  st[flen-2] = '\0';
343  } else {
344  sprintf(st,"%2d%3s%4d:%2d:%2d:%2d",tst.tm_mday,month[tst.tm_mon],
345  1900+tst.tm_year,
346  tst.tm_hour,tst.tm_min,tst.tm_sec);
347  }
348 
349  // Make sure there are no empty spaces
350  if (st[0] == 0x20) st[0] = 0x30;
351  int i = 10;
352  for (; i <= 16; i++ )
353  if (st[i] == 0x20) st[i] = 0x30;
354 
355 
356  // Null termination
357  st[flen] = 0;
358 
359  // Ok
360  return 0;
361 }
362 
363 /******************************************************************************/
364 /* X r d S u t E x p a n d */
365 /******************************************************************************/
367 {
368  // Expand '~' or $PWD for incomplete absolute path specification
369  // Returns 0 in case of success, -EINVAL if path is not defined;
370  // -errno if failure of the pwnam functions; -ENOENT if PWD is not
371  // defined
372  EPNAME("Expand");
373 
374  // Path must be defined
375  if (!path.length())
376  return -EINVAL;
377 
378  // If path is absolute, do nothing
379  if (path[0] == '/')
380  return 0;
381 
382  if (path[0] == '~') {
383  XrdOucString unam, home;
384  XrdOucString sdir(path);
385  int iu = path.find('/');
386  if (iu != STR_NPOS) {
387  if (iu > 1)
388  unam.assign(path, 1, iu-1);
389  sdir.erase(0, iu);
390  } else
391  sdir = '/';
392  if (unam.length() > 0) {
393  struct passwd *pw;
394  XrdSysPwd thePwd(unam.c_str(), &pw);
395  if (!pw) {
396  DEBUG("cannot pwnam information for local user "<<
397  ((unam.length() > 0) ? unam : XrdOucString("")));
398  return -errno;
399  }
400  home = pw->pw_dir;
401  } else
402  home = XrdSutHome();
403  if (home.length() > 0) {
404  sdir.insert(home.c_str(),0);
405  path = sdir;
406  }
407  } else {
408  // relative path, add local dir
409  char *pwd = getenv("PWD");
410  if (pwd) {
411  path.insert('/',0);
412  path.insert(pwd,0);
413  path.erase("//");
414  } else {
415  DEBUG("PWD undefined ");
416  return -ENOENT;
417  }
418  }
419  return 0;
420 }
421 
422 /******************************************************************************/
423 /* X r d S u t R e s o l v e */
424 /******************************************************************************/
426  const char *ho, const char *vo, const char *gr, const char *us)
427 {
428  // Resolve templates <host>, <vo>, <group>, <user> (if any)
429  // Returns 0 in case of success, -EINVAL if path is not defined.
430 
431  // Path must be defined
432  if (!path.length())
433  return -EINVAL;
434 
435  // No templates, nothing to do
436  if (path.find("<") == STR_NPOS)
437  return 0;
438 
439  // Replace <host>, if defined
440  if (ho && strlen(ho) > 0) path.replace("<host>", ho);
441 
442  // Replace <vo>, if defined
443  if (vo && strlen(vo) > 0) path.replace("<vo>", vo);
444 
445  // Replace <group>, if defined
446  if (gr && strlen(gr) > 0) path.replace("<group>", gr);
447 
448  // Replace <user>, if defined
449  if (us && strlen(us) > 0) path.replace("<user>", us);
450 
451  // Replace <rtag>, if defined
452  if (path.find("<rtag>") != STR_NPOS) {
453  XrdOucString rtag;
454  XrdSutRndm::GetString(2,6,rtag);
455  path.replace("<rtag>", rtag);
456  }
457 
458  // Done
459  return 0;
460 }
461 
462 /******************************************************************************/
463 /* X r d S u t H o m e */
464 /******************************************************************************/
465 const char *XrdSutHome()
466 {
467  // Gets the home directory preferentially from HOME or from pwd entry
468  EPNAME("Home");
469 
470  // Use the save value, if any
471  static XrdOucString homedir;
472  if (homedir.length() <= 0) {
473  // Check the HOME environment variable
474  if (getenv("HOME"))
475  homedir = getenv("HOME");
476  if (homedir.length() <= 0) {
477  struct passwd *pw;
478  XrdSysPwd thePwd(getuid(), &pw);
479  if (pw) homedir = pw->pw_dir;
480  }
481  if (homedir.length() <= 0)
482  DEBUG("Warning: home directory undefined! ");
483  }
484 
485  // Done
486  return homedir.c_str();
487 }
488 
489 /******************************************************************************/
490 /* X r d S u t M k d i r */
491 /* */
492 /******************************************************************************/
493 int XrdSutMkdir(const char *dir, unsigned int mode, const char *opt)
494 {
495  // Make directory dir
496  // mode specifies permissions
497  // opt == "-p" : make parent directories as needed
498 
499  if (!dir) {
500  errno = EINVAL;
501  return -1;
502  }
503 
504  if (!strncmp(opt,"-p",2)) {
505  //
506  // make also parent directories, if needed
507  XrdOucString dd(dir);
508  XrdSutExpand(dd);
509  if (dd[dd.length()-1] != '/')
510  dd.append('/');
511  int lsl = dd.find('/',1);
512  while (lsl > -1) {
513  XrdOucString pd(dd,0,lsl-1);
514  struct stat st;
515  if (stat(pd.c_str(),&st) == -1) {
516  if (errno == ENOENT) {
517  // path does not exists: create it
518  if (mkdir(pd.c_str(),mode) != 0)
519  return -1;
520  } else {
521  return -1;
522  }
523  }
524  // Go to next
525  lsl = dd.find('/',lsl+1);
526  }
527 
528  } else {
529  return mkdir(dir,mode);
530  }
531 
532  return 0;
533 }
534 
535 /******************************************************************************/
536 /* X r d S u t P a r s e T i m e */
537 /* */
538 /******************************************************************************/
539 //______________________________________________________________________
540 int XrdSutParseTime(const char *tstr, int opt)
541 {
542  // Parse time string of the form "<val1><unit1>:<val2><unit2>:..."
543  // with <val> any integer and <unit> one of the following chars:
544  // 'y' for years
545  // 'd' for days
546  // 'h' for hours
547  // 'm' for minutes
548  // 's' for seconds
549  // (e.g. "34d:10h:20s")
550  // If opt == 1, assume a string in the form ".hh"[:<ss>[:<mm>]]"
551  // (e.g. "12:24:35" for 12 hours, 24 minutes and 35 secs)
552  // Return the corresponding number of seconds
553  EPNAME("ParseTime");
554 
555  XrdOucString ts = tstr;
556  XrdOucString fr = "";
557  int i = 0;
558  int tsec = 0;
559  // Parse list
560  if (ts.length()) {
561  int ls = 0;
562  int ld = ts.find(':',1);
563  ld = (ld == -1) ? ts.length() - 1 : ld;
564  while (ld >= ls) {
565  fr.assign(ts, ls, ld);
566  fr.erase(":");
567  // Check this fraction
568  if (opt == 0) {
569  if (fr.length() > 1) {
570  // The unit must be known
571  char u = fr[fr.length()-1];
572  fr.erase(fr.length()-1);
573  if (u == 'y') {
574  tsec += atoi(fr.c_str())*31536000;
575  } else if (u == 'd') {
576  tsec += atoi(fr.c_str())*86400;
577  } else if (u == 'h') {
578  tsec += atoi(fr.c_str())*3600;
579  } else if (u == 'm') {
580  tsec += atoi(fr.c_str())*60;
581  } else if (u == 's') {
582  tsec += atoi(fr.c_str());
583  } else {
584  DEBUG("unknown unit: "<<u);
585  }
586  } else {
587  DEBUG("Incomplete fraction: "<<fr.c_str());
588  }
589  } else {
590  if (i == 0) {
591  tsec += atoi(fr.c_str())*3600;
592  } else if (i == 1) {
593  tsec += atoi(fr.c_str())*60;
594  } else if (i == 2) {
595  tsec += atoi(fr.c_str());
596  }
597  }
598  i++;
599  ls = ld + 1;
600  ld = ts.find(':',ls);
601  ld = (ld == -1) ? ts.length() - 1 : ld;
602  }
603  }
604  return tsec;
605 }
606 
607 /******************************************************************************/
608 /* X r d S u t F i l e L o c k e r */
609 /* */
610 /* Guard class for file locking */
611 /* Usage: */
612 /* { */
613 /* XrdSutFileLocker fl(filename,1); */
614 /* // File exclusively locked */
615 /* ... */
616 /* } // Unlocks file 'filename' */
617 /* 's' for seconds */
618 /* */
619 /******************************************************************************/
620 //______________________________________________________________________________
622 {
623  // Constructor: locks the file in 'lock' mode.
624  // Use IsValid() to test success.
625 
626  valid = 0;
627  fdesk = fd;
628 
629  // Exclusive lock of the whole file
630  int lockmode = (lock == XrdSutFileLocker::kExcl) ? (F_WRLCK | F_RDLCK)
631  : F_RDLCK;
632  struct flock flck;
633  memset(&flck, 0, sizeof(flck));
634  flck.l_type = lockmode;
635  flck.l_whence = SEEK_SET;
636  if (fcntl(fdesk, F_SETLK, &flck) != 0)
637  // Failure
638  return;
639 
640  // Success
641  valid = 1;
642 }
643 //______________________________________________________________________________
645 {
646  // Destructor: unlocks the file if locked.
647 
648  if (fdesk < 0 || !IsValid())
649  return;
650  //
651  // Unlock the file
652  struct flock flck = {F_UNLCK, SEEK_SET, 0, 0, 0};
653  memset(&flck, 0, sizeof(flck));
654  flck.l_type = F_UNLCK;
655  flck.l_whence = SEEK_SET;
656  fcntl(fdesk, F_SETLK, &flck);
657 }
658 
int kXR_int32
Definition: XPtypes.hh:89
#define DEBUG(x)
Definition: XrdBwmTrace.hh:54
#define EPNAME(x)
Definition: XrdBwmTrace.hh:56
#define STR_NPOS
int stat(const char *path, struct stat *buf)
int fcntl(int fd, int cmd,...)
int mkdir(const char *path, mode_t mode)
int XrdSutGetPass(const char *prompt, XrdOucString &passwd)
Definition: XrdSutAux.cc:156
int XrdSutParseTime(const char *tstr, int opt)
Definition: XrdSutAux.cc:540
static XrdSysError eDest(0,"sut_")
int XrdSutExpand(XrdOucString &path)
Definition: XrdSutAux.cc:366
int XrdSutResolve(XrdOucString &path, const char *ho, const char *vo, const char *gr, const char *us)
Definition: XrdSutAux.cc:425
volatile void * XrdSutMemSet(volatile void *dst, int c, int len)
Definition: XrdSutAux.cc:140
bool XrdSutAskConfirm(const char *msg1, bool defact, const char *msg2)
Definition: XrdSutAux.cc:209
static const char * gXRSBucketTypes[]
Definition: XrdSutAux.cc:49
int XrdSutToHex(const char *in, int lin, char *out)
Definition: XrdSutAux.cc:241
const char * XrdSutHome()
Definition: XrdSutAux.cc:465
int XrdSutMkdir(const char *dir, unsigned int mode, const char *opt)
Definition: XrdSutAux.cc:493
const char * XrdSutBuckStr(int kbck)
Definition: XrdSutAux.cc:121
static XrdSysLogger Logger
Definition: XrdSutAux.cc:85
int XrdSutTimeString(int t, char *st, int opt)
Definition: XrdSutAux.cc:311
XrdOucTrace * sutTrace
Definition: XrdSutAux.cc:87
void XrdSutSetTrace(kXR_int32 trace)
Definition: XrdSutAux.cc:93
int XrdSutFromHex(const char *in, char *out, int &lout)
Definition: XrdSutAux.cc:274
int XrdSutGetLine(XrdOucString &line, const char *prompt)
Definition: XrdSutAux.cc:185
@ 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)
const char * c_str() const
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)
XrdSutFileLocker(int fd, ELockType lock)
Definition: XrdSutAux.cc:621
bool IsValid() const
Definition: XrdSutAux.hh:246
static int GetString(int opt, int len, XrdOucString &s)
Definition: XrdSutRndm.cc:120
XrdSysLogger * logger(XrdSysLogger *lp=0)
Definition: XrdSysError.hh:141