FOSSology  4.7.1
Open Source License Compliance by Open Source Software
utils.c
Go to the documentation of this file.
1 /*
2  SPDX-FileCopyrightText: © 2011-2013 Hewlett-Packard Development Company, L.P.
3  SPDX-FileContributor: Kaushlendra Pratap <kaushlendra-pratap.singh@siemens.com>
4 
5  SPDX-License-Identifier: GPL-2.0-only
6 */
12 #include "ununpack.h"
13 #include "externs.h"
14 #include "regex.h"
15 
19 enum BITS {
20  BITS_PROJECT = 27,
21  BITS_ARTIFACT = 28,
22  BITS_CONTAINER = 29
23 };
24 
28 const char* SCM_REGEX = "/\\.git|\\.hg|\\.bzr|CVS/ROOT|\\.svn/";
29 
30 
31 
41 int IsInflatedFile(char *FileName, int InflateSize)
42 {
43  int result = 0;
44  char FileNameParent[PATH_MAX];
45  struct stat st, stParent;
46  memcpy(FileNameParent, FileName, sizeof(FileNameParent));
47  FileNameParent[PATH_MAX-1] = 0;
48  char *lastSlashPos = strrchr(FileNameParent, '/');
49  if (NULL != lastSlashPos)
50  {
51  /* get the parent container,
52  e.g. for the file ./10g.tar.bz.dir/10g.tar, partent file is ./10g.tar.bz.dir
53  */
54  FileNameParent[lastSlashPos - FileNameParent] = '\0';
55  if (!strcmp(FileNameParent + strlen(FileNameParent) - 4, ".dir"))
56  {
57  /* get the parent file, must be one file
58  e.g. for the file ./10g.tar.bz.dir/10g.tar, partent file is ./10g.tar.bz
59  */
60  FileNameParent[strlen(FileNameParent) - 4] = '\0';
61 
62  /* Ensure parent and child files exist and can be stated */
63  if (stat(FileNameParent, &stParent) != 0 || stat(FileName, &st) != 0)
64  {
65  return 0;
66  }
67 
68  /* Guard against division by zero */
69  if(S_ISREG(stParent.st_mode) && stParent.st_size > 0 &&
70  (st.st_size/stParent.st_size > InflateSize))
71  {
72  result = 1;
73  }
74  }
75  }
76  return result;
77 }
78 
79 
85 void SafeExit (int rc)
86 {
87  if (pgConn) PQfinish(pgConn);
89  exit(rc);
90 } /* SafeExit() */
91 
98 void RemovePostfix(char *Name)
99 {
100  if (NULL == Name) return; // exception
101  // keep the part before the last dot
102  char *LastDot = strrchr(Name, '.');
103  if (LastDot == NULL) return;
104  // if the part after the last dot is number, do not get rid of the postfix
105  if ((LastDot[1]>='0')&&(LastDot[1]<='9')) return;
106  if (LastDot) *LastDot = 0;
107 }
108 
116 void InitCmd ()
117 {
118  int i;
119  PGresult *result;
120 
121  /* clear existing indexes */
122  for(i=0; CMD[i].Magic != NULL; i++)
123  {
124  CMD[i].DBindex = -1; /* invalid value */
125  }
126 
127  if (!pgConn) return; /* DB must be open */
128 
129  /* Load them up! */
130  for(i=0; CMD[i].Magic != NULL; i++)
131  {
132  if (CMD[i].Magic[0] == '\0') continue;
133  ReGetCmd:
134  memset(SQL,'\0',MAXSQL);
135  snprintf(SQL,MAXSQL,"SELECT mimetype_pk FROM mimetype WHERE mimetype_name = '%s';",CMD[i].Magic);
136  result = PQexec(pgConn, SQL); /* SELECT */
137  if (fo_checkPQresult(pgConn, result, SQL, __FILE__, __LINE__)) SafeExit(1);
138  else if (PQntuples(result) > 0) /* if there is a value */
139  {
140  CMD[i].DBindex = atol(PQgetvalue(result,0,0));
141  PQclear(result);
142  }
143  else /* No value, so add it */
144  {
145  PQclear(result);
146  memset(SQL,'\0',MAXSQL);
147  snprintf(SQL,MAXSQL,"INSERT INTO mimetype (mimetype_name) VALUES ('%s');",CMD[i].Magic);
148  result = PQexec(pgConn, SQL); /* INSERT INTO mimetype */
149  if (fo_checkPQcommand(pgConn, result, SQL, __FILE__ ,__LINE__)) SafeExit(2);
150  else
151  {
152  PQclear(result);
153  goto ReGetCmd;
154  }
155  }
156  }
157 } /* InitCmd() */
158 
159 
173 int TaintString (char *Dest, int DestLen,
174  char *Src, int ProtectQuotes, char *Replace)
175 {
176  int i,d;
177  char Temp[FILENAME_MAX];
178 
179  memset(Dest,'\0',DestLen);
180  i=0;
181  d=0;
182  while((Src[i] != '\0') && (d < DestLen))
183  {
184  /* save */
185  if (ProtectQuotes && (Src[i]=='\''))
186  {
187  if (d+4 >= DestLen) return(1);
188  strcpy(Dest+d,"'\\''"); /* unquote, raw quote, requote (for shells) */
189  d+=4;
190  i++;
191  }
192  else if (!ProtectQuotes && strchr("\\",Src[i]))
193  {
194  if (d+2 >= DestLen) return(1);
195  Dest[d] = '\\'; d++;
196  Dest[d] = Src[i]; d++;
197  i++;
198  }
199  else if (Replace && (Src[i]=='%') && (Src[i+1]=='s'))
200  {
201  TaintString(Temp,sizeof(Temp),Replace,1,NULL);
202  if (d+strlen(Temp) >= DestLen) return(1);
203  strcpy(Dest+d,Temp);
204  d = strlen(Dest);
205  i += 2;
206  }
207  else
208  {
209  Dest[d] = Src[i];
210  d++;
211  i++;
212  }
213  }
214  return(0);
215 } /* TaintString() */
216 
225 int Prune (char *Fname, struct stat Stat)
226 {
227  if (!Fname || (Fname[0]=='\0')) return(1); /* not a good name */
228  /* check file type */
229  if (S_ISLNK(Stat.st_mode) || S_ISCHR(Stat.st_mode) ||
230  S_ISBLK(Stat.st_mode) || S_ISFIFO(Stat.st_mode) ||
231  S_ISSOCK(Stat.st_mode))
232  {
233  unlink(Fname);
234  return(1);
235  }
236  /* check hard-link count */
237  if (S_ISREG(Stat.st_mode) && (Stat.st_nlink > 1))
238  {
239  unlink(Fname);
240  return(1);
241  }
242  /* check zero-length files */
243  if (S_ISREG(Stat.st_mode) && (Stat.st_size == 0))
244  {
245  unlink(Fname);
246  return(1);
247  }
248  return(0);
249 } /* Prune() */
250 
256 int MkDirs (char *Fname)
257 {
258  char Dir[FILENAME_MAX+1];
259  int i;
260  int rc=0;
261  struct stat Status;
262 
263  memset(Dir,'\0',sizeof(Dir));
264  strcpy(Dir,Fname);
265  for(i=1; Dir[i] != '\0'; i++)
266  {
267  if (Dir[i] == '/')
268  {
269  Dir[i]='\0';
270  /* Only mkdir if it does not exist */
271  if (stat(Dir,&Status) == 0)
272  {
273  if (!S_ISDIR(Status.st_mode))
274  {
275  LOG_FATAL("'%s' is not a directory.",Dir);
276  SafeExit(3);
277  }
278  }
279  else /* else, it does not exist */
280  {
281  rc=mkdir(Dir,0770); /* create this path segment + Setgid */
282  if (rc && (errno == EEXIST)) rc=0;
283  if (rc)
284  {
285  LOG_FATAL("mkdir %s' failed, error: %s",Dir,strerror(errno));
286  SafeExit(4);
287  }
288  chmod(Dir,02770);
289  } /* else */
290  Dir[i]='/';
291  }
292  }
293  rc = mkdir(Dir,0770); /* create whatever is left */
294  if (rc && (errno == EEXIST)) rc=0;
295  if (rc)
296  {
297  LOG_FATAL("mkdir %s' failed, error: %s",Dir,strerror(errno));
298  SafeExit(5);
299  }
300  chmod(Dir,02770);
301  return(rc);
302 } /* MkDirs() */
303 
311 int MkDir (char *Fname)
312 {
313  if (mkdir(Fname,0770))
314  {
315  if (errno == EEXIST) return(0); /* failed because it exists is ok */
316  return(MkDirs(Fname));
317  }
318  chmod(Fname,02770);
319  return(0);
320 } /* MkDir() */
321 
327 int IsDir (char *Fname)
328 {
329  struct stat Stat;
330  int rc;
331  if (!Fname || (Fname[0]=='\0')) return(0); /* not a directory */
332  rc = lstat(Fname,&Stat);
333  if (rc != 0) return(0); /* bad name */
334  return(S_ISDIR(Stat.st_mode));
335 } /* IsDir() */
336 
343 int IsFile (char *Fname, int Link)
344 {
345  struct stat Stat;
346  int rc;
347  if (!Fname || (Fname[0]=='\0')) return(0); /* not a directory */
348  if (Link) rc = stat(Fname,&Stat);
349  else rc = lstat(Fname,&Stat);
350  if (rc != 0) return(0); /* bad name */
351  return(S_ISREG(Stat.st_mode));
352 } /* IsFile() */
353 
354 
364 int ReadLine (FILE *Fin, char *Line, int MaxLine)
365 {
366  int C;
367  int i;
368 
369  if (!Fin) return(-1);
370  if (feof(Fin)) return(-1);
371  memset(Line,'\0',MaxLine);
372  i=0;
373  C=fgetc(Fin);
374  if (C<0) return(-1);
375  while(!feof(Fin) && (C>=0) && (i<MaxLine))
376  {
377  if (C=='\n')
378  {
379  if (i > 0) return(i);
380  /* if it is a blank line, then ignore it. */
381  }
382  else
383  {
384  Line[i]=C;
385  i++;
386  }
387  C=fgetc(Fin);
388  }
389  return(i);
390 } /* ReadLine() */
391 
401 int IsExe (char *Exe, int Quiet)
402 {
403  char *Path;
404  int i,j;
405  char TestCmd[FILENAME_MAX];
406 
407  Path = getenv("PATH");
408  if (!Path) return(0); /* nope! */
409 
410  memset(TestCmd,'\0',sizeof(TestCmd));
411  j=0;
412  for(i=0; (j<FILENAME_MAX-1) && (Path[i] != '\0'); i++)
413  {
414  if (Path[i]==':')
415  {
416  if ((j>0) && (TestCmd[j-1] != '/')) strcat(TestCmd,"/");
417  strcat(TestCmd,Exe);
418  if (IsFile(TestCmd,1)) return(1); /* found it! */
419  /* missed */
420  memset(TestCmd,'\0',sizeof(TestCmd));
421  j=0;
422  }
423  else
424  {
425  TestCmd[j]=Path[i];
426  j++;
427  }
428  }
429 
430  /* check last path element */
431  if (j>0)
432  {
433  if (TestCmd[j-1] != '/') strcat(TestCmd,"/");
434  strcat(TestCmd,Exe);
435  if (IsFile(TestCmd,1)) return(1); /* found it! */
436  }
437  if (!Quiet) LOG_WARNING("%s not found in $PATH",Exe);
438  return(0); /* not in path */
439 } /* IsExe() */
440 
448 int CopyFile (char *Src, char *Dst)
449 {
450  int Fin, Fout;
451  unsigned char * Mmap;
452  int LenIn, LenOut, Wrote;
453  struct stat Stat;
454  int rc=0;
455  char *Slash;
456 
457  if (lstat(Src,&Stat) == -1) return(1);
458  LenIn = Stat.st_size;
459  if (!S_ISREG(Stat.st_mode)) return(1);
460 
461  Fin = open(Src,O_RDONLY);
462  if (Fin == -1)
463  {
464  LOG_FATAL("Unable to open source '%s'",Src);
465  SafeExit(22);
466  }
467 
468  /* Make sure the directory exists for copying */
469  Slash = strrchr(Dst,'/');
470  if (Slash && (Slash != Dst))
471  {
472  Slash[0]='\0';
473  MkDir(Dst);
474  Slash[0]='/';
475  }
476 
477  Fout = open(Dst,O_WRONLY|O_CREAT|O_TRUNC,Stat.st_mode);
478  if (Fout == -1)
479  {
480  LOG_FATAL("Unable to open target '%s'",Dst);
481  close(Fin);
482  SafeExit(23);
483  }
484 
485  /* load the source file */
486  Mmap = mmap(0,LenIn,PROT_READ,MAP_PRIVATE,Fin,0);
487  if (Mmap == MAP_FAILED)
488  {
489  LOG_FATAL("pfile %s Unable to process file.",Pfile_Pk);
490  LOG_WARNING("pfile %s Mmap failed during copy.",Pfile_Pk);
491  rc=1;
492  goto CopyFileEnd;
493  }
494 
495  /* write file at maximum speed */
496  LenOut=0;
497  Wrote=0;
498  while((LenOut < LenIn) && (Wrote >= 0))
499  {
500  Wrote = write(Fout,Mmap+LenOut,LenIn-LenOut);
501  LenOut += Wrote;
502  }
503 
504  /* clean up */
505  munmap(Mmap,LenIn);
506  CopyFileEnd:
507  close(Fout);
508  close(Fin);
509  return(rc);
510 } /* CopyFile() */
511 
512 
518 {
519  int i;
520  int Pid;
521  int Status;
522 
523  Pid = wait(&Status);
524  if (Pid <= 0) return(-1); /* no pending children, or call failed */
525 
526  /* find the child! */
527  for(i=0; (i<MAXCHILD) && (Queue[i].ChildPid != Pid); i++) ;
528  if (Queue[i].ChildPid != Pid)
529  {
530  /* child not found */
531  return(-1);
532  }
533 
534  /* check if the child had an error */
535  if (!WIFEXITED(Status))
536  {
537  if (!ForceContinue)
538  {
539  LOG_FATAL("Child had unnatural death");
540  SafeExit(6);
541  }
542  Queue[i].ChildCorrupt=1;
543  Status = -1;
544  }
545  else Status = WEXITSTATUS(Status);
546  if (Status != 0)
547  {
548  if (!ForceContinue)
549  {
550  LOG_FATAL("Child had non-zero status: %d",Status);
551  LOG_FATAL("Child was to recurse on %s",Queue[i].ChildRecurse);
552  SafeExit(10);
553  }
554  Queue[i].ChildCorrupt=1;
555  }
556 
557  /* Finish record */
558  Queue[i].ChildStatus = Status;
559  Queue[i].ChildPid = 0;
560  Queue[i].PI.EndTime = time(NULL);
561  return(i);
562 } /* ParentWait() */
563 
564 /***************************************************************************/
565 /***************************************************************************/
566 /*** Command Processing ***/
567 /***************************************************************************/
568 /***************************************************************************/
569 
575 void CheckCommands (int Show)
576 {
577  int i;
578  int rc;
579 
580  /* Check for CMD_PACK and CMD_ARC tools */
581  for(i=0; CMD[i].Cmd != NULL; i++)
582  {
583  if (CMD[i].Cmd[0] == '\0') continue; /* no command to check */
584  switch(CMD[i].Type)
585  {
586  case CMD_PACK:
587  case CMD_RPM:
588  case CMD_DEB:
589  case CMD_ARC:
590  case CMD_AR:
591  case CMD_PARTITION:
592  case CMD_ZSTD:
593  case CMD_LZIP:
594  CMD[i].Status = IsExe(CMD[i].Cmd,Quiet);
595  break;
596  default:
597  ; /* do nothing */
598  }
599  }
600 
601  /* Check for CMD_ISO */
602  rc = ( IsExe("isoinfo",Quiet) && IsExe("grep",Quiet) );
603  for(i=0; CMD[i].Cmd != NULL; i++)
604  {
605  if (CMD[i].Type == CMD_ISO) CMD[i].Status = rc;
606  }
607 
608  /* Check for CMD_DISK */
609  rc = ( IsExe("icat",Quiet) && IsExe("fls",Quiet) );
610  for(i=0; CMD[i].Cmd != NULL; i++)
611  {
612  if (CMD[i].Type == CMD_DISK) CMD[i].Status = rc;
613  }
614 } /* CheckCommands() */
615 
628 int IsPdfProcessable(const char *QuotedPath)
629 {
630  char InfoCmd[FILENAME_MAX + 64];
631  int rc;
632 
633  if (!IsExe("pdfinfo",1))
634  {
635  /* pdfinfo not installed: cannot pre-validate, let pdftotext try. */
636  return(1);
637  }
638 
639  snprintf(InfoCmd,sizeof(InfoCmd),"pdfinfo %s >/dev/null 2>&1",QuotedPath);
640  rc = system(InfoCmd);
641  if (WIFEXITED(rc)) rc = WEXITSTATUS(rc);
642  else rc = -1;
643 
644  if (rc != 0)
645  {
646  LOG_ERROR("Skipping pdftotext, PDF is encrypted/corrupt (pdfinfo rc=%d): %s",
647  rc,QuotedPath);
648  return(0);
649  }
650  return(1);
651 } /* IsPdfProcessable() */
652 
667 int RunCommand (char *Cmd, char *CmdPre, char *File, char *CmdPost,
668  char *Out, char *Where)
669 {
670  char Cmd1[FILENAME_MAX * 5];
671  char ResolvedPath[FILENAME_MAX * 2];
672  char CWD[FILENAME_MAX];
673  int rc;
674  char TempPre[FILENAME_MAX];
675  char TempFile[FILENAME_MAX];
676  char TempCwd[FILENAME_MAX];
677  char TempPost[FILENAME_MAX];
678 
679  if (!Cmd) return(0); /* nothing to do */
680 
681  if (Verbose)
682  {
683  if (Where && Out)
684  {
685  LOG_DEBUG("Extracting %s: %s > %s",Cmd,File,Out);
686  }
687  else
688  {
689  if (Where)
690  {
691  LOG_DEBUG("Extracting %s in %s: %s\n",Cmd,Where,File);
692  }
693  else
694  {
695  LOG_DEBUG("Testing %s: %s\n",Cmd,File);
696  }
697  }
698  }
699 
700  if (getcwd(CWD,sizeof(CWD)) == NULL)
701  {
702  LOG_FATAL("directory name longer than %d characters",(int)sizeof(CWD));
703  SafeExit(24);
704  }
705  if (Verbose > 1){ LOG_DEBUG("CWD: %s\n",CWD);}
706  if ((Where != NULL) && (Where[0] != '\0'))
707  {
708  if (chdir(Where) != 0)
709  {
710  MkDir(Where);
711  if (chdir(Where) != 0)
712  {
713  LOG_FATAL("Unable to access directory '%s'",Where);
714  SafeExit(25);
715  }
716  }
717  if (Verbose > 1) LOG_DEBUG("CWD: %s",Where);
718  }
719 
720  /* CMD: Cmd CmdPre 'CWD/File' CmdPost */
721  /* CmdPre and CmdPost may contain a "%s" */
722  memset(Cmd1,'\0',sizeof(Cmd1));
723  if (TaintString(TempPre,FILENAME_MAX,CmdPre,0,Out) ||
724  TaintString(TempFile,FILENAME_MAX,File,1,Out) ||
725  TaintString(TempPost,FILENAME_MAX,CmdPost,0,Out))
726  {
727  return(-1);
728  }
729  if (File[0] != '/')
730  {
731  TaintString(TempCwd,FILENAME_MAX,CWD,1,Out);
732  snprintf(Cmd1,sizeof(Cmd1),"%s %s '%s/%s' %s",
733  Cmd,TempPre,TempCwd,TempFile,TempPost);
734  snprintf(ResolvedPath,sizeof(ResolvedPath),"'%s/%s'",TempCwd,TempFile);
735  }
736  else
737  {
738  snprintf(Cmd1,sizeof(Cmd1),"%s %s '%s' %s",
739  Cmd,TempPre,TempFile,TempPost);
740  snprintf(ResolvedPath,sizeof(ResolvedPath),"'%s'",TempFile);
741  }
742 
743  if (strcmp(Cmd,"pdftotext")==0)
744  {
745  char TimedCmd[FILENAME_MAX * 5 + 96];
746  long CmdMemLimitKB;
747  char *CmdMemLimitEnv;
748  int CmdTimeout = DEFAULT_PDF_CMD_TIMEOUT;
749  char *CmdTimeoutEnv = getenv("FOSSOLOGY_CMD_TIMEOUT");
750  if (CmdTimeoutEnv && atoi(CmdTimeoutEnv) > 0) CmdTimeout = atoi(CmdTimeoutEnv);
751 
752  /* Structurally validate the PDF (encryption/corruption) before spending
753  * time and memory on pdftotext. */
754  if (!IsPdfProcessable(ResolvedPath))
755  {
756  if (Out && Out[0]) unlink(Out);
757  if (chdir(CWD) != 0)
758  LOG_ERROR("Unable to change directory to %s", CWD);
759  return(0);
760  }
761 
762  CmdMemLimitEnv = getenv("FOSSOLOGY_CMD_MEM_LIMIT_KB");
763  if (CmdMemLimitEnv && atol(CmdMemLimitEnv) > 0)
764  CmdMemLimitKB = atol(CmdMemLimitEnv);
765  else
766  CmdMemLimitKB = DEFAULT_CMD_MEM_LIMIT_KB;
767 
768  if (CmdMemLimitKB > 0)
769  snprintf(TimedCmd,sizeof(TimedCmd),"ulimit -v %ld 2>/dev/null; timeout -k 10 %ds %s",
770  CmdMemLimitKB,CmdTimeout,Cmd1);
771  else
772  snprintf(TimedCmd,sizeof(TimedCmd),"timeout -k 10 %ds %s",CmdTimeout,Cmd1);
773 
774  int Killed = 0;
775  rc = system(TimedCmd);
776  if (WIFSIGNALED(rc))
777  {
778  LOG_ERROR("Process killed by signal (%d), skipping file: %s",WTERMSIG(rc),Cmd1);
779  rc = -1;
780  Killed = 1;
781  }
782  else
783  {
784  if (WIFEXITED(rc)) rc = WEXITSTATUS(rc);
785  else rc=-1;
786  if (rc == 124 || rc == 137)
787  {
788  LOG_ERROR("Command killed (timeout %ds or memory limit), skipping file: %s",CmdTimeout,Cmd1);
789  Killed = 1;
790  }
791  }
792  /* pdftotext streams its text output as it parses; a killed run leaves a
793  * truncated file that would be scanned as if complete. Drop it. */
794  if (Killed && Out && Out[0]) unlink(Out);
795  }
796  else
797  {
798  rc = system(Cmd1);
799  if (WIFSIGNALED(rc))
800  {
801  LOG_ERROR("Process killed by signal (%d): %s",WTERMSIG(rc),Cmd1);
802  SafeExit(8);
803  }
804  if (WIFEXITED(rc)) rc = WEXITSTATUS(rc);
805  else rc=-1;
806  }
807  if (Verbose) LOG_DEBUG("in %s -- %s ; rc=%d",Where,Cmd1,rc);
808 
809  if(chdir(CWD) != 0)
810  LOG_ERROR("Unable to change directory to %s", CWD);
811  if (Verbose > 1) LOG_DEBUG("CWD: %s",CWD);
812  return(rc);
813 } /* RunCommand() */
814 
815 
822 {
823  MagicCookie = magic_open(MAGIC_MIME);
824  if (MagicCookie == NULL)
825  {
826  LOG_FATAL("Failed to initialize magic cookie");
827  SafeExit(9);
828  }
829  return magic_load(MagicCookie,NULL);
830 }
831 
840 {
841  /* Set .dsc file magic as application/x-debian-source */
842  char *pExt;
843  FILE *fp;
844  char line[500];
845  int j;
846  char c;
847 
848  pExt = strrchr(Filename, '.');
849  if ( pExt != NULL)
850  {
851  if (strcmp(pExt, ".dsc")==0)
852  {
853  /* read the first 500 characters of the file to verify that
854  * it really is a debian source file
855  */
856  if ((fp = fopen(Filename, "r")) == NULL) return 0;
857  j=0;
858  while ((c = fgetc(fp)) != EOF && j < 500 ){
859  line[j]=c;
860  j++;
861  }
862  fclose(fp);
863  if ((strstr(line, "-----BEGIN PGP SIGNED MESSAGE-----") && strstr(line,"Source:")) ||
864  (strstr(line, "Format:") && strstr(line, "Source:") && strstr(line, "Version:")))
865  {
866  return 1;
867  }
868  }
869  }
870  return 0;
871 }
872 
883 {
884  unsigned char hdr[6];
885  FILE *fp;
886  size_t n;
887 
888  if ((fp = fopen(Filename, "rb")) == NULL) return 0;
889  n = fread(hdr, 1, sizeof(hdr), fp);
890  fclose(fp);
891  if (n < 2) return 0;
892  /* binary cpio, either byte order */
893  if ((hdr[0] == 0xC7 && hdr[1] == 0x71) || (hdr[0] == 0x71 && hdr[1] == 0xC7))
894  return 1;
895  if (n < 6) return 0;
896  /* ASCII cpio: odc (070707), newc (070701), crc (070702) */
897  return (memcmp(hdr, "070707", 6) == 0 || memcmp(hdr, "070701", 6) == 0 ||
898  memcmp(hdr, "070702", 6) == 0);
899 }
900 
906 void OctetType(char *Filename, char *TypeBuf)
907 {
908  int rc1, rc2, rc3;
909  char *Type;
910 
911  /* Get more information from magic */
912  magic_setflags(MagicCookie, MAGIC_NONE);
913  Type = (char *)magic_file(MagicCookie, Filename);
914  /* reset magic flags */
915  magic_setflags(MagicCookie, MAGIC_MIME);
916 
917  /* .deb and .udeb as application/x-debian-package*/
918  if (strstr(Type, "Debian binary package"))
919  {
920  strcpy(TypeBuf,"application/x-debian-package");
921  return;
922  }
923 
924  if (strstr(Type, "ISO 9660"))
925  {
926  strcpy(TypeBuf,"application/x-iso9660-image");
927  return;
928  }
929 
930  /* 7zr can handle many formats (including isos), so try this first */
931  rc1 = RunCommand("7z","l -y ",Filename,">/dev/null 2>&1",NULL,NULL);
932  rc2 = RunCommand("7z","t -y -pjunk",Filename,">/dev/null 2>&1",NULL,NULL);
933  if(rc2!=0)
934  {
935  rc3 = RunCommand("7z","t -y -pjunk",Filename," 2>&1 | grep 'Wrong password' >/dev/null",NULL,NULL);
936  if(rc3==0)
937  {
938  LOG_ERROR("'%s' cannot be unpacked, password required.",Filename);
939  return;
940  }
941  }
942  if ((rc1 || rc2)==0)
943  {
944  strcpy(TypeBuf,"application/x-7z-w-compressed");
945  return;
946  }
947 
948  if (strstr(Type, " ext2 "))
949  {
950  strcpy(TypeBuf,"application/x-ext2");
951  return;
952  }
953 
954  if (strstr(Type, " ext3 "))
955  {
956  strcpy(TypeBuf,"application/x-ext3");
957  return;
958  }
959 
960  if (strstr(Type, "x86 boot sector, mkdosfs")) /* the file type is FAT */
961  {
962  strcpy(TypeBuf,"application/x-fat");
963  return;
964  }
965 
966  if (strstr(Type, "NTFS")) /* the file type is NTFS */
967  {
968  strcpy(TypeBuf,"application/x-ntfs");
969  return;
970  }
971 
972  if (strstr(Type, "x86 boot")) /* the file type is boot partition */
973  {
974  strcpy(TypeBuf,"application/x-x86_boot");
975  return;
976  }
977 }
978 
984 int FindCmd (char *Filename)
985 {
986  char *Type;
987  char TypeBuf[256];
988  int Match;
989  int i;
990  int rc;
991 
992  if (!MagicCookie) InitMagic();
993  TypeBuf[0] = 0;
994 
995  Type = (char *)magic_file(MagicCookie,Filename);
996  if (Type == NULL) return(-1);
997 
998  /* Windows executables look like archives and 7z will attempt to unpack them.
999  * If that happens there will be a .bss file representing the .bss segment.
1000  * 7z will try to unpack this further, potentially getting into an infinite
1001  * unpack loop. So if you see an octet type .bss file, consider it text
1002  * to avoid this problem. This problem was first noticed on papi-4.1.3-3.el6.src.rpm
1003  */
1004  if ((strcmp(basename(Filename), ".bss") == 0) && (strstr(Type, "octet")))
1005  {
1006  Type = strdup("text/plain");
1007  }
1008 
1009  /* The Type returned by magic_file needs to be verified and possibly rewritten.
1010  * So save it in a static buffer.
1011  */
1012  strncpy(TypeBuf, Type, sizeof(TypeBuf));
1013  TypeBuf[255] = 0; /* make sure TypeBuf is null terminated */
1014 
1015  /* a cpio can only be misreported as a text type (see IsCpioFile) */
1016  if (strncmp(Type, "text/", 5) == 0 && IsCpioFile(Filename))
1017  {
1018  strcpy(TypeBuf,"application/x-cpio");
1019  }
1020  else
1021  if (strstr(Type, "octet" ))
1022  {
1023  OctetType(Filename, TypeBuf);
1024  }
1025  else
1026  if (IsDebianSourceFile(Filename)) strcpy(TypeBuf,"application/x-debian-source");
1027  else
1028  if (strstr(Type, "msword") || strstr(Type, "vnd.ms"))
1029  strcpy(TypeBuf, "application/x-7z-w-compressed");
1030  else
1031  /* some files you just have to try to verify their type */
1032  if (strstr(Type, "application/x-exe") ||
1033  strstr(Type, "application/x-shellscript"))
1034  {
1035  rc = RunCommand("unzip","-q -l",Filename,">/dev/null 2>&1",NULL,NULL);
1036  if ((rc==0) || (rc==1) || (rc==2) || (rc==51))
1037  {
1038  strcpy(TypeBuf,"application/x-zip");
1039  }
1040  } /* if was x-exe */
1041  else if (strstr(Type, "application/x-tar"))
1042  {
1043  if (RunCommand("tar","-tf",Filename,">/dev/null 2>&1",NULL,NULL) != 0)
1044  return(-1); /* bad tar! (Yes, they do happen) */
1045  } /* if was x-tar */
1046 
1047  /* Match Type (mimetype from magic or from special processing above to determine
1048  * the command for Filename
1049  */
1050  Match=-1;
1051  for(i=0; (CMD[i].Cmd != NULL) && (Match == -1); i++)
1052  {
1053  if (CMD[i].Status == 0) continue; /* cannot check */
1054  if (CMD[i].Type == CMD_DEFAULT)
1055  {
1056  Match=i; /* done! */
1057  }
1058  else
1059  if (!strstr(TypeBuf, CMD[i].Magic))
1060  {
1061  continue; /* not a match */
1062  }
1063  Match=i;
1064  }
1065 
1066  if (Verbose > 0)
1067  {
1068  /* no match */
1069  if (Match == -1)
1070  {
1071  LOG_DEBUG("MISS: Type=%s %s",TypeBuf,Filename);
1072  }
1073  else
1074  {
1075  LOG_DEBUG("MATCH: Type=%d %s %s %s %s",CMD[Match].Type,CMD[Match].Cmd,CMD[Match].CmdPre,Filename,CMD[Match].CmdPost);
1076  }
1077  }
1078  return(Match);
1079 } /* FindCmd() */
1080 
1081 /***************************************************************************/
1082 /***************************************************************************/
1083 /*** File Processing ***/
1084 /***************************************************************************/
1085 /***************************************************************************/
1086 
1092 {
1093  dirlist *d;
1094  /* free records */
1095  while(DL)
1096  {
1097  d=DL; /* grab the head */
1098  DL=DL->Next; /* increment new head */
1099  /* free old head */
1100  if (d->Name) free(d->Name);
1101  free(d);
1102  }
1103 } /* FreeDirList() */
1104 
1110 dirlist * MakeDirList (char *Fullname)
1111 {
1112  dirlist *dlist=NULL, *dhead=NULL;
1113  DIR *Dir;
1114  struct dirent *Entry;
1115 
1116  /* no effort is made to sort since all records need to be processed anyway */
1117  /* Current order is "reverse inode order" */
1118  Dir = opendir(Fullname);
1119  if (Dir == NULL) return(NULL);
1120 
1121  Entry = readdir(Dir);
1122  while(Entry != NULL)
1123  {
1124  if (!strcmp(Entry->d_name,".")) goto skip;
1125  if (!strcmp(Entry->d_name,"..")) goto skip;
1126  dhead = (dirlist *)malloc(sizeof(dirlist));
1127  if (!dhead)
1128  {
1129  LOG_FATAL("Failed to allocate dirlist memory");
1130  SafeExit(10);
1131  }
1132  dhead->Name = (char *)malloc(strlen(Entry->d_name)+1);
1133  if (!dhead->Name)
1134  {
1135  LOG_FATAL("Failed to allocate dirlist.Name memory");
1136  SafeExit(11);
1137  }
1138  memset(dhead->Name,'\0',strlen(Entry->d_name)+1);
1139  strcpy(dhead->Name,Entry->d_name);
1140  /* add record to the list */
1141  dhead->Next = dlist;
1142  dlist = dhead;
1143 #if 0
1144  {
1145  /* bubble-sort name -- head is out of sequence */
1147  char *Name;
1148  dhead = dlist;
1149  while(dhead->Next && (strcmp(dhead->Name,dhead->Next->Name) > 0))
1150  {
1151  /* swap names */
1152  Name = dhead->Name;
1153  dhead->Name = dhead->Next->Name;
1154  dhead->Next->Name = Name;
1155  dhead = dhead->Next;
1156  }
1157  }
1158 #endif
1159 
1160  skip:
1161  Entry = readdir(Dir);
1162  }
1163  closedir(Dir);
1164 
1165 #if 0
1166  /* debug: List the directory */
1167  printf("Directory: %s\n",Fullname);
1168  for(dhead=dlist; dhead; dhead=dhead->Next)
1169  {
1170  printf(" %s\n",dhead->Name);
1171  }
1172 #endif
1173 
1174  return(dlist);
1175 } /* MakeDirList() */
1176 
1187 void SetDir (char *Dest, int DestLen, char *Smain, char *Sfile)
1188 {
1189  int i;
1190 
1191  memset(Dest,'\0',DestLen);
1192  if (Smain)
1193  {
1194  strcpy(Dest,Smain);
1195  /* remove absolute path (stay in destination) */
1196  if (Sfile && (Sfile[0]=='/')) Sfile++;
1197  /* skip "../" */
1200  i=1;
1201  while(i && Sfile)
1202  {
1203  i=0;
1204  if (!memcmp(Sfile,"../",3)) { Sfile+=3; i=1; }
1205  else if (!memcmp(Sfile,"./",2)) { Sfile+=2; i=1; }
1206  }
1207  while(Sfile && !memcmp(Sfile,"../",3)) Sfile+=3;
1208  }
1209 
1210  if ((strlen(Dest) > 0) && (Last(Smain) != '/') && (Sfile[0] != '/'))
1211  strcat(Dest,"/");
1212  if (Sfile) strcat(Dest,Sfile);
1213  /* remove terminating file */
1214  for(i=strlen(Dest)-1; (i>=0) && (Dest[i] != '/'); i--)
1215  {
1216  Dest[i]='\0';
1217  }
1218 } /* SetDir() */
1219 
1220 
1226 {
1227  LOG_DEBUG("Container:");
1228  printf(" Source: %s\n",CI->Source);
1229  printf(" Partdir: %s\n",CI->Partdir);
1230  printf(" Partname: %s\n",CI->Partname);
1231  printf(" PartnameNew: %s\n",CI->PartnameNew);
1232  printf(" TopContainer: %d\n",CI->TopContainer);
1233  printf(" HasChild: %d\n",CI->HasChild);
1234  printf(" Pruned: %d\n",CI->Pruned);
1235  printf(" Corrupt: %d\n",CI->Corrupt);
1236  printf(" Artifact: %d\n",CI->Artifact);
1237  printf(" IsDir: %d\n",CI->IsDir);
1238  printf(" IsCompressed: %d\n",CI->IsCompressed);
1239  printf(" uploadtree_pk: %ld\n",CI->uploadtree_pk);
1240  printf(" pfile_pk: %ld\n",CI->pfile_pk);
1241  printf(" ufile_mode: %ld\n",CI->ufile_mode);
1242  printf(" Parent Cmd: %d\n",CI->PI.Cmd);
1243  printf(" Parent ChildRecurseArtifact: %d\n",CI->PI.ChildRecurseArtifact);
1244  printf(" Parent uploadtree_pk: %ld\n",CI->PI.uploadtree_pk);
1245 } /* DebugContainerInfo() */
1246 
1254 int DBInsertPfile (ContainerInfo *CI, char *Fuid)
1255 {
1256  PGresult *result;
1257  char *Val; /* string result from SQL query */
1258  long tempMimeType;
1259  char *tempSha256;
1260 
1261  /* idiot checking */
1262  if (!Fuid || (Fuid[0] == '\0')) return(1);
1263 
1264  /* Check if the pfile exists */
1265  memset(SQL,'\0',MAXSQL);
1266  snprintf(SQL,MAXSQL,"SELECT pfile_pk,pfile_mimetypefk,pfile_sha256 FROM pfile "
1267  "WHERE pfile_sha1 = '%.40s' AND pfile_md5 = '%.32s' AND pfile_size = '%s';",
1268  Fuid,Fuid+41,Fuid+140);
1269  result = PQexec(pgConn, SQL); /* SELECT */
1270  if (fo_checkPQresult(pgConn, result, SQL, __FILE__, __LINE__)) SafeExit(12);
1271 
1272  /* add it if it was not found */
1273  if (PQntuples(result) == 0)
1274  {
1275  /* blindly insert to pfile table in database (don't care about dups) */
1276  /* If TWO ununpacks are running at the same time, they could both
1277  create the same pfile at the same time. Ignore the dup constraint. */
1278  PQclear(result);
1279  memset(SQL,'\0',MAXSQL);
1280  if (CMD[CI->PI.Cmd].DBindex > 0)
1281  {
1282  snprintf(SQL,MAXSQL,"INSERT INTO pfile (pfile_sha1,pfile_md5,pfile_sha256,pfile_size,pfile_mimetypefk) "
1283  "VALUES ('%.40s','%.32s','%.64s','%s','%ld');",
1284  Fuid,Fuid+41,Fuid+74,Fuid+140,CMD[CI->PI.Cmd].DBindex);
1285  }
1286  else
1287  {
1288  snprintf(SQL,MAXSQL,"INSERT INTO pfile (pfile_sha1,pfile_md5,pfile_sha256,pfile_size) VALUES ('%.40s','%.32s','%.64s','%s');",
1289  Fuid,Fuid+41,Fuid+74,Fuid+140);
1290  }
1291  result = PQexec(pgConn, SQL); /* INSERT INTO pfile */
1292  // ignore duplicate constraint failure (23505), report others
1293  if ((result==0) || ((PQresultStatus(result) != PGRES_COMMAND_OK) &&
1294  (strncmp("23505", PQresultErrorField(result, PG_DIAG_SQLSTATE),5))))
1295  {
1296  LOG_ERROR("Error inserting pfile, %s.", SQL);
1297  SafeExit(13);
1298  }
1299  PQclear(result);
1300 
1301  /* Now find the pfile_pk. Since it might be a dup, we cannot rely
1302  on currval(). */
1303  memset(SQL,'\0',MAXSQL);
1304  snprintf(SQL,MAXSQL,"SELECT pfile_pk,pfile_mimetypefk,pfile_sha256 FROM pfile "
1305  "WHERE pfile_sha1 = '%.40s' AND pfile_md5 = '%.32s' AND pfile_sha256 = '%.64s' AND pfile_size = '%s';",
1306  Fuid,Fuid+41,Fuid+74,Fuid+140);
1307  result = PQexec(pgConn, SQL); /* SELECT */
1308  if (fo_checkPQresult(pgConn, result, SQL, __FILE__, __LINE__)) SafeExit(14);
1309  }
1310 
1311  /* Now *DB contains the pfile_pk information */
1312  Val = PQgetvalue(result,0,0);
1313  if (Val)
1314  {
1315  CI->pfile_pk = atol(Val);
1316  if (Verbose) LOG_DEBUG("pfile_pk = %ld",CI->pfile_pk);
1317  tempMimeType = atol(PQgetvalue(result,0,1));
1318  tempSha256 = PQgetvalue(result,0,2);
1319  /* For backwards compatibility... Do we need to update the mimetype? */
1320  if ((CMD[CI->PI.Cmd].DBindex > 0) &&
1321  ((tempMimeType != CMD[CI->PI.Cmd].DBindex)))
1322  {
1323  PQclear(result);
1324  memset(SQL,'\0',MAXSQL);
1325  snprintf(SQL,MAXSQL,"UPDATE pfile SET pfile_mimetypefk = '%ld' WHERE pfile_pk = '%ld';",
1326  CMD[CI->PI.Cmd].DBindex, CI->pfile_pk);
1327  result = PQexec(pgConn, SQL); /* UPDATE pfile */
1328  if (fo_checkPQcommand(pgConn, result, SQL, __FILE__ ,__LINE__)) SafeExit(16);
1329  }
1330  /* Update the SHA256 for the pfile if it does not exists */
1331  if (strncasecmp(tempSha256, Fuid+74, 64) != 0)
1332  {
1333  PQclear(result);
1334  memset(SQL,'\0',MAXSQL);
1335  snprintf(SQL,MAXSQL,"UPDATE pfile SET pfile_sha256 = '%.64s' WHERE pfile_pk = '%ld';",
1336  Fuid+74, CI->pfile_pk);
1337  result = PQexec(pgConn, SQL); /* UPDATE pfile */
1338  if (fo_checkPQcommand(pgConn, result, SQL, __FILE__ ,__LINE__)) SafeExit(16);
1339  }
1340  PQclear(result);
1341  }
1342  else
1343  {
1344  PQclear(result);
1345  CI->pfile_pk = -1;
1346  return(0);
1347  }
1348 
1349  return(1);
1350 } /* DBInsertPfile() */
1351 
1364 int TestSCMData(char *sourcefilename)
1365 {
1366  regex_t preg;
1367  int err;
1368  int found=0;
1369 
1370  err = regcomp (&preg, SCM_REGEX, REG_NOSUB | REG_EXTENDED);
1371  if (err == 0)
1372  {
1373  int match;
1374 
1375  match = regexec (&preg, sourcefilename, 0, NULL, 0);
1376  regfree (&preg);
1377  if(match == 0)
1378  {
1379  found = 1;
1380  if (Verbose) LOG_DEBUG("match found %s",sourcefilename);
1381  }
1382  else if(match == REG_NOMATCH)
1383  {
1384  found = 0;
1385  if (Verbose) LOG_DEBUG("match not found %s",sourcefilename);
1386  }
1387  else
1388  {
1389  char *text;
1390  size_t size;
1391  size = regerror (err, &preg, NULL, 0);
1392  text = malloc (sizeof (*text) * size);
1393  if(text)
1394  {
1395  regerror (err, &preg, text, size);
1396  LOG_ERROR("Error regexc '%s' '%s' return %d, error %s",SCM_REGEX,sourcefilename,match,text);
1397  }
1398  else
1399  {
1400  LOG_ERROR("Not enough memory (%lu)",sizeof (*text) * size);
1401  SafeExit(127);
1402  }
1403  found = 0;
1404  }
1405  }
1406  else
1407  {
1408  LOG_ERROR("Error regcomp(%d)",err);
1409  SafeExit(127);
1410  }
1411 
1412 
1413  return(found);
1414 } /* TestSCMData() */
1415 
1427 {
1428  char UfileName[1024];
1429  char *cp;
1430  PGresult *result;
1431  char EscBuf[1024];
1432  int error;
1433 
1434  if (!Upload_Pk) return(-1); /* should never happen */
1435  // printf("=========== BEFORE ==========\n"); DebugContainerInfo(CI);
1436 
1437  /* Find record's mode */
1438  CI->ufile_mode = CI->Stat.st_mode & Mask;
1439  if (!CI->TopContainer && CI->Artifact) CI->ufile_mode |= (1 << BITS_ARTIFACT);
1440  if (CI->HasChild) CI->ufile_mode |= (1 << BITS_CONTAINER);
1441 
1442  /* Find record's name */
1443  memset(UfileName,'\0',sizeof(UfileName));
1444  if (CI->TopContainer)
1445  {
1446  char *ufile_name;
1447  snprintf(UfileName,sizeof(UfileName),"SELECT upload_filename FROM upload WHERE upload_pk = %s;",Upload_Pk);
1448  result = PQexec(pgConn, UfileName);
1449  if (fo_checkPQresult(pgConn, result, UfileName, __FILE__, __LINE__)) SafeExit(17);
1450  memset(UfileName,'\0',sizeof(UfileName));
1451  ufile_name = PQgetvalue(result,0,0);
1452  PQclear(result);
1453  if (strchr(ufile_name,'/')) ufile_name = strrchr(ufile_name,'/')+1;
1454  strncpy(CI->Partname,ufile_name,sizeof(CI->Partname)-1);
1455  }
1456  else if (CI->Artifact)
1457  {
1458  int Len;
1459  Len = strlen(CI->Partname);
1460  /* determine type of artifact */
1461  if ((Len > 4) && !strcmp(CI->Partname+Len-4,".dir"))
1462  strcpy(UfileName,"artifact.dir");
1463  else if ((Len > 9) && !strcmp(CI->Partname+Len-9,".unpacked"))
1464  strcpy(UfileName,"artifact.unpacked");
1465  else if ((Len > 5) && !strcmp(CI->Partname+Len-5,".meta"))
1466  strcpy(UfileName,"artifact.meta");
1467  else /* Don't know what it is */
1468  strcpy(UfileName,"artifact");
1469  strncpy(CI->Partname,UfileName,sizeof(CI->Partname)-1);
1470  }
1471 
1472  PQescapeStringConn(pgConn, EscBuf, CI->Partname, strlen(CI->Partname), &error);
1473  if (error)
1474  {
1475  LOG_WARNING("Error escaping filename with multibyte character set (%s).", CI->Partname);
1476  }
1477  else
1478  {
1479  strncpy(UfileName, EscBuf, sizeof(UfileName));
1480  }
1481 
1482  /*
1483  * Tests for SCM Data: IgnoreSCMData is global and defined in ununpack_globals.h with false value
1484  * and pass to true if ununpack is called with -I option to ignore SCM data.
1485  * So if IgnoreSCMData is false the right test is true.
1486  * Otherwise if IgnoreSCMData is true and CI->Source is not a SCM data then add it in database.
1487  */
1488  if(ReunpackSwitch && ((IgnoreSCMData && !TestSCMData(CI->Source)) || !IgnoreSCMData))
1489  {
1490  /* postgres 8.3 seems to have a problem escaping binary characters
1491  * (it works in 8.4). So manually substitute '~' for any unprintable and slash chars.
1492  */
1493  for (cp=UfileName; *cp; cp++) if (!isprint(*cp) || (*cp=='/') || (*cp=='\\')) *cp = '~';
1494 
1495  /* Get the parent ID */
1496  /* Two cases -- depending on if the parent exists */
1497  memset(SQL,'\0',MAXSQL);
1498  if (CI->PI.uploadtree_pk > 0) /* This is a child */
1499  {
1500  /* Prepare to insert child */
1501  snprintf(SQL,MAXSQL,"INSERT INTO %s (parent,pfile_fk,ufile_mode,ufile_name,upload_fk) VALUES (%ld,%ld,%ld,E'%s',%s);",
1503  UfileName, Upload_Pk);
1504  result = PQexec(pgConn, SQL); /* INSERT INTO uploadtree */
1505  if (fo_checkPQcommand(pgConn, result, SQL, __FILE__ ,__LINE__))
1506  {
1507  SafeExit(18);
1508  }
1509  PQclear(result);
1510  }
1511  else /* No parent! This is the first upload! */
1512  {
1513  snprintf(SQL,MAXSQL,"INSERT INTO %s (upload_fk,pfile_fk,ufile_mode,ufile_name) VALUES (%s,%ld,%ld,E'%s');",
1514  uploadtree_tablename, Upload_Pk, CI->pfile_pk, CI->ufile_mode, UfileName);
1515  result = PQexec(pgConn, SQL); /* INSERT INTO uploadtree */
1516  if (fo_checkPQcommand(pgConn, result, SQL, __FILE__ ,__LINE__)) SafeExit(19);
1517  PQclear(result);
1518  }
1519  /* Find the inserted child */
1520  memset(SQL,'\0',MAXSQL);
1521  snprintf(SQL,MAXSQL,"SELECT currval('uploadtree_uploadtree_pk_seq');");
1522  result = PQexec(pgConn, SQL);
1523  if (fo_checkPQresult(pgConn, result, SQL, __FILE__, __LINE__)) SafeExit(20);
1524  CI->uploadtree_pk = atol(PQgetvalue(result,0,0));
1525  PQclear(result);
1526  }
1527  TotalItems++;
1528  fo_scheduler_heart(1);
1529  return(0);
1530 } /* DBInsertUploadTree() */
1531 
1542 int AddToRepository (ContainerInfo *CI, char *Fuid, int Mask)
1543 {
1544  int IsUnique = 1; /* is it a DB replica? */
1545 
1546  /*****************************************/
1547  /* populate repository (include artifacts) */
1548  /* If we ever want to skip artifacts, use && !CI->Artifact */
1549  if ((Fuid[0]!='\0') && UseRepository)
1550  {
1551  /* Translate the new Fuid into old Fuid */
1552  char FuidNew[1024];
1553  memset(FuidNew, '\0', sizeof(FuidNew));
1554  // Copy the value till md5
1555  strncpy(FuidNew, Fuid, 74);
1556  // Copy the size of the file
1557  strcat(FuidNew,Fuid+140);
1558 
1559  /* put file in repository */
1560  if (!fo_RepExist(REP_FILES,Fuid))
1561  {
1562  if (fo_RepImport(CI->Source,REP_FILES,FuidNew,1) != 0)
1563  {
1564  LOG_ERROR("Failed to import '%s' as '%s' into the repository",CI->Source,FuidNew);
1565  SafeExit(21);
1566  }
1567  }
1568  if (Verbose) LOG_DEBUG("Repository[%s]: insert '%s' as '%s'",
1569  REP_FILES,CI->Source,FuidNew);
1570  }
1571 
1572  /* PERFORMANCE NOTE:
1573  I used to use and INSERT and an UPDATE.
1574  Turns out, INSERT is fast, UPDATE is *very* slow (10x).
1575  Now I just use an INSERT.
1576  */
1577 
1578  /* Insert pfile record */
1579  if (pgConn && Upload_Pk)
1580  {
1581  if (!DBInsertPfile(CI,Fuid)) return(0);
1582  /* Update uploadtree table */
1583  IsUnique = !DBInsertUploadTree(CI,Mask);
1584  }
1585 
1586  if (ForceDuplicate) IsUnique=1;
1587  return(IsUnique);
1588 } /* AddToRepository() */
1589 
1598 {
1599  int i;
1600  int Mask=0177000; /* used for XML modemask */
1601  char Fuid[1024];
1602 
1603  if (CI->Source[0] == '\0') return(0);
1604  memset(Fuid,0,sizeof(Fuid));
1605  /* TotalItems++; */
1606 
1607  /* list source */
1608  if (ListOutFile)
1609  {
1610  fputs("<item source=\"",ListOutFile);
1611  for(i=0; CI->Source[i] != '\0'; i++)
1612  {
1613  if (isalnum(CI->Source[i]) ||
1614  strchr(" `~!@#$%^*()-=_+[]{}\\|;:',./?",CI->Source[i]))
1615  fputc(CI->Source[i],ListOutFile);
1616  else fprintf(ListOutFile,"&#x%02x;",(int)(CI->Source[i])&0xff);
1617  }
1618  fputs("\" ",ListOutFile);
1619 
1620  /* list file names */
1621  if (CI->Partname[0] != '\0')
1622  {
1623  fputs("name=\"",ListOutFile);
1624  /* XML taint-protect name */
1625  for(i=0; CI->Partname[i] != '\0'; i++)
1626  {
1627  if (isalnum(CI->Partname[i]) ||
1628  strchr(" `~!@#$%^*()-=_+[]{}\\|;:',./?",CI->Partname[i]))
1629  fputc(CI->Partname[i],ListOutFile);
1630  else fprintf(ListOutFile,"&#x%02x;",(int)(CI->Partname[i])&0xff);
1631  }
1632  fputs("\" ",ListOutFile);
1633  }
1634 
1635  /* list mime info */
1636  if ((CI->PI.Cmd >= 0) && (CMD[CI->PI.Cmd].Type != CMD_DEFAULT))
1637  {
1638  fprintf(ListOutFile,"mime=\"%s\" ",CMD[CI->PI.Cmd].Magic);
1639  TotalFiles++;
1640  }
1641  else if (S_ISDIR(CI->Stat.st_mode))
1642  {
1643  fprintf(ListOutFile,"mime=\"directory\" ");
1644  TotalDirectories++;
1645  }
1646  else TotalFiles++;
1647 
1648  /* identify compressed files */
1649  if (CMD[CI->PI.Cmd].Type == CMD_PACK)
1650  {
1651  fprintf(ListOutFile,"compressed=\"1\" ");
1653  }
1654  /* identify known artifacts */
1655  if (CI->Artifact)
1656  {
1657  fprintf(ListOutFile,"artifact=\"1\" ");
1658  TotalArtifacts++;
1659  }
1660 
1661  if (CI->HasChild) fprintf(ListOutFile,"haschild=\"1\" ");
1662  } /* if ListOutFile */
1663 
1664  if (!CI->TopContainer)
1665  {
1666  /* list mode */
1667  Mask=0177000;
1668  if (Cmd >= 0)
1669  {
1670  if (S_ISDIR(CI->Stat.st_mode))
1671  {
1672  Mask = CMD[Cmd].ModeMaskDir;
1673  }
1674  else if (S_ISREG(CI->Stat.st_mode))
1675  {
1676  Mask = CMD[Cmd].ModeMaskReg;
1677  }
1678  }
1679 
1680  if (ListOutFile)
1681  {
1682  if (!CI->Artifact) /* no masks for an artifact */
1683  {
1684  fprintf(ListOutFile,"mode=\"%07o\" ",CI->Stat.st_mode & Mask);
1685  fprintf(ListOutFile,"modemask=\"%07o\" ",Mask);
1686  }
1687 
1688  /* identify known corrupted files */
1689  if (CI->Corrupt) fprintf(ListOutFile,"error=\"%d\" ",CI->Corrupt);
1690 
1691  /* list timestamps */
1692  if (CI->Stat.st_mtime)
1693  {
1694  if ((CI->Stat.st_mtime < CI->PI.StartTime) || (CI->Stat.st_mtime > CI->PI.EndTime))
1695  fprintf(ListOutFile,"mtime=\"%d\" ",(int)(CI->Stat.st_mtime));
1696  }
1697 #if 0
1698  /* commented out since almost anything can screw this up. */
1699  if (CI->Stat.st_ctime)
1700  {
1701  if ((CI->Stat.st_ctime < CI->PI.StartTime) || (CI->Stat.st_ctime > CI->PI.EndTime))
1702  fprintf(ListOutFile,"ctime=\"%d\" ",(int)(CI->Stat.st_ctime));
1703  }
1704 #endif
1705  } /* if ListOutFile */
1706  } /* if not top container */
1707 
1708  /* list checksum info for files only! */
1709  if (S_ISREG(CI->Stat.st_mode) && !CI->Pruned)
1710  {
1711  CksumFile *CF;
1712  Cksum *Sum;
1713  char SHA256[65];
1714 
1715  memset(SHA256, '\0', sizeof(SHA256));
1716 
1717  CF = SumOpenFile(CI->Source);
1718  if(calc_sha256sum(CI->Source, SHA256))
1719  {
1720  LOG_FATAL("Unable to calculate SHA256 of %s\n", CI->Source);
1721  SafeExit(56);
1722  }
1723 
1724  if (CF)
1725  {
1726  Sum = SumComputeBuff(CF);
1727  SumCloseFile(CF);
1728 
1729  if (Sum)
1730  {
1731  for(i=0; i<20; i++) { sprintf(Fuid+0+i*2,"%02X",Sum->SHA1digest[i]); }
1732  Fuid[40]='.';
1733  for(i=0; i<16; i++) { sprintf(Fuid+41+i*2,"%02X",Sum->MD5digest[i]); }
1734  Fuid[73]='.';
1735  for(i=0; i<64; i++) { sprintf(Fuid+74+i,"%c",SHA256[i]); }
1736  Fuid[139]='.';
1737  snprintf(Fuid+140,sizeof(Fuid)-140,"%Lu",(long long unsigned int)Sum->DataLen);
1738  if (ListOutFile) fprintf(ListOutFile,"fuid=\"%s\" ",Fuid);
1739  free(Sum);
1740  } /* if Sum */
1741  } /* if CF */
1742  else /* file too large to mmap (probably) */
1743  {
1744  FILE *Fin;
1745  Fin = fopen(CI->Source,"rb");
1746  if (Fin)
1747  {
1748  Sum = SumComputeFile(Fin);
1749  if (Sum)
1750  {
1751  for(i=0; i<20; i++) { sprintf(Fuid+0+i*2,"%02X",Sum->SHA1digest[i]); }
1752  Fuid[40]='.';
1753  for(i=0; i<16; i++) { sprintf(Fuid+41+i*2,"%02X",Sum->MD5digest[i]); }
1754  Fuid[73]='.';
1755  for(i=0; i<64; i++) { sprintf(Fuid+74+i,"%c",SHA256[i]); }
1756  Fuid[139]='.';
1757  snprintf(Fuid+140,sizeof(Fuid)-140,"%Lu",(long long unsigned int)Sum->DataLen);
1758  if (ListOutFile) fprintf(ListOutFile,"fuid=\"%s\" ",Fuid);
1759  free(Sum);
1760  }
1761  fclose(Fin);
1762  }
1763  }
1764  } /* if is file */
1765 
1766  /* end XML */
1767  if (ListOutFile)
1768  {
1769  if (CI->HasChild) fputs(">\n",ListOutFile);
1770  else fputs("/>\n",ListOutFile);
1771  } /* if ListOutFile */
1772 
1773  return(AddToRepository(CI,Fuid,Mask));
1774 } /* DisplayContainerInfo() */
1775 
1781 int RemoveDir(char *dirpath)
1782 {
1783  char RMcmd[FILENAME_MAX];
1784  int rc;
1785  memset(RMcmd, '\0', sizeof(RMcmd));
1786  snprintf(RMcmd, FILENAME_MAX -1, "rm -rf '%s' ", dirpath);
1787 // nokill = fo_scheduler_get_special(SPECIAL_NOKILL);
1788  rc = system(RMcmd);
1789 // fo_scheduler_set_special(SPECIAL_NOKILL, nokill);
1790  return rc;
1791 } /* RemoveDir() */
1792 
1793 
1802 char *PathCheck(char *DirPath)
1803 {
1804  char *NewPath;
1805  char *subs;
1806  char TmpPath[2048];
1807  char HostName[2048];
1808  struct timeval time_st;
1809 
1810  NewPath = strdup(DirPath);
1811 
1812  if ((subs = strstr(NewPath,"%U")) )
1813  {
1814  /* dir substitution */
1815  if (gettimeofday(&time_st, 0))
1816  {
1817  /* gettimeofday failure */
1818  LOG_WARNING("gettimeofday() failure.");
1819  time_st.tv_usec = 999999;
1820  }
1821 
1822  *subs = 0;
1823  snprintf(TmpPath, sizeof(TmpPath), "%s%ul", NewPath, (unsigned)time_st.tv_usec);
1824  free(NewPath);
1825  NewPath = strdup(TmpPath);
1826  }
1827 
1828  if ((subs = strstr(NewPath,"%H")) )
1829  {
1830  /* hostname substitution */
1831  gethostname(HostName, sizeof(HostName));
1832 
1833  *subs = 0;
1834  snprintf(TmpPath, sizeof(TmpPath), "%s%s%s", NewPath, HostName, subs+2);
1835  free(NewPath);
1836  NewPath = strdup(TmpPath);
1837  }
1838 #ifndef STANDALONE
1839  if ((subs = strstr(NewPath, "%R")) )
1840  {
1841  /* repo location substitution */
1842  *subs = 0;
1843 
1844  snprintf(TmpPath, sizeof(TmpPath), "%s%s%s", NewPath, fo_config_get(sysconfig, "FOSSOLOGY", "path", NULL), subs+2);
1845  free(NewPath);
1846  NewPath = strdup(TmpPath);
1847  }
1848 #endif
1849  return(NewPath);
1850 }
1851 
1852 void deleteTmpFiles(char *dir)
1853 {
1854  if (strcmp(dir, ".")) RemoveDir(dir);
1855 }
1856 
1857 
1863 void Usage (char *Name, char *Version)
1864 {
1865  fprintf(stderr,"Universal Unpacker, %s, compiled %s %s\n",
1866  Version,__DATE__,__TIME__);
1867  fprintf(stderr,"Usage: %s [options] file [file [file...]]\n",Name);
1868  fprintf(stderr," Extracts each file.\n");
1869  fprintf(stderr," If filename specifies a directory, then extracts everything in it.\n");
1870  fprintf(stderr," Unpack Options:\n");
1871  fprintf(stderr," -h :: help (print this message), then exit.\n");
1872  fprintf(stderr," -C :: force continue when unpack tool fails.\n");
1873  fprintf(stderr," -d dir :: specify alternate extraction directory. %%U substitutes a unique ID.\n");
1874  fprintf(stderr," Default is the same directory as file (usually not a good idea).\n");
1875  fprintf(stderr," -m # :: number of CPUs to use (default: 1).\n");
1876  fprintf(stderr," -P :: prune files: remove links, >1 hard links, zero files, etc.\n");
1877  fprintf(stderr," -R :: recursively unpack (same as '-r -1')\n");
1878  fprintf(stderr," -r # :: recurse to a specified depth (0=none/default, -1=infinite)\n");
1879  fprintf(stderr," -X :: remove recursive sources after unpacking.\n");
1880  fprintf(stderr," -x :: remove ALL unpacked files when done (clean up).\n");
1881  fprintf(stderr," I/O Options:\n");
1882  fprintf(stderr," -L out :: Generate a log of files extracted (in XML) to out.\n");
1883  fprintf(stderr," -F :: Using files from the repository.\n");
1884  fprintf(stderr," -i :: Initialize the database queue system, then exit.\n");
1885  fprintf(stderr," -I :: Ignore SCM Data.\n");
1886  fprintf(stderr," -Q :: Using scheduler queue system. (Includes -F)\n");
1887  fprintf(stderr," If -L is used, unpacked files are placed in 'files'.\n");
1888  fprintf(stderr," -T rep :: Set gold repository name to 'rep' (for testing)\n");
1889  fprintf(stderr," -t rep :: Set files repository name to 'rep' (for testing)\n");
1890  fprintf(stderr," -A :: do not set the initial DB container as an artifact.\n");
1891  fprintf(stderr," -f :: force processing files that already exist in the DB.\n");
1892  fprintf(stderr," -q :: quiet (generate no output).\n");
1893  fprintf(stderr," -U upload_pk :: upload to unpack (implies -RQ). Writes to db.\n");
1894  fprintf(stderr," -v :: verbose (-vv = more verbose).\n");
1895  fprintf(stderr," -V :: print the version info, then exit.\n");
1896  fprintf(stderr,"Currently identifies and processes:\n");
1897  fprintf(stderr," Compressed files: .Z .gz .bz .bz2 upx\n");
1898  fprintf(stderr," Archives files: tar cpio zip jar ar rar cab\n");
1899  fprintf(stderr," Data files: pdf\n");
1900  fprintf(stderr," Installer files: rpm deb\n");
1901  fprintf(stderr," File images: iso9660(plain/Joliet/Rock Ridge) FAT(12/16/32) ext2/ext3 NTFS\n");
1902  fprintf(stderr," Boot partitions: x86, vmlinuz\n");
1904 } /* Usage() */
1905 
1912  void SQLNoticeProcessor(void *arg, const char *message)
1913  {
1914  }
1915 
1927  int ShouldExclude(char *Filename, const char *ExcludePatterns)
1928  {
1929  if (!ExcludePatterns || !Filename) return 0;
1930 
1931  char *patternsCopy = strdup(ExcludePatterns);
1932  if (!patternsCopy) return 0;
1933 
1934  char *pattern = strtok(patternsCopy, ",");
1935  while (pattern != NULL) {
1936  if (strstr(Filename, pattern)) {
1937  if (Verbose) LOG_DEBUG("Excluding: %s (matched substring: %s)", Filename, pattern);
1938  free(patternsCopy);
1939  return 1;
1940  }
1941  pattern = strtok(NULL, ",");
1942  }
1943  free(patternsCopy);
1944  return 0;
1945  }
char SQL[256]
SQL query to execute.
Definition: adj2nest.c:78
char * uploadtree_tablename
upload.uploadtree_tablename
Definition: adj2nest.c:100
Cksum * SumComputeBuff(CksumFile *CF)
Compute the checksum, allocate and return a Cksum containing the sum value.
Definition: checksum.c:182
Cksum * SumComputeFile(FILE *Fin)
Compute the checksum, allocate and return a string containing the sum value.
Definition: checksum.c:115
CksumFile * SumOpenFile(char *Fname)
Open and mmap a file.
Definition: checksum.c:26
void SumCloseFile(CksumFile *CF)
Close a file that was opened with SumOpenFile()
Definition: checksum.c:83
int Verbose
Verbose level.
Definition: util.c:19
PGconn * pgConn
Database connection.
Definition: adj2nest.c:86
Stores all extern variables used by the agent.
char * Pfile_Pk
Pfile pk in DB.
int ReunpackSwitch
Set if the uploadtree records are missing from db.
int UseRepository
Using files from the repository?
int TotalDirectories
Number of directories.
unpackqueue Queue[MAXCHILD+1]
Manage children.
int Quiet
Run in quiet mode?
int TotalFiles
Number of regular files.
int TotalArtifacts
Number of artifacts.
cmdlist CMD[]
Global command table.
char * Upload_Pk
Upload pk in DB.
char REP_FILES[16]
Files repository name.
FILE * ListOutFile
File to store unpack list.
long TotalItems
Number of records inserted.
int IgnoreSCMData
1: Ignore SCM data, 0: dont ignore it.
int TotalCompressedFiles
Number of compressed files.
int ForceDuplicate
When using db, should it process duplicates?
int ForceContinue
Force continue when unpack tool fails?
magic_t MagicCookie
for Magic
Definition: finder.c:23
char * fo_config_get(fo_conf *conf, const char *group, const char *key, GError **error)
Gets an element based on its group name and key name. If the group or key is not found,...
Definition: fossconfig.c:336
int fo_checkPQresult(PGconn *pgConn, PGresult *result, char *sql, char *FileID, int LineNumb)
Check the result status of a postgres SELECT.
Definition: libfossdb.c:170
int fo_checkPQcommand(PGconn *pgConn, PGresult *result, char *sql, char *FileID, int LineNumb)
Check the result status of a postgres commands (not select) If an error occured, write the error to s...
Definition: libfossdb.c:204
int fo_RepImport(char *Source, char *Type, char *Filename, int Link)
Import a file into the repository.
Definition: libfossrepo.c:812
int fo_RepExist(char *Type, char *Filename)
Determine if a file exists.
Definition: libfossrepo.c:486
void fo_scheduler_disconnect(int retcode)
Disconnect the scheduler connection.
fo_conf * sysconfig
Store file handler and mmap of a file.
Definition: checksum.h:44
Store check sum of a file.
Definition: checksum.h:33
uint8_t SHA1digest[20]
SHA1 digest of the file.
Definition: checksum.h:35
uint64_t DataLen
Size of the file.
Definition: checksum.h:36
uint8_t MD5digest[16]
MD5 digest of the file.
Definition: checksum.h:34
Structure for storing information about a particular file.
Definition: ununpack.h:120
int IsCompressed
Definition: ununpack.h:133
long pfile_pk
Definition: ununpack.h:135
int TopContainer
Definition: ununpack.h:125
ParentInfo PI
Definition: ununpack.h:130
char Partname[FILENAME_MAX]
Definition: ununpack.h:123
long uploadtree_pk
Definition: ununpack.h:134
long ufile_mode
Definition: ununpack.h:136
struct stat Stat
Definition: ununpack.h:129
char PartnameNew[FILENAME_MAX]
Definition: ununpack.h:124
char Partdir[FILENAME_MAX]
Definition: ununpack.h:122
Definition: monk.h:61
Definition: match.h:20
time_t StartTime
Definition: ununpack.h:82
long uploadtree_pk
Definition: ununpack.h:85
int ChildRecurseArtifact
Definition: ununpack.h:84
time_t EndTime
Definition: ununpack.h:83
cmdtype Type
Definition: ununpack.h:153
long DBindex
Definition: ununpack.h:157
int Status
Definition: ununpack.h:154
char * Cmd
Definition: ununpack.h:149
int ModeMaskReg
Definition: ununpack.h:156
int ModeMaskDir
Definition: ununpack.h:155
Directory linked list.
Definition: ununpack.h:109
struct dirlist * Next
Definition: ununpack.h:111
Store the results of a regex match.
Definition: scanners.hpp:28
int ChildStatus
Definition: ununpack.h:96
ParentInfo PI
Definition: ununpack.h:101
int ChildCorrupt
Definition: ununpack.h:97
static char * Dst
Destination location.
Definition: test_CopyFile.c:14
static char * Src
Souce location.
Definition: test_CopyFile.c:13
int RunCommand(char *Cmd, char *CmdPre, char *File, char *CmdPost, char *Out, char *Where)
Try a command and return command code.
Definition: utils.c:667
int IsFile(char *Fname, int Link)
Given a filename, is it a file?
Definition: utils.c:343
const char * SCM_REGEX
Definition: utils.c:28
int DisplayContainerInfo(ContainerInfo *CI, int Cmd)
Print what can be printed in XML.
Definition: utils.c:1597
void DebugContainerInfo(ContainerInfo *CI)
Print a ContainerInfo structure.
Definition: utils.c:1225
int RemoveDir(char *dirpath)
Remove all files under dirpath (rm -rf)
Definition: utils.c:1781
int MkDirs(char *Fname)
Same as command-line "mkdir -p".
Definition: utils.c:256
int Prune(char *Fname, struct stat Stat)
Given a filename and its stat, prune it.
Definition: utils.c:225
int IsCpioFile(char *Filename)
Check the leading magic bytes for a cpio archive.
Definition: utils.c:882
int TestSCMData(char *sourcefilename)
Search for SCM data in the filename.
Definition: utils.c:1364
int InitMagic()
Open and load Magic file Initializes global MagicCookie.
Definition: utils.c:821
void CheckCommands(int Show)
Make sure all commands are usable.
Definition: utils.c:575
int IsDebianSourceFile(char *Filename)
Read file to see if it is a Debian source file.
Definition: utils.c:839
int MkDir(char *Fname)
Smart mkdir.
Definition: utils.c:311
int TaintString(char *Dest, int DestLen, char *Src, int ProtectQuotes, char *Replace)
Protect strings intelligently.
Definition: utils.c:173
void SetDir(char *Dest, int DestLen, char *Smain, char *Sfile)
Set a destination directory name.
Definition: utils.c:1187
int ParentWait()
Wait for a child. Sets child status.
Definition: utils.c:517
void RemovePostfix(char *Name)
get rid of the postfix
Definition: utils.c:98
void OctetType(char *Filename, char *TypeBuf)
Figure out the real type of "octet" files in case we can unarchive them.
Definition: utils.c:906
int AddToRepository(ContainerInfo *CI, char *Fuid, int Mask)
Add a ContainerInfo record to the repository AND to the database.
Definition: utils.c:1542
void FreeDirList(dirlist *DL)
Free a list of files in a directory list.
Definition: utils.c:1091
int DBInsertPfile(ContainerInfo *CI, char *Fuid)
Insert a Pfile record. Sets the pfile_pk in CI.
Definition: utils.c:1254
int DBInsertUploadTree(ContainerInfo *CI, int Mask)
Insert an UploadTree record.
Definition: utils.c:1426
int IsPdfProcessable(const char *QuotedPath)
Structurally validate a PDF before handing it to pdftotext.
Definition: utils.c:628
void Usage(char *Name, char *Version)
Display program usage.
Definition: utils.c:1863
void InitCmd()
Initialize the metahandler CMD table.
Definition: utils.c:116
int IsExe(char *Exe, int Quiet)
Check if the executable exists.
Definition: utils.c:401
void SafeExit(int rc)
Close scheduler and database connections, then exit.
Definition: utils.c:85
int FindCmd(char *Filename)
Given a file name, determine the type of extraction command. This uses Magic.
Definition: utils.c:984
int ShouldExclude(char *Filename, const char *ExcludePatterns)
Determines if a file or folder should be excluded.
Definition: utils.c:1927
int CopyFile(char *Src, char *Dst)
Copy a file. For speed: mmap and save.
Definition: utils.c:448
int IsInflatedFile(char *FileName, int InflateSize)
Test if the file is a compression bomb.
Definition: utils.c:41
char * PathCheck(char *DirPath)
Check if path contains a "%U" or "%H". If so, substitute a unique ID for U.
Definition: utils.c:1802
void SQLNoticeProcessor(void *arg, const char *message)
Dummy postgresql notice processor. This prevents Notices from being written to stderr.
Definition: utils.c:1912
dirlist * MakeDirList(char *Fullname)
Create a list of files in a directory.
Definition: utils.c:1110
int ReadLine(FILE *Fin, char *Line, int MaxLine)
Read a command from a stream.
Definition: utils.c:364
BITS
File mode BITS.
Definition: utils.c:19
int IsDir(char *Fname)
Given a filename, is it a directory?
Definition: utils.c:327
char * Filename
Filename.
Definition: run_tests.c:17