+
+static void cleanup_old_files()
+{
+ DIR* dp;
+ struct dirent *entry, *result;
+ int rc, name_max;
+ int my_name_len = strlen(my_name);
+ int len = strlen(director->working_directory);
+ POOLMEM *cleanup = get_pool_memory(PM_MESSAGE);
+ POOLMEM *basename = get_pool_memory(PM_MESSAGE);
+ regex_t preg1;
+ char prbuf[500];
+ const int nmatch = 30;
+ regmatch_t pmatch[nmatch];
+ berrno be;
+
+ /* Exclude spaces and look for .mail, .tmp or .restore.xx.bsr files */
+ const char *pat1 = "^[^ ]+\\.(restore\\.[^ ]+\\.bsr|mail|tmp)$";
+
+ /* Setup working directory prefix */
+ pm_strcpy(basename, director->working_directory);
+ if (len > 0 && !IsPathSeparator(director->working_directory[len-1])) {
+ pm_strcat(basename, "/");
+ }
+
+ /* Compile regex expressions */
+ rc = regcomp(&preg1, pat1, REG_EXTENDED);
+ if (rc != 0) {
+ regerror(rc, &preg1, prbuf, sizeof(prbuf));
+ Pmsg2(000, _("Could not compile regex pattern \"%s\" ERR=%s\n"),
+ pat1, prbuf);
+ goto get_out2;
+ }
+
+ name_max = pathconf(".", _PC_NAME_MAX);
+ if (name_max < 1024) {
+ name_max = 1024;
+ }
+
+ if (!(dp = opendir(director->working_directory))) {
+ berrno be;
+ Pmsg2(000, "Failed to open working dir %s for cleanup: ERR=%s\n",
+ director->working_directory, be.bstrerror());
+ goto get_out1;
+ return;
+ }
+
+ entry = (struct dirent *)malloc(sizeof(struct dirent) + name_max + 1000);
+ while (1) {
+ if ((readdir_r(dp, entry, &result) != 0) || (result == NULL)) {
+ break;
+ }
+ /* Exclude any name with ., .., not my_name or containing a space */
+ if (strcmp(result->d_name, ".") == 0 || strcmp(result->d_name, "..") == 0 ||
+ strncmp(result->d_name, my_name, my_name_len) != 0) {
+ Dmsg1(500, "Skipped: %s\n", result->d_name);
+ continue;
+ }
+
+ /* Unlink files that match regexes */
+ if (regexec(&preg1, result->d_name, nmatch, pmatch, 0) == 0) {
+ pm_strcpy(cleanup, basename);
+ pm_strcat(cleanup, result->d_name);
+ Dmsg1(100, "Unlink: %s\n", cleanup);
+ unlink(cleanup);
+ }
+ }
+
+ free(entry);
+ closedir(dp);
+/* Be careful to free up the correct resources */
+get_out1:
+ regfree(&preg1);
+get_out2:
+ free_pool_memory(cleanup);
+ free_pool_memory(basename);
+}