dsalib_util.c 28 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212
  1. /** BEGIN COPYRIGHT BLOCK
  2. * This Program is free software; you can redistribute it and/or modify it under
  3. * the terms of the GNU General Public License as published by the Free Software
  4. * Foundation; version 2 of the License.
  5. *
  6. * This Program is distributed in the hope that it will be useful, but WITHOUT
  7. * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
  8. * FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details.
  9. *
  10. * You should have received a copy of the GNU General Public License along with
  11. * this Program; if not, write to the Free Software Foundation, Inc., 59 Temple
  12. * Place, Suite 330, Boston, MA 02111-1307 USA.
  13. *
  14. * In addition, as a special exception, Red Hat, Inc. gives You the additional
  15. * right to link the code of this Program with code not covered under the GNU
  16. * General Public License ("Non-GPL Code") and to distribute linked combinations
  17. * including the two, subject to the limitations in this paragraph. Non-GPL Code
  18. * permitted under this exception must only link to the code of this Program
  19. * through those well defined interfaces identified in the file named EXCEPTION
  20. * found in the source code files (the "Approved Interfaces"). The files of
  21. * Non-GPL Code may instantiate templates or use macros or inline functions from
  22. * the Approved Interfaces without causing the resulting work to be covered by
  23. * the GNU General Public License. Only Red Hat, Inc. may make changes or
  24. * additions to the list of Approved Interfaces. You must obey the GNU General
  25. * Public License in all respects for all of the Program code and other code used
  26. * in conjunction with the Program except the Non-GPL Code covered by this
  27. * exception. If you modify this file, you may extend this exception to your
  28. * version of the file, but you are not obligated to do so. If you do not wish to
  29. * provide this exception without modification, you must delete this exception
  30. * statement from your version and license this file solely under the GPL without
  31. * exception.
  32. *
  33. *
  34. * Copyright (C) 2001 Sun Microsystems, Inc. Used by permission.
  35. * Copyright (C) 2005 Red Hat, Inc.
  36. * All rights reserved.
  37. * END COPYRIGHT BLOCK **/
  38. #ifdef HAVE_CONFIG_H
  39. # include <config.h>
  40. #endif
  41. #if defined( XP_WIN32 )
  42. #include <windows.h>
  43. #include <io.h>
  44. #else /* XP_WIN32 */
  45. # if defined( AIXV4 )
  46. # include <fcntl.h>
  47. # else /* AIXV4 */
  48. # include <sys/fcntl.h>
  49. # endif /* AIXV4 */
  50. #include <dirent.h>
  51. #include <unistd.h>
  52. #include <fcntl.h>
  53. #endif /* XP_WIN3 */
  54. #include "dsalib.h"
  55. #include <sys/types.h>
  56. #include <stdio.h>
  57. #include <stdlib.h>
  58. #include <string.h>
  59. #include <sys/stat.h>
  60. #include <ctype.h>
  61. #include "nspr.h"
  62. #include "plstr.h"
  63. #define COPY_BUFFER_SIZE 4096
  64. /* This is the separator string to use when outputting key/value pairs
  65. to be read by the non-HTML front end (Java console)
  66. */
  67. static const char *SEPARATOR = ":"; /* from AdmTask.java */
  68. #define LOGFILEENVVAR "DEBUG_LOGFILE" /* used for logfp */
  69. static int internal_rm_rf(const char *path, DS_RM_RF_ERR_FUNC ds_rm_rf_err_func, void *arg);
  70. /* return a FILE * opened in append mode to the log file
  71. caller must use fclose to close it
  72. */
  73. static FILE *
  74. get_logfp(void)
  75. {
  76. FILE *logfp = NULL;
  77. char *logfile = getenv(LOGFILEENVVAR);
  78. if (logfile) {
  79. logfp = fopen(logfile, "a");
  80. }
  81. return logfp;
  82. }
  83. DS_EXPORT_SYMBOL int
  84. ds_file_exists(char *filename)
  85. {
  86. struct stat finfo;
  87. if ( filename == NULL )
  88. return 0;
  89. if ( stat(filename, &finfo) == 0 ) /* successful */
  90. return 1;
  91. else
  92. return 0;
  93. }
  94. DS_EXPORT_SYMBOL int
  95. ds_mkdir(char *dir, int mode)
  96. {
  97. if(!ds_file_exists(dir)) {
  98. #ifdef XP_UNIX
  99. if(mkdir(dir, mode) == -1)
  100. #else /* XP_WIN32 */
  101. if(!CreateDirectory(dir, NULL))
  102. #endif /* XP_WIN32 */
  103. return -1;
  104. }
  105. return 0;
  106. }
  107. DS_EXPORT_SYMBOL char *
  108. ds_mkdir_p(char *dir, int mode)
  109. {
  110. static char errmsg[ERR_SIZE];
  111. struct stat fi;
  112. char *t;
  113. #ifdef XP_UNIX
  114. t = dir + 1;
  115. #else /* XP_WIN32 */
  116. t = dir + 3;
  117. #endif /* XP_WIN32 */
  118. while(1) {
  119. t = strchr(t, FILE_PATHSEP);
  120. if(t) *t = '\0';
  121. if(stat(dir, &fi) == -1) {
  122. if(ds_mkdir(dir, mode) == -1) {
  123. PR_snprintf(errmsg, sizeof(errmsg), "mkdir %s failed (%s)", dir, ds_system_errmsg());
  124. return errmsg;
  125. }
  126. }
  127. if(t) *t++ = FILE_PATHSEP;
  128. else break;
  129. }
  130. return NULL;
  131. }
  132. /*
  133. * Given the name of a directory, return a NULL-terminated array of
  134. * the file names contained in that directory. Returns NULL if the directory
  135. * does not exist or an error occurs, and returns an array with a
  136. * single NULL string if the directory exists but is empty. The caller
  137. * is responsible for freeing the returned array of strings.
  138. * File names "." and ".." are not returned.
  139. */
  140. #if !defined( XP_WIN32 )
  141. DS_EXPORT_SYMBOL char **
  142. ds_get_file_list( char *dir )
  143. {
  144. DIR *dirp;
  145. struct dirent *direntp;
  146. char **ret = NULL;
  147. int nfiles = 0;
  148. if (( dirp = opendir( dir )) == NULL ) {
  149. return NULL;
  150. }
  151. if (( ret = malloc( sizeof( char * ))) == NULL ) {
  152. return NULL;
  153. };
  154. while (( direntp = readdir( dirp )) != NULL ) {
  155. if ( strcmp( direntp->d_name, "." ) &&
  156. strcmp( direntp->d_name, ".." )) {
  157. if (( ret = (char **) realloc( ret,
  158. sizeof( char * ) * ( nfiles + 2 ))) == NULL );
  159. ret[ nfiles ] = strdup( direntp->d_name );
  160. nfiles++;
  161. }
  162. }
  163. (void) closedir( dirp );
  164. ret[ nfiles ] = NULL;
  165. return ret;
  166. }
  167. #else
  168. DS_EXPORT_SYMBOL char **
  169. ds_get_file_list( char *dir )
  170. {
  171. char szWildcardFileSpec[MAX_PATH];
  172. char **ret = NULL;
  173. long hFile;
  174. struct _finddata_t fileinfo;
  175. int nfiles = 0;
  176. if( ( dir == NULL ) || (strlen( dir ) == 0) )
  177. return NULL;
  178. if( ( ret = malloc( sizeof( char * ) ) ) == NULL )
  179. return NULL;
  180. PL_strncpyz(szWildcardFileSpec, dir, sizeof(szWildcardFileSpec));
  181. PL_strcatn(szWildcardFileSpec, sizeof(szWildcardFileSpec), "/*");
  182. hFile = _findfirst( szWildcardFileSpec, &fileinfo);
  183. if( hFile == -1 )
  184. return NULL;
  185. if( ( strcmp( fileinfo.name, "." ) != 0 ) &&
  186. ( strcmp( fileinfo.name, ".." ) != 0 ) )
  187. {
  188. ret[ nfiles++ ] = strdup( fileinfo.name );
  189. }
  190. while( _findnext( hFile, &fileinfo ) == 0 )
  191. {
  192. if( ( strcmp( fileinfo.name, "." ) != 0 ) &&
  193. ( strcmp( fileinfo.name, ".." ) != 0 ) )
  194. {
  195. if( ( ret = (char **) realloc( ret, sizeof( char * ) * ( nfiles + 2 ) ) ) != NULL )
  196. ret[ nfiles++ ] = strdup( fileinfo.name);
  197. }
  198. }
  199. _findclose( hFile );
  200. ret[ nfiles ] = NULL;
  201. return ret;
  202. }
  203. #endif /* ( XP_WIN32 ) */
  204. DS_EXPORT_SYMBOL time_t
  205. ds_get_mtime(char *filename)
  206. {
  207. struct stat fi;
  208. if ( stat(filename, &fi) )
  209. return 0;
  210. return fi.st_mtime;
  211. }
  212. /*
  213. * Copy files: return is
  214. * 1: success
  215. * 0: failure
  216. * Print errors as needed.
  217. */
  218. DS_EXPORT_SYMBOL int
  219. ds_cp_file(char *sfile, char *dfile, int mode)
  220. {
  221. #if defined( XP_WIN32 )
  222. return( CopyFile( sfile, dfile, FALSE ) ); /* Copy even if dfile exists */
  223. #else
  224. int sfd, dfd, len;
  225. struct stat fi;
  226. char copy_buffer[COPY_BUFFER_SIZE];
  227. unsigned long read_len;
  228. char error[BIG_LINE];
  229. /* Make sure we're in the right umask */
  230. umask(022);
  231. if( (sfd = open(sfile, O_RDONLY)) == -1) {
  232. PR_snprintf(error, sizeof(error), "Can't open file %s for reading.", sfile);
  233. ds_send_error(error, 1);
  234. return(0);
  235. }
  236. fstat(sfd, &fi);
  237. if (!(S_ISREG(fi.st_mode))) {
  238. PR_snprintf(error, sizeof(error), "File %s is not a regular file.", sfile);
  239. ds_send_error(error, 1);
  240. close(sfd);
  241. return(0);
  242. }
  243. len = fi.st_size;
  244. if( (dfd = open(dfile, O_RDWR | O_CREAT | O_TRUNC, mode)) == -1) {
  245. PR_snprintf(error, sizeof(error), "can't write to file %s", dfile);
  246. ds_send_error(error, 1);
  247. close(sfd);
  248. return(0);
  249. }
  250. while (len) {
  251. read_len = len>COPY_BUFFER_SIZE?COPY_BUFFER_SIZE:len;
  252. if ( (read_len = read(sfd, copy_buffer, read_len)) == -1) {
  253. PR_snprintf(error, sizeof(error), "Error reading file %s for copy.", sfile);
  254. ds_send_error(error, 1);
  255. close(sfd);
  256. close(dfd);
  257. return(0);
  258. }
  259. if ( write(dfd, copy_buffer, read_len) != read_len) {
  260. PR_snprintf(error, sizeof(error), "Error writing file %s for copy.", dfile);
  261. ds_send_error(error, 1);
  262. close(sfd);
  263. close(dfd);
  264. return(0);
  265. }
  266. len -= read_len;
  267. }
  268. close(sfd);
  269. close(dfd);
  270. return(1);
  271. #endif
  272. }
  273. DS_EXPORT_SYMBOL void
  274. ds_unixtodospath(char *szText)
  275. {
  276. if(szText)
  277. {
  278. while(*szText)
  279. {
  280. if( *szText == '/' )
  281. *szText = '\\';
  282. szText++;
  283. }
  284. }
  285. }
  286. /* converts '\' chars to '/' */
  287. DS_EXPORT_SYMBOL void
  288. ds_dostounixpath(char *szText)
  289. {
  290. if(szText)
  291. {
  292. while(*szText)
  293. {
  294. if( *szText == '\\' )
  295. *szText = '/';
  296. szText++;
  297. }
  298. }
  299. }
  300. /* converts ':' chars to ' ' */
  301. DS_EXPORT_SYMBOL void
  302. ds_timetofname(char *szText)
  303. {
  304. if(szText)
  305. {
  306. /* Replace trailing newline */
  307. szText[ strlen( szText ) -1 ] = 0;
  308. while(*szText)
  309. {
  310. if( *szText == ':' ||
  311. *szText == ' ' )
  312. *szText = '_';
  313. szText++;
  314. }
  315. }
  316. }
  317. /* Effects a rename in 2 steps, needed on NT because if the
  318. target of a rename() already exists, the rename() will fail. */
  319. DS_EXPORT_SYMBOL int
  320. ds_saferename(char *szSrc, char *szTarget)
  321. {
  322. #ifdef XP_WIN32
  323. int iRetVal;
  324. char *szTmpFile;
  325. struct stat buf;
  326. #endif
  327. if( !szSrc || !szTarget )
  328. return 1;
  329. #if defined( XP_WIN32 )
  330. szTmpFile = mktemp("slrnXXXXXX" );
  331. if( stat( szTarget, &buf ) == 0 )
  332. {
  333. /* Target file exists */
  334. if( !szTmpFile )
  335. return 1;
  336. if( !ds_cp_file( szTarget, szTmpFile, 0644) )
  337. return( 1 );
  338. unlink( szTarget );
  339. if( (iRetVal = rename( szSrc, szTarget )) != 0 )
  340. {
  341. /* Failed to rename, copy back. */
  342. ds_cp_file( szTmpFile, szTarget, 0644);
  343. }
  344. /* Now remove temp file */
  345. unlink( szTmpFile );
  346. }
  347. else
  348. iRetVal = rename(szSrc, szTarget);
  349. return iRetVal;
  350. #else
  351. return rename(szSrc, szTarget);
  352. #endif
  353. }
  354. DS_EXPORT_SYMBOL char*
  355. ds_encode_all (const char* s)
  356. {
  357. char* r;
  358. size_t l;
  359. size_t i;
  360. if (s == NULL || *s == '\0') {
  361. return strdup ("");
  362. }
  363. l = strlen (s);
  364. r = malloc (l * 3 + 1);
  365. for (i = 0; *s != '\0'; ++s) {
  366. r[i++] = '%';
  367. sprintf (r + i, "%.2X", 0xFF & (unsigned int)*s);
  368. i += 2;
  369. }
  370. r[i] = '\0';
  371. return r;
  372. }
  373. DS_EXPORT_SYMBOL char*
  374. ds_URL_encode (const char* s)
  375. {
  376. char* r;
  377. size_t l;
  378. size_t i;
  379. if (s == NULL || *s == '\0') {
  380. return strdup ("");
  381. }
  382. l = strlen (s) + 1;
  383. r = malloc (l);
  384. for (i = 0; *s != '\0'; ++s) {
  385. if (*s >= 0x20 && *s <= 0x7E && strchr (" <>\"#%{}[]|\\^~`?,;=+\n", *s) == NULL) {
  386. if (l - i <= 1) r = realloc (r, l *= 2);
  387. r[i++] = *s;
  388. } else { /* encode *s */
  389. if (l - i <= 3) r = realloc (r, l *= 2);
  390. r[i++] = '%';
  391. sprintf (r + i, "%.2X", 0xFF & (unsigned int)*s);
  392. i += 2;
  393. }
  394. }
  395. r[i] = '\0';
  396. return r;
  397. }
  398. DS_EXPORT_SYMBOL char*
  399. ds_URL_decode (const char* original)
  400. {
  401. char* r = strdup (original);
  402. char* s;
  403. for (s = r; *s != '\0'; ++s) {
  404. if (*s == '+') {
  405. *s = ' ';
  406. }
  407. else if (*s == '%' && isxdigit(s[1]) && isxdigit(s[2])) {
  408. memmove (s, s+1, 2);
  409. s[2] = '\0';
  410. *s = (char)strtoul (s, NULL, 16);
  411. memmove (s+1, s+3, strlen (s+3) + 1);
  412. }
  413. }
  414. return r;
  415. }
  416. #if !defined( XP_WIN32 )
  417. #include <errno.h> /* errno */
  418. #include <pwd.h> /* getpwnam */
  419. static int saved_uid_valid = 0;
  420. static uid_t saved_uid;
  421. static int saved_gid_valid = 0;
  422. static gid_t saved_gid;
  423. #if defined( HPUX )
  424. #define SETEUID(id) setresuid((uid_t) -1, id, (uid_t) -1)
  425. #else
  426. #define SETEUID(id) seteuid(id)
  427. #endif
  428. #endif
  429. DS_EXPORT_SYMBOL char*
  430. ds_become_localuser_name (char *localuser)
  431. {
  432. #if !defined( XP_WIN32 )
  433. if (localuser != NULL) {
  434. struct passwd* pw = getpwnam (localuser);
  435. if (pw == NULL) {
  436. fprintf (stderr, "getpwnam(%s) == NULL; errno %d",
  437. localuser, errno);
  438. fprintf (stderr, "\n");
  439. fflush (stderr);
  440. } else {
  441. if ( ! saved_uid_valid) saved_uid = geteuid();
  442. if ( ! saved_gid_valid) saved_gid = getegid();
  443. if (setgid (pw->pw_gid) == 0) {
  444. saved_gid_valid = 1;
  445. } else {
  446. fprintf (stderr, "setgid(%li) != 0; errno %d",
  447. (long)pw->pw_gid, errno);
  448. fprintf (stderr, "\n");
  449. fflush (stderr);
  450. }
  451. if (SETEUID (pw->pw_uid) == 0) {
  452. saved_uid_valid = 1;
  453. } else {
  454. fprintf (stderr, "seteuid(%li) != 0; errno %d",
  455. (long)pw->pw_uid, errno);
  456. fprintf (stderr, "\n");
  457. fflush (stderr);
  458. }
  459. }
  460. }
  461. return NULL;
  462. #else
  463. return NULL;
  464. #endif
  465. }
  466. DS_EXPORT_SYMBOL char*
  467. ds_become_localuser (char **ds_config)
  468. {
  469. #if !defined( XP_WIN32 )
  470. char* localuser = ds_get_value (ds_config, ds_get_var_name(DS_LOCALUSER), 0, 1);
  471. if (localuser != NULL) {
  472. char *rv = ds_become_localuser_name(localuser);
  473. free(localuser);
  474. return rv;
  475. }
  476. return NULL;
  477. #else
  478. return NULL;
  479. #endif
  480. }
  481. DS_EXPORT_SYMBOL char*
  482. ds_become_original (char **ds_config)
  483. {
  484. #if !defined( XP_WIN32 )
  485. if (saved_uid_valid) {
  486. if (SETEUID (saved_uid) == 0) {
  487. saved_uid_valid = 0;
  488. } else {
  489. fprintf (stderr, "seteuid(%li) != 0; errno %d<br>n",
  490. (long)saved_uid, errno);
  491. fflush (stderr);
  492. }
  493. }
  494. if (saved_gid_valid) {
  495. if (setgid (saved_gid) == 0) {
  496. saved_gid_valid = 0;
  497. } else {
  498. fprintf (stderr, "setgid(%li) != 0; errno %d<br>\n",
  499. (long)saved_gid, errno);
  500. fflush (stderr);
  501. }
  502. }
  503. return NULL;
  504. #else
  505. return NULL;
  506. #endif
  507. }
  508. /*
  509. * When a path containing a long filename is passed to system(), the call
  510. * fails. Therfore, we need to use the short version of the path, when
  511. * constructing the path to pass to system().
  512. */
  513. DS_EXPORT_SYMBOL char*
  514. ds_makeshort( char * filepath )
  515. {
  516. #if defined( XP_WIN32 )
  517. char *shortpath = malloc( MAX_PATH );
  518. DWORD dwStatus;
  519. if( shortpath )
  520. {
  521. dwStatus = GetShortPathName( filepath, shortpath, MAX_PATH );
  522. return( shortpath );
  523. }
  524. #endif
  525. return filepath;
  526. }
  527. /* returns 1 if string "searchstring" found in file "filename" */
  528. /* if found, returnstring is allocated and filled with the line */
  529. /* caller should release the memory */
  530. DS_EXPORT_SYMBOL int
  531. ds_search_file(char *filename, char *searchstring, char **returnstring)
  532. {
  533. struct stat finfo;
  534. FILE * sf;
  535. char big_line[BIG_LINE];
  536. if( filename == NULL )
  537. return 0;
  538. if( stat(filename, &finfo) != 0 ) /* successful */
  539. return 0;
  540. if( !(sf = fopen(filename, "r")) )
  541. return 0;
  542. while ( fgets(big_line, BIG_LINE, sf) ) {
  543. if( strstr( big_line, searchstring ) != NULL ) {
  544. *returnstring = (char *)malloc(strlen(big_line) + 1);
  545. if (NULL != *returnstring) {
  546. strcpy(*returnstring, big_line);
  547. }
  548. fclose(sf);
  549. return 1;
  550. }
  551. }
  552. fclose(sf);
  553. return 0;
  554. }
  555. /*
  556. * on linux when running as root, doing something like
  557. * system("date > out.log 2>&1") will fail, because of an
  558. * ambigious redirect. This works for /bin/sh, but not /bin/csh or /bin/tcsh
  559. *
  560. * using this would turn
  561. * system("date > out.log 2>&1");
  562. * into
  563. * system("/bin/sh/ -c \"date > out.log 2>&1\"")
  564. *
  565. */
  566. DS_EXPORT_SYMBOL void
  567. alter_startup_line(char *startup_line)
  568. {
  569. #if (defined Linux && !defined LINUX2_4)
  570. char temp_startup_line[BIG_LINE+40];
  571. PR_snprintf(temp_startup_line, sizeof(temp_startup_line), "/bin/sh -c \"%s\"", startup_line);
  572. PL_strncpyz(startup_line, temp_startup_line, BIG_LINE);
  573. #else
  574. /* do nothing */
  575. #endif /* Linux */
  576. }
  577. DS_EXPORT_SYMBOL void
  578. ds_send_error(char *errstr, int print_errno)
  579. {
  580. FILE *logfp;
  581. fprintf(stdout, "error%s%s\n", SEPARATOR, errstr);
  582. if (print_errno && errno)
  583. fprintf(stdout, "system_errno%s%d\n", SEPARATOR, errno);
  584. fflush(stdout);
  585. if ((logfp = get_logfp())) {
  586. fprintf(logfp, "error%s%s\n", SEPARATOR, errstr);
  587. if (print_errno && errno)
  588. fprintf(logfp, "system_errno%s%d\n", SEPARATOR, errno);
  589. fclose(logfp);
  590. }
  591. }
  592. DS_EXPORT_SYMBOL void
  593. ds_send_status(char *str)
  594. {
  595. FILE *logfp;
  596. fprintf(stdout, "[%s]: %s\n", ds_get_server_name(), str);
  597. fflush(stdout);
  598. if ((logfp = get_logfp())) {
  599. fprintf(logfp, "[%s]: %s\n", ds_get_server_name(), str);
  600. fclose(logfp);
  601. }
  602. }
  603. /* type and doexit are unused
  604. I'm not sure what type is supposed to be used for
  605. removed the doexit code because we don't want to
  606. exit abruptly anymore, we must exit by returning an
  607. exit code from the return in main()
  608. */
  609. static void
  610. report_error(int type, char *msg, char *details, int doexit)
  611. {
  612. char error[BIG_LINE*4] = {0};
  613. if (msg)
  614. {
  615. PL_strcatn(error, BIG_LINE*4, msg);
  616. PL_strcatn(error, BIG_LINE*4, SEPARATOR);
  617. }
  618. if (details)
  619. PL_strcatn(error, BIG_LINE*4, details);
  620. ds_send_error(error, 1);
  621. }
  622. DS_EXPORT_SYMBOL void
  623. ds_report_error(int type, char *msg, char *details)
  624. {
  625. /* richm - changed exit flag to 0 - we must not exit
  626. abruptly, we should instead exit by returning a code
  627. as the return value of main - this ensures that callers
  628. are properly notified of the status
  629. */
  630. report_error(type, msg, details, 0);
  631. }
  632. DS_EXPORT_SYMBOL void
  633. ds_report_warning(int type, char *msg, char *details)
  634. {
  635. report_error(type, msg, details, 0);
  636. }
  637. DS_EXPORT_SYMBOL void
  638. ds_show_message(const char *message)
  639. {
  640. FILE *logfp;
  641. printf("%s\n", message);
  642. fflush(stdout);
  643. if ((logfp = get_logfp())) {
  644. fprintf(logfp, "%s\n", message);
  645. fclose(logfp);
  646. }
  647. return;
  648. }
  649. DS_EXPORT_SYMBOL void
  650. ds_show_key_value(char *key, char *value)
  651. {
  652. FILE *logfp;
  653. printf("%s%s%s\n", key, SEPARATOR, value);
  654. if ((logfp = get_logfp())) {
  655. fprintf(logfp, "%s%s%s\n", key, SEPARATOR, value);
  656. fclose(logfp);
  657. }
  658. return;
  659. }
  660. /* Stolen from the Admin Server dsgw_escape_for_shell */
  661. DS_EXPORT_SYMBOL char *
  662. ds_escape_for_shell( char *s )
  663. {
  664. char *escaped;
  665. char tmpbuf[4];
  666. size_t x,l;
  667. if ( s == NULL ) {
  668. return( s );
  669. }
  670. l = 3 * strlen( s ) + 1;
  671. escaped = malloc( l );
  672. memset( escaped, 0, l );
  673. for ( x = 0; s[x]; x++ ) {
  674. if (( (unsigned char)s[x] & 0x80 ) == 0 ) {
  675. strncat( escaped, &s[x], 1 );
  676. } else {
  677. /* not an ASCII character - escape it */
  678. sprintf( tmpbuf, "\\%x", (unsigned)(((unsigned char)(s[x])) & 0xff) );
  679. strcat( escaped, tmpbuf );
  680. }
  681. }
  682. return( escaped );
  683. }
  684. DS_EXPORT_SYMBOL char *
  685. ds_system_errmsg(void)
  686. {
  687. static char static_error[BUFSIZ];
  688. char *lmsg = 0; /* Local message pointer */
  689. size_t msglen = 0;
  690. int sys_error = 0;
  691. #ifdef XP_WIN32
  692. LPTSTR sysmsg = 0;
  693. #endif
  694. /* Grab the OS error message */
  695. #ifdef XP_WIN32
  696. sys_error = GetLastError();
  697. #else
  698. sys_error = errno;
  699. #endif
  700. #if defined(XP_WIN32)
  701. msglen = FormatMessage(
  702. FORMAT_MESSAGE_FROM_SYSTEM|FORMAT_MESSAGE_ALLOCATE_BUFFER,
  703. NULL,
  704. GetLastError(),
  705. LOCALE_SYSTEM_DEFAULT,
  706. (LPTSTR)&sysmsg,
  707. 0,
  708. 0);
  709. if (msglen > 0)
  710. lmsg = sysmsg;
  711. SetLastError(0);
  712. #else
  713. lmsg = strerror(errno);
  714. errno = 0;
  715. #endif
  716. if (!lmsg)
  717. static_error[0] = 0;
  718. else
  719. {
  720. /* At this point lmsg points to something. */
  721. int min = 0;
  722. msglen = strlen(lmsg);
  723. min = msglen > BUFSIZ ? BUFSIZ : msglen;
  724. strncpy(static_error, lmsg, min-1);
  725. static_error[min-1] = 0;
  726. }
  727. #ifdef XP_WIN32
  728. /* NT's FormatMessage() dynamically allocated the msg; free it */
  729. if (sysmsg)
  730. LocalFree(sysmsg);
  731. #endif
  732. return static_error;
  733. }
  734. #ifndef MAXPATHLEN
  735. #define MAXPATHLEN 1024
  736. #endif
  737. enum {
  738. DB_DIRECTORY = 0,
  739. DB_LOGDIRECTORY,
  740. DB_CHANGELOGDIRECTORY,
  741. DB_HOME_DIRECTORY
  742. };
  743. static int
  744. is_fullpath(char *path)
  745. {
  746. int len;
  747. if (NULL == path || '\0' == *path)
  748. return 0;
  749. if (FILE_PATHSEP == *path) /* UNIX */
  750. return 1;
  751. len = strlen(path);
  752. if (len > 2)
  753. {
  754. if (':' == path[1] && ('/' == path[2] || '\\' == path[2])) /* Windows */
  755. return 1;
  756. }
  757. return 0;
  758. }
  759. static void
  760. rm_db_dirs(char *fullpath, DS_RM_RF_ERR_FUNC ds_rm_rf_err_func, void *arg)
  761. {
  762. FILE *fp = fopen(fullpath, "r");
  763. char buf[2][MAXPATHLEN];
  764. char *bufp, *nextbufp;
  765. char *retp;
  766. int readit = 0;
  767. if (fp == NULL)
  768. {
  769. ds_rm_rf_err_func(fullpath, "opening the config file", arg);
  770. return;
  771. }
  772. bufp = buf[0]; *bufp = '\0';
  773. nextbufp = buf[1]; *nextbufp = '\0';
  774. while (readit || (retp = fgets(bufp, MAXPATHLEN, fp)) != NULL)
  775. {
  776. int len = strlen(bufp);
  777. int type = -1;
  778. char *p, *q;
  779. if (strstr(bufp, "nsslapd-directory"))
  780. type = DB_DIRECTORY;
  781. else if (strstr(bufp, "nsslapd-db-home-directory"))
  782. type = DB_HOME_DIRECTORY;
  783. else if (strstr(bufp, "nsslapd-db-logdirectory"))
  784. type = DB_LOGDIRECTORY;
  785. else if (strstr(bufp, "nsslapd-changelogdir"))
  786. type = DB_CHANGELOGDIRECTORY;
  787. else
  788. {
  789. readit = 0;
  790. continue;
  791. }
  792. p = bufp + len;
  793. while ((retp = fgets(nextbufp, MAXPATHLEN, fp)) != NULL)
  794. {
  795. int thislen;
  796. if (*nextbufp == ' ')
  797. {
  798. thislen = strlen(nextbufp);
  799. len += thislen;
  800. if (len < MAXPATHLEN)
  801. {
  802. strncpy(p, nextbufp, thislen);
  803. p += thislen;
  804. }
  805. /* else too long as a path. ignore it */
  806. }
  807. else
  808. break;
  809. }
  810. if (retp == NULL) /* done */
  811. break;
  812. p = strchr(bufp, ':');
  813. if (p == NULL)
  814. {
  815. char *tmpp = bufp;
  816. bufp = nextbufp;
  817. nextbufp = tmpp;
  818. readit = 1;
  819. continue;
  820. }
  821. while (*(++p) == ' ') ;
  822. q = p + strlen(p) - 1;
  823. while (*q == ' ' || *q == '\t' || *q == '\n')
  824. q--;
  825. *(q+1) = '\0';
  826. switch (type)
  827. {
  828. case DB_DIRECTORY:
  829. case DB_LOGDIRECTORY:
  830. case DB_CHANGELOGDIRECTORY:
  831. if (is_fullpath(p))
  832. internal_rm_rf(p, ds_rm_rf_err_func, NULL);
  833. break;
  834. case DB_HOME_DIRECTORY:
  835. internal_rm_rf(p, ds_rm_rf_err_func, NULL);
  836. break;
  837. }
  838. }
  839. fclose(fp);
  840. }
  841. static char *
  842. get_dir_from_startslapd(char *loc, char *keyword)
  843. {
  844. char *returnstr = NULL;
  845. char *ptr = NULL;
  846. char *confdir = NULL;
  847. if (ds_search_file(loc, keyword, &returnstr) > 0 && returnstr) {
  848. ptr = strchr(returnstr, '=');
  849. if (NULL != ptr) {
  850. confdir = strdup(++ptr);
  851. }
  852. free(returnstr);
  853. }
  854. return confdir;
  855. }
  856. static char *
  857. get_dir_from_config(char *config_dir, char *config_attr)
  858. {
  859. char *configfile = NULL;
  860. char *returnstr = NULL;
  861. char *ptr = NULL;
  862. char *dir = NULL;
  863. configfile = PR_smprintf("%s%c%s", config_dir, FILE_PATHSEP, DS_CONFIG_FILE);
  864. if (configfile && ds_search_file(configfile, config_attr, &returnstr) > 0
  865. && returnstr) {
  866. ptr = strchr(returnstr, ':');
  867. if (NULL != ptr) {
  868. while (' ' == *ptr || '\t' == *ptr) ptr++;
  869. dir = strdup(ptr);
  870. }
  871. free(returnstr);
  872. PR_smprintf_free(configfile);
  873. }
  874. return dir;
  875. }
  876. /* this function will recursively remove a directory hierarchy from the file
  877. system, like "rm -rf"
  878. In order to handle errors, the user supplies a callback function. When an
  879. error occurs, the callback function is called with the file or directory name
  880. and the system errno. The callback function should return TRUE if it wants
  881. to continue or FALSE if it wants the remove aborted.
  882. The error callback should use PR_GetError and/or PR_GetOSError to
  883. determine the cause of the failure
  884. */
  885. /* you could locate db dirs non standard location
  886. we should remove them, as well.
  887. */
  888. static int
  889. internal_rm_rf(const char *path, DS_RM_RF_ERR_FUNC ds_rm_rf_err_func, void *arg)
  890. {
  891. struct PRFileInfo prfi;
  892. int retval = 0;
  893. if (PR_GetFileInfo(path, &prfi) != PR_SUCCESS) {
  894. if (!ds_rm_rf_err_func(path, "reading directory", arg)) {
  895. return 1;
  896. }
  897. }
  898. if (prfi.type == PR_FILE_DIRECTORY)
  899. {
  900. PRDir *dir;
  901. PRDirEntry *dirent;
  902. if (!(dir = PR_OpenDir(path))) {
  903. if (!ds_rm_rf_err_func(path, "opening directory", arg)) {
  904. return 1;
  905. }
  906. return 0;
  907. }
  908. while ((dirent = PR_ReadDir(dir, PR_SKIP_BOTH))) {
  909. char *fullpath = PR_smprintf("%s%c%s", path, FILE_PATHSEP, dirent->name);
  910. if (PR_GetFileInfo(fullpath, &prfi) != PR_SUCCESS) {
  911. if (!ds_rm_rf_err_func(fullpath, "reading file", arg)) {
  912. PR_smprintf_free(fullpath);
  913. PR_CloseDir(dir);
  914. return 1;
  915. } /* else just continue */
  916. } else if (prfi.type == PR_FILE_DIRECTORY) {
  917. retval = internal_rm_rf(fullpath, ds_rm_rf_err_func, arg);
  918. if (retval) { /* non zero return means stop */
  919. PR_smprintf_free(fullpath);
  920. break;
  921. }
  922. } else {
  923. /* FHS changes the directory structure.
  924. * Config dir is no longer in the instance dir.
  925. * The info should be found in start-slapd,
  926. * therefore get the path from the file here.
  927. */
  928. if (0 == strcmp(dirent->name, "start-slapd")) {
  929. char *config_dir = ds_get_config_dir();
  930. char *run_dir = ds_get_run_dir();
  931. if (NULL == config_dir || '\0' == *config_dir) {
  932. config_dir = get_dir_from_startslapd(fullpath, DS_CONFIG_DIR);
  933. }
  934. if (NULL == run_dir || '\0' == *run_dir) {
  935. char *ptr = NULL;
  936. run_dir = get_dir_from_startslapd(fullpath, PIDFILE);
  937. ptr = strrchr(run_dir, FILE_PATHSEP);
  938. if (NULL != ptr) {
  939. *ptr = '\0'; /* equiv to dirname */
  940. }
  941. }
  942. if (NULL != run_dir) {
  943. internal_rm_rf(run_dir, ds_rm_rf_err_func, NULL);
  944. free(run_dir);
  945. }
  946. if (NULL != config_dir) {
  947. char *lock_dir = get_dir_from_config(config_dir, DS_CONFIG_LOCKDIR);
  948. char *err_log = get_dir_from_config(config_dir, DS_CONFIG_ERRLOG);
  949. if (NULL != lock_dir) {
  950. internal_rm_rf(lock_dir, ds_rm_rf_err_func, NULL);
  951. free(lock_dir);
  952. }
  953. if (NULL != err_log) {
  954. char *ptr = strrchr(err_log, FILE_PATHSEP);
  955. if (NULL != ptr) {
  956. *ptr = '\0'; /* equiv to 'dirname' */
  957. internal_rm_rf(err_log, ds_rm_rf_err_func, NULL);
  958. }
  959. free(err_log);
  960. }
  961. /* removing db dirs */
  962. rm_db_dirs(config_dir, ds_rm_rf_err_func, arg);
  963. /* removing config dir */
  964. internal_rm_rf(config_dir, ds_rm_rf_err_func, NULL);
  965. }
  966. }
  967. /*
  968. * When the file is the config file,
  969. * check if db dir is in the instance dir or not.
  970. * If db dir exists in the instance dir, it's an old structure.
  971. * Let's clean the old db here, as well.
  972. */
  973. if (0 == strcmp(dirent->name, DS_CONFIG_FILE)) {
  974. rm_db_dirs(fullpath, ds_rm_rf_err_func, arg);
  975. }
  976. if (PR_Delete(fullpath) != PR_SUCCESS) {
  977. if (!ds_rm_rf_err_func(fullpath, "deleting file", arg)) {
  978. PR_smprintf_free(fullpath);
  979. PR_CloseDir(dir);
  980. return 1;
  981. }
  982. }
  983. }
  984. PR_smprintf_free(fullpath);
  985. }
  986. PR_CloseDir(dir);
  987. if (PR_RmDir(path) != PR_SUCCESS) {
  988. if (!ds_rm_rf_err_func(path, "removing directory", arg)) {
  989. retval = 1;
  990. }
  991. }
  992. }
  993. return retval;
  994. }
  995. static int
  996. default_err_func(const char *path, const char *op, void *arg)
  997. {
  998. PRInt32 errcode = PR_GetError();
  999. char *msg;
  1000. const char *errtext;
  1001. if (!errcode || (errcode == PR_UNKNOWN_ERROR)) {
  1002. errcode = PR_GetOSError();
  1003. errtext = ds_system_errmsg();
  1004. } else {
  1005. errtext = PR_ErrorToString(errcode, PR_LANGUAGE_I_DEFAULT);
  1006. }
  1007. msg = PR_smprintf("%s %s: error code %d (%s)", op, path, errcode, errtext);
  1008. ds_send_error(msg, 0);
  1009. PR_smprintf_free(msg);
  1010. return 1; /* just continue */
  1011. }
  1012. /* dir: instance dir, e.g., "$NETSITE_ROOT/slapd-<id>" */
  1013. DS_EXPORT_SYMBOL int
  1014. ds_rm_rf(const char *dir, DS_RM_RF_ERR_FUNC ds_rm_rf_err_func, void *arg)
  1015. {
  1016. struct PRFileInfo prfi;
  1017. if (!dir) {
  1018. ds_send_error("Could not remove NULL directory name", 1);
  1019. return 1;
  1020. }
  1021. if (!ds_rm_rf_err_func) {
  1022. ds_rm_rf_err_func = default_err_func;
  1023. }
  1024. if (PR_GetFileInfo(dir, &prfi) != PR_SUCCESS) {
  1025. if (ds_rm_rf_err_func(dir, "reading directory", arg)) {
  1026. return 0;
  1027. } else {
  1028. return 1;
  1029. }
  1030. }
  1031. if (prfi.type != PR_FILE_DIRECTORY) {
  1032. char *msg = PR_smprintf("Cannot remove directory %s because it is not a directory", dir);
  1033. ds_send_error(msg, 0);
  1034. PR_smprintf_free(msg);
  1035. return 1;
  1036. }
  1037. return internal_rm_rf(dir, ds_rm_rf_err_func, arg);
  1038. }
  1039. DS_EXPORT_SYMBOL int
  1040. ds_remove_reg_key(void *base, const char *format, ...)
  1041. {
  1042. int rc = 0;
  1043. #ifdef XP_WIN32
  1044. int retries = 3;
  1045. HKEY hkey = (HKEY)base;
  1046. char *key;
  1047. va_list ap;
  1048. va_start(ap, format);
  1049. key = PR_vsmprintf(format, ap);
  1050. va_end(ap);
  1051. do {
  1052. if (ERROR_SUCCESS != RegDeleteKey(hkey, key)) {
  1053. rc = GetLastError();
  1054. if (rc == ERROR_BADKEY || rc == ERROR_CANTOPEN ||
  1055. rc == ERROR_CANTREAD ||
  1056. rc == ERROR_CANTWRITE || rc == ERROR_KEY_DELETED ||
  1057. rc == ERROR_ALREADY_EXISTS || rc == ERROR_NO_MORE_FILES) {
  1058. rc = 0; /* key already deleted - no error */
  1059. } else if ((retries > 1) && (rc == ERROR_IO_PENDING)) {
  1060. /* the key is busy - lets wait and try again */
  1061. PR_Sleep(PR_SecondsToInterval(3));
  1062. retries--;
  1063. } else {
  1064. char *errmsg = PR_smprintf("Could not remove registry key %s - error %d (%s)",
  1065. key, rc, ds_system_errmsg());
  1066. ds_send_error(errmsg, 0);
  1067. PR_smprintf_free(errmsg);
  1068. break; /* no retry, just fail */
  1069. }
  1070. }
  1071. } while (rc && retries);
  1072. PR_smprintf_free(key);
  1073. #endif
  1074. return rc;
  1075. }