dsalib_util.c 28 KB

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