/
wget_agent.c
1089 lines (964 loc) · 32.6 KB
/
wget_agent.c
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/***************************************************************
wget_agent: Retrieve a file and put it in the database.
Copyright (C) 2007-2014 Hewlett-Packard Development Company, L.P.
This program is free software; you can redistribute it and/or
modify it under the terms of the GNU General Public License
version 2 as published by the Free Software Foundation.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License along
with this program; if not, write to the Free Software Foundation, Inc.,
51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
***************************************************************/
/**
* \file wget_agent.c
* \brief wget_agent: Retrieve a file and put it in the database.
*/
#define _GNU_SOURCE // for asprintf
#define ASPRINTF_MEM_ERROR 88
#define ASPRINTF_MEM_ERROR_LOG LOG_FATAL("Not enough memory for asprintf before line %d", __LINE__)
#include "wget_agent.h"
char SQL[MAXCMD];
PGconn *pgConn = NULL; ///< For the DB
long GlobalUploadKey=-1; ///< Input for this system
char GlobalTempFile[MAXCMD]; ///< Temp file to be used
char GlobalURL[MAXCMD]; ///< URL to download
char GlobalType[MAXCMD]; ///< Type of download (FILE/version control)
char GlobalParam[MAXCMD]; ///< Additional parameters
char *GlobalProxy[6]; ///< Proxy from fossology.conf
char GlobalHttpProxy[MAXCMD]; ///< HTTP proxy command to use
int GlobalImportGold=1; ///< Set to 0 to not store file in gold repository
gid_t ForceGroup=-1; ///< Set to group id to be used for download files
/**
* \brief Given a filename, is it a file?
* \param Link Should it follow symbolic links?
* \return int 1=yes, 0=no.
*/
int IsFile(char *Fname, int Link)
{
stat_t Stat;
int rc;
if (!Fname || (Fname[0]=='\0')) return(0); /* not a directory */
if (Link) rc = stat64(Fname,&Stat);
else rc = lstat64(Fname,&Stat);
if (rc != 0) return(0); /* bad name */
return(S_ISREG(Stat.st_mode));
} /* IsFile() */
/**
* \brief Closes the connection to the server, free the database connection, and exit.
* \param rc Exit value
*/
void SafeExit(int rc)
{
if (pgConn) PQfinish(pgConn);
fo_scheduler_disconnect(rc);
exit(rc);
} /* SafeExit() */
/**
* \brief Get the position (ending + 1) of http|https|ftp:// of one url
* \param URL The URL
* \return the position (ending + 1) of http|https|ftp:// of one url
* E.g. http://fossology.org, return 7
*/
int GetPosition(char *URL)
{
if (NULL != strstr(URL, "http://")) return 7;
if (NULL != strstr(URL, "https://")) return 8;
if (NULL != strstr(URL, "ftp://")) return 6;
return 0;
}
/**
* \brief Insert a file into the database and repository.
*
* Copy the downloaded file to gold repository according to
* the checksum and change the owner if ForceGroup is set.
* Then insert in upload and pfile tables.
*/
void DBLoadGold()
{
Cksum *Sum;
char *Unique=NULL;
char *SHA1, *MD5, *Len;
char SQL[MAXCMD];
long PfileKey;
char *Path;
char SHA256[65];
char *cmd;
FILE *Fin;
int rc = -1, i;
PGresult *result;
int read = 0;
int res;
memset(SHA256, '\0', sizeof(SHA256));
LOG_VERBOSE0("Processing %s",GlobalTempFile);
Fin = fopen(GlobalTempFile,"rb");
// Calculate sha256 value
res = asprintf(&cmd, "sha256sum '%s'", GlobalTempFile);
if (res == -1)
{
SafeExit(ASPRINTF_MEM_ERROR);
}
if (!Fin)
{
LOG_FATAL("upload %ld Unable to open temp file %s from %s",
GlobalUploadKey,GlobalTempFile,GlobalURL);
SafeExit(1);
}
FILE* file = popen(cmd, "r");
if (!file)
{
LOG_FATAL("Unable to get SHA256 from command %s\n", cmd);
free(cmd);
SafeExit(56);
}
free(cmd);
read = fscanf(file, "%64s", SHA256);
rc = WEXITSTATUS(pclose(file));
if (rc || read != 1)
{
LOG_FATAL("Unable to calculate SHA256 of %s\n", GlobalTempFile);
SafeExit(56);
}
// Change SHA256 to upper case like other checksums
for (i = 0; i < 65; i++)
{
SHA256[i] = toupper(SHA256[i]);
}
Sum = SumComputeFile(Fin);
fclose(Fin);
if ((int)ForceGroup > 0)
{
rc = chown(GlobalTempFile,-1,ForceGroup);
if (rc) LOG_ERROR("chown failed on %s, error: %s", GlobalTempFile, strerror(errno));
}
if (!Sum)
{
LOG_FATAL("upload %ld Unable to compute checksum for %s from %s",
GlobalUploadKey,GlobalTempFile,GlobalURL);
SafeExit(2);
}
if (Sum->DataLen <= 0)
{
LOG_FATAL("upload %ld No bytes downloaded from %s to %s.",
GlobalUploadKey,GlobalURL,GlobalTempFile);
SafeExit(3);
}
Unique = SumToString(Sum);
LOG_VERBOSE0("Unique %s",Unique);
if (GlobalImportGold)
{
LOG_VERBOSE0("Import Gold %s",Unique);
rc = fo_RepImport(GlobalTempFile,"gold",Unique,1);
if (rc != 0)
{
LOG_FATAL("upload %ld Failed to import %s from %s into repository gold %s",
GlobalUploadKey,GlobalTempFile,GlobalURL,Unique);
SafeExit(4);
}
/* Put the file in the "files" repository too */
Path = fo_RepMkPath("gold",Unique);
if ((int)ForceGroup >= 0)
{
rc = chown(Path,-1,ForceGroup);
if (rc) LOG_ERROR("chown failed on %s, error: %s", Path, strerror(errno));
}
} /* if GlobalImportGold */
else /* if !GlobalImportGold */
{
Path = GlobalTempFile;
} /* else if !GlobalImportGold */
LOG_VERBOSE0("Path is %s",Path);
if (!Path)
{
LOG_FATAL("upload %ld Failed to determine repository location for %s in gold",
GlobalUploadKey,Unique);
SafeExit(5);
}
LOG_VERBOSE0("Import files %s",Path);
if (fo_RepImport(Path,"files",Unique,1) != 0)
{
LOG_FATAL("upload %ld Failed to import %s from %s into files",
GlobalUploadKey,Unique,Path);
SafeExit(6);
}
if ((int)ForceGroup >= 0)
{
rc = chown(Path,-1,ForceGroup);
if (rc) LOG_ERROR("chown failed on %s, error: %s", Path, strerror(errno));
}
if (Path != GlobalTempFile)
{
if(Path)
{
free(Path);
Path = NULL;
}
}
/* Now update the DB */
/* Break out the sha1, md5, len components **/
SHA1 = Unique;
MD5 = Unique+41; /* 40 for sha1 + 1 for '.' */
Len = Unique+41+33; /* 32 for md5 + 1 for '.' */
/* Set the pfile */
memset(SQL,'\0',MAXCMD);
snprintf(SQL,MAXCMD-1,"SELECT pfile_pk FROM pfile WHERE pfile_sha1 = '%.40s' AND pfile_md5 = '%.32s' AND pfile_size = %s;",
SHA1,MD5,Len);
result = PQexec(pgConn, SQL); /* SELECT */
if (fo_checkPQresult(pgConn, result, SQL, __FILE__, __LINE__)) SafeExit(7);
/* See if pfile needs to be added */
if (PQntuples(result) <=0)
{
/* Insert it */
memset(SQL,'\0',MAXCMD);
snprintf(SQL,MAXCMD-1,"INSERT INTO pfile (pfile_sha1, pfile_md5, pfile_sha256, pfile_size) VALUES ('%.40s','%.32s','%.64s',%s)",
SHA1,MD5,SHA256,Len);
PQclear(result);
result = PQexec(pgConn, SQL);
if (fo_checkPQcommand(pgConn, result, SQL, __FILE__, __LINE__)) SafeExit(8);
PQclear(result);
result = PQexec(pgConn, "SELECT currval('pfile_pfile_pk_seq')");
if (fo_checkPQresult(pgConn, result, SQL, __FILE__, __LINE__)) SafeExit(182);
}
PfileKey = atol(PQgetvalue(result,0,0));
LOG_VERBOSE0("pfile_pk = %ld",PfileKey);
/* Update the DB so the pfile is linked to the upload record */
PQclear(result);
result = PQexec(pgConn, "BEGIN");
if (fo_checkPQcommand(pgConn, result, SQL, __FILE__, __LINE__)) SafeExit(-1);
memset(SQL,0,MAXCMD);
snprintf(SQL,MAXCMD-1,"SELECT * FROM upload WHERE upload_pk=%ld FOR UPDATE;",GlobalUploadKey);
PQclear(result);
result = PQexec(pgConn, SQL);
if (fo_checkPQresult(pgConn, result, SQL, __FILE__, __LINE__)) SafeExit(-1);
memset(SQL,0,MAXCMD);
snprintf(SQL,MAXCMD-1,"UPDATE upload SET pfile_fk=%ld WHERE upload_pk=%ld",
PfileKey,GlobalUploadKey);
LOG_VERBOSE0("SQL=%s\n",SQL);
PQclear(result);
result = PQexec(pgConn, SQL);
if (fo_checkPQcommand(pgConn, result, SQL, __FILE__, __LINE__)) SafeExit(9);
PQclear(result);
result = PQexec(pgConn, "COMMIT;");
if (fo_checkPQcommand(pgConn, result, SQL, __FILE__, __LINE__)) SafeExit(92);
PQclear(result);
/* Clean up */
if (Sum)
{
free(Sum);
Sum = NULL;
}
if (Unique)
{
free(Unique);
Unique = NULL;
}
} /* DBLoadGold() */
/**
* \brief Given a URL string, taint-protect it.
* \param[in] Sin The source URL
* \param[out] Sout The tainted URL
* \param[in] SoutSize The capacity of Sout
* \return 1=tainted, 0=failed to taint
*/
int TaintURL(char *Sin, char *Sout, int SoutSize)
{
int i;
int si;
memset(Sout,'\0',SoutSize);
SoutSize--; /* always keep the EOL */
for(i=0,si=0; (si<SoutSize) && (Sin[i] != '\0'); i++)
{
if (Sin[i] == '#') return(0); /* end at the start of comment */
if (!strchr("'`",Sin[i]) && !isspace(Sin[i])) Sout[si++] = Sin[i];
else
{
if (si+3 >= SoutSize) return(0); /* no room */
snprintf(Sout+si,4,"%%%02X",Sin[i]);
si+=3;
}
}
return(Sin[i]=='\0');
} /* TaintURL() */
/**
* \brief Prepare directory for wget.
* \param TempFile
* \param TempFileDir
* \param TempFileDirectory
* \parblock
* Internal helper function for function GetURL
* \endparblock
* \return destination for wget download or NULL
*/
char *PrepareWgetDest(char *TempFile, char *TempFileDir, char *TempFileDirectory)
{
if (TempFile && TempFile[0])
{
/* Delete the temp file if it exists */
unlink(TempFile);
return TempFileDirectory;
}
else if(TempFileDir && TempFileDir[0])
{
return TempFileDir;
}
return NULL;
}
/**
* \brief Do the wget.
* \param TempFile
* \parblock
* Used when upload from URL by the scheduler, the downloaded file(directory) will be archived as this file.
* When running from command, this parameter is null, e.g. /srv/fossology/repository/localhost/wget/wget.32732
* \endparblock
* \param URL The url you want to download
* \param TempFileDir Where you want to store your downloaded file(directory)
* \return int, 0 on success, non-zero on failure.
*/
int GetURL(char *TempFile, char *URL, char *TempFileDir)
{
char *cmd;
char TaintedURL[MAXCMD];
char TempFileDirectory[MAXCMD];
char DeleteTempDirCmd[MAXCMD];
int rc;
memset(TempFileDirectory,'\0',MAXCMD);
memset(DeleteTempDirCmd,'\0',MAXCMD);
/* save each upload files in /srv/fossology/repository/localhost/wget/wget.xxx.dir/ */
sprintf(TempFileDirectory, "%s.dir", TempFile);
sprintf(DeleteTempDirCmd, "rm -rf %s", TempFileDirectory);
#if 1
char WgetArgs[]="--no-check-certificate --progress=dot -rc -np -e robots=off";
#else
/* wget < 1.10 does not support "--no-check-certificate" */
char WgetArgs[]="--progress=dot -rc -np -e robots=off";
#endif
if (!TaintURL(URL,TaintedURL,MAXCMD))
{
LOG_FATAL("Failed to taint the URL '%s'",URL);
SafeExit(10);
}
/*
Wget options:
--progress=dot :: display a new line as it progresses.
--no-check-certificate :: download HTTPS files even if the cert cannot
be validated. (Neal has many issues with SSL and does not view it
as very secure.) Without this, some caching proxies and web sites
with old certs won't download. Granted, in theory a bad cert should
prevent downloads. In reality, 99.9% of bad certs are because the
admin did not notice that they expired and not because of a hijacking
attempt.
*/
struct stat sb;
int rc_system =0;
char no_proxy[MAXCMD] = {0};
char proxy[MAXCMD] = {0};
char proxy_temp[MAXCMD] = {0};
/* http_proxy is optional so don't error if it doesn't exist */
/** set proxy */
if (GlobalProxy[0] && GlobalProxy[0][0])
{
snprintf(proxy_temp, MAXCMD-1, "export http_proxy='%s' ;", GlobalProxy[0]);
strcat(proxy, proxy_temp);
}
if (GlobalProxy[1] && GlobalProxy[1][0])
{
snprintf(proxy_temp, MAXCMD-1, "export https_proxy='%s' ;", GlobalProxy[1]);
strcat(proxy, proxy_temp);
}
if (GlobalProxy[2] && GlobalProxy[2][0])
{
snprintf(proxy_temp, MAXCMD-1, "export ftp_proxy='%s' ;", GlobalProxy[2]);
strcat(proxy, proxy_temp);
}
if (GlobalProxy[3] && GlobalProxy[3][0])
{
snprintf(no_proxy, MAXCMD-1, "-e no_proxy='%s'", GlobalProxy[3]);
}
char *dest;
int res;
dest = PrepareWgetDest(TempFile, TempFileDir, TempFileDirectory);
if (dest) {
res = asprintf(&cmd," %s /usr/bin/wget -q %s -P '%s' '%s' %s %s 2>&1",
proxy, WgetArgs, dest, TaintedURL, GlobalParam, no_proxy);
}
else
{
res = asprintf(&cmd," %s /usr/bin/wget -q %s '%s' %s %s 2>&1",
proxy, WgetArgs, TaintedURL, GlobalParam, no_proxy);
}
if (res == -1)
{
ASPRINTF_MEM_ERROR_LOG;
SafeExit(ASPRINTF_MEM_ERROR);
}
/* the command is like
". /usr/local/etc/fossology/Proxy.conf;
/usr/bin/wget -q --no-check-certificate --progress=dot -rc -np -e robots=off -P
'/srv/fossology/repository/localhost/wget/wget.xxx.dir/'
'http://a.org/file' -l 1 -R index.html* 2>&1"
*/
LOG_VERBOSE0("CMD: %s", cmd);
rc = system(cmd);
if (WIFEXITED(rc) && (WEXITSTATUS(rc) != 0))
{
LOG_FATAL("upload %ld Download failed; Return code %d from: %s",GlobalUploadKey,WEXITSTATUS(rc),cmd);
unlink(GlobalTempFile);
rc_system = system(DeleteTempDirCmd);
if (!WIFEXITED(rc_system)) systemError(__LINE__, rc_system, DeleteTempDirCmd)
SafeExit(12);
}
/* Run from scheduler! store /srv/fossology/repository/localhost/wget/wget.xxx.dir/<files|directories> to one temp file */
if (TempFile && TempFile[0])
{
char TempFilePath[MAXCMD];
memset(TempFilePath,'\0',MAXCMD);
/* for one url http://a.org/test.deb, TempFilePath should be /srv/fossology/repository/localhost/wget/wget.xxx.dir/a.org/test.deb */
int Position = GetPosition(TaintedURL);
if (0 == Position)
{
LOG_FATAL("path %s is not http://, https://, or ftp://", TaintedURL);
unlink(GlobalTempFile);
rc_system = system(DeleteTempDirCmd);
if (!WIFEXITED(rc_system)) systemError(__LINE__, rc_system, DeleteTempDirCmd)
SafeExit(26);
}
snprintf(TempFilePath, MAXCMD-1, "%s/%s", TempFileDirectory, TaintedURL + Position);
if (!stat(TempFilePath, &sb))
{
if (S_ISDIR(sb.st_mode))
{
res = asprintf(&cmd, "find '%s' -mindepth 1 -type d -empty -exec rmdir {} \\; > /dev/null 2>&1", TempFilePath);
if (res == -1)
{
ASPRINTF_MEM_ERROR_LOG;
SafeExit(ASPRINTF_MEM_ERROR);
}
rc_system = system(cmd); // delete all empty directories downloaded
if (!WIFEXITED(rc_system)) systemError(__LINE__, rc_system, cmd)
free(cmd);
res = asprintf(&cmd, "tar -cf '%s' -C '%s' ./ 1>/dev/null", TempFile, TempFilePath);
if (res == -1)
{
ASPRINTF_MEM_ERROR_LOG;
SafeExit(ASPRINTF_MEM_ERROR);
}
}
else
{
res = asprintf(&cmd, "mv '%s' '%s' 2>&1", TempFilePath, TempFile);
if (res == -1)
{
ASPRINTF_MEM_ERROR_LOG;
SafeExit(ASPRINTF_MEM_ERROR);
}
}
rc_system = system(cmd);
if (rc_system != 0)
{
systemError(__LINE__, rc_system, cmd)
free(cmd);
unlink(GlobalTempFile);
rc_system = system(DeleteTempDirCmd);
if (!WIFEXITED(rc_system)) systemError(__LINE__, rc_system, DeleteTempDirCmd)
SafeExit(24); // failed to store the temperary directory(one file) as one temperary file
}
}
else
{
res = asprintf(&cmd, "find '%s' -type f -exec mv {} %s \\; > /dev/null 2>&1", TempFileDirectory, TempFile);
if (res == -1)
{
ASPRINTF_MEM_ERROR_LOG;
SafeExit(ASPRINTF_MEM_ERROR);
}
rc_system = system(cmd);
if (rc_system != 0)
{
systemError(__LINE__, rc_system, cmd)
free(cmd);
unlink(GlobalTempFile);
rc_system = system(DeleteTempDirCmd);
if (!WIFEXITED(rc_system)) systemError(__LINE__, rc_system, DeleteTempDirCmd)
SafeExit(24); // failed to store the temperary directory(one file) as one temperary file
}
}
}
if (TempFile && TempFile[0] && !IsFile(TempFile,1))
{
LOG_FATAL("upload %ld File %s not created from URL: %s, CMD: %s",GlobalUploadKey,TempFile,URL, cmd);
free(cmd);
unlink(GlobalTempFile);
rc_system = system(DeleteTempDirCmd);
if (!WIFEXITED(rc_system)) systemError(__LINE__, rc_system, DeleteTempDirCmd)
SafeExit(15);
}
free(cmd);
/* remove the temp dir /srv/fossology/repository/localhost/wget/wget.xxx.dir/ for this upload */
rc_system = system(DeleteTempDirCmd);
if (!WIFEXITED(rc_system)) systemError(__LINE__, rc_system, DeleteTempDirCmd)
LOG_VERBOSE0("upload %ld Downloaded %s to %s",GlobalUploadKey,URL,TempFile);
return(0);
} /* GetURL() */
/**
* \brief Get source code from version control system
* \return int - 0: successful; others: fail
*/
int GetVersionControl()
{
char *command = NULL;
char *tmp_file_directory;
char *delete_tmpdir_cmd;
char *tmp_home;
int rc = 0;
int resethome = 0; // 0: default; 1: home is null before setting, should rollback
char *homeenv = NULL;
int res;
homeenv = getenv("HOME");
if(NULL == homeenv) resethome = 1;
/* We need HOME to point to where .gitconfig is installed
* path is the repository path and .gitconfig is installed in its parent directory
*/
res = asprintf(&tmp_home, "%s/..", fo_config_get(sysconfig, "FOSSOLOGY", "path", NULL));
if (res == -1)
{
return ASPRINTF_MEM_ERROR;
}
setenv("HOME", tmp_home, 1);
free(tmp_home);
/* save each upload files in /srv/fossology/repository/localhost/wget/wget.xxx.dir/ */
res = asprintf(&tmp_file_directory, "%s.dir", GlobalTempFile);
if (res == -1)
{
return ASPRINTF_MEM_ERROR;
}
res = asprintf(&delete_tmpdir_cmd, "rm -rf %s", tmp_file_directory);
if (res == -1)
{
free(tmp_file_directory);
return ASPRINTF_MEM_ERROR;
}
command = GetVersionControlCommand(1);
rc = system(command);
if (resethome) // rollback
unsetenv("HOME");
else
setenv("HOME", homeenv, 1);
if (rc != 0)
{
command = GetVersionControlCommand(-1);
systemError(__LINE__, rc, command)
/** for user fossy
\code git: git config --global http.proxy web-proxy.cce.hp.com:8088; git clone http://github.com/schacon/grit.git
svn: svn checkout --config-option servers:global:http-proxy-host=web-proxy.cce.hp.com --config-option servers:global:http-proxy-port=8088 https://svn.code.sf.net/p/fossology/code/trunk/fossology/utils/ \endcode
*/
LOG_FATAL("please make sure the URL of repo is correct, also add correct proxy for your version control system, command is:%s, GlobalTempFile is:%s, rc is:%d. \n", command, GlobalTempFile, rc);
/* remove the temp dir /srv/fossology/repository/localhost/wget/wget.xxx.dir/ for this upload */
rc = system(delete_tmpdir_cmd);
if (!WIFEXITED(rc)) systemError(__LINE__, rc, delete_tmpdir_cmd)
free(tmp_file_directory);
free(delete_tmpdir_cmd);
return 1;
}
snprintf(command,MAXCMD-1, "tar -cf '%s' -C '%s' ./ 1>/dev/null", GlobalTempFile, tmp_file_directory);
free(tmp_file_directory);
rc = system(command);
if (rc != 0)
{
systemError(__LINE__, rc, command)
/* remove the temp dir /srv/fossology/repository/localhost/wget/wget.xxx.dir/ for this upload */
rc = system(delete_tmpdir_cmd);
if (!WIFEXITED(rc)) systemError(__LINE__, rc, delete_tmpdir_cmd)
LOG_FATAL("DeleteTempDirCmd is:%s\n", delete_tmpdir_cmd);
free(delete_tmpdir_cmd);
return 1;
}
/* remove the temp dir /srv/fossology/repository/localhost/wget/wget.xxx.dir/ for this upload */
rc = system(delete_tmpdir_cmd);
if (!WIFEXITED(rc)) systemError(__LINE__, rc, delete_tmpdir_cmd)
free(delete_tmpdir_cmd);
return 0; // succeed to retrieve source
}
/**
* \brief Convert input pairs into globals.
*
* This functions taints the parameters as needed.
* \param S The parameters for wget_aget have 2 parts, one is from scheduler, that is S
* \param TempFileDir The parameters for wget_aget have 2 parts, one is from wget_agent.conf, that is TempFileDir
*/
void SetEnv (char *S, char *TempFileDir)
{
int SLen,GLen; /* lengths for S and global string */
GlobalUploadKey = -1;
memset(GlobalTempFile,'\0',MAXCMD);
memset(GlobalURL,'\0',MAXCMD);
if (!S) return;
/* first value is the upload_pk */
GlobalUploadKey = atol(S);
while(S[0] && isdigit(S[0])) S++;
while(S[0] && isspace(S[0])) S++; /* skip spaces */
#if 1
/* second value is the temp file location */
/** This will be removed when the jobqueue is changed. **/
SLen=0;
GLen=0;
while((GLen < MAXCMD-4) && S[SLen] && !isspace(S[SLen]))
{
if ((S[SLen] == '\'') || isspace(S[SLen]) || !isprint(S[SLen]))
{
sprintf(GlobalTempFile+GLen,"%%%02x",(unsigned char)(S[SLen]));
GLen += 3;
}
else GlobalTempFile[GLen++] = S[SLen];
SLen++;
}
S+=SLen;
while(S[0] && isspace(S[0])) S++; /* skip spaces */
#endif
if (TempFileDir)
{
memset(GlobalTempFile,'\0',MAXCMD);
snprintf(GlobalTempFile,MAXCMD-1,"%s/wget.%d",TempFileDir,getpid());
}
/* third value is the URL location -- taint any single-quotes */
SLen=0;
GLen=0;
while((GLen < MAXCMD-4) && S[SLen])
{
if ((S[SLen] == '\\') && isprint(S[SLen+1])) // in file path, if include '\ ', that mean this file name include spaces
{
LOG_FATAL("S[SLen] is:%c\n", S[SLen]);
GlobalURL[GLen++] = ' ';
SLen += 2;
continue;
}
else if ((S[SLen] != '\\') && isspace(S[SLen])) break;
else if ((S[SLen] == '\'') || isspace(S[SLen]) || !isprint(S[SLen]))
{
sprintf(GlobalURL+GLen,"%%%02x",(unsigned char)(S[SLen]));
GLen += 3;
}
else GlobalURL[GLen++] = S[SLen];
SLen++;
}
S+=SLen;
while(S[0] && isspace(S[0])) S++; /* skip spaces */
char Type[][4] = {"SVN", "Git", "CVS"};
int i = 0; // type index
memset(GlobalType,'\0',MAXCMD);
strncpy(GlobalType, S, 3);
if ((0 == strcmp(GlobalType, Type[i++])) || (0 == strcmp(GlobalType, Type[i++])) || (0 == strcmp(GlobalType, Type[i++])))
{
S += 3;
}
else
{
memset(GlobalType,'\0',MAXCMD);
}
strncpy(GlobalParam, S, sizeof(GlobalParam)); // get the parameters, kind of " -A rpm -R fosso -l 1* "
LOG_VERBOSE0(" upload %ld wget_agent globals loaded:\n upload_pk = %ld\n tmpfile=%s URL=%s GlobalParam=%s\n",GlobalUploadKey, GlobalUploadKey,GlobalTempFile,GlobalURL,GlobalParam);
} /* SetEnv() */
/**
* \brief Check if path contains a "%H", "%R".
*
* Substitute the "%H" with hostname and "%R" with repo location.
* \parm DirPath Directory path.
* \returns new directory path
*/
char *PathCheck(char *DirPath)
{
char *NewPath;
char *subs;
char TmpPath[2048];
char HostName[2048];
NewPath = strdup(DirPath);
if ((subs = strstr(NewPath,"%H")) )
{
/* hostname substitution */
gethostname(HostName, sizeof(HostName));
*subs = 0;
snprintf(TmpPath, sizeof(TmpPath), "%s%s%s", NewPath, HostName, subs+2);
free(NewPath);
NewPath = strdup(TmpPath);
}
if ((subs = strstr(NewPath, "%R")) )
{
/* repo location substitution */
*subs = 0;
snprintf(TmpPath, sizeof(TmpPath), "%s%s%s", NewPath, fo_config_get(sysconfig, "FOSSOLOGY", "path", NULL), subs+2);
free(NewPath);
NewPath = strdup(TmpPath);
}
return(NewPath);
}
/**
* \brief Copy downloaded files to temporary directory
*
* If the path(fs) is a directory, create a tar file from files(dir) in a directory
* to the temporary directory.
*
* If the path(fs) is a file, copy the file to the temporary directory
* \param Path The fs will be handled, directory(file) you want to upload from server
* \param TempFile The tar(regular) file name
* \param TempFileDir Temporary directory path
* \param Status The status of Path
*
* \return 1 on sucess, 0 on failure
*/
int Archivefs(char *Path, char *TempFile, char *TempFileDir, struct stat Status)
{
char CMD[MAXCMD] = {0};
int rc_system = 0;
snprintf(CMD,MAXCMD-1, "mkdir -p '%s' >/dev/null 2>&1", TempFileDir);
rc_system = system(CMD);
if (!WIFEXITED(rc_system))
{
LOG_FATAL("[%s:%d] Could not create temporary directory", __FILE__, __LINE__);
systemError(__LINE__, rc_system, CMD)
return 0;
}
if (S_ISDIR(Status.st_mode)) /* directory? */
{
memset(CMD,'\0', MAXCMD);
snprintf(CMD,MAXCMD-1, "tar %s -cf '%s' -C '%s' ./ 1>/dev/null", GlobalParam, TempFile, Path);
rc_system = system(CMD);
if (!WIFEXITED(rc_system))
{
systemError(__LINE__, rc_system, CMD)
return 0;
}
} else if (strstr(Path, "*")) // wildcards
{
memset(CMD, '\0', MAXCMD);
/* for the wildcards upload, keep the path */
/* copy * files to TempFileDir/temp primarily */
snprintf(CMD,MAXCMD-1, "mkdir -p '%s/temp' > /dev/null 2>&1 && cp -r %s '%s/temp' > /dev/null 2>&1", TempFileDir, Path, TempFileDir);
rc_system = system(CMD);
if (rc_system != 0)
{
systemError(__LINE__, rc_system, CMD)
return 0;
}
memset(CMD, '\0', MAXCMD);
snprintf(CMD,MAXCMD-1, "tar -cf '%s' -C %s/temp ./ 1> /dev/null && rm -rf %s/temp > /dev/null 2>&1", TempFile, TempFileDir, TempFileDir);
rc_system = system(CMD);
if (rc_system != 0)
{
systemError(__LINE__, rc_system, CMD)
return 0;
}
} else if(S_ISREG(Status.st_mode)) /* regular file? */
{
memset(CMD, '\0', MAXCMD);
snprintf(CMD,MAXCMD-1, "cp '%s' '%s' >/dev/null 2>&1", Path, TempFile);
rc_system = system(CMD);
if (rc_system != 0)
{
systemError(__LINE__, rc_system, CMD)
return 0;
}
}
else return 0; /* neither a directory nor a regular file */
return 1;
}
/**
* \brief Get proxy from fossology.conf
*
* Get proxy from fossology.conf and copy in GlobalProxy array
*/
void GetProxy()
{
int i = 0;
int count_temp = 0;
char *http_proxy_host = NULL;
char *http_proxy_port = NULL;
char *http_temp = NULL;
for (i = 0; i < 6; i++)
{
GlobalProxy[i++] = NULL;
}
GError* error1 = NULL;
GError* error2 = NULL;
GError* error3 = NULL;
GError* error4 = NULL;
i = 0;
GlobalProxy[i] = fo_config_get(sysconfig, "FOSSOLOGY", "http_proxy", &error1);
trim(GlobalProxy[i++]);
GlobalProxy[i] = fo_config_get(sysconfig, "FOSSOLOGY", "https_proxy", &error2);
trim(GlobalProxy[i++]);
GlobalProxy[i] = fo_config_get(sysconfig, "FOSSOLOGY", "ftp_proxy", &error3);
trim(GlobalProxy[i++]);
GlobalProxy[i] = fo_config_get(sysconfig, "FOSSOLOGY", "no_proxy", &error4);
trim(GlobalProxy[i++]);
if (GlobalProxy[0] && GlobalProxy[0][0])
{
http_proxy_port = strrchr(GlobalProxy[0], ':');
strncpy(GlobalHttpProxy, GlobalProxy[0], (http_proxy_port - GlobalProxy[0]));
http_proxy_port++;
if (http_proxy_port && http_proxy_port[0])
{
/* exclude '/' in http_proxy_port and 'http://' in http_proxy_host */
http_temp = strchr(http_proxy_port, '/');
if (http_temp && http_temp[0])
{
count_temp = http_temp - http_proxy_port;
http_proxy_port[count_temp] = 0;
}
GlobalProxy[4] = GlobalHttpProxy;
GlobalProxy[5] = http_proxy_port;
http_proxy_host = strrchr(GlobalHttpProxy, '/');
if (http_proxy_host && http_proxy_host[0])
{
http_proxy_host++;
GlobalProxy[4] = http_proxy_host;
}
}
}
}
/**
* \brief Here are some suggested options
* \param Name The name of the executable, usually it is wget_agent
*/
void Usage(char *Name)
{
printf("Usage: %s [options] [OBJ]\n",Name);
printf(" -h :: help (print this message), then exit.\n");
printf(" -i :: Initialize the DB connection then exit (nothing downloaded)\n");
printf(" -g group :: Set the group on processed files (e.g., -g fossy).\n");
printf(" -G :: Do NOT copy the file to the gold repository.\n");
printf(" -d dir :: directory for downloaded file storage\n");
printf(" -k key :: upload key identifier (number)\n");
printf(" -A acclist :: Specify comma-separated lists of file name suffixes or patterns to accept.\n");
printf(" -R rejlist :: Specify comma-separated lists of file name suffixes or patterns to reject.\n");
printf(" -l depth :: Specify recursion maximum depth level depth. The default maximum depth is 5.\n");
printf(" -c configdir :: Specify the directory for the system configuration.\n");
printf(" -C :: run from command line.\n");
printf(" -v :: verbose (-vv = more verbose).\n");
printf(" -V :: print the version info, then exit.\n");
printf(" OBJ :: if a URL is listed, then it is retrieved.\n");
printf(" if a file is listed, then it used.\n");
printf(" if OBJ and Key are provided, then it is inserted into\n");
printf(" the DB and repository.\n");
printf(" no file :: process data from the scheduler.\n");
} /* Usage() */
/**
* \brief Translate authentication of git clone
*
* Translate authentication of git clone
* from http://git.code.sf.net/p/fossology/fossology.git --username --password password (input)
* to http://username:password@git.code.sf.net/p/fossology/fossology.git
*/
void replace_url_with_auth()
{
const char needle[] = " ";
const char needle2[] = "//";
int index = 0;
char *username = NULL;
char *password = NULL;
char http[10] = "";
char URI[FILEPATH] = "";
char *token = NULL;
char *temp = NULL;
if (strstr(GlobalParam, "password") && strstr(GlobalParam, "username"))
{
temp = strstr(GlobalURL, needle2);
strcpy(URI, temp + 2);
strncpy(http, GlobalURL, strlen(GlobalURL) - strlen(URI));
/* get the first token */
token = strtok(GlobalParam, needle);
/* walk through other tokens */
while( token != NULL )
{
if (1 == index) username = token;
if (3 == index) password = token;
token = strtok(NULL, needle);
index++;
}
snprintf(GlobalURL, FILEPATH, "%s%s:%s@%s", http, username, password, URI);
memset(GlobalParam,'\0',MAXCMD);
}
}