home *** CD-ROM | disk | FTP | other *** search
/ PC World 2007 March / PCWorld_2007-03_cd.bin / v cisle / httrack / httrack-3.41-2.exe / {app} / src / htslib.c < prev    next >
Encoding:
C/C++ Source or Header  |  2007-02-03  |  155.7 KB  |  5,574 lines

  1. /* ------------------------------------------------------------ */
  2. /*
  3. HTTrack Website Copier, Offline Browser for Windows and Unix
  4. Copyright (C) Xavier Roche and other contributors
  5.  
  6. This program is free software; you can redistribute it and/or
  7. modify it under the terms of the GNU General Public License
  8. as published by the Free Software Foundation; either version 2
  9. of the License, or any later version.
  10.  
  11. This program is distributed in the hope that it will be useful,
  12. but WITHOUT ANY WARRANTY; without even the implied warranty of
  13. MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
  14. GNU General Public License for more details.
  15.  
  16. You should have received a copy of the GNU General Public License
  17. along with this program; if not, write to the Free Software
  18. Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA  02111-1307, USA.
  19.  
  20.  
  21. Important notes:
  22.  
  23. - We hereby ask people using this source NOT to use it in purpose of grabbing
  24. emails addresses, or collecting any other private information on persons.
  25. This would disgrace our work, and spoil the many hours we spent on it.
  26.  
  27.  
  28. Please visit our Website: http://www.httrack.com
  29. */
  30.  
  31.  
  32. /* ------------------------------------------------------------ */
  33. /* File: Subroutines                                            */
  34. /* Author: Xavier Roche                                         */
  35. /* ------------------------------------------------------------ */
  36.  
  37. /* Internal engine bytecode */
  38. #define HTS_INTERNAL_BYTECODE
  39.  
  40. // Fichier librairie .c
  41.  
  42. #include "htscore.h"
  43.  
  44. #ifdef _WIN32_WCE
  45. #ifndef HTS_CECOMPAT
  46. #pragma comment(lib, "celib.lib") //link with celib
  47. #endif
  48. #endif
  49.  
  50. /* specific definitions */
  51. #include "htsbase.h"
  52. #include "htsnet.h"
  53. #include "htsbauth.h"
  54. #include "htsthread.h"
  55. #include "htsback.h"
  56. #include "htswrap.h"
  57. #include "htsmd5.h"
  58. #include "htsmodules.h"
  59.  
  60. #ifdef _WIN32
  61. #ifndef  _WIN32_WCE
  62. #include <direct.h>
  63. #endif
  64. #else
  65. #ifdef HAVE_SYS_TYPES_H
  66. #include <sys/types.h>
  67. #endif
  68. #ifdef HAVE_SYS_STAT_H
  69. #include <sys/stat.h>
  70. #endif
  71. #ifdef HAVE_UNISTD_H
  72. #include <unistd.h>
  73. #endif
  74. #endif  /* _WIN32 */
  75.  
  76. #include <string.h>
  77. #include <time.h>
  78.  
  79. #ifndef  _WIN32_WCE
  80. #include <sys/timeb.h>
  81. #include <fcntl.h>
  82. #else
  83. #ifndef HTS_CECOMPAT
  84. #include <sys/timeb.h>
  85. #endif
  86. #endif  /* _WIN32_WCE */
  87.  
  88. // pour utimbuf
  89. #ifdef _WIN32
  90. #ifndef _WIN32_WCE
  91. #include <sys/utime.h>
  92. #else
  93. #ifndef HTS_CECOMPAT
  94. #include <sys/utime.h>
  95. #endif
  96. #endif
  97. #else
  98. #include <utime.h>
  99. #endif  /* _WIN32 */
  100.  
  101. #ifndef _WIN32_WCE
  102. #include <sys/stat.h>
  103. #endif
  104. /* END specific definitions */
  105.  
  106.  
  107. // Debugging
  108. #if _HTS_WIDE
  109. FILE* DEBUG_fp=NULL;
  110. #endif
  111.  
  112. /* variables globales */
  113. int _DEBUG_HEAD;
  114. FILE* ioinfo;
  115.  
  116. #if HTS_USEOPENSSL
  117.  SSL_CTX *openssl_ctx = NULL;
  118. #endif
  119. int IPV6_resolver = 0;
  120.  
  121. /* dΘtection complΘmentaire */
  122. const char* hts_detect[] = {
  123.   "archive",
  124.   "background",
  125.   "data",         // OBJECT
  126.   "dynsrc",
  127.   "lowsrc",
  128.   "profile",      // element META
  129.   "src",
  130.   "swurl",
  131.   "url",
  132.   "usemap",
  133.   "longdesc",     // accessibility
  134.   "xlink:href",   // xml/svg tag
  135.   ""
  136. };
  137.  
  138. /* dΘtecter dΘbut */
  139. const char* hts_detectbeg[] = {
  140.   "hotspot",      /* hotspot1=..,hotspot2=.. */
  141.   ""
  142. };
  143.  
  144. /* ne pas dΘtcter de liens dedans */
  145. const char* hts_nodetect[] = {
  146.   "accept-charset",
  147.   "accesskey",
  148.   "action",
  149.   "align",
  150.   "alt",
  151.   "axes",
  152.   "axis",
  153.   "char",
  154.   "charset",
  155.   "cite",
  156.   "class",
  157.   "classid",
  158.   "code",
  159.   "color",
  160.   "datetime",
  161.   "dir",
  162.   "enctype",
  163.   "face",
  164.   "height",
  165.   "id",
  166.   "lang",
  167.   "language",
  168.   "media",
  169.   "method",
  170.   "name",
  171.   "prompt",
  172.   "scheme",
  173.   "size",
  174.   "style",
  175.   "target",
  176.   "title",
  177.   "type",
  178.   "valign",
  179.   "version",
  180.   "width",
  181.   ""
  182. };
  183.  
  184.  
  185. /* dΘtection de mini-code javascript */
  186. /* ALSO USED: detection based on the name: onXXX="<tag>" where XXX starts with upper case letter */
  187. const char* hts_detect_js[] = {
  188.   "onAbort",
  189.   "onBlur",
  190.   "onChange",
  191.   "onClick",
  192.   "onDblClick",
  193.   "onDragDrop",
  194.   "onError",
  195.   "onFocus",
  196.   "onKeyDown",
  197.   "onKeyPress",
  198.   "onKeyUp",
  199.   "onLoad",
  200.   "onMouseDown",
  201.   "onMouseMove",
  202.   "onMouseOut",
  203.   "onMouseOver",
  204.   "onMouseUp",
  205.   "onMove",
  206.   "onReset",
  207.   "onResize",
  208.   "onSelect",
  209.   "onSubmit",
  210.   "onUnload",
  211.   "style",          /* hack for CSS code data */
  212.   ""
  213. };
  214.  
  215. const char* hts_main_mime[] = {
  216.   "application",
  217.   "audio",
  218.   "image",
  219.   "message",
  220.   "multipart",
  221.   "text",
  222.   "video",
  223.   ""
  224. };
  225.  
  226. /* dΘtection "...URL=<url>" */
  227. const char* hts_detectURL[] = {
  228.   "content",
  229.   ""
  230. };
  231.  
  232. /* tags o∙ l'URL doit Ωtre rΘΘcrite mais non capturΘe */
  233. const char* hts_detectandleave[] = {
  234.   "action",
  235.   ""
  236. };
  237.  
  238. /* ne pas renommer les types renvoyΘs (souvent types inconnus) */
  239. const char* hts_mime_keep[] = {
  240.   "application/octet-stream",
  241.   "text/plain",
  242.   ""
  243. };
  244.  
  245. /* pas de type mime connu, mais extension connue */
  246. const char* hts_ext_dynamic[] = {
  247.   "php3",
  248.   "php",
  249.   "php4",
  250.   "php2",
  251.   "cgi",
  252.   "asp",
  253.   "jsp",
  254.   "pl",
  255.   /*"exe",*/
  256.   "cfm",
  257.   "nsf", /* lotus */
  258.   ""
  259. };
  260.  
  261. /* types MIME 
  262.    note: application/octet-stream should not be used here
  263. */
  264. const char* hts_mime[][2] = {
  265.   {"application/acad","dwg"},
  266.   {"application/arj","arj"},
  267.   {"application/clariscad","ccad"},
  268.   {"application/drafting","drw"},
  269.   {"application/dxf","dxf"},
  270.   {"application/excel","xls"},
  271.   {"application/i-deas","unv"},
  272.   {"application/iges","isg"},
  273.   {"application/iges","iges"},
  274.   {"application/mac-binhex40","hqx"},
  275.   {"application/mac-compactpro","cpt"},
  276.   {"application/msword","doc"},
  277.   {"application/msword","w6w"},
  278.   {"application/msword","word"},
  279.   {"application/mswrite","wri"},
  280.   /*{"application/octet-stream","dms"},*/
  281.   /*{"application/octet-stream","lzh"},*/
  282.   /*{"application/octet-stream","lha"},*/
  283.   /*{"application/octet-stream","bin"},*/
  284.   {"application/oda","oda"},
  285.   {"application/pdf","pdf"},
  286.   {"application/postscript","ps"},
  287.   {"application/postscript","ai"},
  288.   {"application/postscript","eps"},
  289.   {"application/powerpoint","ppt"},
  290.   {"application/pro_eng","prt"},
  291.   {"application/pro_eng","part"},
  292.   {"application/rtf","rtf"},
  293.   {"application/set","set"},
  294.   {"application/sla","stl"},
  295.   {"application/smil","smi"},
  296.   {"application/smil","smil"},
  297.   {"application/smil","sml"},
  298.   {"application/solids","sol"},
  299.   {"application/STEP","stp"},
  300.   {"application/STEP","step"},
  301.   {"application/vda","vda"},
  302.   {"application/x-authorware-map","aam"},     
  303.   {"application/x-authorware-seg","aas"},
  304.   {"application/x-authorware-bin","aab"},
  305.   {"application/x-bzip2","bz2"},
  306.   {"application/x-cocoa","cco"},
  307.   {"application/x-csh","csh"},
  308.   {"application/x-director","dir"},
  309.   {"application/x-director","dcr"},
  310.   {"application/x-director","dxr"},
  311.   {"application/x-mif","mif"},
  312.   {"application/x-dvi","dvi"},
  313.   {"application/x-gzip","gz"},
  314.   {"application/x-gzip","gzip"},
  315.   {"application/x-hdf","hdf"},
  316.   {"application/x-javascript","js"},
  317.   {"application/x-koan","skp"},
  318.   {"application/x-koan","skd"},
  319.   {"application/x-koan","skt"},
  320.   {"application/x-koan","skm"},
  321.   {"application/x-latex","latex"},
  322.   {"application/x-netcdf","nc"},
  323.   {"application/x-netcdf","cdf"},
  324.   /* {"application/x-sh","sh"}, */
  325.   /* {"application/x-csh","csh"}, */
  326.   /* {"application/x-ksh","ksh"}, */
  327.   {"application/x-shar","shar"},
  328.   {"application/x-stuffit","sit"},
  329.   {"application/x-tcl","tcl"},
  330.   {"application/x-tex","tex"},
  331.   {"application/x-texinfo","texinfo"},
  332.   {"application/x-texinfo","texi"},
  333.   {"application/x-troff","t"},
  334.   {"application/x-troff","tr"},
  335.   {"application/x-troff","roff"},
  336.   {"application/x-troff-man","man"},
  337.   {"application/x-troff-me","ms"},
  338.   {"application/x-wais-source","src"},
  339.   {"application/zip","zip"},
  340.   {"application/x-zip-compressed","zip"},
  341.   {"application/x-bcpio","bcpio"},
  342.   {"application/x-cdlink","vcd"},
  343.   {"application/x-cpio","cpio"},
  344.   {"application/x-gtar","tgz"},
  345.   {"application/x-gtar","gtar"},
  346.   {"application/x-shar","shar"},
  347.   {"application/x-shockwave-flash","swf"},
  348.   {"application/x-sv4cpio","sv4cpio"},
  349.   {"application/x-sv4crc","sv4crc"},
  350.   {"application/x-tar","tar"},
  351.   {"application/x-ustar","ustar"},
  352.   {"application/x-winhelp","hlp"},
  353.   {"application/xml","xml"},  
  354.   {"audio/midi","mid"},
  355.   {"audio/midi","midi"},
  356.   {"audio/midi","kar"},
  357.   {"audio/mpeg","mp3"},
  358.   {"audio/mpeg","mpga"},
  359.   {"audio/mpeg","mp2"},
  360.   {"audio/basic","au"},
  361.   {"audio/basic","snd"},
  362.   {"audio/x-aiff","aif"},
  363.   {"audio/x-aiff","aiff"},
  364.   {"audio/x-aiff","aifc"},
  365.   {"audio/x-pn-realaudio","rm"},
  366.   {"audio/x-pn-realaudio","ram"},
  367.   {"audio/x-pn-realaudio","ra"},
  368.   {"audio/x-pn-realaudio-plugin","rpm"},
  369.   {"audio/x-wav","wav"},
  370.   {"chemical/x-pdb","pdb"},
  371.   {"chemical/x-pdb","xyz"},
  372.   {"drawing/x-dwf","dwf"},
  373.   {"image/gif","gif"},
  374.   {"image/ief","ief"},
  375.   {"image/jpeg","jpg"},
  376.   {"image/jpeg","jpe"},
  377.   {"image/jpeg","jpeg"},
  378.   {"image/pict","pict"},
  379.   {"image/png","png"},
  380.   {"image/tiff","tiff"},
  381.   {"image/tiff","tif"},
  382.   {"image/svg+xml","svg"},
  383.   {"image/svg-xml","svg"},
  384.   {"image/x-cmu-raster","ras"},
  385.   {"image/x-freehand","fh4"},
  386.   {"image/x-freehand","fh7"},
  387.   {"image/x-freehand","fh5"},  
  388.   {"image/x-freehand","fhc"},
  389.   {"image/x-freehand","fh"},   
  390.   {"image/x-portable-anymap","pnm"},
  391.   {"image/x-portable-bitmap","pgm"},
  392.   {"image/x-portable-pixmap","ppm"},
  393.   {"image/x-rgb","rgb"},
  394.   {"image/x-xbitmap","xbm"},
  395.   {"image/x-xpixmap","xpm"},
  396.   {"image/x-xwindowdump","xwd"},
  397.   {"model/mesh","msh"},  
  398.   {"model/mesh","mesh"},  
  399.   {"model/mesh","silo"},  
  400.   {"multipart/x-zip","zip"},
  401.   {"multipart/x-gzip","gzip"},
  402.   {"text/css","css"},
  403.   {"text/html","html"},
  404.   {"text/html","htm"},
  405.   {"text/plain","txt"},
  406.   {"text/plain","g"},
  407.   {"text/plain","h"},
  408.   {"text/plain","c"},
  409.   {"text/plain","cc"},
  410.   {"text/plain","hh"},
  411.   {"text/plain","m"},
  412.   {"text/plain","f90"},
  413.   {"text/richtext","rtx"},
  414.   {"text/tab-separated-values","tsv"},
  415.   {"text/x-setext","etx"},
  416.   {"text/x-sgml","sgml"},
  417.   {"text/x-sgml","sgm"},
  418.   {"text/xml","xml"},  
  419.   {"text/xml","dtd"},  
  420.   {"video/mpeg","mpeg"},
  421.   {"video/mpeg","mpg"},
  422.   {"video/mpeg","mpe"},
  423.   {"video/quicktime","qt"},
  424.   {"video/quicktime","mov"},
  425.   {"video/x-msvideo","avi"},
  426.   {"video/x-sgi-movie","movie"},
  427.   {"x-conference/x-cooltalk","ice"},
  428.   /*{"application/x-httpd-cgi","cgi"},*/
  429.   {"x-world/x-vrml","wrl"},
  430.  
  431.   /* More from w3schools.com */
  432.   { "application/envoy", "evy" },
  433.   { "application/fractals", "fif" },
  434.   { "application/futuresplash", "spl" },
  435.   { "application/hta", "hta" },
  436.   { "application/internet-property-stream", "acx" },
  437.   { "application/msword", "dot" },
  438.   { "application/olescript", "axs" },
  439.   { "application/pics-rules", "prf" },
  440.   { "application/pkcs10", "p10" },
  441.   { "application/pkix-crl", "crl" },
  442.   { "application/set-payment-initiation", "setpay" },
  443.   { "application/set-registration-initiation", "setreg" },
  444.   { "application/vnd.ms-excel", "xls" },
  445.   { "application/vnd.ms-excel", "xla" },
  446.   { "application/vnd.ms-excel", "xlc" },
  447.   { "application/vnd.ms-excel", "xlm" },
  448.   { "application/vnd.ms-excel", "xlt" },
  449.   { "application/vnd.ms-excel", "xlw" },
  450.   { "application/vnd.ms-pkicertstore", "sst" },
  451.   { "application/vnd.ms-pkiseccat", "cat" },
  452.   { "application/vnd.ms-powerpoint", "ppt" },
  453.   { "application/vnd.ms-powerpoint", "pot" },
  454.   { "application/vnd.ms-powerpoint", "pps" },
  455.   { "application/vnd.ms-project", "mpp" },
  456.   { "application/vnd.ms-works", "wcm" },
  457.   { "application/vnd.ms-works", "wdb" },
  458.   { "application/vnd.ms-works", "wks" },
  459.   { "application/vnd.ms-works", "wps" },
  460.   { "application/x-compress", "z" },
  461.   { "application/x-compressed", "tgz" },
  462.   { "application/x-internet-signup", "ins" },
  463.   { "application/x-internet-signup", "isp" },
  464.   { "application/x-iphone", "iii" },
  465.   { "application/x-javascript", "js" },
  466.   { "application/x-msaccess", "mdb" },
  467.   { "application/x-mscardfile", "crd" },
  468.   { "application/x-msclip", "clp" },
  469.   { "application/x-msmediaview", "m13" },
  470.   { "application/x-msmediaview", "m14" },
  471.   { "application/x-msmediaview", "mvb" },
  472.   { "application/x-msmetafile", "wmf" },
  473.   { "application/x-msmoney", "mny" },
  474.   { "application/x-mspublisher", "pub" },
  475.   { "application/x-msschedule", "scd" },
  476.   { "application/x-msterminal", "trm" },
  477.   { "application/x-perfmon", "pma" },
  478.   { "application/x-perfmon", "pmc" },
  479.   { "application/x-perfmon", "pml" },
  480.   { "application/x-perfmon", "pmr" },
  481.   { "application/x-perfmon", "pmw" },
  482.   { "application/x-pkcs12", "p12" },
  483.   { "application/x-pkcs12", "pfx" },
  484.   { "application/x-pkcs7-certificates", "p7b" },
  485.   { "application/x-pkcs7-certificates", "spc" },
  486.   { "application/x-pkcs7-certreqresp", "p7r" },
  487.   { "application/x-pkcs7-mime", "p7c" },
  488.   { "application/x-pkcs7-mime", "p7m" },
  489.   { "application/x-pkcs7-signature", "p7s" },
  490.   { "application/x-troff-me", "me" },
  491.   { "application/x-x509-ca-cert", "cer" },
  492.   { "application/x-x509-ca-cert", "crt" },
  493.   { "application/x-x509-ca-cert", "der" },
  494.   { "application/ynd.ms-pkipko", "pko" },
  495.   { "audio/mid", "mid" },
  496.   { "audio/mid", "rmi" },
  497.   { "audio/mpeg", "mp3" },
  498.   { "audio/x-mpegurl", "m3u" },
  499.   { "image/bmp", "bmp" },
  500.   { "image/cis-cod", "cod" },
  501.   { "image/pipeg", "jfif" },
  502.   { "image/x-cmx", "cmx" },
  503.   { "image/x-icon", "ico" },
  504.   { "image/x-portable-bitmap", "pbm" },
  505.   { "message/rfc822", "mht" },
  506.   { "message/rfc822", "mhtml" },
  507.   { "message/rfc822", "nws" },
  508.   { "text/css", "css" },
  509.   { "text/h323", "323" },
  510.   { "text/html", "stm" },
  511.   { "text/iuls", "uls" },
  512.   { "text/plain", "bas" },
  513.   { "text/scriptlet", "sct" },
  514.   { "text/webviewhtml", "htt" },
  515.   { "text/x-component", "htc" },
  516.   { "text/x-vcard", "vcf" },
  517.   { "video/mpeg", "mp2" },
  518.   { "video/mpeg", "mpa" },
  519.   { "video/mpeg", "mpv2" },
  520.   { "video/x-la-asf", "lsf" },
  521.   { "video/x-la-asf", "lsx" },
  522.   { "video/x-ms-asf", "asf" },
  523.   { "video/x-ms-asf", "asr" },
  524.   { "video/x-ms-asf", "asx" },
  525.   { "x-world/x-vrml", "flr" },
  526.   { "x-world/x-vrml", "vrml" },
  527.   { "x-world/x-vrml", "wrz" },
  528.   { "x-world/x-vrml", "xaf" },
  529.   { "x-world/x-vrml", "xof" },
  530.  
  531.   /* Various */
  532.   { "application/ogg", "ogg" },
  533.  
  534.   {"application/x-java-vm","class"},
  535.   
  536.   {"",""}};
  537.  
  538.  
  539. // Reserved (RFC2396)
  540. #define CIS(c,ch) ( ((unsigned char)(c)) == (ch) )
  541. #define CHAR_RESERVED(c)  ( CIS(c,';') \
  542.                          || CIS(c,'/') \
  543.                          || CIS(c,'?') \
  544.                          || CIS(c,':') \
  545.                          || CIS(c,'@') \
  546.                          || CIS(c,'&') \
  547.                          || CIS(c,'=') \
  548.                          || CIS(c,'+') \
  549.                          || CIS(c,'$') \
  550.                          || CIS(c,',') )
  551. //#define CHAR_RESERVED(c)  ( strchr(";/?:@&=+$,",(unsigned char)(c)) != 0 )
  552. // Delimiters (RFC2396)
  553. #define CHAR_DELIM(c)     ( CIS(c,'<') \
  554.                          || CIS(c,'>') \
  555.                          || CIS(c,'#') \
  556.                          || CIS(c,'%') \
  557.                          || CIS(c,'\"') )
  558. //#define CHAR_DELIM(c)     ( strchr("<>#%\"",(unsigned char)(c)) != 0 )
  559. // Unwise (RFC2396)
  560. #define CHAR_UNWISE(c)    ( CIS(c,'{') \
  561.                          || CIS(c,'}') \
  562.                          || CIS(c,'|') \
  563.                          || CIS(c,'\\') \
  564.                          || CIS(c,'^') \
  565.                          || CIS(c,'[') \
  566.                          || CIS(c,']') \
  567.                          || CIS(c,'`') )
  568. //#define CHAR_UNWISE(c)    ( strchr("{}|\\^[]`",(unsigned char)(c)) != 0 )
  569. // Special (escape chars) (RFC2396 + >127 )
  570. #define CHAR_LOW(c)       ( ((unsigned char)(c) <= 31) )
  571. #define CHAR_HIG(c)       ( ((unsigned char)(c) >= 127) )
  572. #define CHAR_SPECIAL(c)   ( CHAR_LOW(c) || CHAR_HIG(c) )
  573. // We try to avoid them and encode them instead
  574. #define CHAR_XXAVOID(c)   ( CIS(c,' ') \
  575.                          || CIS(c,'*') \
  576.                          || CIS(c,'\'') \
  577.                          || CIS(c,'\"') \
  578.                          || CIS(c,'&') \
  579.                          || CIS(c,'!') )
  580. //#define CHAR_XXAVOID(c)   ( strchr(" *'\"!",(unsigned char)(c)) != 0 )
  581. #define CHAR_MARK(c)      ( CIS(c,'-') \
  582.                          || CIS(c,'_') \
  583.                          || CIS(c,'.') \
  584.                          || CIS(c,'!') \
  585.                          || CIS(c,'~') \
  586.                          || CIS(c,'*') \
  587.                          || CIS(c,'\'') \
  588.                          || CIS(c,'(') \
  589.                          || CIS(c,')') )
  590. //#define CHAR_MARK(c)      ( strchr("-_.!~*'()",(unsigned char)(c)) != 0 )
  591.  
  592.  
  593.  
  594. // conversion Θventuelle / vers antislash
  595. #ifdef _WIN32
  596. char* antislash(char *catbuff, const char* s) {
  597.   char* a;
  598.   strcpybuff(catbuff,s);
  599.   while(a=strchr(catbuff,'/')) *a='\\';
  600.   return catbuff;
  601. }
  602. #endif
  603.  
  604. #ifdef _WIN32_WCE
  605. char cwd[MAX_PATH+1] = "";
  606. #endif
  607.  
  608. // RΘcupΘration d'un fichier http sur le net.
  609. // Renvoie une adresse sur le bloc de mΘmoire, ou bien
  610. // NULL si un retour.msgeur (buffer retour.msg) est survenue. 
  611. //
  612. // Une adresse de structure htsmsg peut Ωtre transmise pour
  613. // suivre l'Θvolution du chargement si le process a ΘtΘ lancΘ 
  614. // en background
  615.  
  616. htsblk httpget(httrackp *opt,char* url) {
  617.   char BIGSTK adr[HTS_URLMAXSIZE*2];   // adresse
  618.   char BIGSTK fil[HTS_URLMAXSIZE*2];   // chemin
  619.   
  620.   // sΘparer URL en adresse+chemin
  621.   if (ident_url_absolute(url,adr,fil)==-1) {
  622.     htsblk retour;
  623.     memset(&retour, 0, sizeof(htsblk));    // effacer
  624.     // retour prΘdΘfini: erreur
  625.     retour.adr=NULL;
  626.     retour.size=0;
  627.     retour.msg[0]='\0';
  628.     retour.statuscode=STATUSCODE_INVALID;    
  629.     strcpybuff(retour.msg,"Error invalid URL");
  630.     return retour;
  631.   }
  632.   
  633.   return xhttpget(opt,adr,fil);
  634. }
  635.  
  636. // ouvre une liaison http, envoie une requΦte GET et rΘceptionne le header
  637. // retour: socket
  638. int http_fopen(httrackp *opt,char* adr,char* fil,htsblk* retour) {
  639.   //                / GET, traiter en-tΩte
  640.   return http_xfopen(opt,0,1,1,NULL,adr,fil,retour);
  641. }
  642.  
  643. // ouverture d'une liaison http, envoi d'une requΦte
  644. // mode: 0 GET  1 HEAD  [2 POST]
  645. // treat: traiter header?
  646. // waitconnect: attendre le connect()
  647. // note: dans retour, on met les params du proxy
  648. int http_xfopen(httrackp *opt,int mode,int treat,int waitconnect,char* xsend,char* adr,char* fil,htsblk* retour) {
  649.   //htsblk retour;
  650.   //int bufl=TAILLE_BUFFER;    // 8Ko de buffer
  651.   T_SOC soc=INVALID_SOCKET;
  652.   //char *p,*q;
  653.   
  654.   // retour prΘdΘfini: erreur
  655.   if (retour) {
  656.     retour->adr=NULL;
  657.     retour->size=0;
  658.     retour->msg[0]='\0';
  659.     retour->statuscode=STATUSCODE_NON_FATAL;          // a priori erreur non fatale
  660.   }
  661.  
  662. #if HDEBUG
  663.   printf("adr=%s\nfichier=%s\n",adr,fil);
  664. #endif
  665.   
  666.   // ouvrir liaison
  667. #if HDEBUG
  668.   printf("CrΘation d'une socket sur %s\n",adr);
  669. #endif
  670.  
  671. #if CNXDEBUG
  672.   printf("..newhttp\n");
  673. #endif
  674.  
  675.   /* connexion */
  676.   if (retour) {
  677.     if ( (!(retour->req.proxy.active)) 
  678.       ||
  679.       (
  680.         (strcmp(adr,"file://")==0) 
  681.         ||
  682.         (strncmp(adr,"https://", 8)==0) 
  683.       )
  684.       ) {    /* pas de proxy, ou non utilisable ici */
  685.       soc=newhttp(opt,adr,retour,-1,waitconnect);
  686.     } else {
  687.       soc=newhttp(opt, retour->req.proxy.name, retour,retour->req.proxy.port, waitconnect);  // ouvrir sur le proxy α la place
  688.     }
  689.   } else {
  690.     soc=newhttp(opt,adr,NULL,-1,waitconnect);    
  691.   }
  692.  
  693.   // copier index socket retour
  694.   if (retour) retour->soc=soc;
  695.  
  696.   /* Check for errors */
  697.   if (soc == INVALID_SOCKET) {
  698.     if (retour) {
  699.       if (retour->msg) {
  700.         if (!strnotempty(retour->msg)) {
  701. #ifdef _WIN32
  702.           int last_errno = WSAGetLastError();
  703.           sprintf(retour->msg,"Connect error: %s", strerror(last_errno));
  704. #else
  705.           int last_errno = errno;
  706.           sprintf(retour->msg,"Connect error: %s", strerror(last_errno));
  707. #endif
  708.         }
  709.       }
  710.     }
  711.   }
  712.  
  713.   // --------------------
  714.   // court-circuit (court circuite aussi le proxy..)
  715.   // LOCAL_SOCKET_ID est une pseudo-socket locale
  716.   if (soc==LOCAL_SOCKET_ID) {
  717.     retour->is_file=1;  // fichier local
  718.     if (mode==0) {    // GET
  719.  
  720.       // Test en cas de file:///C|...
  721.       if (!fexist(fconv(OPT_GET_BUFF(opt), unescape_http(OPT_GET_BUFF(opt),fil))))
  722.         if (fexist(fconv(OPT_GET_BUFF(opt), unescape_http(OPT_GET_BUFF(opt),fil+1)))) {
  723.           char BIGSTK tempo[HTS_URLMAXSIZE*2];
  724.           strcpybuff(tempo,fil+1);
  725.           strcpybuff(fil,tempo);
  726.         }
  727.  
  728.       // Ouvrir
  729.       retour->totalsize=fsize(fconv(OPT_GET_BUFF(opt), unescape_http(OPT_GET_BUFF(opt),fil)));  // taille du fichier
  730.       retour->msg[0]='\0';
  731.       soc=INVALID_SOCKET;
  732.       if (retour->totalsize<0)
  733.         strcpybuff(retour->msg,"Unable to open local file");
  734.       else if (retour->totalsize==0)
  735.         strcpybuff(retour->msg,"File empty");
  736.       else {
  737.         // Note: On passe par un FILE* (plus propre)
  738.         //soc=open(fil,O_RDONLY,0);    // en lecture seule!
  739.         retour->fp=fopen(fconv(OPT_GET_BUFF(opt), unescape_http(OPT_GET_BUFF(opt),fil)),"rb");  // ouvrir
  740.         if (retour->fp==NULL)
  741.           soc=INVALID_SOCKET;
  742.         else
  743.           soc=LOCAL_SOCKET_ID;
  744.       }
  745.       retour->soc=soc;
  746.       if (soc!=INVALID_SOCKET) {
  747.         retour->statuscode=HTTP_OK;   // OK
  748.         strcpybuff(retour->msg,"OK");
  749.         guess_httptype(opt,retour->contenttype,fil);
  750.       } else if (strnotempty(retour->msg)==0)
  751.           strcpybuff(retour->msg,"Unable to open local file");
  752.       return soc;  // renvoyer
  753.     } else {    // HEAD ou POST : interdit sur un local!!!! (c'est idiot!)
  754.       strcpybuff(retour->msg,"Unexpected Head/Post local request");
  755.       soc=INVALID_SOCKET;    // erreur
  756.       retour->soc=soc;
  757.       return soc;
  758.     }
  759.   } 
  760.   // --------------------
  761.  
  762.   if (soc!=INVALID_SOCKET) {    
  763.     char rcvd[1100];
  764.     rcvd[0]='\0';
  765. #if HDEBUG
  766.     printf("Ok, connexion rΘussie, id=%d\n",soc);
  767. #endif
  768.     
  769.     // connectΘ?
  770.     if (waitconnect) {
  771.       http_sendhead(opt,NULL,mode,xsend,adr,fil,NULL,NULL,retour);
  772.     } 
  773.     
  774.     if (soc!=INVALID_SOCKET) {
  775.       
  776. #if HDEBUG
  777.       printf("Attente de la rΘponse:\n");
  778. #endif
  779.       
  780.       // si GET (rΘception d'un fichier), rΘceptionner en-tΩte d'abord,
  781.       // et ensuite le corps
  782.       // si POST on ne rΘceptionne rien du tout, c'est aprΦs que l'on fera
  783.       // une rΘception standard pour rΘcupΘrer l'en tΩte
  784.       if ((treat) && (waitconnect)) {  // traiter (attendre!) en-tΩte        
  785.         // RΘception de la status line et de l'en-tΩte (norme RFC1945)
  786.         
  787.         // status-line α rΘcupΘrer
  788.         finput(soc,rcvd,1024);
  789.         if (strnotempty(rcvd)==0)
  790.           finput(soc,rcvd,1024);    // "certains serveurs buggΘs envoient un \n au dΘbut" (RFC)
  791.  
  792.         // traiter status-line
  793.         treatfirstline(retour,rcvd);
  794.  
  795. #if HDEBUG
  796.         printf("Status-Code=%d\n",retour->statuscode);
  797. #endif
  798.         
  799.         // en-tΩte
  800.         
  801.         // header // ** !attention! HTTP/0.9 non supportΘ
  802.         do {
  803.           finput(soc,rcvd,1024);          
  804. #if HDEBUG
  805.           printf(">%s\n",rcvd);      
  806. #endif
  807.           if (strnotempty(rcvd))
  808.             treathead(NULL,NULL,NULL,retour,rcvd);  // traiter
  809.  
  810.         } while(strnotempty(rcvd));
  811.         
  812.         //rcvsize=-1;    // forCER CHARGEMENT INCONNU
  813.         
  814.         //if (retour)
  815.         //  retour->totalsize=rcvsize;
  816.         
  817.       } else { // si GET, on recevra l'en tΩte APRES
  818.         //rcvsize=-1;    // on ne connait pas la taille de l'en-tΩte
  819.         if (retour)
  820.           retour->totalsize=-1;
  821.       }
  822.       
  823.     }
  824.  
  825.   }
  826.     
  827.   return soc;
  828. }
  829.  
  830.  
  831. // envoi d'une requΦte
  832. int http_sendhead(httrackp *opt,t_cookie* cookie,int mode,char* xsend,char* adr,char* fil,char* referer_adr,char* referer_fil,htsblk* retour) {
  833.   char BIGSTK buff[8192];
  834.   //int use_11=0;     // HTTP 1.1 utilisΘ
  835.   int direct_url=0; // ne pas analyser l'url (exemple: ftp://)
  836.   char* search_tag=NULL;
  837.   buff[0]='\0';
  838.  
  839.   // header Date
  840.   //strcatbuff(buff,"Date: ");
  841.   //time_gmt_rfc822(buff);    // obtenir l'heure au format rfc822
  842.   //sendc("\n");
  843.   //strcatbuff(buff,buff);
  844.  
  845.   // possibilitΘ non documentΘe: >post: et >postfile:
  846.   // si prΘsence d'un tag >post: alors executer un POST
  847.   // exemple: http://www.someweb.com/test.cgi?foo>post:posteddata=10&foo=5
  848.   // si prΘsence d'un tag >postfile: alors envoyer en tΩte brut contenu dans le fichier en question
  849.   // exemple: http://www.someweb.com/test.cgi?foo>postfile:post0.txt
  850.   search_tag=strstr(fil,POSTTOK":");
  851.   if (!search_tag) {
  852.     search_tag=strstr(fil,POSTTOK"file:");
  853.     if (search_tag) {     // postfile
  854.       if (mode==0) {      // GET!
  855.         FILE* fp=fopen(unescape_http(OPT_GET_BUFF(opt),search_tag+strlen(POSTTOK)+5),"rb");
  856.         if (fp) {
  857.           char BIGSTK line[1100];
  858.           char BIGSTK protocol[256],url[HTS_URLMAXSIZE*2],method[256];
  859.           linput(fp,line,1000);
  860.           if (sscanf(line,"%s %s %s",method,url,protocol) == 3) {
  861.             // selon que l'on a ou pas un proxy
  862.             if (retour->req.proxy.active)
  863.               sprintf(buff,"%s http://%s%s %s\r\n",method,adr,url,protocol);
  864.             else
  865.               sprintf(buff,"%s %s %s\r\n",method,url,protocol);
  866.             // lire le reste en brut
  867.             fread(buff+strlen(buff),8000-strlen(buff),1,fp);
  868.           }
  869.           fclose(fp);
  870.         }
  871.       }
  872.     }
  873.   }
  874.   // Fin postfile
  875.   
  876.   if (strnotempty(buff)==0) {    // PAS POSTFILE
  877.     // Type de requΦte?
  878.     if ((search_tag) && (mode==0)) {
  879.       strcatbuff(buff,"POST ");
  880.     } else if (mode==0) {    // GET
  881.       strcatbuff(buff,"GET ");
  882.     } else {  // if (mode==1) {
  883.       if (!retour->req.http11)        // forcer HTTP/1.0
  884.         strcatbuff(buff,"GET ");      // certains serveurs (cgi) buggent avec HEAD
  885.       else
  886.         strcatbuff(buff,"HEAD ");
  887.     }
  888.     
  889.     // si on gΦre un proxy, il faut une Absolute URI: on ajoute avant http://www.adr.dom
  890.     if ( retour->req.proxy.active && (strncmp(adr,"https://", 8) != 0) ) {
  891.       if (!link_has_authority(adr)) {  // default http
  892. #if HDEBUG
  893.         printf("Proxy Use: for %s%s proxy %d port %d\n",adr,fil,retour->req.proxy.name,retour->req.proxy.port);
  894. #endif
  895.         strcatbuff(buff,"http://");
  896.         strcatbuff(buff,jump_identification(adr));
  897.       } else {          // ftp:// en proxy http
  898. #if HDEBUG
  899.         printf("Proxy Use for ftp: for %s%s proxy %d port %d\n",adr,fil,retour->req.proxy.name,retour->req.proxy.port);
  900. #endif
  901.         direct_url=1;             // ne pas analyser user/pass
  902.         strcatbuff(buff,adr);
  903.       }
  904.     } 
  905.     
  906.     // NOM DU FICHIER
  907.     // on slash doit Ωtre prΘsent en dΘbut, sinon attention aux bad request! (400)
  908.     if (*fil!='/') strcatbuff(buff,"/");
  909.     {
  910.       char BIGSTK tempo[HTS_URLMAXSIZE*2];
  911.       tempo[0]='\0';
  912.       if (search_tag)
  913.         strncatbuff(tempo,fil,(int) (search_tag - fil));
  914.       else
  915.         strcpybuff(tempo,fil);
  916.       escape_check_url(tempo);
  917.       strcatbuff(buff,tempo);       // avec Θchappement
  918.     }
  919.     
  920.     // protocole
  921.     if (!retour->req.http11) {     // forcer HTTP/1.0
  922.       //use_11=0;
  923.       strcatbuff(buff," HTTP/1.0\x0d\x0a");
  924.     } else {                   // RequΦte 1.1
  925.       //use_11=1;
  926.       strcatbuff(buff," HTTP/1.1\x0d\x0a");
  927.     }
  928.  
  929.     /* supplemental data */
  930.     if (xsend) strcatbuff(buff,xsend);    // Θventuelles autres lignes
  931.  
  932.     // tester proxy authentication
  933.     if (retour->req.proxy.active) {
  934.       if (link_has_authorization(retour->req.proxy.name)) {  // et hop, authentification proxy!
  935.         const char* a = jump_identification(retour->req.proxy.name);
  936.         const char* astart = jump_protocol(retour->req.proxy.name);
  937.         char autorisation[1100];
  938.         char user_pass[256];        
  939.         autorisation[0]=user_pass[0]='\0';
  940.         //
  941.         strncatbuff(user_pass,astart,(int) (a - astart) - 1);
  942.         strcpybuff(user_pass,unescape_http(OPT_GET_BUFF(opt),user_pass));
  943.         code64((unsigned char*)user_pass,(int)strlen(user_pass),(unsigned char*)autorisation,0);
  944.         strcatbuff(buff,"Proxy-Authorization: Basic ");
  945.         strcatbuff(buff,autorisation);
  946.         strcatbuff(buff,H_CRLF);
  947. #if HDEBUG
  948.         printf("Proxy-Authenticate, %s (code: %s)\n",user_pass,autorisation);
  949. #endif
  950.       }
  951.     }
  952.     
  953.     // Referer?
  954.     if (referer_adr != NULL && referer_fil != NULL 
  955.       && strnotempty(referer_adr) && strnotempty(referer_fil)
  956.       ) {   // non vide
  957.       if (
  958.         (strcmp(referer_adr,"file://") != 0)
  959.         &&
  960.         (  /* no https referer to http urls */
  961.         (strncmp(referer_adr, "https://", 8) != 0)  /* referer is not https */
  962.         ||
  963.         (strncmp(adr, "https://", 8) == 0)          /* or referer AND addresses are https */
  964.         )
  965.         ) {      // PAS file://
  966.         strcatbuff(buff,"Referer: ");
  967.         strcatbuff(buff,"http://");
  968.         strcatbuff(buff,jump_identification(referer_adr));
  969.         strcatbuff(buff,referer_fil);
  970.         strcatbuff(buff,H_CRLF);
  971.       }
  972.     }
  973.     // HTTP field: referer
  974.     else if (retour->req.referer[0] != '\0') {
  975.       strcatbuff(buff,"Referer: ");
  976.       strcatbuff(buff, retour->req.referer);
  977.       strcatbuff(buff, H_CRLF);     
  978.     }
  979.     
  980.     // POST?
  981.     if (mode==0) {      // GET!
  982.       if (search_tag) {
  983.         char clen[256];
  984.         sprintf(clen,"Content-length: %d"H_CRLF,(int)(strlen(unescape_http(OPT_GET_BUFF(opt),search_tag+strlen(POSTTOK)+1))));
  985.         strcatbuff(buff,clen);
  986.       }
  987.     }
  988.     
  989.     // gestion cookies?
  990.     if (cookie) {
  991.             char buffer[8192];
  992.       char* b=cookie->data;
  993.       int cook=0;
  994.       int max_cookies=8;
  995.       size_t max_size=2048;
  996.       max_size+=strlen(buff);
  997.       do {
  998.         b=cookie_find(b,"",jump_identification(adr),fil);       // prochain cookie satisfaisant aux conditions
  999.         if (b) {
  1000.           max_cookies--;
  1001.           if (!cook) {
  1002.             strcatbuff(buff,"Cookie: ");
  1003.             strcatbuff(buff,"$Version=1; ");
  1004.             cook=1;
  1005.           } else
  1006.             strcatbuff(buff,"; ");
  1007.           strcatbuff(buff,cookie_get(buffer,b,5));
  1008.           strcatbuff(buff,"=");
  1009.           strcatbuff(buff,cookie_get(buffer,b,6));
  1010.           strcatbuff(buff,"; $Path=");
  1011.           strcatbuff(buff,cookie_get(buffer,b,2));
  1012.           b=cookie_nextfield(b);
  1013.         }
  1014.       } while( (b) && (max_cookies>0) && ((int)strlen(buff)<max_size));
  1015.       if (cook) {                           // on a envoyΘ un (ou plusieurs) cookie?
  1016.         strcatbuff(buff,H_CRLF);
  1017. #if DEBUG_COOK
  1018.         printf("Header:\n%s\n",buff);
  1019. #endif
  1020.       }
  1021.     }
  1022.     
  1023.     // gΘrer le keep-alive (garder socket)
  1024.     if (retour->req.http11 && !retour->req.nokeepalive) {
  1025.             strcatbuff(buff,"Connection: Keep-Alive"H_CRLF);
  1026.         } else {
  1027.       strcatbuff(buff,"Connection: close"H_CRLF);
  1028.         }
  1029.     
  1030.     {
  1031.       char* real_adr=jump_identification(adr);
  1032.       //if ((use_11) || (retour->user_agent_send)) {   // Pour le 1.1 on utilise un Host:
  1033.       if (!direct_url) {     // pas ftp:// par exemple
  1034.         //if (!retour->req.proxy.active) {
  1035.         strcatbuff(buff,"Host: "); strcatbuff(buff,real_adr); strcatbuff(buff,H_CRLF);
  1036.         //}
  1037.       }
  1038.       //}
  1039.  
  1040.       // HTTP field: from
  1041.       if (retour->req.from[0] != '\0') {  // HTTP from
  1042.         strcatbuff(buff,"From: ");
  1043.         strcatbuff(buff, retour->req.from);
  1044.         strcatbuff(buff, H_CRLF);
  1045.       }
  1046.  
  1047.       // PrΘsence d'un user-agent?
  1048.       if (retour->req.user_agent_send) {  // ohh un user-agent
  1049.         char s[256];
  1050.         // HyperTextSeeker/"HTSVERSION
  1051.         sprintf(s,"User-Agent: %s"H_CRLF,retour->req.user_agent);
  1052.         strcatbuff(buff,s);
  1053.         
  1054.         // pour les serveurs difficiles
  1055.         strcatbuff(buff,"Accept: "
  1056.                         "image/png, image/jpeg, image/pjpeg, image/x-xbitmap, image/svg+xml"  /* Accepted */
  1057.                         ", "
  1058.                         "image/gif;q=0.9"  /* also accepted but with lower preference */
  1059.                         ", "
  1060.                         "*/*;q=0.1"        /* also accepted but with even lower preference */
  1061.                         H_CRLF);
  1062.         if (strnotempty(retour->req.lang_iso)) {
  1063.           strcatbuff(buff,"Accept-Language: "); strcatbuff(buff,retour->req.lang_iso); strcatbuff(buff,H_CRLF);
  1064.         }
  1065.         strcatbuff(buff,"Accept-Charset: "
  1066.                         "iso-8859-1"       /* we prefer ISO-8859-1 */
  1067.                         ", "
  1068.                         "iso-8859-*;q=0.9" /* or ISO-8859-* */
  1069.                         ", "
  1070.                         "utf-8;q=0.66"     /* UTF8 is also accepted */
  1071.                         ", "
  1072.                         "*;q=0.33"         /* and any other charset */
  1073.                         H_CRLF);   
  1074.         if (retour->req.http11) {
  1075. #if HTS_USEZLIB
  1076.           //strcatbuff(buff,"Accept-Encoding: gzip, deflate, compress, identity"H_CRLF);
  1077.           if (gz_is_available && (!retour->req.range_used) && (!retour->req.nocompression))
  1078.             strcatbuff(buff,"Accept-Encoding: "
  1079.                             "gzip"         /* gzip if the preffered encoding */
  1080.                             ", "
  1081.                             "identity;q=0.9"
  1082.                             H_CRLF);
  1083.           else
  1084.             strcatbuff(buff,"Accept-Encoding: identity"H_CRLF);       /* no compression */
  1085. #else
  1086.           strcatbuff(buff,"Accept-Encoding: identity"H_CRLF);         /* no compression */
  1087. #endif
  1088.         }
  1089.       } else {
  1090.         strcatbuff(buff,"Accept: */*"H_CRLF);         // le minimum
  1091.       }
  1092.  
  1093.       /* Authentification */
  1094.       {
  1095.         char autorisation[1100];
  1096.         char* a;
  1097.         autorisation[0]='\0';
  1098.         if (link_has_authorization(adr)) {  // ohh une authentification!
  1099.           char* a=jump_identification(adr);
  1100.           char* astart=jump_protocol(adr);
  1101.           if (!direct_url) {      // pas ftp:// par exemple
  1102.             char user_pass[256];
  1103.             user_pass[0]='\0';
  1104.             strncatbuff(user_pass,astart,(int) (a - astart) - 1);
  1105.             strcpybuff(user_pass,unescape_http(OPT_GET_BUFF(opt),user_pass));
  1106.             code64((unsigned char*)user_pass,(int)strlen(user_pass),(unsigned char*)autorisation,0);
  1107.             if (strcmp(fil,"/robots.txt"))      /* pas robots.txt */
  1108.               bauth_add(cookie,astart,fil,autorisation);
  1109.           }
  1110.         } else if ( (a=bauth_check(cookie,real_adr,fil)) )
  1111.           strcpybuff(autorisation,a);
  1112.         /* On a une autorisation a donner?  */
  1113.         if (strnotempty(autorisation)) {
  1114.           strcatbuff(buff,"Authorization: Basic ");
  1115.           strcatbuff(buff,autorisation);
  1116.           strcatbuff(buff,H_CRLF);
  1117.         }
  1118.       }
  1119.  
  1120.     }
  1121.     //strcatbuff(buff,"Accept-Language: en\n");
  1122.     //strcatbuff(buff,"Accept-Charset: iso-8859-1,*,utf-8\n");
  1123.     
  1124.     // CRLF de fin d'en tΩte
  1125.     strcatbuff(buff,H_CRLF);
  1126.     
  1127.     // donnΘes complΘmentaires?
  1128.     if (search_tag)
  1129.     if (mode==0)      // GET!
  1130.       strcatbuff(buff,unescape_http(OPT_GET_BUFF(opt),search_tag+strlen(POSTTOK)+1));
  1131.   }
  1132.   
  1133. #if HDEBUG
  1134. #endif
  1135.   if (_DEBUG_HEAD) {
  1136.     if (ioinfo) {
  1137.       fprintf(ioinfo,"[%d] request for %s%s:\r\n",retour->debugid,jump_identification(adr),fil);
  1138.       fprintfio(ioinfo,buff,"<<< ");
  1139.       fprintf(ioinfo,"\r\n");
  1140.       fflush(ioinfo);
  1141.     }
  1142.   }  // Fin test pas postfile
  1143.   //
  1144.  
  1145.   // Callback
  1146.   {
  1147.     int test_head = RUN_CALLBACK6(opt, sendhead, buff, adr, fil, referer_adr, referer_fil, retour);
  1148.     if (test_head!=1) {
  1149.       deletesoc_r(retour);
  1150.       strcpybuff(retour->msg,"Header refused by external wrapper");
  1151.       retour->soc=INVALID_SOCKET;
  1152.     }
  1153.   }
  1154.  
  1155.   // Envoi
  1156.   HTS_STAT.last_request = mtime_local();
  1157.   if (sendc(retour, buff)<0) {  // ERREUR, socket rompue?...
  1158.   //if (sendc(retour->soc,buff) != strlen(buff)) {  // ERREUR, socket rompue?...
  1159.     deletesoc_r(retour);  // fermer tout de mΩme
  1160.     // et tenter de reconnecter
  1161.     
  1162.     strcpybuff(retour->msg, "Write error");
  1163.     retour->soc=INVALID_SOCKET;
  1164.   }
  1165.   
  1166.   // RX'98
  1167.   return 0;
  1168. }
  1169.  
  1170.  
  1171.  
  1172.  
  1173. // traiter 1ere ligne d'en tΩte
  1174. void treatfirstline(htsblk* retour,char* rcvd) {
  1175.   char* a=rcvd;
  1176.   // exemple:
  1177.   // HTTP/1.0 200 OK
  1178.   if (*a) {
  1179.     // note: certains serveurs buggΘs renvoient HTTP/1.0\n200 OK ou " HTTP/1.0 200 OK"
  1180.     while ((*a==' ') || (*a==10) || (*a==13) || (*a==9)) a++;      // Θpurer espaces au dΘbut
  1181.     if (strfield(a, "HTTP/")) {
  1182.       // sauter HTTP/1.x
  1183.       while ((*a!=' ') && (*a!='\0') && (*a!=10) && (*a!=13) && (*a!=9)) a++;   
  1184.       if (*a != '\0') {
  1185.         while ((*a==' ') || (*a==10) || (*a==13) || (*a==9)) a++;      // Θpurer espaces
  1186.         if ((*a>='0') && (*a<='9')) {
  1187.           sscanf(a,"%d",&(retour->statuscode));
  1188.           // sauter 200
  1189.           while ((*a!=' ') && (*a!='\0') && (*a!=10) && (*a!=13) && (*a!=9)) a++;   
  1190.           while ((*a==' ') || (*a==10) || (*a==13) || (*a==9)) a++;      // Θpurer espaces
  1191.           if ((strlen(a) > 1) && (strlen(a) < 64) )                // message retour
  1192.             strcpybuff(retour->msg,a);
  1193.           else
  1194.             infostatuscode(retour->msg,retour->statuscode);
  1195.           // type MIME par dΘfaut2
  1196.           strcpybuff(retour->contenttype,HTS_HYPERTEXT_DEFAULT_MIME);
  1197.         } else {  // pas de code!
  1198.           retour->statuscode=STATUSCODE_INVALID;
  1199.           strcpybuff(retour->msg,"Unknown response structure");
  1200.         }
  1201.       } else {  // euhh??
  1202.         retour->statuscode=STATUSCODE_INVALID;
  1203.         strcpybuff(retour->msg,"Unknown response structure");
  1204.       }
  1205.     } else {
  1206.             if (*a == '<') {
  1207.         /* This is dirty .. */
  1208.         retour->statuscode=HTTP_OK;
  1209.         retour->keep_alive=0;
  1210.         strcpybuff(retour->msg, "Unknown, assuming junky server");
  1211.         strcpybuff(retour->contenttype,HTS_HYPERTEXT_DEFAULT_MIME);
  1212.             } else if (strnotempty(a)) {
  1213.         retour->statuscode=STATUSCODE_INVALID;
  1214.         strcpybuff(retour->msg,"Unknown (not HTTP/xx) response structure");
  1215.       } else {
  1216.         /* This is dirty .. */
  1217.         retour->statuscode=HTTP_OK;
  1218.         retour->keep_alive=0;
  1219.         strcpybuff(retour->msg, "Unknown, assuming junky server");
  1220.         strcpybuff(retour->contenttype,HTS_HYPERTEXT_DEFAULT_MIME);
  1221.       }
  1222.     }
  1223.   } else {  // vide!
  1224.     /*
  1225.     retour->statuscode=STATUSCODE_INVALID;
  1226.     strcpybuff(retour->msg,"Empty reponse or internal error");
  1227.     */
  1228.     /* This is dirty .. */
  1229.     retour->statuscode=HTTP_OK;
  1230.     strcpybuff(retour->msg, "Unknown, assuming junky server");
  1231.     strcpybuff(retour->contenttype,HTS_HYPERTEXT_DEFAULT_MIME);
  1232.   }
  1233. }
  1234.  
  1235. // traiter ligne par ligne l'en tΩte
  1236. // gestion des cookies
  1237. void treathead(t_cookie* cookie,char* adr,char* fil,htsblk* retour,char* rcvd) {
  1238.   int p;
  1239.   if ((p=strfield(rcvd,"Content-length:"))!=0) {
  1240. #if HDEBUG
  1241.     printf("ok, Content-length: dΘtectΘ\n");
  1242. #endif
  1243.     sscanf(rcvd+p,LLintP,&(retour->totalsize));
  1244.     if (retour->totalsize == 0) {
  1245.       retour->empty = 1;
  1246.     }
  1247.   }
  1248.   else if ((p=strfield(rcvd,"Content-Disposition:"))!=0) {
  1249.     while(is_realspace(*(rcvd+p))) p++;    // sauter espaces
  1250.     if ((int) strlen(rcvd+p)<250) { // pas trop long?
  1251.       char tmp[256];
  1252.       char *a=NULL,*b=NULL;
  1253.       strcpybuff(tmp,rcvd+p);
  1254.       a=strstr(tmp,"filename=");
  1255.       if (a) {
  1256.         a+=strlen("filename=");
  1257.         while(is_space(*a)) a++;
  1258.         //a=strchr(a,'"');
  1259.         if (a) {
  1260.           char *c=NULL;
  1261.           //a++;      /* jump " */
  1262.           while((c=strchr(a,'/')))    /* skip all / (see RFC2616) */
  1263.             a=c+1;
  1264.           //b=strchr(a+1,'"');
  1265.           b=a+strlen(a)-1;
  1266.           while(is_space(*b)) b--;
  1267.           b++;
  1268.           if (b) {
  1269.             *b='\0';
  1270.             if ((int) strlen(a) < 200) { // pas trop long?
  1271.               strcpybuff(retour->cdispo,a);
  1272.             }
  1273.           }
  1274.         }
  1275.       } 
  1276.     }
  1277.   }
  1278.   else if ((p=strfield(rcvd,"Last-Modified:"))!=0) {
  1279.     while(is_realspace(*(rcvd+p))) p++;    // sauter espaces
  1280.     if ((int) strlen(rcvd+p)<64) { // pas trop long?
  1281.       //struct tm* tm_time=convert_time_rfc822(rcvd+p);
  1282.       strcpybuff(retour->lastmodified,rcvd+p);
  1283.     }
  1284.   }
  1285.   else if ((p=strfield(rcvd,"Date:"))!=0) {
  1286.     if (strnotempty(retour->lastmodified)==0) {          /* pas encore de last-modified */
  1287.       while(is_realspace(*(rcvd+p))) p++;    // sauter espaces
  1288.       if ((int) strlen(rcvd+p)<64) { // pas trop long?
  1289.         //struct tm* tm_time=convert_time_rfc822(rcvd+p);
  1290.         strcpybuff(retour->lastmodified,rcvd+p);
  1291.       }
  1292.     }
  1293.   }
  1294.   else if ((p=strfield(rcvd,"Etag:"))!=0) {   /* Etag */
  1295.     if (retour) {
  1296.       while(is_realspace(*(rcvd+p))) p++;    // sauter espaces
  1297.       if ((int) strlen(rcvd+p)<64)  // pas trop long?
  1298.         strcpybuff(retour->etag,rcvd+p);
  1299.       else    // erreur.. ignorer
  1300.         retour->etag[0]='\0';
  1301.     }
  1302.   }
  1303.   // else if ((p=strfield(rcvd,"Transfer-Encoding: chunked"))!=0) {  // chunk!
  1304.   else if ((p=strfield(rcvd,"Transfer-Encoding:"))!=0) {  // chunk!
  1305.     while(is_realspace(*(rcvd+p))) p++;    // sauter espaces
  1306.     if (strfield(rcvd+p,"chunked")) {
  1307.       retour->is_chunk=1;     // chunked
  1308.       //retour->http11=2;     // chunked
  1309. #if HDEBUG
  1310.       printf("ok, Transfer-Encoding: dΘtectΘ\n");
  1311. #endif
  1312.     }
  1313.   }
  1314.   else if ((p=strfield(rcvd,"Content-type:"))!=0) {
  1315.     if (retour) {
  1316.       char tempo[1100];
  1317.       // Θviter les text/html; charset=foo
  1318.       {
  1319.         char* a=strchr(rcvd+p,';');
  1320.         if (a) {   // extended information
  1321.           *a='\0';
  1322.           a++;
  1323.               while(is_space(*a)) a++;
  1324.           if (strfield(a, "charset")) {
  1325.             a += 7;
  1326.                 while(is_space(*a)) a++;
  1327.             if (*a == '=') {
  1328.               a++;
  1329.                   while(is_space(*a)) a++;
  1330.               if (*a == '\"') a++;
  1331.                   while(is_space(*a)) a++;
  1332.               if (*a) {
  1333.                 char* chs = a;
  1334.                 while(*a && !is_space(*a) && *a != '\"' && *a != ';') a++;
  1335.                 *a = '\0';
  1336.                 if (*chs) {
  1337.                   if (strlen(chs) < sizeof(retour->charset) - 2) {
  1338.                     strcpybuff(retour->charset, chs);
  1339.                   }
  1340.                 }
  1341.               }
  1342.             }
  1343.           }
  1344.         }
  1345.       }
  1346.       sscanf(rcvd+p,"%s",tempo);
  1347.       if (strlen(tempo) < sizeof(retour->contenttype) - 2)    // pas trop long!!
  1348.         strcpybuff(retour->contenttype,tempo);
  1349.       else
  1350.         strcpybuff(retour->contenttype,"application/octet-stream-unknown");    // erreur
  1351.     }
  1352.   }
  1353.   else if ((p=strfield(rcvd,"Content-Range:"))!=0) {
  1354.     char* a=strstr(rcvd+p,"*/");
  1355.     if (a) {
  1356.       if (sscanf(a+2,LLintP,&retour->crange) != 1) {
  1357.         retour->crange=0;
  1358.       }
  1359.     }
  1360.   }
  1361.   else if ((p=strfield(rcvd,"Connection:"))!=0) {
  1362.         char* a = rcvd + p;
  1363.         while(is_space(*a)) a++;
  1364.         if (*a) {
  1365.             if (strfield(a, "Keep-Alive")) {
  1366.         if (!retour->keep_alive) {
  1367.           retour->keep_alive_max = 10;
  1368.           retour->keep_alive_t = 15;
  1369.         }
  1370.         retour->keep_alive = 1;
  1371.       } else {
  1372.                 retour->keep_alive = 0;
  1373.       }
  1374.         }
  1375.     }
  1376.   else if ((p=strfield(rcvd,"Keep-Alive:"))!=0) {
  1377.         char* a = rcvd + p;
  1378.         while(is_space(*a)) a++;
  1379.         if (*a) {
  1380.       char* p;
  1381.       retour->keep_alive = 1;
  1382.       retour->keep_alive_max = 10;
  1383.       retour->keep_alive_t = 15;
  1384.       if ((p=strstr(a, "timeout="))) {
  1385.         p+=strlen("timeout=");
  1386.         sscanf(p, "%d", &retour->keep_alive_t);
  1387.       }
  1388.       if ((p=strstr(a, "max="))) {
  1389.         p+=strlen("max=");
  1390.         sscanf(p, "%d", &retour->keep_alive_max);
  1391.       }
  1392.       if (retour->keep_alive_max <= 1 || retour->keep_alive_t < 3) {
  1393.         retour->keep_alive = 0;
  1394.       }
  1395.     }
  1396.   }
  1397.   else if ((p=strfield(rcvd,"TE:"))!=0) {
  1398.         char* a = rcvd + p;
  1399.         while(is_space(*a)) a++;
  1400.         if (*a) {
  1401.       if (strfield(a, "trailers")) {
  1402.         retour->keep_alive_trailers=1;
  1403.       }
  1404.     }
  1405.   }
  1406.     else if ((p=strfield(rcvd,"Content-Encoding:"))!=0) {
  1407.         if (retour) {
  1408.             char tempo[1100];
  1409.       char* a = rcvd + p;
  1410.       while(is_space(*a)) a++;
  1411.             {
  1412.                 char* a=strchr(rcvd+p,';');
  1413.                 if (a) *a='\0';
  1414.             }
  1415.             sscanf(a,"%s",tempo);
  1416.       if (strlen(tempo)<64)    // pas trop long!!
  1417.         strcpybuff(retour->contentencoding,tempo);
  1418.       else
  1419.         retour->contentencoding[0]='\0';    // erreur
  1420. #if HTS_USEZLIB
  1421.       /* Check known encodings */
  1422.       if (retour->contentencoding[0]) {
  1423.         if (
  1424.           (strfield2(retour->contentencoding, "gzip"))
  1425.           || (strfield2(retour->contentencoding, "x-gzip"))
  1426.           /*
  1427.           || (strfield2(retour->contentencoding, "compress"))
  1428.           || (strfield2(retour->contentencoding, "x-compress"))
  1429.           */
  1430.           || (strfield2(retour->contentencoding, "deflate"))
  1431.           || (strfield2(retour->contentencoding, "x-deflate"))
  1432.           ) {
  1433.         retour->compressed=1;
  1434.         }
  1435.       }
  1436. #endif
  1437.     }
  1438.   }
  1439.   else if ((p=strfield(rcvd,"Location:"))!=0) {
  1440.     if (retour) {
  1441.       if (retour->location) {
  1442.         while(is_realspace(*(rcvd+p))) p++;    // sauter espaces
  1443.         if ((int) strlen(rcvd+p)<HTS_URLMAXSIZE)  // pas trop long?
  1444.           strcpybuff(retour->location,rcvd+p);
  1445.         else    // erreur.. ignorer
  1446.           retour->location[0]='\0';
  1447.       }
  1448.     }
  1449.   }
  1450.   else if ( ((p=strfield(rcvd,"Set-Cookie:"))!=0) && (cookie) ) {    // ohh un cookie
  1451.     char* a = rcvd+p;           // pointeur
  1452.     char domain[256];           // domaine cookie (.netscape.com)
  1453.     char path[256];             // chemin (/)
  1454.     char cook_name[256];        // nom cookie (MYCOOK)
  1455.     char BIGSTK cook_value[8192];      // valeur (ID=toto,S=1234)
  1456. #if DEBUG_COOK
  1457.     printf("set-cookie detected\n");
  1458. #endif
  1459.     while(*a) {
  1460.       char *token_st,*token_end;
  1461.       char *value_st,*value_end;
  1462.       char name[256];
  1463.       char BIGSTK value[8192];
  1464.       int next=0;
  1465.       name[0]=value[0]='\0';
  1466.       //
  1467.  
  1468.       // initialiser cookie lu actuellement
  1469.       if (adr)
  1470.         strcpybuff(domain,jump_identification(adr));     // domaine
  1471.       strcpybuff(path,"/");         // chemin (/)
  1472.       strcpybuff(cook_name,"");     // nom cookie (MYCOOK)
  1473.       strcpybuff(cook_value,"");    // valeur (ID=toto,S=1234)
  1474.       // boucler jusqu'au prochain cookie ou la fin
  1475.       do {
  1476.         char* start_loop=a;
  1477.         while(is_space(*a)) a++;    // sauter espaces
  1478.         token_st=a;                 // dΘpart token
  1479.         while((!is_space(*a)) && (*a) && (*a!=';') && (*a!='=')) a++;    // arrΩter si espace, point virgule
  1480.         token_end=a;
  1481.         while(is_space(*a)) a++;    // sauter espaces
  1482.         if (*a=='=') {    // name=value
  1483.           a++;
  1484.           while(is_space(*a)) a++;    // sauter espaces
  1485.           value_st=a;
  1486.           while( (*a!=';') && (*a)) a++;    // prochain ;
  1487.           //while( ((*a!='"') || (*(a-1)=='\\')) && (*a)) a++;    // prochain " (et pas \")
  1488.           value_end=a;
  1489.           //if (*a==';') {  // finit par un ;
  1490.           // vΘrifier dΘbordements
  1491.           if ( (((int) (token_end - token_st))<200) && (((int) (value_end - value_st))<8000)
  1492.             && (((int) (token_end - token_st))>0)   && (((int) (value_end - value_st))>0) ) 
  1493.           {
  1494.             int name_len = (int) (token_end - token_st);
  1495.             int value_len = (int) (value_end - value_st);
  1496.             name[0]='\0';
  1497.             value[0]='\0';
  1498.             strncatbuff(name,token_st,name_len);
  1499.             strncatbuff(value,value_st,value_len);
  1500. #if DEBUG_COOK
  1501.             printf("detected cookie-av: name=\"%s\" value=\"%s\"\n",name,value);
  1502. #endif
  1503.             if (strfield2(name,"domain")) {
  1504.               if (value_len < sizeof(domain) - 1) {
  1505.                 strcpybuff(domain,value);
  1506.               } else {
  1507.                 cook_name[0] = 0;
  1508.                 break;
  1509.               }
  1510.             }
  1511.             else if (strfield2(name,"path")) {
  1512.               if (value_len < sizeof(path) - 1) {
  1513.                 strcpybuff(path,value);
  1514.               } else {
  1515.                 cook_name[0] = 0;
  1516.                 break;
  1517.               }
  1518.             }
  1519.             else if (strfield2(name,"max-age")) {
  1520.               // ignorΘ..
  1521.             }
  1522.             else if (strfield2(name,"expires")) {
  1523.               // ignorΘ..
  1524.             }
  1525.             else if (strfield2(name,"version")) {
  1526.               // ignorΘ..
  1527.             }
  1528.             else if (strfield2(name,"comment")) {
  1529.               // ignorΘ
  1530.             }
  1531.             else if (strfield2(name,"secure")) {    // ne devrait pas arriver ici
  1532.               // ignorΘ
  1533.             }
  1534.             else {
  1535.               if (value_len < sizeof(cook_value) - 1 && name_len < sizeof(cook_name) - 1) {
  1536.                 if (strnotempty(cook_name)==0) {          // noter premier: nom et valeur cookie
  1537.                   strcpybuff(cook_name,name);
  1538.                   strcpybuff(cook_value,value);
  1539.                 } else {                             // prochain cookie
  1540.                   a=start_loop;      // on devra recommencer α cette position
  1541.                   next=1;            // enregistrer
  1542.                 }
  1543.               } else {
  1544.                 cook_name[0] = 0;
  1545.                 break;
  1546.               }
  1547.             }
  1548.           }
  1549.         }
  1550.         if (!next) {
  1551.           while((*a!=';') && (*a)) a++;    // prochain
  1552.           while(*a==';') a++;             // sauter ;
  1553.         }
  1554.       } while((*a) && (!next));
  1555.       if (strnotempty(cook_name)) {          // cookie?
  1556. #if DEBUG_COOK
  1557.         printf("new cookie: name=\"%s\" value=\"%s\" domain=\"%s\" path=\"%s\"\n",cook_name,cook_value,domain,path);
  1558. #endif
  1559.         cookie_add(cookie,cook_name,cook_value,domain,path);
  1560.       }
  1561.     }
  1562.   }
  1563. }
  1564.  
  1565.  
  1566. // transforme le message statuscode en chaεne
  1567. HTSEXT_API void infostatuscode(char* msg,int statuscode) {
  1568.   switch( statuscode) {    
  1569.     // Erreurs HTTP, selon RFC
  1570.   case 100: strcpybuff( msg,"Continue"); break; 
  1571.   case 101: strcpybuff( msg,"Switching Protocols"); break; 
  1572.   case 200: strcpybuff( msg,"OK"); break; 
  1573.   case 201: strcpybuff( msg,"Created"); break; 
  1574.   case 202: strcpybuff( msg,"Accepted"); break; 
  1575.   case 203: strcpybuff( msg,"Non-Authoritative Information"); break; 
  1576.   case 204: strcpybuff( msg,"No Content"); break; 
  1577.   case 205: strcpybuff( msg,"Reset Content"); break; 
  1578.   case 206: strcpybuff( msg,"Partial Content"); break; 
  1579.   case 300: strcpybuff( msg,"Multiple Choices"); break; 
  1580.   case 301: strcpybuff( msg,"Moved Permanently"); break; 
  1581.   case 302: strcpybuff( msg,"Moved Temporarily"); break; 
  1582.   case 303: strcpybuff( msg,"See Other"); break; 
  1583.   case 304: strcpybuff( msg,"Not Modified"); break; 
  1584.   case 305: strcpybuff( msg,"Use Proxy"); break; 
  1585.   case 306: strcpybuff( msg,"Undefined 306 error"); break; 
  1586.   case 307: strcpybuff( msg,"Temporary Redirect"); break; 
  1587.   case 400: strcpybuff( msg,"Bad Request"); break; 
  1588.   case 401: strcpybuff( msg,"Unauthorized"); break; 
  1589.   case 402: strcpybuff( msg,"Payment Required"); break; 
  1590.   case 403: strcpybuff( msg,"Forbidden"); break; 
  1591.   case 404: strcpybuff( msg,"Not Found"); break; 
  1592.   case 405: strcpybuff( msg,"Method Not Allowed"); break; 
  1593.   case 406: strcpybuff( msg,"Not Acceptable"); break; 
  1594.   case 407: strcpybuff( msg,"Proxy Authentication Required"); break; 
  1595.   case 408: strcpybuff( msg,"Request Time-out"); break; 
  1596.   case 409: strcpybuff( msg,"Conflict"); break; 
  1597.   case 410: strcpybuff( msg,"Gone"); break; 
  1598.   case 411: strcpybuff( msg,"Length Required"); break; 
  1599.   case 412: strcpybuff( msg,"Precondition Failed"); break; 
  1600.   case 413: strcpybuff( msg,"Request Entity Too Large"); break; 
  1601.   case 414: strcpybuff( msg,"Request-URI Too Large"); break; 
  1602.   case 415: strcpybuff( msg,"Unsupported Media Type"); break; 
  1603.   case 416: strcpybuff( msg,"Requested Range Not Satisfiable"); break; 
  1604.   case 417: strcpybuff( msg,"Expectation Failed"); break; 
  1605.   case 500: strcpybuff( msg,"Internal Server Error"); break; 
  1606.   case 501: strcpybuff( msg,"Not Implemented"); break; 
  1607.   case 502: strcpybuff( msg,"Bad Gateway"); break; 
  1608.   case 503: strcpybuff( msg,"Service Unavailable"); break; 
  1609.   case 504: strcpybuff( msg,"Gateway Time-out"); break; 
  1610.   case 505: strcpybuff( msg,"HTTP Version Not Supported"); break; 
  1611.     //
  1612.   default: if (strnotempty(msg)==0) strcpybuff( msg,"Unknown error"); break;
  1613.   }
  1614. }
  1615.  
  1616.  
  1617. // identique au prΘcΘdent, sauf que l'on donne adr+fil et non url complΦte
  1618. htsblk xhttpget(httrackp *opt,char* adr,char* fil) {
  1619.   T_SOC soc;
  1620.   htsblk retour;
  1621.   
  1622.   memset(&retour, 0, sizeof(htsblk));
  1623.   soc=http_fopen(opt,adr,fil,&retour);
  1624.  
  1625.   if (soc!=INVALID_SOCKET) {
  1626.     http_fread(soc,&retour);
  1627. #if HTS_DEBUG_CLOSESOCK
  1628.     DEBUG_W("xhttpget: deletehttp\n");
  1629. #endif
  1630.     if (retour.soc!=INVALID_SOCKET) deletehttp(&retour);  // fermer
  1631.     retour.soc=INVALID_SOCKET;
  1632.   }
  1633.   return retour;
  1634. }
  1635.  
  1636. // variation sur un thΦme...
  1637. // rΘceptionne uniquement un en-tΩte (HEAD)
  1638. // retourne dans xx.adr l'adresse pointant sur le bloc de mΘmoire de l'en tΩte
  1639. htsblk http_gethead(httrackp *opt,char* adr,char* fil) {
  1640.   T_SOC soc;
  1641.   htsblk retour;
  1642.  
  1643.   memset(&retour, 0, sizeof(htsblk));
  1644.   soc=http_xfopen(opt,1,0,1,NULL,adr,fil,&retour);  // HEAD, pas de traitement en-tΩte
  1645.  
  1646.   if (soc!=INVALID_SOCKET) {
  1647.     http_fread(soc,&retour);    // rΘception en-tΩte
  1648. #if HTS_DEBUG_CLOSESOCK
  1649.     DEBUG_W("http_gethead: deletehttp\n");
  1650. #endif
  1651.     if (retour.soc!=INVALID_SOCKET) deletehttp(&retour);  // fermer
  1652.     retour.soc=INVALID_SOCKET;
  1653.   }
  1654.   return retour;
  1655. }
  1656. // oui ca ressemble vachement α xhttpget - en Θtant sobre on peut voir LA diffΘrence..
  1657.  
  1658.  
  1659. // lecture sur une socket ouverte, le header a dΘja ΘtΘ envoyΘ dans le cas de GET
  1660. // il ne reste plus qu'α lire les donnΘes
  1661. // (pour HEAD le header est lu ici!)
  1662. void http_fread(T_SOC soc,htsblk* retour) {  
  1663.   //int bufl=TAILLE_BUFFER;    // 8Ko de buffer
  1664.   
  1665.   if (retour) retour->soc=soc;
  1666.   if (soc!=INVALID_SOCKET) {    
  1667.     // fonction de lecture d'une socket (plus propre)
  1668.     while(http_fread1(retour)!=-1);
  1669.     soc=retour->soc;
  1670.     if (retour->adr==NULL) {
  1671.       if (strnotempty(retour->msg)==0)
  1672.         sprintf(retour->msg,"Unable to read");
  1673.       return ;    // erreur
  1674.     } 
  1675.     
  1676. #if HDEBUG
  1677.     printf("Ok, donnΘes reτues\n");
  1678. #endif   
  1679.  
  1680.     return ;
  1681.     
  1682.   } 
  1683.   
  1684.   return ;
  1685. }
  1686.  
  1687. // check if data is available
  1688. int check_readinput(htsblk* r) {
  1689.   if (r->soc != INVALID_SOCKET) {
  1690.     fd_set fds;           // poll structures
  1691.     struct timeval tv;          // structure for select
  1692.     FD_ZERO(&fds);
  1693.     FD_SET(r->soc,&fds);           
  1694.     tv.tv_sec=0;
  1695.     tv.tv_usec=0;
  1696.     select(r->soc + 1,&fds,NULL,NULL,&tv);
  1697.     if (FD_ISSET(r->soc,&fds))
  1698.       return 1;
  1699.     else
  1700.       return 0;
  1701.   } else
  1702.     return 0;
  1703. }
  1704.  
  1705. // check if data is available
  1706. int check_readinput_t(T_SOC soc, int timeout) {
  1707.   if (soc != INVALID_SOCKET) {
  1708.     fd_set fds;           // poll structures
  1709.     struct timeval tv;          // structure for select
  1710.     FD_ZERO(&fds);
  1711.     FD_SET(soc,&fds);           
  1712.     tv.tv_sec=timeout;
  1713.     tv.tv_usec=0;
  1714.     select(soc + 1,&fds,NULL,NULL,&tv);
  1715.     if (FD_ISSET(soc,&fds))
  1716.       return 1;
  1717.     else
  1718.       return 0;
  1719.   } else
  1720.     return 0;
  1721. }
  1722.  
  1723.  
  1724. // lecture d'un bloc sur une socket (ou un fichier!)
  1725. // >=0 : nombre d'octets lus
  1726. // <0 : fin ou erreur
  1727. HTS_INLINE LLint http_fread1(htsblk* r) {
  1728.   //int bufl=TAILLE_BUFFER;  // taille d'un buffer max.
  1729.   return http_xfread1(r,TAILLE_BUFFER);
  1730. }
  1731.  
  1732. // idem, sauf qu'ici on peut choisir la taille max de donnΘes α recevoir
  1733. // SI bufl==0 alors le buffer est censΘ Ωtre de 8kos, et on recoit par bloc de lignes
  1734. // en Θliminant les cr (ex: header), arrΩt si double-lf
  1735. // SI bufl==-1 alors le buffer est censΘ Ωtre de 8kos, et on recoit ligne par ligne
  1736. // en Θliminant les cr (ex: header), arrΩt si double-lf
  1737. // Note: les +1 dans les malloc sont d√s α l'octet nul rajoutΘ en fin de fichier
  1738. LLint http_xfread1(htsblk* r,int bufl) {
  1739.   int nl=-1;
  1740.  
  1741.   // EOF
  1742.   if (r->totalsize > 0 && r->size == r->totalsize) {
  1743.     return READ_EOF;
  1744.   }
  1745.  
  1746.   if (bufl>0) {
  1747.     if (!r->is_write) {     // stocker en mΘmoire
  1748.       if (r->totalsize>0) {    // totalsize dΘterminΘ ET ALLOUE
  1749.         if (r->adr==NULL) {
  1750.           r->adr = (char*) malloct((size_t) r->totalsize + 1);
  1751.           r->size = 0;
  1752.         }
  1753.         if (r->adr != NULL) {
  1754.           // lecture
  1755.           nl = hts_read(r,r->adr + ((int) r->size),(int) (r->totalsize-r->size) );     /* NO 32 bit overlow possible here (no 4GB html!) */
  1756.           // nouvelle taille
  1757.           if (nl >= 0) r->size+=nl;
  1758.  
  1759.           /*
  1760.           if (r->size >= r->totalsize)
  1761.             nl = -1;  // break
  1762.           */
  1763.           
  1764.           r->adr[r->size]='\0';    // caractΦre NULL en fin au cas o∙ l'on traite des HTML
  1765.         }
  1766.         
  1767.       } else {                 // inconnu..
  1768.         // rΘserver de la mΘmoire?
  1769.         if (r->adr==NULL) {
  1770. #if HDEBUG
  1771.           printf("..alloc xfread\n");
  1772. #endif
  1773.           r->adr=(char*) malloct(bufl + 1);
  1774.           r->size=0;
  1775.         }
  1776.         else {
  1777. #if HDEBUG
  1778.           printf("..realloc xfread1\n");
  1779. #endif
  1780.           r->adr=(char*) realloct(r->adr,(int)r->size+bufl + 1);
  1781.         }
  1782.         
  1783.         if (r->adr!=NULL) {
  1784.           // lecture
  1785.           nl = hts_read(r,r->adr+(int)r->size,bufl);
  1786.           if (nl > 0) {
  1787.             // resize
  1788.             r->adr=(char*) realloct(r->adr,(int)r->size+nl + 1);
  1789.             // nouvelle taille
  1790.             r->size+=nl;
  1791.             // octet nul
  1792.             if (r->adr) r->adr[r->size]='\0';
  1793.  
  1794.           } // sinon on a fini
  1795. #if HDEBUG
  1796.           else if (nl < 0)
  1797.             printf("..end read (%d)\n", nl);
  1798. #endif
  1799.         }
  1800. #if HDEBUG
  1801.         else printf("..-> error\n");
  1802. #endif
  1803.       }
  1804.  
  1805.       // pas de adr=erreur
  1806.       if (r->adr == NULL) nl = READ_ERROR;
  1807.  
  1808.     } else {    // stocker sur disque
  1809.       char* buff;
  1810.       buff=(char*) malloct(bufl);
  1811.       if (buff!=NULL) {
  1812.         // lecture
  1813.         nl = hts_read(r,buff,bufl);
  1814.         // nouvelle taille
  1815.         if (nl > 0) { 
  1816.           r->size+=nl;
  1817.           if (fwrite(buff,1,nl,r->out)!=nl) {
  1818.             r->statuscode=STATUSCODE_INVALID;
  1819.             strcpybuff(r->msg,"Write error on disk");
  1820.             nl=READ_ERROR;
  1821.           }
  1822.         }
  1823.  
  1824.         //if ((nl < 0) || ((r->totalsize>0) && (r->size >= r->totalsize)))
  1825.         //  nl=-1;  // break
  1826.  
  1827.         // libΘrer bloc tempo
  1828.         freet(buff);
  1829.       } else
  1830.         nl=READ_ERROR;
  1831.       
  1832.       if ((nl < 0) && (r->out!=NULL)) {
  1833.         fflush(r->out); 
  1834.       }
  1835.         
  1836.         
  1837.     } // stockage disque ou mΘmoire
  1838.  
  1839.   } else if (bufl == -2) {  // force reserve
  1840.     if (r->adr==NULL) {
  1841.       r->adr=(char*) malloct(8192);
  1842.       r->size=0;
  1843.       return 0;
  1844.     }
  1845.     return -1;
  1846.   } else {    // rΘception d'un en-tΩte octet par octet
  1847.     int count=256;
  1848.     int tot_nl=0;
  1849.     int lf_detected=0;
  1850.     int at_begining=1;
  1851.     do {
  1852.       nl = READ_INTERNAL_ERROR;
  1853.       count--;
  1854.       if (r->adr==NULL) {
  1855.         r->adr=(char*) malloct(8192);
  1856.         r->size=0;
  1857.       }
  1858.       if (r->adr!=NULL) {
  1859.         if (r->size < 8190) {
  1860.           // lecture
  1861.           nl = hts_read(r,r->adr+r->size,1);
  1862.           if (nl > 0) {
  1863.             // exit if:
  1864.             // lf detected AND already detected before
  1865.             // or
  1866.             // lf detected AND first character read
  1867.             if (*(r->adr+r->size) == 10) {
  1868.               if (lf_detected || (at_begining) || (bufl<0))
  1869.                 count=-1;
  1870.               lf_detected=1;
  1871.             }
  1872.             if (*(r->adr+r->size) != 13) {   // sauter caractΦres 13
  1873.               if (
  1874.                 (*(r->adr+r->size) != 10)
  1875.                 &&
  1876.                 (*(r->adr+r->size) != 13)
  1877.                 ) {
  1878.                 // restart for new line
  1879.                 lf_detected=0;
  1880.               }
  1881.               (r->size)++;
  1882.               at_begining=0;
  1883.             }
  1884.             *(r->adr+r->size)='\0';    // terminer par octet nul
  1885.           }
  1886.         }
  1887.       }
  1888.       if (nl >= 0) {
  1889.         tot_nl+=nl;
  1890.         if (!check_readinput(r))
  1891.           count=-1;
  1892.       }
  1893.     } while((nl >= 0) && (count>0));
  1894.     if (nl >= 0) {
  1895.       nl = tot_nl;
  1896.     }
  1897.   }
  1898.   // EOF
  1899.   if (r->totalsize > 0 && r->size == r->totalsize) {
  1900.     return READ_EOF;
  1901.   } else {
  1902.     return nl;
  1903.   }
  1904. }
  1905.  
  1906.  
  1907. // teste une adresse, et suit l'Θventuel chemin "moved"
  1908. // retourne 200 ou le code d'erreur (404=NOT FOUND, etc)
  1909. // copie dans loc la vΘritable adresse si celle-ci est diffΘrente
  1910. htsblk http_location(httrackp *opt,char* adr,char* fil,char* loc) {
  1911.   htsblk retour;
  1912.   int retry=0;
  1913.   int tryagain;
  1914.   // note: "RFC says"
  1915.   // 5 boucles au plus, on en teste au plus 8 ici
  1916.   // sinon abandon..
  1917.   do {
  1918.     tryagain=0;
  1919.     switch ((retour=http_test(opt,adr,fil,loc)).statuscode) {
  1920.     case HTTP_OK:
  1921.       break;   // ok!
  1922.     case HTTP_MOVED_PERMANENTLY:
  1923.     case HTTP_FOUND:
  1924.     case HTTP_SEE_OTHER:
  1925.     case HTTP_TEMPORARY_REDIRECT: // moved!
  1926.       // recalculer adr et fil!
  1927.       if (ident_url_absolute(loc,adr,fil)!=-1) {
  1928.         tryagain=1;  // retenter
  1929.         retry++;     // ..encore une fois
  1930.       }
  1931.     }
  1932.   } while((tryagain) && (retry<5+3));
  1933.   return retour;
  1934. }
  1935.  
  1936.  
  1937. // teste si une URL (validitΘ, header, taille)
  1938. // retourne 200 ou le code d'erreur (404=NOT FOUND, etc)
  1939. // en cas de moved xx, dans location
  1940. // abandonne dΘsormais au bout de 30 secondes (aurevoir les sites
  1941. // qui nous font poireauter 5 heures..) -> -2=timeout
  1942. htsblk http_test(httrackp *opt,char* adr,char* fil,char* loc) {
  1943.   T_SOC soc;
  1944.   htsblk retour;
  1945.   //int rcvsize=-1;
  1946.   //char* rcv=NULL;    // adresse de retour
  1947.   //int bufl=TAILLE_BUFFER;    // 8Ko de buffer
  1948.   TStamp tl;
  1949.   int timeout=30;  // timeout pour un check (arbitraire) // **
  1950.  
  1951.   // pour abandonner un site trop lent
  1952.   tl=time_local();
  1953.  
  1954.   loc[0]='\0';
  1955.   memset(&retour, 0, sizeof(htsblk));    // effacer
  1956.   retour.location=loc;    // si non nul, contiendra l'adresse vΘritable en cas de moved xx
  1957.  
  1958.   //soc=http_fopen(adr,fil,&retour,NULL);  // ouvrir, + header
  1959.  
  1960.   // on ouvre en head, et on traite l'en tΩte
  1961.   soc=http_xfopen(opt,1,0,1,NULL,adr,fil,&retour);  // ouvrir HEAD, + envoi header
  1962.   
  1963.   if (soc!=INVALID_SOCKET) {
  1964.     int e=0;
  1965.     // tant qu'on a des donnΘes, et qu'on ne recoit pas deux LF, et que le timeout n'arrie pas
  1966.     do {
  1967.       if (http_xfread1(&retour,0) < 0)
  1968.         e=1;
  1969.       else {
  1970.         if (retour.adr!=NULL) {
  1971.           if ((retour.adr[retour.size-1]!=10) || (retour.adr[retour.size-2]!=10))
  1972.             e=1;
  1973.         }
  1974.       }
  1975.             
  1976.       if (!e) {
  1977.         if ((time_local()-tl)>=timeout) {
  1978.           e=-1;
  1979.         }
  1980.       }
  1981.       
  1982.     } while (!e);
  1983.     
  1984.     if (e==1) {
  1985.       if (adr!=NULL) {
  1986.         int ptr=0;
  1987.         char rcvd[1100];
  1988.  
  1989.         // note: en gros recopie du traitement de back_wait()
  1990.         //
  1991.  
  1992.  
  1993.         // ----------------------------------------
  1994.         // traiter en-tΩte!
  1995.         // status-line α rΘcupΘrer
  1996.         ptr+=binput(retour.adr+ptr,rcvd,1024);
  1997.         if (strnotempty(rcvd)==0)
  1998.           ptr+=binput(retour.adr+ptr,rcvd,1024);    // "certains serveurs buggΘs envoient un \n au dΘbut" (RFC)
  1999.         
  2000.         // traiter status-line
  2001.         treatfirstline(&retour,rcvd);
  2002.         
  2003. #if HDEBUG
  2004.         printf("(Buffer) Status-Code=%d\n",retour.statuscode);
  2005. #endif
  2006.         
  2007.         // en-tΩte
  2008.         
  2009.         // header // ** !attention! HTTP/0.9 non supportΘ
  2010.         do {
  2011.           ptr+=binput(retour.adr+ptr,rcvd,1024);          
  2012. #if HDEBUG
  2013.           printf("(buffer)>%s\n",rcvd);      
  2014. #endif
  2015.           if (strnotempty(rcvd))
  2016.             treathead(NULL,NULL,NULL,&retour,rcvd);  // traiter
  2017.           
  2018.         } while(strnotempty(rcvd));
  2019.         // ----------------------------------------                    
  2020.         
  2021.         // libΘrer mΘmoire
  2022.         if (retour.adr!=NULL) { freet(retour.adr); retour.adr=NULL; }
  2023.       }
  2024.     } else {
  2025.       retour.statuscode=STATUSCODE_TIMEOUT;
  2026.       strcpybuff(retour.msg,"Timeout While Testing");
  2027.     }
  2028.     
  2029.     
  2030. #if HTS_DEBUG_CLOSESOCK
  2031.     DEBUG_W("http_test: deletehttp\n");
  2032. #endif
  2033.     deletehttp(&retour);
  2034.     retour.soc=INVALID_SOCKET;
  2035.   }
  2036.   return retour;    
  2037. }
  2038.  
  2039. // CrΘe un lien (http) vers une adresse internet iadr
  2040. // retour: structure (adresse, taille, message si erreur (si !adr))
  2041. // peut ouvrir avec des connect() non bloquants: waitconnect=0/1
  2042. int newhttp(httrackp *opt,const char* _iadr,htsblk* retour,int port,int waitconnect) {  
  2043.   t_fullhostent fullhostent_buffer;    // buffer pour resolver
  2044.   T_SOC soc;                           // descipteur de la socket
  2045.   char* iadr;
  2046.   // unsigned short int port;
  2047.   
  2048.   // si iadr="#" alors c'est une fausse URL, mais un vrai fichier
  2049.   // local.
  2050.   // utile pour les tests!
  2051.   //## if (iadr[0]!=lOCAL_CHAR) {
  2052.   if (strcmp(_iadr,"file://") != 0) {           /* non fichier */
  2053.     SOCaddr server;
  2054.     int server_size=sizeof(server);
  2055.     t_hostent* hp;    
  2056.     // effacer structure
  2057.     memset(&server, 0, sizeof(server));
  2058.  
  2059.     // tester un Θventuel id:pass et virer id:pass@ si dΘtectΘ
  2060.     iadr = jump_identification(_iadr);
  2061.   
  2062. #if HDEBUG
  2063.     printf("gethostbyname\n");
  2064. #endif
  2065.     
  2066.     // tester un Θventuel port
  2067.     if (port==-1) {
  2068.       char *a=jump_toport(iadr);
  2069. #if HTS_USEOPENSSL
  2070.       if (retour->ssl)
  2071.         port=443;
  2072.       else
  2073.         port=80;    // port par dΘfaut
  2074. #else
  2075.       port=80;    // port par dΘfaut
  2076. #endif
  2077.       if (a) {
  2078.         char BIGSTK iadr2[HTS_URLMAXSIZE*2];
  2079.         int i=-1;
  2080.         iadr2[0]='\0';
  2081.         sscanf(a+1,"%d",&i);
  2082.         if (i!=-1) {
  2083.           port=(unsigned short int) i;
  2084.         }
  2085.         
  2086.         // adresse vΘritable (sans :xx)
  2087.         strncatbuff(iadr2,iadr,(int) (a - iadr));
  2088.  
  2089.         // adresse sans le :xx
  2090.         hp = hts_gethostbyname(opt,iadr2, &fullhostent_buffer);
  2091.         
  2092.       } else {
  2093.  
  2094.         // adresse normale (port par dΘfaut par la suite)
  2095.         hp = hts_gethostbyname(opt,iadr, &fullhostent_buffer);
  2096.         
  2097.       }
  2098.       
  2099.     } else    // port dΘfini
  2100.       hp = hts_gethostbyname(opt,iadr, &fullhostent_buffer);
  2101.  
  2102.     
  2103.     // Conversion iadr -> adresse
  2104.     // structure recevant le nom de l'h⌠te, etc
  2105.     //struct     hostent     *hp;
  2106.     if (hp == NULL) {
  2107. #if DEBUG
  2108.       printf("erreur gethostbyname\n");
  2109. #endif
  2110.       if (retour && retour->msg) {
  2111. #ifdef _WIN32
  2112.         int last_errno = WSAGetLastError();
  2113.         sprintf(retour->msg,"Unable to get server's address: %s", strerror(last_errno));
  2114. #else
  2115.         int last_errno = errno;
  2116.         sprintf(retour->msg,"Unable to get server's address: %s", strerror(last_errno));
  2117. #endif
  2118.       }
  2119.       return INVALID_SOCKET;
  2120.     }  
  2121.     // copie adresse
  2122.     SOCaddr_copyaddr(server, server_size, hp->h_addr_list[0], hp->h_length);
  2123.     // make a copy for external clients
  2124.     retour->address_size = sizeof(retour->address);
  2125.     SOCaddr_copyaddr(retour->address, retour->address_size, hp->h_addr_list[0], hp->h_length);
  2126.     // memcpy(&SOCaddr_sinaddr(server), hp->h_addr_list[0], hp->h_length);
  2127.      
  2128.     // crΘer ("attachement") une socket (point d'accΦs) internet,en flot
  2129. #if HDEBUG
  2130.     printf("socket\n");
  2131. #endif
  2132. #if HTS_WIDE_DEBUG    
  2133.     DEBUG_W("socket\n");
  2134. #endif
  2135.     soc = (T_SOC) socket(SOCaddr_sinfamily(server), SOCK_STREAM, 0);
  2136.     if (retour != NULL) {
  2137.       retour->debugid = HTS_STAT.stat_sockid++;
  2138.     }
  2139. #if HTS_WIDE_DEBUG    
  2140.     DEBUG_W("socket()=%d\n" _ (int) soc);
  2141. #endif
  2142.     if (soc==INVALID_SOCKET) {
  2143.       if (retour && retour->msg) {
  2144. #ifdef _WIN32
  2145.         int last_errno = WSAGetLastError();
  2146.         sprintf(retour->msg,"Unable to create a socket: %s", strerror(last_errno));
  2147. #else
  2148.         int last_errno = errno;
  2149.         sprintf(retour->msg,"Unable to create a socket: %s", strerror(last_errno));
  2150. #endif
  2151.       }
  2152.       return INVALID_SOCKET;                        // erreur crΘation socket impossible
  2153.     }
  2154.  
  2155.     // bind this address
  2156.     if (retour != NULL && retour->req.proxy.bindhost[0] != 0) {
  2157.       t_fullhostent bind_buffer;
  2158.       hp = hts_gethostbyname(opt, retour->req.proxy.bindhost, &bind_buffer);
  2159.       if (hp == NULL ||
  2160.         bind(soc, (struct sockaddr *)hp->h_addr_list[0], hp->h_length) != 0) {
  2161.           if (retour && retour->msg) {
  2162. #ifdef _WIN32
  2163.             int last_errno = WSAGetLastError();
  2164.             sprintf(retour->msg,"Unable to bind the specificied server address: %s", strerror(last_errno));
  2165. #else
  2166.             int last_errno = errno;
  2167.             sprintf(retour->msg,"Unable to bind the specificied server address: %s", strerror(last_errno));
  2168. #endif
  2169.           }
  2170.           deletesoc(soc);
  2171.           return INVALID_SOCKET;
  2172.       }
  2173.     }
  2174.     
  2175.     // structure: connexion au domaine internet, port 80 (ou autre)
  2176.     SOCaddr_initport(server, port);
  2177. #if HDEBUG
  2178.     printf("==%d\n",soc);
  2179. #endif
  2180.  
  2181.     // connexion non bloquante?
  2182.     if (!waitconnect ) {
  2183.       unsigned long p=1;  // non bloquant
  2184. #ifdef _WIN32
  2185.       ioctlsocket(soc,FIONBIO,&p);
  2186. #else
  2187.       ioctl(soc,FIONBIO,&p);
  2188. #endif
  2189.     }
  2190.     
  2191.     // Connexion au serveur lui mΩme
  2192. #if HDEBUG
  2193.     printf("connect\n");
  2194. #endif
  2195.     HTS_STAT.last_connect = mtime_local();
  2196.     
  2197. #if HTS_WIDE_DEBUG
  2198.     DEBUG_W("connect\n");
  2199. #endif
  2200. #ifdef _WIN32
  2201.     if (connect(soc, (const struct sockaddr FAR *)&server, server_size) != 0) {
  2202. #else
  2203.       if (connect(soc, (struct sockaddr *)&server, server_size) == -1) {
  2204. #endif
  2205.  
  2206.         // bloquant
  2207.         if (waitconnect) {
  2208. #if HDEBUG
  2209.           printf("unable to connect!\n");
  2210. #endif
  2211.           if (retour && retour->msg) {
  2212. #ifdef _WIN32
  2213.             int last_errno = WSAGetLastError();
  2214.             sprintf(retour->msg,"Unable to connect to the server: %s", strerror(last_errno));
  2215. #else
  2216.             int last_errno = errno;
  2217.             sprintf(retour->msg,"Unable to connect to the server: %s", strerror(last_errno));
  2218. #endif
  2219.           }
  2220.           /* Close the socket and notify the error!!! */
  2221.           deletesoc(soc);
  2222.           return INVALID_SOCKET;
  2223.         }
  2224.       }
  2225. #if HTS_WIDE_DEBUG    
  2226.       DEBUG_W("connect done\n");
  2227. #endif
  2228.       
  2229. #if HDEBUG
  2230.       printf("connexion Θtablie\n");
  2231. #endif
  2232.     
  2233.     // A partir de maintenant, on peut envoyer et recevoir des donnΘes
  2234.     // via le flot identifiΘ par soc (socket): write(soc,adr,taille) et 
  2235.     // read(soc,adr,taille)
  2236.  
  2237.   } else {    // on doit ouvrir un fichier local!
  2238.     // il sera gΘrΘ de la mΩme maniΦre qu'une socket (c'est idem!)
  2239.  
  2240.     soc=LOCAL_SOCKET_ID;    // pseudo-socket locale..
  2241.     // soc sera remplacΘ lors d'un http_fopen() par un handle vΘritable!
  2242.  
  2243.   }   // teste fichier local ou http
  2244.   
  2245.   return soc;
  2246. }
  2247.  
  2248.  
  2249.  
  2250. // couper http://www.truc.fr/pub/index.html -> www.truc.fr /pub/index.html
  2251. // retour=-1 si erreur.
  2252. // si file://... alors adresse=file:// (et coupe le ?query dans ce cas)
  2253. int ident_url_absolute(const char* url,char* adr,char* fil) {
  2254.   int pos=0;
  2255.   int scheme=0;
  2256.  
  2257.   // effacer adr et fil
  2258.   adr[0]=fil[0]='\0';
  2259.   
  2260. #if HDEBUG
  2261.   printf("protocol: %s\n",url);
  2262. #endif
  2263.  
  2264.   // Scheme?
  2265.   {
  2266.     const char* a=url;
  2267.     while (isalpha((unsigned char)*a))
  2268.       a++;
  2269.     if (*a == ':')
  2270.       scheme=1;
  2271.   }
  2272.  
  2273.   // 1. optional scheme ":"
  2274.   if ((pos=strfield(url,"file:"))) {    // fichier local!! (pour les tests)
  2275.     //!!p+=3;
  2276.     strcpybuff(adr,"file://");
  2277.   } else if ((pos=strfield(url,"http:"))) {    // HTTP
  2278.     //!!p+=3;
  2279.   } else if ((pos=strfield(url,"ftp:"))) {    // FTP
  2280.     strcpybuff(adr,"ftp://");    // FTP!!
  2281.     //!!p+=3;
  2282. #if HTS_USEOPENSSL
  2283.   } else if (SSL_is_available && (pos=strfield(url,"https:"))) {    // HTTPS
  2284.     strcpybuff(adr,"https://");
  2285. #endif
  2286. #if HTS_USEMMS
  2287.   } else if ((pos = strfield(url,"mms:"))) {    // mms
  2288.     strcpybuff(adr,"mms://");
  2289. #endif
  2290.   } else if (scheme) {
  2291.     return -1;    // erreur non reconnu
  2292.   } else
  2293.     pos=0;
  2294.  
  2295.   // 2. optional "//" authority
  2296.   if (strncmp(url+pos,"//",2)==0)
  2297.     pos+=2;
  2298.  
  2299.   // (url+pos) now points to the path (not net path)
  2300.  
  2301.   //## if (adr[0]!=lOCAL_CHAR) {    // adresse normale http
  2302.   if (!strfield(adr,"file:")) {      // PAS file://
  2303.     const char *p,*q;
  2304.     p=url+pos;
  2305.  
  2306.     // p pointe sur le dΘbut de l'adresse, ex: www.truc.fr/sommaire/index.html
  2307.     q=strchr(jump_identification(p),'/');
  2308.     if (q==0) q=strchr(jump_identification(p),'?');     // http://www.foo.com?bar=1
  2309.     if (q==0) q=p+strlen(p);  // pointe sur \0
  2310.     // q pointe sur le chemin, ex: index.html?query=recherche
  2311.     
  2312.     // chemin www... trop long!!
  2313.     if ( ( ((int) (q - p)) )  > HTS_URLMAXSIZE) {
  2314.       //strcpybuff(retour.msg,"Path too long");
  2315.       return -1;    // erreur
  2316.     }
  2317.     
  2318.     // recopier adresse www..
  2319.     strncatbuff(adr,p, ((int) (q - p)) );
  2320.     // *( adr+( ((int) q) - ((int) p) ) )=0;  // faut arrΩter la fumette!
  2321.     // recopier chemin /pub/..
  2322.     if (q[0] != '/')    // page par dΘfaut (/)
  2323.       strcatbuff(fil,"/");
  2324.     strcatbuff(fil,q);
  2325.     // SECURITE:
  2326.     // simplifier url pour les ../
  2327.     fil_simplifie(fil);
  2328.   } else {    // localhost file://
  2329.     const char *p;
  2330.     int i;
  2331.     char* a;
  2332.     
  2333.     p=url+pos;
  2334.     if (*p == '/' || *p == '\\') {  /* file:///.. */
  2335.       strcatbuff(fil,p);    // fichier local ; adr="#"
  2336.     } else {
  2337.       if (p[1] != ':') {
  2338.         strcatbuff(fil,"//");   /* file://server/foo */
  2339.         strcatbuff(fil,p);
  2340.       } else {
  2341.         strcatbuff(fil,p);    // file://C:\..
  2342.       }
  2343.     }
  2344.     
  2345.     a=strchr(fil,'?');
  2346.     if (a) 
  2347.       *a='\0';      /* couper query (inutile pour file:// lors de la requΩte) */
  2348.     // filtrer les \\ -> / pour les fichiers DOS
  2349.     for(i=0;i<(int) strlen(fil);i++)
  2350.       if (fil[i]=='\\')
  2351.         fil[i]='/';
  2352.   }
  2353.  
  2354.   // no hostname
  2355.   if (!strnotempty(adr))
  2356.     return -1;    // erreur non reconnu
  2357.  
  2358.   // nommer au besoin.. (non utilisΘ normalement)
  2359.   if (!strnotempty(fil))
  2360.     strcpybuff(fil,"default-index.html");
  2361.  
  2362.   // case insensitive pour adresse
  2363.   {
  2364.     char *a=jump_identification(adr);
  2365.     while(*a) {
  2366.       if ((*a>='A') && (*a<='Z'))
  2367.         *a+='a'-'A';       
  2368.       a++;
  2369.     }
  2370.   }
  2371.   
  2372.   return 0;
  2373. }
  2374.  
  2375. /* simplify ../ and ./ */
  2376. void fil_simplifie(char* f) {
  2377.   char *a, *b;
  2378.   char *rollback[128];
  2379.   int rollid = 0;
  2380.   char lc = '/';
  2381.   int query = 0;
  2382.   int wasAbsolute = (*f == '/');
  2383.   for(a = b = f ; *a != '\0' ; ) {
  2384.     if (*a == '?')
  2385.       query = 1;
  2386.     if (query == 0 && lc == '/' && a[0] == '.' && a[1] == '/') {    /* foo/./bar or ./foo  */
  2387.       a += 2;
  2388.     }
  2389.     else if (query == 0 && lc == '/' && a[0] == '.' && a[1] == '.' && ( a[2] == '/' || a[2] == '\0' ) ) {    /* foo/../bar or ../foo or .. */
  2390.       if (a[2] == '\0')
  2391.         a += 2;
  2392.       else
  2393.         a += 3;
  2394.       if (rollid > 1) {
  2395.         rollid--;
  2396.         b = rollback[rollid - 1];
  2397.       } else {   /* too many ../ */
  2398.         rollid = 0;
  2399.         b = f;
  2400.         if (wasAbsolute)
  2401.           b++;   /* after the / */
  2402.       }
  2403.     }
  2404.     else {
  2405.       *b++ = lc = *a;
  2406.       if (*a == '/') {
  2407.         rollback[rollid++] = b;
  2408.         if (rollid >= 127) {
  2409.           *f = '\0';      /* ERROR */
  2410.           break;
  2411.         }
  2412.       }
  2413.       a++;
  2414.     }
  2415.   }
  2416.   *b = '\0';
  2417.   if (*f == '\0') {
  2418.     if (wasAbsolute) {
  2419.       f[0] = '/';
  2420.       f[1] = '\0';
  2421.     } else {
  2422.       f[0] = '.';
  2423.       f[1] = '/';
  2424.       f[2] = '\0';
  2425.     }
  2426.   }
  2427. }
  2428.  
  2429. // fermer liaison fichier ou socket
  2430. HTS_INLINE void deletehttp(htsblk* r) {
  2431. #if HTS_DEBUG_CLOSESOCK
  2432.     DEBUG_W("deletehttp: (htsblk*) 0x%p\n" _ (void*) r);
  2433. #endif
  2434. #if HTS_USEOPENSSL
  2435.     /* Free OpenSSL structures */
  2436.     if (SSL_is_available && r->ssl_con) {
  2437.       SSL_shutdown(r->ssl_con);
  2438.       SSL_free(r->ssl_con);
  2439.       r->ssl_con=NULL;
  2440.     }
  2441. #endif  
  2442.   if (r->soc!=INVALID_SOCKET) {
  2443.     if (r->is_file) {
  2444.       if (r->fp)
  2445.         fclose(r->fp);
  2446.       r->fp=NULL;
  2447.     } else {
  2448.       if (r->soc!=LOCAL_SOCKET_ID)
  2449.         deletesoc_r(r);
  2450.     }
  2451.     r->soc=INVALID_SOCKET;
  2452.   }
  2453. }
  2454.  
  2455. // free the addr buffer
  2456. // always returns 1
  2457. HTS_INLINE int deleteaddr(htsblk* r) {
  2458.   if (r->adr != NULL) {
  2459.     freet(r->adr);
  2460.     r->adr = NULL;
  2461.   }
  2462.   if (r->headers != NULL) {
  2463.     freet(r->headers);
  2464.     r->headers = NULL;
  2465.   }
  2466.   return 1;
  2467. }
  2468.  
  2469. // fermer une socket
  2470. HTS_INLINE void deletesoc(T_SOC soc) {
  2471.   if (soc!=INVALID_SOCKET && soc!=LOCAL_SOCKET_ID) {
  2472. #if HTS_WIDE_DEBUG    
  2473.     DEBUG_W("close %d\n" _ (int) soc);
  2474. #endif
  2475. #ifdef _WIN32
  2476.     closesocket(soc);
  2477. #else
  2478.     close(soc);
  2479. #endif
  2480. #if HTS_WIDE_DEBUG    
  2481.     DEBUG_W(".. done\n");
  2482. #endif
  2483.   }
  2484. }
  2485.  
  2486. /* Will also clean other things */
  2487. HTS_INLINE void deletesoc_r(htsblk* r) {
  2488. #if HTS_USEOPENSSL
  2489.   if (SSL_is_available && r->ssl_con) {
  2490.     SSL_shutdown(r->ssl_con);
  2491.     // SSL_CTX_set_quiet_shutdown(r->ssl_con->ctx, 1);
  2492.     SSL_free(r->ssl_con);
  2493.     r->ssl_con=NULL;
  2494.   }
  2495. #endif
  2496.   if (r->soc!=INVALID_SOCKET) {
  2497.     deletesoc(r->soc);
  2498.     r->soc=INVALID_SOCKET;
  2499.   }
  2500. }
  2501.  
  2502. // renvoi le nombre de secondes depuis 1970
  2503. HTS_INLINE TStamp time_local(void) {
  2504.   return ((TStamp) time(NULL));
  2505. }
  2506.  
  2507. // number of millisec since 1970
  2508. HTSEXT_API HTS_INLINE TStamp mtime_local(void) {
  2509. #ifndef HTS_DO_NOT_USE_FTIME
  2510.   struct timeb B;
  2511.   ftime( &B );
  2512.   return (TStamp) ( ((TStamp) B.time * (TStamp) 1000)
  2513.         + ((TStamp) B.millitm) );
  2514. #else
  2515.   // not precise..
  2516.   return (TStamp) ( ((TStamp) time_local() * (TStamp) 1000)
  2517.         + ((TStamp) 0) );
  2518. #endif
  2519. }
  2520.  
  2521. // convertit un nombre de secondes en temps (chaine)
  2522. void sec2str(char *st,TStamp t) {
  2523.   int j,h,m,s;
  2524.   
  2525.   j=(int) (t/(3600*24));
  2526.   t-=((TStamp) j)*(3600*24);
  2527.   h=(int) (t/(3600));
  2528.   t-=((TStamp) h)*3600;
  2529.   m=(int) (t/60);
  2530.   t-=((TStamp) m)*60;
  2531.   s=(int) t;
  2532.   
  2533.   if (j>0)
  2534.     sprintf(st,"%d days, %d hours %d minutes %d seconds",j,h,m,s);
  2535.   else if (h>0)
  2536.     sprintf(st,"%d hours %d minutes %d seconds",h,m,s);
  2537.   else if (m>0)
  2538.     sprintf(st,"%d minutes %d seconds",m,s);
  2539.   else
  2540.     sprintf(st,"%d seconds",s);
  2541. }
  2542.  
  2543. // idem, plus court (chaine)
  2544. HTSEXT_API void qsec2str(char *st,TStamp t) {
  2545.   int j,h,m,s;
  2546.   
  2547.   j=(int) (t/(3600*24));
  2548.   t-=((TStamp) j)*(3600*24);
  2549.   h=(int) (t/(3600));
  2550.   t-=((TStamp) h)*3600;
  2551.   m=(int) (t/60);
  2552.   t-=((TStamp) m)*60;
  2553.   s=(int) t;
  2554.   
  2555.   if (j>0)
  2556.     sprintf(st,"%dd,%02dh,%02dmin%02ds",j,h,m,s);
  2557.   else if (h>0)
  2558.     sprintf(st,"%dh,%02dmin%02ds",h,m,s);
  2559.   else if (m>0)
  2560.     sprintf(st,"%dmin%02ds",m,s);
  2561.   else
  2562.     sprintf(st,"%ds",s);
  2563. }
  2564.  
  2565.  
  2566. // heure actuelle, GMT, format rfc (taille buffer 256o)
  2567. void time_gmt_rfc822(char* s) {
  2568.   time_t tt;
  2569.   struct tm* A;
  2570.   tt=time(NULL);
  2571.   A=gmtime(&tt);
  2572.   if (A==NULL)
  2573.     A=localtime(&tt);
  2574.   time_rfc822(s,A);
  2575. }
  2576.  
  2577. // heure actuelle, format rfc (taille buffer 256o)
  2578. void time_local_rfc822(char* s) {
  2579.   time_t tt;
  2580.   struct tm* A;
  2581.   tt=time(NULL);
  2582.   A=localtime(&tt);
  2583.   time_rfc822_local(s,A);
  2584. }
  2585.  
  2586. /* convertir une chaine en temps */
  2587. struct tm* convert_time_rfc822(struct tm *result, const char* s) {
  2588.   char months[]="jan feb mar apr may jun jul aug sep oct nov dec";
  2589.   char str[256];
  2590.   char* a;
  2591.   /* */
  2592.   int result_mm=-1;
  2593.   int result_dd=-1;
  2594.   int result_n1=-1;
  2595.   int result_n2=-1;
  2596.   int result_n3=-1;
  2597.   int result_n4=-1;
  2598.   /* */
  2599.  
  2600.   if ((int) strlen(s) > 200)
  2601.     return NULL;
  2602.   strcpybuff(str,s);
  2603.   hts_lowcase(str);
  2604.   /* Θliminer :,- */
  2605.   while( (a=strchr(str,'-')) ) *a=' ';
  2606.   while( (a=strchr(str,':')) ) *a=' ';
  2607.   while( (a=strchr(str,',')) ) *a=' ';
  2608.   /* tokeniser */
  2609.   a=str;
  2610.   while(*a) {
  2611.     char *first,*last;
  2612.     char tok[256];
  2613.     /* dΘcouper mot */
  2614.     while(*a==' ') a++;   /* sauter espaces */
  2615.     first=a;
  2616.     while((*a) && (*a!=' ')) a++;
  2617.     last=a;
  2618.     tok[0]='\0';
  2619.     if (first!=last) {
  2620.       char* pos;
  2621.       strncatbuff(tok,first,(int) (last - first));
  2622.       /* analyser */
  2623.       if ( (pos=strstr(months,tok)) ) {               /* month always in letters */
  2624.         result_mm=((int) (pos - months))/4;
  2625.       } else {
  2626.         int number;
  2627.         if (sscanf(tok,"%d",&number) == 1) {      /* number token */
  2628.           if (result_dd<0)                        /* day always first number */
  2629.             result_dd=number;
  2630.           else if (result_n1<0)
  2631.             result_n1=number;
  2632.           else if (result_n2<0)
  2633.             result_n2=number;
  2634.           else if (result_n3<0)
  2635.             result_n3=number;
  2636.           else if (result_n4<0)
  2637.             result_n4=number;
  2638.         }   /* sinon, bruit de fond(+1GMT for exampel) */
  2639.       }
  2640.     }
  2641.   }
  2642.   if ((result_n1>=0) && (result_mm>=0) && (result_dd>=0) && (result_n2>=0) && (result_n3>=0) && (result_n4>=0)) {
  2643.     if (result_n4>=1000) {               /* Sun Nov  6 08:49:37 1994 */
  2644.       result->tm_year=result_n4-1900;
  2645.       result->tm_hour=result_n1;
  2646.       result->tm_min=result_n2;
  2647.       result->tm_sec=max(result_n3,0);
  2648.     } else {                            /* Sun, 06 Nov 1994 08:49:37 GMT or Sunday, 06-Nov-94 08:49:37 GMT */
  2649.       result->tm_hour=result_n2;
  2650.       result->tm_min=result_n3;
  2651.       result->tm_sec=max(result_n4,0);
  2652.       if (result_n1<=50)                /* 00 means 2000 */
  2653.         result->tm_year=result_n1+100;
  2654.       else if (result_n1<1000)          /* 99 means 1999 */
  2655.         result->tm_year=result_n1;
  2656.       else                              /* 2000 */
  2657.         result->tm_year=result_n1-1900;
  2658.     }
  2659.     result->tm_isdst=0;        /* assume GMT */
  2660.     result->tm_yday=-1;        /* don't know */
  2661.     result->tm_wday=-1;        /* don't know */
  2662.     result->tm_mon=result_mm;
  2663.     result->tm_mday=result_dd;
  2664.     return result;
  2665.   }
  2666.   return NULL;
  2667. }
  2668.  
  2669. static time_t getGMT(struct tm *tm) {        /* hey, time_t is local! */
  2670.     time_t t = mktime(tm);
  2671.     if (t != (time_t) -1 && t != (time_t) 0) {
  2672.     /* BSD does not have static "timezone" declared */
  2673. #if (defined(BSD) || defined(__FreeBSD__) || defined(__OpenBSD__) || defined(__NetBSD__) || defined(__FreeBSD_kernel__))
  2674.     time_t now = time(NULL); 
  2675.     time_t timezone = - localtime(&now)->tm_gmtoff;
  2676. #endif
  2677.     return (time_t) (t - timezone);
  2678.     }
  2679.     return (time_t) -1;
  2680. }
  2681.  
  2682. /* sets file time. -1 if error */
  2683. int set_filetime(const char* file, struct tm* tm_time) {
  2684.     time_t t = getGMT(tm_time);
  2685.     if (t != (time_t) -1) {
  2686.       struct utimbuf tim;
  2687.         memset(&tim, 0, sizeof(tim));
  2688.       tim.actime = tim.modtime = t; 
  2689.         return utime(file, &tim);
  2690.     }
  2691.     return -1;
  2692. }
  2693.  
  2694. /* sets file time from RFC822 date+time, -1 if error*/
  2695. int set_filetime_rfc822(const char* file, const char* date) {
  2696.     struct tm buffer;
  2697.   struct tm* tm_s = convert_time_rfc822(&buffer, date);
  2698.   if (tm_s) {
  2699.     return set_filetime(file,tm_s);
  2700.   } else return -1;
  2701. }
  2702.  
  2703. int get_filetime_rfc822(const char* file, char* date) {
  2704.   struct stat buf;
  2705.   date[0] = '\0';
  2706.   if (stat(file, &buf) == 0) {
  2707.     struct tm* A;
  2708.     time_t tt = buf.st_mtime;
  2709.     A=gmtime(&tt);
  2710.     if (A==NULL)
  2711.       A=localtime(&tt);
  2712.     if (A != NULL) {
  2713.       time_rfc822(date, A);
  2714.       return 1;
  2715.     }
  2716.   }
  2717.   return 0;
  2718. }
  2719.  
  2720. // heure au format rfc (taille buffer 256o)
  2721. HTS_INLINE void time_rfc822(char* s,struct tm * A) {
  2722.   if (A == NULL) {
  2723.     int localtime_returned_null=0;
  2724.     assert(localtime_returned_null);
  2725.   }
  2726.   strftime(s,256,"%a, %d %b %Y %H:%M:%S GMT",A);
  2727. }
  2728.  
  2729. // heure locale au format rfc (taille buffer 256o)
  2730. HTS_INLINE void time_rfc822_local(char* s,struct tm * A) {
  2731.   if (A == NULL) {
  2732.     int localtime_returned_null=0;
  2733.     assert(localtime_returned_null);
  2734.   }
  2735.   strftime(s,256,"%a, %d %b %Y %H:%M:%S",A);
  2736. }
  2737.  
  2738. // conversion en b,Kb,Mb
  2739. HTSEXT_API char* int2bytes(strc_int2bytes2* strc, LLint n) {
  2740.   char** a = int2bytes2(strc, n);
  2741.   strcpybuff(strc->catbuff, a[0]);
  2742.   strcatbuff(strc->catbuff, a[1]);
  2743.   return strc->catbuff;
  2744. }
  2745.  
  2746. // conversion en b/s,Kb/s,Mb/s
  2747. HTSEXT_API char* int2bytessec(strc_int2bytes2* strc, long int n) {
  2748.     char buff[256];
  2749.   char** a = int2bytes2(strc, n);
  2750.   strcpybuff(buff, a[0]);
  2751.   strcatbuff(buff, a[1]);
  2752.   return concat(strc->catbuff, buff, "/s");
  2753. }
  2754. HTSEXT_API char* int2char(strc_int2bytes2* strc, int n) {
  2755.   sprintf(strc->buff2, "%d", n);
  2756.   return strc->buff2;
  2757. }
  2758.  
  2759. // conversion en b,Kb,Mb, nombre et type sΘparΘs
  2760. // limite: 2.10^9.10^6B
  2761.  
  2762. /* See http://physics.nist.gov/cuu/Units/binary.html */
  2763. #define ToLLint(a) ((LLint)(a))
  2764. #define ToLLintKiB (ToLLint(1024))
  2765. #define ToLLintMiB (ToLLintKiB*ToLLintKiB)
  2766. #ifdef HTS_LONGLONG
  2767. #define ToLLintGiB (ToLLintKiB*ToLLintKiB*ToLLintKiB)
  2768. #define ToLLintTiB (ToLLintKiB*ToLLintKiB*ToLLintKiB*ToLLintKiB)
  2769. #define ToLLintPiB (ToLLintKiB*ToLLintKiB*ToLLintKiB*ToLLintKiB*ToLLintKiB)
  2770. #endif
  2771. HTSEXT_API char** int2bytes2(strc_int2bytes2* strc, LLint n) {
  2772.   if (n < ToLLintKiB) {
  2773.     sprintf(strc->buff1,"%d",(int)(LLint)n);
  2774.     strcpybuff(strc->buff2,"B");
  2775.   } else if (n < ToLLintMiB) {
  2776.     sprintf(strc->buff1,"%d,%02d",(int)((LLint)(n/ToLLintKiB)),(int)((LLint)((n%ToLLintKiB)*100)/ToLLintKiB));
  2777.     strcpybuff(strc->buff2,"KiB");
  2778.   }
  2779. #ifdef HTS_LONGLONG
  2780.   else if (n < ToLLintGiB) {
  2781.     sprintf(strc->buff1,"%d,%02d",(int)((LLint)(n/(ToLLintMiB))),(int)((LLint)(((n%(ToLLintMiB))*100)/(ToLLintMiB))));
  2782.     strcpybuff(strc->buff2,"MiB");
  2783.   } else if (n < ToLLintTiB) {
  2784.     sprintf(strc->buff1,"%d,%02d",(int)((LLint)(n/(ToLLintGiB))),(int)((LLint)(((n%(ToLLintGiB))*100)/(ToLLintGiB))));
  2785.     strcpybuff(strc->buff2,"GiB");
  2786.   } else if (n < ToLLintPiB) {
  2787.     sprintf(strc->buff1,"%d,%02d",(int)((LLint)(n/(ToLLintTiB))),(int)((LLint)(((n%(ToLLintTiB))*100)/(ToLLintTiB))));
  2788.     strcpybuff(strc->buff2,"TiB");
  2789.   } else {
  2790.     sprintf(strc->buff1,"%d,%02d",(int)((LLint)(n/(ToLLintPiB))),(int)((LLint)(((n%(ToLLintPiB))*100)/(ToLLintPiB))));
  2791.     strcpybuff(strc->buff2,"PiB");
  2792.   }
  2793. #else
  2794.   else {
  2795.     sprintf(strc->buff1,"%d,%02d",(int)((LLint)(n/(ToLLintMiB))),(int)((LLint)(((n%(ToLLintMiB))*100)/(ToLLintMiB))));
  2796.     strcpybuff(strc->buff2,"MiB");
  2797.   }
  2798. #endif
  2799.   strc->buffadr[0]=strc->buff1;
  2800.   strc->buffadr[1]=strc->buff2;
  2801.   return strc->buffadr;
  2802. }
  2803.  
  2804. #ifdef _WIN32
  2805. #else
  2806. // ignore sigpipe?
  2807. int sig_ignore_flag( int setflag ) {     // flag ignore
  2808.   static int flag=0;   /* YES, this one is true static */
  2809.   if (setflag>=0)
  2810.     flag=setflag;
  2811.   return flag;
  2812. }
  2813. #endif
  2814.  
  2815. // envoi de texte (en tΩtes gΘnΘralement) sur la socket soc
  2816. HTS_INLINE int sendc(htsblk* r, const char* s) {
  2817.   int n, ssz = (int)strlen(s);
  2818.  
  2819. #ifdef _WIN32
  2820. #else
  2821.   sig_ignore_flag(1);
  2822. #endif
  2823. #if HDEBUG
  2824.   write(0,s,ssz);
  2825. #endif
  2826.  
  2827. #if HTS_USEOPENSSL
  2828.   if (SSL_is_available && r->ssl) {
  2829.     n = SSL_write(r->ssl_con, s, ssz);
  2830.   } else
  2831. #endif
  2832.     n = send(r->soc,s,ssz,0);
  2833.  
  2834. #ifdef _WIN32
  2835. #else
  2836.   sig_ignore_flag(0);
  2837. #endif
  2838.  
  2839.   return ( n == ssz ) ? n : -1;
  2840. }
  2841.  
  2842.  
  2843. // Remplace read
  2844. int finput(int fd,char* s,int max) {
  2845.   char c;
  2846.   int j=0;
  2847.   do {
  2848.     //c=fgetc(fp);
  2849.     if (read(fd,&c,1)<=0) {
  2850.       c=0;
  2851.     }
  2852.     if (c!=0) {
  2853.       switch(c) {
  2854.       case 10: c=0; break;
  2855.       case 13: break;  // sauter ces caractΦres
  2856.       default: s[j++]=c; break;
  2857.       }
  2858.     }
  2859.   }  while((c!=0) && (j<max-1));
  2860.   s[j]='\0';
  2861.   return j;
  2862.  
  2863. // Like linput, but in memory (optimized)
  2864. int binput(char* buff, char* s, int max) {
  2865.   int count = 0;
  2866.   int destCount = 0;
  2867.  
  2868.   // Note: \0 will return 1
  2869.   while(destCount < max && buff != NULL && buff[count] != '\0' && buff[count] != '\n') {
  2870.     if (buff[count] != '\r') {
  2871.       s[destCount++] = buff[count];
  2872.     }
  2873.     count++;
  2874.   }
  2875.   s[destCount] = '\0';
  2876.  
  2877.   // then return the supplemental jump offset
  2878.   return count + 1;
  2879.  
  2880. // Lecture d'une ligne (peut Ωtre unicode α priori)
  2881. int linput(FILE* fp,char* s,int max) {
  2882.   int c;
  2883.   int j=0;
  2884.   do {
  2885.     c=fgetc(fp);
  2886.     if (c!=EOF) {
  2887.       switch(c) {
  2888.         case 13: break;  // sauter CR
  2889.         case 10: c=-1; break;
  2890.         case 9: case 12: break;  // sauter ces caractΦres
  2891.         default: s[j++]=(char) c; break;
  2892.       }
  2893.     }
  2894.   }  while((c!=-1) && (c!=EOF) && (j<(max-1)));
  2895.   s[j]='\0';
  2896.   return j;
  2897. }
  2898. int linputsoc(T_SOC soc, char* s, int max) {
  2899.   int c;
  2900.   int j=0;
  2901.   do {
  2902.     unsigned char ch;
  2903.     if (recv(soc, &ch, 1, 0) == 1) {
  2904.       c = ch;
  2905.     } else {
  2906.       c = EOF;
  2907.     }
  2908.     if (c!=EOF) {
  2909.       switch(c) {
  2910.         case 13: break;  // sauter CR
  2911.         case 10: c=-1; break;
  2912.         case 9: case 12: break;  // sauter ces caractΦres
  2913.         default: s[j++]=(char) c; break;
  2914.       }
  2915.     }
  2916.   }  while((c!=-1) && (c!=EOF) && (j<(max-1)));
  2917.   s[j]='\0';
  2918.   return j;
  2919. }
  2920. int linputsoc_t(T_SOC soc, char* s, int max, int timeout) {
  2921.   if (check_readinput_t(soc, timeout)) {
  2922.     return linputsoc(soc, s, max);
  2923.   }
  2924.   return -1;
  2925. }
  2926. int linput_trim(FILE* fp,char* s,int max) {
  2927.   int rlen=0;
  2928.   char* ls=(char*) malloct(max+2);
  2929.   s[0]='\0';
  2930.   if (ls) {
  2931.     char* a;
  2932.     // lire ligne
  2933.     rlen=linput(fp,ls,max);
  2934.     if (rlen) {
  2935.       // sauter espaces et tabs en fin
  2936.       while( (rlen>0) && ((ls[max(rlen-1,0)]==' ') || (ls[max(rlen-1,0)]=='\t')) )
  2937.         ls[--rlen]='\0';
  2938.       // sauter espaces en dΘbut
  2939.       a=ls;
  2940.       while((rlen>0) && ((*a==' ') || (*a=='\t'))) {
  2941.         a++;
  2942.         rlen--;
  2943.       }
  2944.       if (rlen>0) {
  2945.         memcpy(s,a,rlen);      // can copy \0 chars
  2946.         s[rlen]='\0';
  2947.       }
  2948.     }
  2949.     //
  2950.     freet(ls);
  2951.   }
  2952.   return rlen;
  2953. }
  2954. int linput_cpp(FILE* fp,char* s,int max) {
  2955.   int rlen=0;
  2956.   s[0]='\0';
  2957.   do {
  2958.     int ret;
  2959.     if (rlen>0)
  2960.     if (s[rlen-1]=='\\')
  2961.       s[--rlen]='\0';      // couper \ final
  2962.     // lire ligne
  2963.     ret=linput_trim(fp,s+rlen,max-rlen);
  2964.     if (ret>0)
  2965.       rlen+=ret;
  2966.   } while((s[max(rlen-1,0)]=='\\') && (rlen<max));
  2967.   return rlen;
  2968. }
  2969.  
  2970. // idem avec les car spΘciaux
  2971. void rawlinput(FILE* fp,char* s,int max) {
  2972.   int c;
  2973.   int j=0;
  2974.   do {
  2975.     c=fgetc(fp);
  2976.     if (c!=EOF) {
  2977.       switch(c) {
  2978.         case 13: break;  // sauter CR
  2979.         case 10: c=-1; break;
  2980.         default: s[j++]=(char) c; break;
  2981.       }
  2982.     }
  2983.   }  while((c!=-1) && (c!=EOF) && (j<(max-1)));
  2984.   s[j++]='\0';
  2985. }
  2986.  
  2987. //cherche chaine, case insensitive
  2988. char* strstrcase(char *s,char *o) {
  2989.   while((*s) && (strfield(s,o)==0)) s++;
  2990.   if (*s=='\0') return NULL;
  2991.   return s;  
  2992. }
  2993.  
  2994.  
  2995. // Unicode detector
  2996. // See http://www.unicode.org/unicode/reports/tr28/
  2997. // (sect Table 3.1B. Legal UTF-8 Byte Sequences)
  2998. typedef struct {
  2999.   unsigned int pos;
  3000.   unsigned char data[4];
  3001. } t_auto_seq;
  3002.  
  3003. // char between a and b
  3004. #define CHAR_BETWEEN(c, a, b)       ( (c) >= 0x##a ) && ( (c) <= 0x##b )
  3005. // sequence start
  3006. #define SEQBEG                      ( inseq == 0 )
  3007. // in this block
  3008. #define BLK(n,a, b)                 ( (seq.pos >= n) && ((err = CHAR_BETWEEN(seq.data[n], a, b))) )
  3009. #define ELT(n,a)                    BLK(n,a,a)
  3010. // end
  3011. #define SEQEND                      ((ok = 1))
  3012. // sequence started, character will fail if error
  3013. #define IN_SEQ                      ( (inseq = 1) )
  3014. // decoding error
  3015. #define BAD_SEQ                     ( (ok == 0) && (inseq != 0) && (!err) )
  3016. // no sequence started
  3017. #define NO_SEQ                      ( inseq == 0 )
  3018.  
  3019. // is this block an UTF unicode textfile?
  3020. // 0 : no
  3021. // 1 : yes
  3022. // -1: don't know
  3023. int is_unicode_utf8(unsigned char* buffer, unsigned int size) {
  3024.   t_auto_seq seq;
  3025.   unsigned int i;
  3026.   int is_utf=-1;
  3027.  
  3028.   seq.pos=0;
  3029.   for(i=0 ; i < size ; i++) {
  3030.     unsigned int ok=0;
  3031.     unsigned int inseq=0;
  3032.     unsigned int err=0;
  3033.  
  3034.     seq.data[seq.pos]=buffer[i];
  3035.     /**/ if ( SEQBEG && BLK(0,00,7F) && IN_SEQ && SEQEND                                                 ) { }
  3036.     else if ( SEQBEG && BLK(0,C2,DF) && IN_SEQ && BLK(1,80,BF) && SEQEND                                 ) { }
  3037.     else if ( SEQBEG && ELT(0,E0   ) && IN_SEQ && BLK(1,A0,BF) && BLK(2,80,BF) && SEQEND                 ) { }
  3038.     else if ( SEQBEG && BLK(0,E1,EC) && IN_SEQ && BLK(1,80,BF) && BLK(2,80,BF) && SEQEND                 ) { }
  3039.     else if ( SEQBEG && ELT(0,ED   ) && IN_SEQ && BLK(1,80,9F) && BLK(2,80,BF) && SEQEND                 ) { }
  3040.     else if ( SEQBEG && BLK(0,EE,EF) && IN_SEQ && BLK(1,80,BF) && BLK(2,80,BF) && SEQEND                 ) { }
  3041.     else if ( SEQBEG && ELT(0,F0   ) && IN_SEQ && BLK(1,90,BF) && BLK(2,80,BF) && BLK(3,80,BF) && SEQEND ) { }
  3042.     else if ( SEQBEG && BLK(0,F1,F3) && IN_SEQ && BLK(1,80,BF) && BLK(2,80,BF) && BLK(3,80,BF) && SEQEND ) { }
  3043.     else if ( SEQBEG && ELT(0,F4   ) && IN_SEQ && BLK(1,80,8F) && BLK(2,80,BF) && BLK(3,80,BF) && SEQEND ) { }
  3044.     else if ( NO_SEQ ) {    // bad, unknown
  3045.       return 0;
  3046.     }
  3047.     /* */
  3048.     
  3049.     /* Error */
  3050.     if ( BAD_SEQ ) {
  3051.       return 0;
  3052.     }
  3053.  
  3054.     /* unicode character */
  3055.     if (seq.pos > 0)
  3056.       is_utf=1;
  3057.  
  3058.     /* Next */
  3059.     if (ok)
  3060.       seq.pos=0;
  3061.     else
  3062.       seq.pos++;
  3063.  
  3064.     /* Internal error */
  3065.     if (seq.pos >= 4)
  3066.       return 0;
  3067.  
  3068.   }
  3069.  
  3070.   return is_utf;
  3071. }
  3072.  
  3073. void map_characters(unsigned char* buffer, unsigned int size, unsigned int* map) {
  3074.   unsigned int i;
  3075.   memset(map, 0, sizeof(unsigned int) * 256);
  3076.   for(i = 0 ; i < size ; i++) {
  3077.     map[buffer[i]]++;
  3078.   }
  3079. }
  3080.  
  3081.  
  3082. // le fichier est-il un fichier html?
  3083. //  0 : non
  3084. //  1 : oui
  3085. // -1 : on sait pas
  3086. // -2 : on sait pas, pas d'extension
  3087. int ishtml(httrackp *opt,const char* fil) {
  3088.   /* User-defined MIME types (overrides ishtml()) */
  3089.   char BIGSTK fil_noquery[HTS_URLMAXSIZE*2];
  3090.   char mime[256];
  3091.   char* a;
  3092.   strcpybuff(fil_noquery, fil);
  3093.   if ((a = strchr(fil_noquery, '?')) != NULL) {
  3094.     *a = '\0';
  3095.   }
  3096.   if (get_userhttptype(opt, mime, fil_noquery)) {
  3097.     if (strfield2(mime, "text/html")) {
  3098.       return 1;
  3099.     } else {
  3100.       return 0;
  3101.     }
  3102.   }
  3103.  
  3104.   /* Search for known ext */
  3105.   for (a = fil_noquery + strlen(fil_noquery) - 1 ; (*a!='.') && (*a!='/')  && ( a > fil_noquery ) ; a-- );
  3106.   if (*a == '.') {  // a une extension
  3107.     char BIGSTK fil_noquery[HTS_URLMAXSIZE*2];
  3108.     char* b;
  3109.     int ret;
  3110.     char* dotted = a;
  3111.     fil_noquery[0]='\0';
  3112.     a++;  // pointer sur extension
  3113.     strncatbuff(fil_noquery,a,HTS_URLMAXSIZE);
  3114.     b=strchr(fil_noquery,'?');
  3115.     if (b)
  3116.       *b='\0';
  3117.     ret = ishtml_ext(fil_noquery);     // retour
  3118.     if (ret == -1) {
  3119.       switch(is_knowntype(opt,dotted)) {
  3120.       case 1:
  3121.         ret = 0;     // connu, non html
  3122.         break;
  3123.       case 2:
  3124.         ret = 1;     // connu, html
  3125.         break;
  3126.       default:
  3127.         ret = -1;    // inconnu..
  3128.         break;
  3129.       }
  3130.     }
  3131.     return ret;
  3132.   } else return -2;   // indΘterminΘ, par exemple /truc
  3133. }
  3134.  
  3135. // idem, mais pour uniquement l'extension
  3136. int ishtml_ext(const char* a) {
  3137.   int html=0;  
  3138.   //
  3139.   if (strfield2(a,"html"))       html = 1;
  3140.   else if (strfield2(a,"htm"))   html = 1;
  3141.   else if (strfield2(a,"shtml")) html = 1;
  3142.   else if (strfield2(a,"phtml")) html = 1;
  3143.   else if (strfield2(a,"htmlx")) html = 1;
  3144.   else if (strfield2(a,"shtm"))  html = 1;
  3145.   else if (strfield2(a,"phtm"))  html = 1;
  3146.   else if (strfield2(a,"htmx"))  html = 1;
  3147.   //
  3148.   // insuccΦs..
  3149.   else {
  3150. #if 1
  3151.     html = -1;    // inconnu..
  3152. #else
  3153.     // XXXXXX not suitable (ext)
  3154.     switch(is_knownext(a)) {
  3155.     case 1:
  3156.       html = 0;     // connu, non html
  3157.       break;
  3158.     case 2:
  3159.       html = 1;     // connu, html
  3160.       break;
  3161.     default:
  3162.       html = -1;    // inconnu..
  3163.       break;
  3164.     }
  3165. #endif
  3166.   }
  3167.   return html;  
  3168. }
  3169.  
  3170. // error (404,500..)
  3171. HTS_INLINE int ishttperror(int err) {
  3172.   switch (err/100) {
  3173.     case 4: case 5: return 1;
  3174.       break;
  3175.   }
  3176.   return 0;
  3177. }
  3178.  
  3179.  
  3180. // retourne le pointeur ou le pointeur + offset si il existe dans la chaine un @ signifiant 
  3181. // une identification
  3182. HTSEXT_API char* jump_identification(const char* source) {
  3183.   const char *a,*trytofind;
  3184.   if (strcmp(source, "file://") == 0)
  3185.       return (char*) source;
  3186.   // rechercher dernier @ (car parfois email transmise dans adresse!)
  3187.   // mais sauter ftp:// Θventuel
  3188.   a = jump_protocol(source);
  3189.   trytofind = strrchr_limit(a, '@', strchr(a,'/'));
  3190.   return (char*) ( (trytofind != NULL) ? trytofind : a );
  3191. }
  3192.  
  3193. HTSEXT_API char* jump_normalized(const char* source) {
  3194.   if (strcmp(source, "file://") == 0)
  3195.       return (char*) source;
  3196.   source = jump_identification(source); 
  3197.   if (strfield(source, "www") && source[3] != '\0') {
  3198.     if (source[3] == '.') {       // www.foo.com -> foo.com
  3199.       source += 4;  
  3200.     } else {                      // www-4.foo.com -> foo.com
  3201.       const char* a = source + 3;
  3202.       while(*a && ( isdigit(*a) || *a == '-') ) a++;
  3203.       if (*a == '.') {
  3204.         source = a + 1;
  3205.       }
  3206.     }
  3207.   }
  3208.   return (char*) source;  
  3209. }
  3210.  
  3211. static int sortNormFnc(const void * a_, const void * b_) {
  3212.   char** a = (char**) a_;
  3213.   char** b = (char**) b_;
  3214.   return strcmp(*a+1, *b+1);
  3215. }
  3216.  
  3217.  
  3218. HTSEXT_API char* fil_normalized(const char* source, char* dest) {
  3219.   char lastc = 0;
  3220.   int gotquery=0;
  3221.   int ampargs=0;
  3222.   int i,j;
  3223.   char* query=NULL;
  3224.   for(i=j=0 ; source[i] != '\0'; i++) {
  3225.     if (!gotquery && source[i] == '?')
  3226.       gotquery=ampargs=1;
  3227.     if ( 
  3228.       (!gotquery && lastc == '/' && source[i] == '/')  // foo//bar -> foo/bar
  3229.       ) {
  3230.     }
  3231.     else {
  3232.       if (gotquery && source[i] == '&') {
  3233.         ampargs++;
  3234.       }
  3235.       dest[j++] = source[i];
  3236.     }
  3237.     lastc = source[i];
  3238.   }
  3239.   dest[j++] = '\0';
  3240.  
  3241.   /* Sort arguments (&foo=1&bar=2 == &bar=2&foo=1) */
  3242.   if (ampargs > 1) {
  3243.     char** amps = malloct(ampargs * sizeof(char*));
  3244.     char* copyBuff = NULL;
  3245.     int qLen=0;
  3246.     assertf(amps != NULL);
  3247.     gotquery = 0;
  3248.     for(i=j=0 ; dest[i] != '\0'; i++) {
  3249.       if ( (gotquery && dest[i] == '&') || ( !gotquery && dest[i] == '?') ) {
  3250.         if (!gotquery) {
  3251.           gotquery=1;
  3252.           query = &dest[i];
  3253.           qLen = (int)strlen(query);
  3254.         }
  3255.         assertf(j < ampargs);
  3256.         amps[j++] = &dest[i];
  3257.         dest[i] = '\0';
  3258.       }
  3259.     }
  3260.     assertf(j == ampargs);
  3261.  
  3262.     /* Sort 'em all */
  3263.     qsort(amps, ampargs, sizeof(char*), sortNormFnc);
  3264.  
  3265.     /* Replace query by sorted query */
  3266.     copyBuff = malloct(qLen + 1);
  3267.     assertf(copyBuff != NULL);
  3268.     copyBuff[0] = '\0';
  3269.     for(i = 0 ; i < ampargs ; i++) {
  3270.       if (i == 0)
  3271.         strcatbuff(copyBuff, "?");
  3272.       else
  3273.         strcatbuff(copyBuff, "&");
  3274.       strcatbuff(copyBuff, amps[i] + 1);
  3275.     }
  3276.     assert((int)strlen(copyBuff) <= qLen);
  3277.     strcpybuff(query, copyBuff);
  3278.  
  3279.     /* Cleanup */
  3280.     freet(amps);
  3281.     freet(copyBuff);
  3282.   }
  3283.   
  3284.   return dest;
  3285. }
  3286.  
  3287. #define endwith(a) ( (len >= (sizeof(a)-1)) ? ( strncmp(dest, a+len-(sizeof(a)-1), sizeof(a)-1) == 0 ) : 0 );
  3288. HTSEXT_API char* adr_normalized(const char* source, char* dest) {
  3289.   /* not yet too aggressive (no com<->net<->org checkings) */
  3290.   strcpybuff(dest, jump_normalized(source));
  3291.   return dest;
  3292. }
  3293. #undef endwith
  3294.  
  3295.  
  3296. // find port (:80) or NULL if not found
  3297. // can handle IPV6 addresses
  3298. HTSEXT_API char* jump_toport(const char* source) {
  3299.   const char *a,*trytofind;
  3300.   a = jump_identification(source);
  3301.   trytofind = strrchr_limit(a, ']', strchr(source, '/'));    // find last ] (http://[3ffe:b80:1234::1]:80/foo.html)
  3302.   a = strchr( (trytofind)?trytofind:a, ':');
  3303.   return (char*)a;
  3304. }
  3305.  
  3306. // strrchr, but not too far
  3307. char* strrchr_limit(const char* s, char c, const char* limit) {
  3308.   if (limit == NULL) {
  3309.     const char* p = strrchr(s, c);
  3310.     return (char*) ( p ? (p+1) : NULL );
  3311.   } else {
  3312.     const char *a = NULL, *p;
  3313.     for(;;) {
  3314.       p = strchr( (a) ? a : s, c);
  3315.       if ((p >= limit) || (p == NULL))
  3316.         return (char*) a;
  3317.       a=p+1;
  3318.     }
  3319.   }
  3320. }
  3321.  
  3322. // strrchr, but not too far
  3323. char* strstr_limit(const char* s, const char* sub, const char* limit) {
  3324.   if (limit == NULL) {
  3325.     return strstr(s, sub);
  3326.   } else {
  3327.     const char* pos = strstr(s, sub);
  3328.     if (pos != NULL) {
  3329.       const char* farpos = strstr(s, limit);
  3330.       if (farpos == NULL || pos < farpos)
  3331.         return (char*) pos;
  3332.     }
  3333.   }
  3334.   return NULL;
  3335. }
  3336.  
  3337. // retourner adr sans ftp://
  3338. HTS_INLINE char* jump_protocol(const char* source) {
  3339.   int p;
  3340.   // scheme
  3341.   // "Comparisons of scheme names MUST be case-insensitive" (RFC2616)
  3342.   if ((p=strfield(source,"http:")))
  3343.     source+=p;
  3344.   else if ((p=strfield(source,"ftp:")))
  3345.     source+=p;
  3346.   else if ((p=strfield(source,"https:")))
  3347.     source+=p;
  3348.   else if ((p=strfield(source,"file:")))
  3349.     source+=p;
  3350. #if HTS_USEMMS
  3351.   else if ((p=strfield(source,"mms:")))
  3352.     source+=p;
  3353. #endif
  3354.   // net_path
  3355.   if (strncmp(source,"//",2)==0)
  3356.     source+=2;
  3357.   return (char*) source;
  3358. }
  3359.  
  3360. // codage base 64 a vers b
  3361. void code64(unsigned char* a,int size_a,unsigned char* b,int crlf) {
  3362.   int i1=0,i2=0,i3=0,i4=0;
  3363.   int loop=0;
  3364.   unsigned long int store;
  3365.   int n;
  3366.   const char _hts_base64[] = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
  3367.   while(size_a-- > 0) {  
  3368.     // 24 bits
  3369.     n=1; 
  3370.     store = *a++;
  3371.     if (size_a-- > 0) { n=2; store <<= 8; store |= *a++; }
  3372.     if (size_a-- > 0) { n=3; store <<= 8; store |= *a++; }
  3373.     if (n==3) {
  3374.       i4=store & 63;
  3375.       i3=(store>>6) & 63;
  3376.       i2=(store>>12) & 63;
  3377.       i1=(store>>18) & 63;
  3378.     } else if (n==2) {
  3379.       store<<=2;    
  3380.       i3=store & 63;
  3381.       i2=(store>>6) & 63;
  3382.       i1=(store>>12) & 63;
  3383.     } else {
  3384.       store<<=4;
  3385.       i2=store & 63;
  3386.       i1=(store>>6) & 63;
  3387.     }
  3388.     
  3389.     *b++ = _hts_base64[i1];
  3390.     *b++ = _hts_base64[i2];
  3391.     if (n>=2)
  3392.       *b++ = _hts_base64[i3];
  3393.     else
  3394.       *b++ = '=';
  3395.     if (n>=3)
  3396.       *b++ = _hts_base64[i4];
  3397.     else
  3398.       *b++ = '=';
  3399.  
  3400.     if (crlf && ( ( loop += 3 ) % 60) == 0 ) {
  3401.       *b++ = '\r';
  3402.       *b++ = '\n';
  3403.     }
  3404.   }
  3405.   *b++='\0';
  3406. }
  3407.  
  3408. // remplacer " par " etc..
  3409. // buffer MAX 1Ko
  3410. #define strcmpbeg(a, b) strncmp(a, b, strlen(b))
  3411. HTSEXT_API void unescape_amp(char* s) {
  3412.   while(*s) {
  3413.     if (*s=='&') {
  3414.       char* end=strchr(s,';');
  3415.       if ( end && (((int) (end - s)) <= 8) ) {
  3416.         unsigned char c=0;
  3417.         
  3418.         // http://www.w3.org/TR/xhtml-modularization/dtd_module_defs.html
  3419.         if (strcmpbeg(s, "&#") == 0) {
  3420.           int num=0;
  3421.           if ( (s[2] == 'x') || (s[2] == 'X')) {
  3422.             if (sscanf(s+3, "%x", &num) == 1 && num <= 0xff) {
  3423.               c=(unsigned char) num;
  3424.             }
  3425.           } else {
  3426.             if (sscanf(s+2, "%d", &num) == 1 && num <= 0xff) {
  3427.               c=(unsigned char) num;
  3428.             }
  3429.           }
  3430.         }
  3431.         else if (strcmpbeg(s, " ")==0)
  3432.           c=32; // hack - c=160;
  3433.         else if (strcmpbeg(s, "¡")==0)
  3434.           c=161;
  3435.         else if (strcmpbeg(s, "¢")==0)
  3436.           c=162;
  3437.         else if (strcmpbeg(s, "£")==0)
  3438.           c=163;
  3439.         else if (strcmpbeg(s, "¤")==0)
  3440.           c=164;
  3441.         else if (strcmpbeg(s, "¥")==0)
  3442.           c=165;
  3443.         else if (strcmpbeg(s, "¦")==0)
  3444.           c=166;
  3445.         else if (strcmpbeg(s, "§")==0)
  3446.           c=167;
  3447.         else if (strcmpbeg(s, "¨")==0)
  3448.           c=168;
  3449.         else if (strcmpbeg(s, "©")==0)
  3450.           c=169;
  3451.         else if (strcmpbeg(s, "ª")==0)
  3452.           c=170;
  3453.         //else if (strcmpbeg(s, "«")==0)
  3454.         //  c=171;
  3455.         else if (strcmpbeg(s, "¬")==0)
  3456.           c=172;
  3457.         //else if (strcmpbeg(s, "­")==0)
  3458.         //  c=173;
  3459.         else if (strcmpbeg(s, "®")==0)
  3460.           c=174;
  3461.         else if (strcmpbeg(s, "¯")==0)
  3462.           c=175;
  3463.         else if (strcmpbeg(s, "°")==0)
  3464.           c=176;
  3465.         else if (strcmpbeg(s, "±")==0)
  3466.           c=177;
  3467.         else if (strcmpbeg(s, "²")==0)
  3468.           c=178;
  3469.         else if (strcmpbeg(s, "³")==0)
  3470.           c=179;
  3471.         else if (strcmpbeg(s, "´")==0)
  3472.           c=180;
  3473.         else if (strcmpbeg(s, "µ")==0)
  3474.           c=181;
  3475.         else if (strcmpbeg(s, "¶")==0)
  3476.           c=182;
  3477.         else if (strcmpbeg(s, "·")==0)
  3478.           c=183;
  3479.         else if (strcmpbeg(s, "¸")==0)
  3480.           c=184;
  3481.         else if (strcmpbeg(s, "¹")==0)
  3482.           c=185;
  3483.         else if (strcmpbeg(s, "º")==0)
  3484.           c=186;
  3485.         //else if (strcmpbeg(s, "»")==0)
  3486.         //  c=187;
  3487.         else if (strcmpbeg(s, "¼")==0)
  3488.           c=188;
  3489.         else if (strcmpbeg(s, "½")==0)
  3490.           c=189;
  3491.         else if (strcmpbeg(s, "¾")==0)
  3492.           c=190;
  3493.         else if (strcmpbeg(s, "¿")==0)
  3494.           c=191;
  3495.         else if (strcmpbeg(s, "À")==0)
  3496.           c=192;
  3497.         else if (strcmpbeg(s, "Á")==0)
  3498.           c=193;
  3499.         else if (strcmpbeg(s, "Â")==0)
  3500.           c=194;
  3501.         else if (strcmpbeg(s, "Ã")==0)
  3502.           c=195;
  3503.         else if (strcmpbeg(s, "Ä")==0)
  3504.           c=196;
  3505.         else if (strcmpbeg(s, "Å")==0)
  3506.           c=197;
  3507.         else if (strcmpbeg(s, "Æ")==0)
  3508.           c=198;
  3509.         else if (strcmpbeg(s, "Ç")==0)
  3510.           c=199;
  3511.         else if (strcmpbeg(s, "È")==0)
  3512.           c=200;
  3513.         else if (strcmpbeg(s, "É")==0)
  3514.           c=201;
  3515.         else if (strcmpbeg(s, "Ê")==0)
  3516.           c=202;
  3517.         else if (strcmpbeg(s, "Ë")==0)
  3518.           c=203;
  3519.         else if (strcmpbeg(s, "Ì")==0)
  3520.           c=204;
  3521.         else if (strcmpbeg(s, "Í")==0)
  3522.           c=205;
  3523.         else if (strcmpbeg(s, "Î")==0)
  3524.           c=206;
  3525.         else if (strcmpbeg(s, "Ï")==0)
  3526.           c=207;
  3527.         else if (strcmpbeg(s, "Ð")==0)
  3528.           c=208;
  3529.         else if (strcmpbeg(s, "Ñ")==0)
  3530.           c=209;
  3531.         else if (strcmpbeg(s, "Ò")==0)
  3532.           c=210;
  3533.         else if (strcmpbeg(s, "Ó")==0)
  3534.           c=211;
  3535.         else if (strcmpbeg(s, "Ô")==0)
  3536.           c=212;
  3537.         else if (strcmpbeg(s, "Õ")==0)
  3538.           c=213;
  3539.         else if (strcmpbeg(s, "Ö")==0)
  3540.           c=214;
  3541.         else if (strcmpbeg(s, "×")==0)
  3542.           c=215;
  3543.         else if (strcmpbeg(s, "Ø")==0)
  3544.           c=216;
  3545.         else if (strcmpbeg(s, "Ù")==0)
  3546.           c=217;
  3547.         else if (strcmpbeg(s, "Ú")==0)
  3548.           c=218;
  3549.         else if (strcmpbeg(s, "Û")==0)
  3550.           c=219;
  3551.         else if (strcmpbeg(s, "Ü")==0)
  3552.           c=220;
  3553.         else if (strcmpbeg(s, "Ý")==0)
  3554.           c=221;
  3555.         else if (strcmpbeg(s, "Þ")==0)
  3556.           c=222;
  3557.         else if (strcmpbeg(s, "ß")==0)
  3558.           c=223;
  3559.         else if (strcmpbeg(s, "à")==0)
  3560.           c=224;
  3561.         else if (strcmpbeg(s, "á")==0)
  3562.           c=225;
  3563.         else if (strcmpbeg(s, "â")==0)
  3564.           c=226;
  3565.         else if (strcmpbeg(s, "ã")==0)
  3566.           c=227;
  3567.         else if (strcmpbeg(s, "ä")==0)
  3568.           c=228;
  3569.         else if (strcmpbeg(s, "å")==0)
  3570.           c=229;
  3571.         else if (strcmpbeg(s, "æ")==0)
  3572.           c=230;
  3573.         else if (strcmpbeg(s, "ç")==0)
  3574.           c=231;
  3575.         else if (strcmpbeg(s, "è")==0)
  3576.           c=232;
  3577.         else if (strcmpbeg(s, "é")==0)
  3578.           c=233;
  3579.         else if (strcmpbeg(s, "ê")==0)
  3580.           c=234;
  3581.         else if (strcmpbeg(s, "ë")==0)
  3582.           c=235;
  3583.         else if (strcmpbeg(s, "ì")==0)
  3584.           c=236;
  3585.         else if (strcmpbeg(s, "í")==0)
  3586.           c=237;
  3587.         else if (strcmpbeg(s, "î")==0)
  3588.           c=238;
  3589.         else if (strcmpbeg(s, "ï")==0)
  3590.           c=239;
  3591.         else if (strcmpbeg(s, "ð")==0)
  3592.           c=240;
  3593.         else if (strcmpbeg(s, "ñ")==0)
  3594.           c=241;
  3595.         else if (strcmpbeg(s, "ò")==0)
  3596.           c=242;
  3597.         else if (strcmpbeg(s, "ó")==0)
  3598.           c=243;
  3599.         else if (strcmpbeg(s, "ô")==0)
  3600.           c=244;
  3601.         else if (strcmpbeg(s, "õ")==0)
  3602.           c=245;
  3603.         else if (strcmpbeg(s, "ö")==0)
  3604.           c=246;
  3605.         else if (strcmpbeg(s, "÷")==0)
  3606.           c=247;
  3607.         else if (strcmpbeg(s, "ø")==0)
  3608.           c=248;
  3609.         else if (strcmpbeg(s, "ù")==0)
  3610.           c=249;
  3611.         else if (strcmpbeg(s, "ú")==0)
  3612.           c=250;
  3613.         else if (strcmpbeg(s, "û")==0)
  3614.           c=251;
  3615.         else if (strcmpbeg(s, "ü")==0)
  3616.           c=252;
  3617.         else if (strcmpbeg(s, "ý")==0)
  3618.           c=253;
  3619.         else if (strcmpbeg(s, "þ")==0)
  3620.           c=254;
  3621.         else if (strcmpbeg(s, "ÿ")==0)
  3622.           c=255;
  3623.         //        
  3624.         else if (strcmpbeg(s,"&")==0)
  3625.           c='&';
  3626.         else if (strcmpbeg(s,">")==0)
  3627.           c='>';
  3628.         else if (strcmpbeg(s,"«")==0)
  3629.           c='\"';
  3630.         else if (strcmpbeg(s,"<")==0)
  3631.           c='<';
  3632.         else if (strcmpbeg(s," ")==0)
  3633.           c=' ';
  3634.         else if (strcmpbeg(s,""")==0)
  3635.           c='\"';
  3636.         else if (strcmpbeg(s,"»")==0)
  3637.           c='\"';
  3638.         else if (strcmpbeg(s,"­")==0)
  3639.           c='-';
  3640.         else if (strcmpbeg(s,"˜")==0)
  3641.           c='~';
  3642.         // remplacer?
  3643.         if (c) {
  3644.           char BIGSTK buff[HTS_URLMAXSIZE*2];
  3645.           buff[0]=(char) c;
  3646.           strcpybuff(buff+1,end+1);
  3647.           strcpybuff(s,buff);
  3648.         }
  3649.       }
  3650.     }
  3651.     s++;
  3652.   }
  3653. }
  3654.  
  3655. static int ehexh(char c) {
  3656.   if ((c>='0') && (c<='9')) return c-'0';
  3657.   if ((c>='a') && (c<='f')) c-=('a'-'A');
  3658.   if ((c>='A') && (c<='F')) return (c-'A'+10);
  3659.   return 0;
  3660. }
  3661.  
  3662. static int ehex(const char* s) {
  3663.   return 16*ehexh(*s)+ehexh(*(s+1));
  3664. }
  3665.  
  3666. // remplacer %20 par ' ', | par : etc..
  3667. // buffer MAX 1Ko
  3668. HTSEXT_API char* unescape_http(char *catbuff, const char* s) {
  3669.   int i,j=0;
  3670.   for (i=0;i<(int) strlen(s);i++) {
  3671.     if (s[i]=='%') {
  3672.       i++;
  3673.       catbuff[j++]=(char) ehex(s+i);
  3674.       i++;    // sauter 2 caractΦres finalement
  3675.     }
  3676.     /*
  3677.     NON a cause de trucs comme /home/0,1837,1|7|1173|Content,00.html
  3678.     else if (s[i]=='|') {                     // exemple: file:///C|Program%20Files...
  3679.       tempo[j++]=':';
  3680.     }
  3681.     */
  3682.     else
  3683.       catbuff[j++]=s[i];
  3684.   }
  3685.   catbuff[j++]='\0';
  3686.   return catbuff;
  3687. }
  3688.  
  3689. // unescape in URL/URI ONLY what has to be escaped, to form a standard URL/URI
  3690. // DOES NOT DECODE %25
  3691. HTSEXT_API char* unescape_http_unharm(char *catbuff, const char* s, int no_high) {
  3692.   int i,j=0;
  3693.   for (i=0;i<(int) strlen(s);i++) {
  3694.     if (s[i]=='%') {
  3695.       int nchar=(char) ehex(s+i+1);
  3696.  
  3697.       int test = (  CHAR_RESERVED(nchar)
  3698.                 || ( nchar != '%' && CHAR_DELIM(nchar) )
  3699.                 || CHAR_UNWISE(nchar)
  3700.                 || CHAR_LOW(nchar)        /* CHAR_SPECIAL */
  3701.                 || CHAR_XXAVOID(nchar) 
  3702.                 || (
  3703.                   (no_high)
  3704.                   &&
  3705.                   CHAR_HIG(nchar)
  3706.                 )
  3707.                 );
  3708.  
  3709.       if (!test) {
  3710.         catbuff[j++]=(char) ehex(s+i+1);
  3711.         i+=2;
  3712.       } else {
  3713.         catbuff[j++]='%';
  3714.       }
  3715.     }
  3716.     /*
  3717.     NON a cause de trucs comme /home/0,1837,1|7|1173|Content,00.html
  3718.     else if (s[i]=='|') {                     // exemple: file:///C|Program%20Files...
  3719.       tempo[j++]=':';
  3720.     }
  3721.     */
  3722.     else
  3723.       catbuff[j++]=s[i];
  3724.   }
  3725.   catbuff[j++]='\0';
  3726.   return catbuff;
  3727. }
  3728.  
  3729. // remplacer " par %xx etc..
  3730. // buffer MAX 1Ko
  3731. HTSEXT_API void escape_spc_url(char* s) {
  3732.   x_escape_http(s,2);
  3733. }
  3734. // smith / john -> smith%20%2f%20john
  3735. HTSEXT_API void escape_in_url(char* s) {
  3736.   x_escape_http(s,1);
  3737. }
  3738. // smith / john -> smith%20/%20john
  3739. HTSEXT_API void escape_uri(char* s) {
  3740.   x_escape_http(s,3);
  3741. }
  3742. HTSEXT_API void escape_uri_utf(char* s) {
  3743.   x_escape_http(s,30);
  3744. }
  3745. HTSEXT_API void escape_check_url(char* s) {
  3746.   x_escape_http(s,0);
  3747. }
  3748. // same as escape_check_url, but returns char*
  3749. HTSEXT_API char* escape_check_url_addr(char *catbuff, const char* s) {
  3750.   char* adr;
  3751.   escape_check_url(adr = concat(catbuff, s, ""));
  3752.   return adr;
  3753. }
  3754.  
  3755. // strip all control characters
  3756. HTSEXT_API void escape_remove_control(char* s) {
  3757.   unsigned char* ss = (unsigned char*) s;
  3758.   while(*ss) {
  3759.     if (*ss < 32) {    /* CONTROL characters go away! */
  3760.       char BIGSTK tmp[HTS_URLMAXSIZE*2];
  3761.       strcpybuff(tmp, ss+1);
  3762.       strcpybuff(ss, tmp);
  3763.     } else {
  3764.       ss++;
  3765.     }
  3766.   }
  3767. }
  3768.  
  3769. HTSEXT_API void x_escape_html(char* s) {
  3770.   while(*s) {
  3771.     int test=0;
  3772.       test = (
  3773.                 CHAR_HIG(*s)
  3774.              || CHAR_XXAVOID(*s) );
  3775.  
  3776.     if (test) {
  3777.       char BIGSTK buffer[HTS_URLMAXSIZE*3];
  3778.       int n;
  3779.       n = (int)(unsigned char) *s;
  3780.       strcpybuff(buffer, s+1);
  3781.       sprintf(s,"&#x%02x;", n);
  3782.       strcatbuff(s, buffer);
  3783.     }
  3784.     s++;
  3785.   }
  3786. }
  3787.  
  3788.  
  3789. HTSEXT_API void x_escape_http(char* s,int mode) {
  3790.   while(*s) {
  3791.     int test=0;
  3792.     if (mode == 0)
  3793.       test=(strchr("\" ",*s)!=0);
  3794.     else if (mode==1) {
  3795.       test = (  CHAR_RESERVED(*s)
  3796.              || CHAR_DELIM(*s)
  3797.              || CHAR_UNWISE(*s)
  3798.              || CHAR_SPECIAL(*s)
  3799.              || CHAR_XXAVOID(*s)
  3800.              || CHAR_MARK(*s));
  3801.     }
  3802.     else if (mode==2)
  3803.       test=(*s == ' ');           // n'escaper que espace
  3804.     else if (mode==3) {                   // Θchapper que ce qui est nΘcessaire
  3805.       test = (
  3806.                 CHAR_SPECIAL(*s)
  3807.              || CHAR_XXAVOID(*s) );
  3808.     }
  3809.     else if (mode==30) {                   // Θchapper que ce qui est nΘcessaire
  3810.       test = (
  3811.                 CHAR_LOW(*s)
  3812.              || CHAR_XXAVOID(*s) );
  3813.     }
  3814.  
  3815.     if (test) {
  3816.       char BIGSTK buffer[HTS_URLMAXSIZE*3];
  3817.       int n;
  3818.       n=(int)(unsigned char) *s;
  3819.       strcpybuff(buffer,s+1);
  3820.       sprintf(s,"%%%02x",n);
  3821.       strcatbuff(s,buffer);
  3822.     }
  3823.     s++;
  3824.   }
  3825. }
  3826.  
  3827. HTSEXT_API void escape_for_html_print(char* s, char* d) {
  3828.   for( ; *s ; s++) {
  3829.     if (*s == '&') {
  3830.       strcpybuff(d, "&");
  3831.       d += strlen(d);
  3832.     } else {
  3833.       *d++ = *s;
  3834.     }
  3835.   }
  3836.   *d = '\0';
  3837. }
  3838.  
  3839. HTSEXT_API void escape_for_html_print_full(char* s, char* d) {
  3840.   for( ; *s ; s++) {
  3841.     if (*s == '&') {
  3842.       strcpybuff(d, "&");
  3843.       d += strlen(d);
  3844.     } else if (CHAR_HIG(*s)) {
  3845.       sprintf(d, "&#x%02x;", (unsigned char) *s);
  3846.       d += strlen(d);
  3847.     } else {
  3848.       *d++ = *s;
  3849.     }
  3850.   }
  3851.   *d = '\0';
  3852. }
  3853.  
  3854.  
  3855.  
  3856. // concat, concatΦne deux chaines et renvoi le rΘsultat
  3857. // permet d'allΘger grandement le code
  3858. // il faut savoir qu'on ne peut mettre plus de 16 concat() dans une expression
  3859. HTSEXT_API char* concat(char *catbuff,const char* a,const char* b) {
  3860.     if (a != NULL && a[0] != '\0') {
  3861.         strcpybuff(catbuff, a);
  3862.     } else {
  3863.         catbuff[0] = '\0';
  3864.     }
  3865.     if (b != NULL && b[0] != '\0') {
  3866.         strcatbuff(catbuff, b);
  3867.     }
  3868.   return catbuff;
  3869. }
  3870. // conversion fichier / -> antislash
  3871. static char* __fconv(char* a) {
  3872. #if HTS_DOSNAME
  3873.   int i;
  3874.   for(i = 0 ; a[i] != 0 ; i++)
  3875.     if (a[i] == '/')  // Unix-to-DOS style
  3876.       a[i] = '\\';
  3877. #endif
  3878.   return a;
  3879. }
  3880.  
  3881. HTSEXT_API char* fconcat(char *catbuff, const char* a, const char* b) {
  3882.   return __fconv(concat(catbuff,a,b));
  3883. }
  3884. HTSEXT_API char* fconv(char *catbuff, const char* a) {
  3885.   return __fconv(concat(catbuff,a,""));
  3886. }
  3887.  
  3888. /* / et \\ en / */
  3889. static char* __fslash(char* a) {
  3890.   int i;
  3891.   for(i = 0 ; a[i] != 0 ; i++)
  3892.     if (a[i] == '\\')  // convertir
  3893.       a[i] = '/';
  3894.   return a;
  3895. }
  3896. char* fslash(char *catbuff, const char* a) {
  3897.   return __fslash(concat(catbuff,a,NULL));
  3898. }
  3899.  
  3900. // conversion minuscules, avec buffer
  3901. char* convtolower(char *catbuff, const char* a) {
  3902.   strcpybuff(catbuff,a);
  3903.   hts_lowcase(catbuff);  // lower case
  3904.   return catbuff;
  3905. }
  3906.  
  3907. // conversion en minuscules
  3908. void hts_lowcase(char* s) {
  3909.   int i;
  3910.   for(i=0;i<(int) strlen(s);i++)
  3911.     if ((s[i]>='A') && (s[i]<='Z'))
  3912.       s[i]+=('a'-'A');
  3913. }
  3914.  
  3915. // remplacer un caractΦre d'une chaεne dans une autre
  3916. HTS_INLINE void hts_replace(char *s,char from,char to) { 
  3917.   char* a;
  3918.   while ((a=strchr(s,from))!=NULL) {
  3919.     *a=to;
  3920.   }
  3921. }
  3922.  
  3923.  
  3924. // caractΦre espace, guillemets, CR, LF etc..
  3925. /* SECTION OPTIMISEE:
  3926.   #define  is_space(c) (strchr(" \"\x0d\x0a\x09'",c)!=NULL)
  3927.   #define  is_realspace(c) (strchr(" \x0d\x0a\x09\x0c",c)!=NULL)
  3928. */
  3929. /*
  3930. HTS_INLINE int is_space(char c) {
  3931.   if (c==' ')  return 1;  // spc
  3932.   if (c=='"')  return 1;  // quote
  3933.   if (c==10)   return 1;  // lf
  3934.   if (c==13)   return 1;  // cr
  3935.   if (c=='\'') return 1;  // quote
  3936.   //if (c=='`')  return 1;  // backquote      << non
  3937.   if (c==9)    return 1;  // tab
  3938.   return 0;
  3939. }
  3940. */
  3941.  
  3942. // caractΦre espace, CR, LF, TAB
  3943. /*
  3944. HTS_INLINE int is_realspace(char c) {
  3945.   if (c==' ')  return 1;  // spc
  3946.   if (c==10)   return 1;  // lf
  3947.   if (c==13)   return 1;  // cr
  3948.   if (c==9)    return 1;  // tab
  3949.   return 0;
  3950. }
  3951. */
  3952.  
  3953.  
  3954.  
  3955.  
  3956.  
  3957. // deviner type d'un fichier local..
  3958. // ex: fil="toto.gif" -> s="image/gif"
  3959. void guess_httptype(httrackp *opt,char *s,const char *fil) {
  3960.   get_httptype(opt,s, fil, 1);
  3961. }
  3962. // idem
  3963. // flag: 1 si toujours renvoyer un type
  3964. HTSEXT_API void get_httptype(httrackp *opt,char *s,const char *fil,int flag) {
  3965.   // userdef overrides get_httptype
  3966.   if (get_userhttptype(opt, s, fil)) {
  3967.     return ;
  3968.   }
  3969.   // regular tests
  3970.   if (ishtml(opt,fil) == 1) {
  3971.     strcpybuff(s,"text/html");
  3972.   } else {
  3973.     /* Check html -> text/html */
  3974.     const char* a = fil + strlen(fil) - 1;    
  3975.     while ( (*a!='.') && (*a!='/') && (a>fil)) a--;
  3976.     if (*a=='.' && strlen(a) < 32) {
  3977.       int j=0;
  3978.       a++;
  3979.       while(strnotempty(hts_mime[j][1])) {
  3980.         if (strfield2(hts_mime[j][1],a)) {
  3981.           if (hts_mime[j][0][0]!='*') {    // Une correspondance existe
  3982.             strcpybuff(s,hts_mime[j][0]);
  3983.             return;
  3984.           }
  3985.         }
  3986.         j++;
  3987.       }
  3988.       
  3989.       if (flag)
  3990.         sprintf(s,"application/%s",a);
  3991.     } else {
  3992.       if (flag)
  3993.         strcpybuff(s,"application/octet-stream");
  3994.     }
  3995.   }
  3996. }
  3997.  
  3998. // get type of fil (php)
  3999. // s: buffer (text/html) or NULL
  4000. // return: 1 if known by user
  4001. int get_userhttptype(httrackp *opt, char *s, const char *fil) {
  4002.   if (s != NULL) {
  4003.     if (s)
  4004.       s[0]='\0';
  4005.     if (fil == NULL || *fil == '\0')
  4006.       return 0;
  4007. #if 1
  4008.     if (StringLength(opt->mimedefs) > 0) {
  4009.  
  4010.       /* Check --assume foooo/foo/bar.cgi=text/html, then foo/bar.cgi=text/html, then bar.cgi=text/html */
  4011.       /* also: --assume baz,bar,foooo/foo/bar.cgi=text/html */
  4012.       /* start from path begining */
  4013.       do {
  4014.         const char* next;
  4015.         const char* mimedefs = StringBuff(opt->mimedefs);    /* loop through mime definitions : \nfoo=bar\nzoo=baz\n.. */
  4016.         while(*mimedefs != '\0') {
  4017.           const char* segment = fil + 1;
  4018.           if (*mimedefs == '\n') {
  4019.             mimedefs++;
  4020.           }
  4021.           /* compare current segment with user's definition */
  4022.           do {
  4023.             int i;
  4024.             /* check current item */
  4025.             for(i = 0 ; 
  4026.               mimedefs[i] != '\0'           /* end of all defs */
  4027.               && mimedefs[i] != ' '         /* next item in left list */
  4028.               && mimedefs[i] != '='         /* end of left list */
  4029.               && mimedefs[i] != '\n'        /* end of this def (?) */
  4030.               && mimedefs[i] == segment[i]  /* same item */
  4031.               ; i++);
  4032.             /* success */
  4033.             if ( ( mimedefs[i] == '=' || mimedefs[i] == ' ' ) && segment[i] == '\0') {
  4034.               int i2;
  4035.               while(mimedefs[i] != 0 && mimedefs[i] != '\n' && mimedefs[i] != '=') i++;
  4036.               if (mimedefs[i] == '=') {
  4037.                 i++;
  4038.                 for(i2 = 0 ; mimedefs[i + i2] != '\n' && mimedefs[i + i2] != '\0' ; i2++) {
  4039.                   s[i2] = mimedefs[i + i2];
  4040.                 }
  4041.                 s[i2] = '\0';
  4042.                 return 1;   /* SUCCESS! */
  4043.               }
  4044.             }
  4045.             /* next item in list */
  4046.             for(mimedefs += i ; 
  4047.               *mimedefs != '\0' && *mimedefs != '\n' && *mimedefs != '=' && *mimedefs != ' ' ; 
  4048.               mimedefs++);
  4049.             if (*mimedefs == ' ') {
  4050.               mimedefs++;
  4051.             }
  4052.           } while(*mimedefs != '\0' && *mimedefs != '\n' && *mimedefs != '=');
  4053.           /* next user-def */
  4054.           for( ; *mimedefs != '\0' && *mimedefs != '\n' ; mimedefs++);
  4055.         }
  4056.         /* shorten segment */
  4057.         next = strchr(fil + 1, '/');
  4058.         if (next == NULL) {
  4059.           /* ext tests */
  4060.           next = strchr(fil + 1, '.');
  4061.         }
  4062.         fil = next;
  4063.       } while(fil != NULL);
  4064.     }
  4065. #else
  4066.     if (*buffer) {
  4067.       char BIGSTK search[1024];
  4068.       char* detect;
  4069.  
  4070.  
  4071.       sprintf(search,"\n%s=",ext);    // php=text/html
  4072.       detect=strstr(*buffer,search);
  4073.       if (!detect) {
  4074.         sprintf(search,"\n%s\n",ext); // php\ncgi=text/html
  4075.         detect=strstr(*buffer,search);
  4076.       }
  4077.       if (detect) {
  4078.         detect=strchr(detect,'=');
  4079.         if (detect) {
  4080.           detect++;
  4081.           if (s) {
  4082.             char* a;
  4083.             a=strchr(detect,'\n');
  4084.             if (a) {
  4085.               strncatbuff(s,detect,(int) (a - detect));
  4086.             }
  4087.           }
  4088.           return 1;
  4089.         }
  4090.       }
  4091.     }
  4092. #endif
  4093.   }
  4094.   return 0;
  4095. }
  4096. // renvoyer extesion d'un type mime..
  4097. // ex: "image/gif" -> gif
  4098. void give_mimext(char *s,const char *st) {   
  4099.   int ok=0;
  4100.   int j=0;
  4101.   s[0]='\0';
  4102.   while( (!ok) && (strnotempty(hts_mime[j][1])) ) {
  4103.     if (strfield2(hts_mime[j][0],st)) {
  4104.       if (hts_mime[j][1][0]!='*') {    // Une correspondance existe
  4105.         strcpybuff(s,hts_mime[j][1]);
  4106.         ok=1;
  4107.       }
  4108.     }
  4109.     j++;
  4110.   }
  4111.   // wrap "x" mimetypes, such as:
  4112.   // application/x-mp3
  4113.   // or
  4114.   // application/mp3
  4115.   if (!ok) {
  4116.     int p;
  4117.     const char* a=NULL;
  4118.     if ((p=strfield(st,"application/x-")))
  4119.       a=st+p;
  4120.     else if ((p=strfield(st,"application/")))
  4121.       a=st+p;
  4122.     if (a) {
  4123.       if ((int)strlen(a) >= 1) {
  4124.         if ((int)strlen(a) <= 4) {
  4125.           strcpybuff(s,a);
  4126.           ok=1;
  4127.         }
  4128.       }
  4129.     }
  4130.   }
  4131. }
  4132. // extension connue?..
  4133. //  0 : non
  4134. //  1 : oui
  4135. //  2 : html
  4136. HTSEXT_API int is_knowntype(httrackp *opt,const char *fil) {
  4137.     char catbuff[CATBUFF_SIZE];
  4138.   const char *ext;
  4139.   int j=0;
  4140.   if (!fil)
  4141.     return 0;
  4142.   ext = get_ext(catbuff, fil);
  4143.   while(strnotempty(hts_mime[j][1])) {
  4144.     if (strfield2(hts_mime[j][1], ext)) {
  4145.       if (strfield2(hts_mime[j][0], "text/html"))
  4146.         return 2;
  4147.       else
  4148.         return 1;
  4149.     }
  4150.     j++;
  4151.   }
  4152.  
  4153.   // Known by user?
  4154.   return (is_userknowntype(opt,fil));
  4155. }
  4156. // extension : html,gif..
  4157. HTSEXT_API char* get_ext(char *catbuff, const char *fil) {
  4158.   const char *a=fil+strlen(fil)-1;    
  4159.  
  4160.   while ( (*a!='.') && (*a!='/')  && (a>fil)) a--;
  4161.   if (*a=='.') {
  4162.         char fil_noquery[HTS_URLMAXSIZE*2];
  4163.     char* b;
  4164.     fil_noquery[0]='\0';
  4165.     a++;  // pointer sur extension
  4166.     strncatbuff(fil_noquery,a,HTS_URLMAXSIZE);
  4167.     b=strchr(fil_noquery,'?');
  4168.     if (b)
  4169.       *b='\0';
  4170.     return concat(catbuff,fil_noquery,"");
  4171.   }
  4172.   else
  4173.     return "";
  4174. }
  4175. // known type?..
  4176. //  0 : no
  4177. //  1 : yes
  4178. //  2 : html
  4179. // setdefs : set mime buffer:
  4180. //   file=(char*) "asp=text/html\nphp=text/html\n"
  4181. HTSEXT_API int is_userknowntype(httrackp *opt,const char *fil) {
  4182.   char BIGSTK mime[1024];
  4183.   if (!fil)
  4184.     return 0;
  4185.   if (!strnotempty(fil))
  4186.     return 0;
  4187.   mime[0]='\0';
  4188.   get_userhttptype(opt, mime, fil);
  4189.   if (!strnotempty(mime))
  4190.     return 0;
  4191.   else if (strfield2(mime,"text/html"))
  4192.     return 2;
  4193.   else
  4194.     return 1;
  4195. }
  4196.  
  4197. // page dynamique?
  4198. // is_dyntype(get_ext("foo.asp"))
  4199. HTSEXT_API int is_dyntype(const char *fil) {
  4200.   int j=0;
  4201.   if (!fil)
  4202.     return 0;
  4203.   if (!strnotempty(fil))
  4204.     return 0;
  4205.   while(strnotempty(hts_ext_dynamic[j])) {
  4206.     if (strfield2(hts_ext_dynamic[j],fil)) {
  4207.       return 1;
  4208.     }
  4209.     j++;
  4210.   }
  4211.   return 0;
  4212. }
  4213.  
  4214. // types critiques qui ne doivent pas Ωtre changΘs car renvoyΘs par des serveurs qui ne
  4215. // connaissent pas le type
  4216. int may_unknown(httrackp *opt,const char* st) {
  4217.   int j=0;
  4218.   // types mΘdia
  4219.   if (may_be_hypertext_mime(opt,st, "")) {
  4220.     return 1;
  4221.   }
  4222.   while(strnotempty(hts_mime_keep[j])) {
  4223.     if (strfield2(hts_mime_keep[j],st)) {      // trouvΘ
  4224.       return 1;
  4225.     }
  4226.     j++;
  4227.   }    
  4228.   return 0;
  4229. }
  4230.  
  4231.  
  4232. // -- Utils fichiers
  4233.  
  4234. // pretty print for i/o
  4235. void fprintfio(FILE* fp,char* buff,char* prefix) {
  4236.   char nl=1;
  4237.   while(*buff) {
  4238.     switch(*buff) {
  4239.     case 13: break;
  4240.     case 10:
  4241.       fprintf(fp,"\r\n");
  4242.       nl=1;
  4243.     break;
  4244.     default:
  4245.       if (nl)
  4246.         fprintf(fp,prefix);
  4247.       nl=0;
  4248.       fputc(*buff,fp);
  4249.     }
  4250.     buff++;
  4251.   }
  4252. }
  4253.  
  4254. /* Le fichier existe-t-il? (ou est-il accessible?) */
  4255. int fexist(const char* s) {
  4256.     char catbuff[CATBUFF_SIZE];
  4257.   struct stat st;
  4258.   memset(&st, 0, sizeof(st));
  4259.   if (stat(fconv(catbuff,s), &st) == 0) {
  4260.     if (S_ISREG(st.st_mode)) {
  4261.       return 1;
  4262.     }
  4263.   }
  4264.   return 0;
  4265.  
  4266. /* Taille d'un fichier, -1 si n'existe pas */
  4267. /* fp->_cnt ne fonctionne pas sur toute les plate-formes :-(( */
  4268. /* Note: NOT YET READY FOR 64-bit */
  4269. off_t fsize(const char* s) {
  4270.     char catbuff[CATBUFF_SIZE];
  4271.     FILE* fp;
  4272.   if (strnotempty(s)==0)     // nom vide: erreur
  4273.     return -1;
  4274.   fp=fopen(fconv(catbuff,s),"rb");
  4275.   if (fp!=NULL) {
  4276.     off_t i;
  4277.     fseek(fp,0,SEEK_END);
  4278. #ifdef HTS_FSEEKO
  4279.     i=ftello(fp);
  4280. #else
  4281.     i=ftell(fp);
  4282. #endif
  4283.     fclose(fp);
  4284.     return i;
  4285.   } else
  4286.     return -1;
  4287. }
  4288.  
  4289. off_t fpsize(FILE* fp) {
  4290.   off_t oldpos,size;
  4291.   if (!fp)
  4292.     return -1;
  4293. #ifdef HTS_FSEEKO
  4294.   oldpos=ftello(fp);
  4295. #else
  4296.   oldpos=ftell(fp);
  4297. #endif
  4298.   fseek(fp,0,SEEK_END);
  4299. #ifdef HTS_FSEEKO
  4300.   size=ftello(fp);
  4301.   fseeko(fp,oldpos,SEEK_SET);
  4302. #else
  4303.   size=ftell(fp);
  4304.   fseek(fp,oldpos,SEEK_SET);
  4305. #endif
  4306.   return size;
  4307. }
  4308.  
  4309. /* root dir, with ending / */
  4310. typedef struct {
  4311.   char path[1024+4];
  4312.   int init;
  4313. } hts_rootdir_strc;
  4314. HTSEXT_API char* hts_rootdir(char* file) {
  4315.   static hts_rootdir_strc strc = {"", 0};
  4316.   if (file) {
  4317.     if (!strc.init) {
  4318.       strc.path[0]='\0';
  4319.       strc.init=1;
  4320.       if (strnotempty(file)) {
  4321.         char* a;
  4322.         strcpybuff(strc.path,file);
  4323.         while((a=strrchr(strc.path,'\\'))) *a='/';
  4324.         if ((a=strrchr(strc.path,'/'))) {
  4325.           *(a+1)='\0';
  4326.         } else
  4327.           strc.path[0]='\0';
  4328.       }
  4329.       if (!strnotempty(strc.path)) {
  4330.         if( getcwd( strc.path, 1024 ) == NULL )
  4331.             strc.path[0]='\0';
  4332.         else
  4333.           strcatbuff(strc.path,"/");
  4334.       }
  4335.     }
  4336.     return NULL;
  4337.   } else if (strc.init)
  4338.     return strc.path;
  4339.   else
  4340.     return "";
  4341. }
  4342.  
  4343.  
  4344.  
  4345. HTSEXT_API hts_stat_struct HTS_STAT;
  4346. //
  4347. // return  number of downloadable bytes, depending on rate limiter
  4348. // see engine_stats() routine, too
  4349. // this routine works quite well for big files and regular ones, but apparently the rate limiter has
  4350. // some problems with very small files (rate too high)
  4351. LLint check_downloadable_bytes(int rate) {
  4352.   if (rate>0) {
  4353.     TStamp time_now;
  4354.     TStamp elapsed_useconds;
  4355.     LLint bytes_transfered_during_period;
  4356.     LLint left;
  4357.  
  4358.     // get the older timer
  4359.     int id_timer = (HTS_STAT.istat_idlasttimer + 1) % 2;
  4360.  
  4361.     time_now=mtime_local();
  4362.     elapsed_useconds = time_now - HTS_STAT.istat_timestart[id_timer];
  4363.     // NO totally stupid - elapsed_useconds+=1000;      // for the next second, too
  4364.     bytes_transfered_during_period = (HTS_STAT.HTS_TOTAL_RECV-HTS_STAT.istat_bytes[id_timer]);
  4365.     
  4366.     left = ((rate * elapsed_useconds)/1000) - bytes_transfered_during_period;
  4367.     if (left <= 0)
  4368.       left = 0;
  4369.     
  4370.     return left;
  4371.   } else
  4372.     return TAILLE_BUFFER;
  4373. }
  4374.  
  4375. //
  4376. // 0 : OK
  4377. // 1 : slow down
  4378. #if 0
  4379. int HTS_TOTAL_RECV_CHECK(int var) {
  4380.   if (HTS_STAT.HTS_TOTAL_RECV_STATE)
  4381.     return 1;
  4382.     /*
  4383.     {
  4384.     if (HTS_STAT.HTS_TOTAL_RECV_STATE==3) { 
  4385.       var = min(var,32); 
  4386.       Sleep(250); 
  4387.     } else if (HTS_STAT.HTS_TOTAL_RECV_STATE==2) { 
  4388.       var = min(var,256); 
  4389.       Sleep(100); 
  4390.     } else { 
  4391.       var/=2; 
  4392.       if (var<=0) var=1; 
  4393.       Sleep(50); 
  4394.     } 
  4395.   }
  4396.     */
  4397.   return 0;
  4398. }
  4399. #endif
  4400.  
  4401. // Lecture dans buff de size octets au maximum en utilisant la socket r (structure htsblk)
  4402. // returns: 
  4403. // >0 : data received
  4404. // == 0 : not yet data
  4405. // <0: error or no data: READ_ERROR, READ_EOF or READ_TIMEOUT
  4406. HTS_INLINE int hts_read(htsblk* r,char* buff,int size) {
  4407.   int retour;
  4408.   //  return read(soc,buff,size);
  4409.   if (r->is_file) {
  4410. #if HTS_WIDE_DEBUG    
  4411.     DEBUG_W("read(%p, %d, %d)\n" _ (void*) buff _ (int) size _ (int) r->fp);
  4412. #endif
  4413.     if (r->fp)
  4414.       retour = (int)fread(buff,1,size,r->fp);
  4415.     else
  4416.       retour = READ_ERROR;
  4417.   } else {
  4418. #if HTS_WIDE_DEBUG    
  4419.     DEBUG_W("recv(%d, %p, %d)\n" _ (int) r->soc _ (void*) buff _ (int) size);
  4420.     if (r->soc==INVALID_SOCKET)
  4421.       printf("!!WIDE_DEBUG ERROR, soc==INVALID hts_read\n");
  4422. #endif
  4423.     //HTS_TOTAL_RECV_CHECK(size);         // Diminuer au besoin si trop de donnΘes reτues
  4424. #if HTS_USEOPENSSL
  4425.     if (SSL_is_available && r->ssl) {
  4426.       retour = SSL_read(r->ssl_con, buff, size);
  4427.       if (retour <= 0) {
  4428.         int err_code = SSL_get_error(r->ssl_con, retour);
  4429.         if (
  4430.           (err_code == SSL_ERROR_WANT_READ)
  4431.           ||
  4432.           (err_code == SSL_ERROR_WANT_WRITE)
  4433.           ) 
  4434.         {
  4435.           retour = 0;             /* no data yet (ssl cache) */
  4436.         } else if (err_code == SSL_ERROR_ZERO_RETURN) {
  4437.           retour = READ_EOF;             /* completed */
  4438.         } else {
  4439.           retour = READ_ERROR;            /* eof or error */
  4440.         }
  4441.       }
  4442.     } else {
  4443. #endif
  4444.     retour=recv(r->soc,buff,size,0);
  4445.     if (retour == 0) {
  4446.       retour = READ_EOF;
  4447.     } else if (retour < 0) {
  4448.       retour = READ_ERROR;
  4449.     }
  4450.   }
  4451.   if (retour > 0)    // compter flux entrant
  4452.     HTS_STAT.HTS_TOTAL_RECV+=retour;
  4453. #if HTS_USEOPENSSL
  4454.   }
  4455. #endif
  4456. #if HTS_WIDE_DEBUG    
  4457.   DEBUG_W("recv/read done (%d bytes)\n" _ (int) retour);
  4458. #endif
  4459.   return retour;
  4460. }
  4461.  
  4462.  
  4463. // -- Gestion cache DNS --
  4464. // 'RX98
  4465. #if HTS_DNSCACHE
  4466.  
  4467. // 'capsule' contenant uniquement le cache
  4468. t_dnscache* _hts_cache(httrackp *opt) {
  4469.     if (opt->state.dns_cache == NULL) {
  4470.         opt->state.dns_cache = (t_dnscache*)malloct(sizeof(t_dnscache));
  4471.         memset(opt->state.dns_cache, 0, sizeof(t_dnscache));
  4472.     }
  4473.   return opt->state.dns_cache;
  4474. }
  4475. // free the cache
  4476. static void hts_cache_free_(t_dnscache* cache) {
  4477.   if (cache != NULL) {
  4478.     if (cache->n != NULL) {
  4479.       hts_cache_free_(cache->n);
  4480.     }
  4481.     freet(cache);
  4482.   }
  4483. }
  4484. void hts_cache_free(t_dnscache* cache) {
  4485.     if (cache != NULL && cache->n != NULL) {
  4486.         hts_cache_free_(cache->n);
  4487.         cache->n = NULL;
  4488.     }
  4489. }
  4490.  
  4491. // lock le cache dns pour tout opΘration d'ajout
  4492. // plus prudent quand plusieurs threads peuvent Θcrire dedans..
  4493. // -1: status? 0: libΘrer 1:locker
  4494.  
  4495. /* 
  4496.   Simple lock for cache
  4497. */
  4498. htsmutex dns_lock = HTSMUTEX_INIT;
  4499.  
  4500. // routine pour le cache - retour optionnel α donner α chaque fois
  4501. // NULL: nom non encore testΘ dans le cache
  4502. // si h_length==0 alors le nom n'existe pas dans le dns
  4503. t_hostent* _hts_ghbn(t_dnscache* cache,const char* iadr,t_hostent* retour) {
  4504.   t_hostent* ret = NULL;
  4505.   hts_mutexlock(&dns_lock);
  4506.   for(;;) {
  4507.     if (strcmp(cache->iadr,iadr) == 0) {  // ok trouvΘ
  4508.       if (cache->host_length > 0) {  // entrΘe valide
  4509.         if (retour->h_addr_list[0])
  4510.           memcpy(retour->h_addr_list[0], cache->host_addr, cache->host_length);
  4511.         retour->h_length=cache->host_length;
  4512.       } else if (cache->host_length == 0) {  // en cours
  4513.         ret = NULL;
  4514.         break;
  4515.       } else {                    // erreur dans le dns, dΘja vΘrifiΘ
  4516.         if (retour->h_addr_list[0])
  4517.           retour->h_addr_list[0][0]='\0';
  4518.         retour->h_length=0;  // erreur, n'existe pas
  4519.       }
  4520.       ret = retour;
  4521.       break;
  4522.     } else {    // on a pas encore trouvΘ
  4523.       if (cache->n!=NULL) { // chercher encore
  4524.         cache = cache->n;   // suivant!
  4525.       } else {
  4526.         ret = NULL;
  4527.         break;
  4528.       }
  4529.     }    
  4530.   }
  4531.   hts_mutexrelease(&dns_lock);
  4532.   return ret;
  4533. }
  4534.  
  4535. // tester si iadr a dΘja ΘtΘ testΘ (ou en cours de test)
  4536. // 0 non encore
  4537. // 1 ok
  4538. // 2 non prΘsent
  4539. int hts_dnstest(httrackp *opt, const char* _iadr) {
  4540.   int ret = 0;
  4541.   t_dnscache* cache=_hts_cache(opt);  // adresse du cache 
  4542.     char iadr[HTS_URLMAXSIZE*2];
  4543.  
  4544.   // sauter user:pass@ Θventuel
  4545.   strcpybuff(iadr, jump_identification(_iadr));
  4546.   // couper Θventuel :
  4547.   {
  4548.     char *a;
  4549.     if ( (a = jump_toport(iadr)) )
  4550.       *a='\0';
  4551.   }
  4552.  
  4553. #ifdef _WIN32
  4554.   if (inet_addr(iadr)!=INADDR_NONE)  // numΘrique
  4555. #else
  4556.   if (inet_addr(iadr)!=(in_addr_t) -1 )  // numΘrique
  4557. #endif
  4558.     return 1;
  4559.  
  4560.   hts_mutexlock(&dns_lock);
  4561.   for(;;) {
  4562.     if (strcmp(cache->iadr, iadr)==0) {  // ok trouvΘ
  4563.       ret = 1;
  4564.       break;
  4565.     } else {    // on a pas encore trouvΘ
  4566.       if (cache->n!=NULL) { // chercher encore
  4567.         cache=cache->n;   // suivant!
  4568.       } else {
  4569.         ret = 2;    // non prΘsent        
  4570.         break ;
  4571.       }
  4572.     }    
  4573.   }
  4574.   hts_mutexrelease(&dns_lock);
  4575.   return ret;
  4576. }
  4577.  
  4578.  
  4579. HTSEXT_API t_hostent* vxgethostbyname(char* hostname, void* v_buffer) {
  4580.   t_fullhostent* buffer = (t_fullhostent*) v_buffer;
  4581.   /* Clear */
  4582.   fullhostent_init(buffer);
  4583.  
  4584.   /* Protection */
  4585.   if (!strnotempty(hostname)) {
  4586.     return NULL;
  4587.   }
  4588.  
  4589.   /* 
  4590.     Strip [] if any : [3ffe:b80:1234:1::1] 
  4591.     The resolver doesn't seem to handle IP6 addresses in brackets
  4592.   */
  4593.   if ((hostname[0] == '[') && (hostname[strlen(hostname)-1] == ']')) {
  4594.     char BIGSTK tempo[HTS_URLMAXSIZE*2];
  4595.     tempo[0]='\0';
  4596.     strncatbuff(tempo, hostname+1, strlen(hostname)-2);
  4597.     strcpybuff(hostname, tempo);
  4598.   }
  4599.  
  4600.   {
  4601. #if HTS_INET6==0
  4602.   /*
  4603.   ipV4 resolver
  4604.     */
  4605.     t_hostent* hp=gethostbyname(hostname);
  4606.     if (hp!=NULL) {
  4607.       if ( (hp->h_length) && ( ((unsigned int) hp->h_length) <= buffer->addr_maxlen) ) {
  4608.         memcpy(buffer->hp.h_addr_list[0], hp->h_addr_list[0], hp->h_length);
  4609.         buffer->hp.h_length = hp->h_length;
  4610.         return &(buffer->hp);
  4611.       }
  4612.     }
  4613. #else
  4614.     /*
  4615.     ipV6 resolver
  4616.     */
  4617.     /*
  4618.     int error_num=0;
  4619.     t_hostent* hp=getipnodebyname(hostname, AF_INET6, AI_DEFAULT, &error_num);
  4620.     oops, deprecated :(
  4621.     */
  4622.     struct addrinfo* res = NULL;
  4623.     struct addrinfo hints;
  4624.     memset(&hints, 0, sizeof(hints));
  4625.     if (IPV6_resolver == 1)        // V4 only (for bogus V6 entries)
  4626.       hints.ai_family = PF_INET;
  4627.     else if (IPV6_resolver == 2)   // V6 only (for testing V6 only)
  4628.       hints.ai_family = PF_INET6;
  4629.     else                           // V4 + V6
  4630.       hints.ai_family = PF_UNSPEC;
  4631.     hints.ai_socktype = SOCK_STREAM;
  4632.     hints.ai_protocol = IPPROTO_TCP;
  4633.     if (getaddrinfo(hostname, NULL, &hints, &res) == 0) {
  4634.       if (res) {
  4635.         if ( (res->ai_addr) && (res->ai_addrlen) && (res->ai_addrlen <= buffer->addr_maxlen) ) {
  4636.           memcpy(buffer->hp.h_addr_list[0], res->ai_addr, res->ai_addrlen);
  4637.           buffer->hp.h_length = (short) res->ai_addrlen;
  4638.           freeaddrinfo(res);
  4639.           return &(buffer->hp);
  4640.         }
  4641.       }
  4642.     }
  4643.     if (res) {
  4644.       freeaddrinfo(res);
  4645.     }
  4646.     
  4647. #endif
  4648.   }
  4649.   return NULL;
  4650. }
  4651.  
  4652. // cache dns interne α HTS // ** FREE A FAIRE sur la chaine
  4653. t_hostent* hts_gethostbyname(httrackp *opt,const char* _iadr, void* v_buffer) {
  4654.   char BIGSTK iadr[HTS_URLMAXSIZE*2];
  4655.   t_fullhostent* buffer = (t_fullhostent*) v_buffer;
  4656.   t_dnscache* cache=_hts_cache(opt);  // adresse du cache
  4657.   t_hostent* hp;
  4658.  
  4659.   /* Clear */
  4660.   fullhostent_init(buffer);
  4661.  
  4662.   strcpybuff(iadr,jump_identification(_iadr));
  4663.   // couper Θventuel :
  4664.   {
  4665.     char *a;
  4666.     if ( (a=jump_toport(iadr)) )
  4667.       *a='\0';
  4668.   }
  4669.  
  4670.   // effacer structure de retour, crΘer nouvelle
  4671.   /*
  4672.   memset(&host, 0, sizeof(t_hostent));  
  4673.   host.h_addr_list=he;
  4674.   he[0]=NULL;
  4675.   he[1]=NULL;  
  4676.   host.h_length=0;  
  4677.   */
  4678.   cache->iadr[0]='*';
  4679.   cache->iadr[1]='\0';
  4680.   
  4681.   /* get IP from the dns cache */
  4682.   hp = _hts_ghbn(cache, iadr, &buffer->hp);
  4683.   if (hp) {
  4684.     if (hp->h_length>0)
  4685.       return hp;
  4686.     else
  4687.       return NULL;    // entrΘe erronΘe (erreur DNS) dans le DNS
  4688.   } else {  // non prΘsent dans le cache dns, tester
  4689.     t_dnscache* c=cache;
  4690.     while(c->n) c=c->n;    // calculer queue
  4691.     
  4692. #if HTS_WIDE_DEBUG    
  4693.     DEBUG_W("gethostbyname\n");
  4694. #endif      
  4695. #if HDEBUG
  4696.     printf("gethostbyname (not in cache)\n");
  4697. #endif
  4698.     {
  4699.       unsigned long inetaddr;
  4700. #ifdef _WIN32
  4701.       if ((inetaddr=inet_addr(iadr))==INADDR_NONE) {
  4702. #else
  4703.       if ((inetaddr=inet_addr(iadr))==(in_addr_t) -1 ) {
  4704. #endif        
  4705. #if DEBUGDNS 
  4706.         printf("resolving (not cached) %s\n",iadr);
  4707. #endif
  4708.         hp=vxgethostbyname(iadr, buffer);  // calculer IP host
  4709.       } else {     // numΘrique, convertir sans passer par le dns
  4710.         buffer->hp.h_addr_list[0]=(char*) &inetaddr;
  4711.         buffer->hp.h_length=4;
  4712.         hp=&buffer->hp;
  4713.       }
  4714.     }
  4715. #if HTS_WIDE_DEBUG    
  4716.     DEBUG_W("gethostbyname done\n");
  4717. #endif
  4718.     cache->n=(t_dnscache*) calloct(1,sizeof(t_dnscache));
  4719.     if (cache->n!=NULL) {
  4720.       strcpybuff(cache->n->iadr,iadr);
  4721.       if (hp!=NULL) {
  4722.         memcpy(cache->n->host_addr, hp->h_addr_list[0], hp->h_length);
  4723.         cache->n->host_length=hp->h_length;
  4724.       } else {
  4725.         cache->n->host_addr[0]='\0';
  4726.         cache->n->host_length=0;  // non existant dans le dns
  4727.       }
  4728.       cache->n->n=NULL;
  4729.       return hp;
  4730.     } else {  // on peut pas noter, mais on peut renvoyer le rΘsultat
  4731.       return hp;
  4732.     }        
  4733.   }  // retour hp du cache
  4734. }
  4735.  
  4736. #else
  4737. HTS_INLINE t_hostent* hts_gethostbyname(httrackp *opt,char* iadr, t_fullhostent* buffer) {
  4738.   t_hostent* retour;
  4739. #if HTS_WIDE_DEBUG    
  4740.   DEBUG_W("gethostbyname (2)\n");
  4741. #endif
  4742. #if DEBUGDNS 
  4743.     printf("blocking method gethostbyname() in progress for %s\n",iadr);
  4744. #endif
  4745.   retour=vxgethostbyname(jump_identification(iadr), );
  4746. #if HTS_WIDE_DEBUG    
  4747.   DEBUG_W("gethostbyname (2) done\n");
  4748. #endif
  4749.   return retour;
  4750. }
  4751. #endif
  4752.  
  4753.  
  4754. // --- Tracage des mallocs() ---
  4755. #ifdef HTS_TRACE_MALLOC
  4756. //#define htsLocker(A, N) htsLocker(A, N)
  4757. #define htsLocker(A, N) do {} while(0)
  4758. static mlink trmalloc = {NULL,0,0,NULL};
  4759. static int trmalloc_id=0;
  4760. static htsmutex* mallocMutex = NULL;
  4761. static void hts_meminit(void) {
  4762.   //if (mallocMutex == NULL) {
  4763.   //  mallocMutex = calloc(sizeof(*mallocMutex), 1);
  4764.   //  htsLocker(mallocMutex, -999);
  4765.   //}
  4766. }
  4767. void* hts_malloc(size_t len) {
  4768.   void* adr;
  4769.   hts_meminit();
  4770.   htsLocker(mallocMutex, 1);
  4771.   fassert(len > 0);
  4772.   adr = hts_xmalloc(len, 0);
  4773.   htsLocker(mallocMutex, 0);
  4774.   return adr;
  4775. }
  4776. void* hts_calloc(size_t len,size_t len2) {
  4777.   void* adr;
  4778.   hts_meminit();
  4779.   fassert(len > 0);
  4780.   fassert(len2 > 0);
  4781.   htsLocker(mallocMutex, 1);
  4782.   adr = hts_xmalloc(len, len2);
  4783.   htsLocker(mallocMutex, 0);
  4784.   memset(adr, 0, len * len2);
  4785.   return adr;
  4786. }
  4787. void* hts_strdup(char* str) {
  4788.   size_t size = str ? strlen(str) : 0;
  4789.   char* adr = (char*) hts_malloc(size + 1);
  4790.   fassert(adr != NULL);
  4791.   strcpy(adr, str ? str : "");
  4792.   return adr;
  4793. }
  4794. void* hts_xmalloc(size_t len,size_t len2) {
  4795.   mlink* lnk = (mlink*) calloc(1,sizeof(mlink));
  4796.   fassert(lnk != NULL);
  4797.   fassert(len > 0);
  4798.   fassert(len2 >= 0);
  4799.   if (lnk) {
  4800.     void*  r   = NULL;
  4801.     int size, bsize = sizeof(t_htsboundary);
  4802.     if (len2)
  4803.       size = len * len2;
  4804.     else
  4805.       size = len;
  4806.     size += ((bsize - (size % bsize)) % bsize);  /* check alignement */
  4807.     r = malloc(size + bsize*2);
  4808.     fassert(r != NULL);
  4809.     if (r) {
  4810.       * ( (t_htsboundary*) ((char*) r ) ) 
  4811.         = * ( (t_htsboundary*) ( (char*) r + size + bsize ) )
  4812.         = htsboundary;
  4813.       ((char*) r) += bsize;    /* boundary */
  4814.       lnk->adr = r;
  4815.       lnk->len = size;
  4816.       lnk->id = trmalloc_id++;
  4817.       lnk->next = trmalloc.next;
  4818.       trmalloc.next = lnk;
  4819.       return r;
  4820.     } else {
  4821.       free(lnk);
  4822.     }
  4823.   }
  4824.   return NULL;
  4825. }
  4826. void hts_free(void* adr) {
  4827.   mlink* lnk = &trmalloc;
  4828.   int bsize = sizeof(t_htsboundary);
  4829.   fassert(adr != NULL);
  4830.   if (!adr) {
  4831.     return;
  4832.   }
  4833.   htsLocker(mallocMutex, 1);
  4834.   while(lnk->next != NULL) {
  4835.     if (lnk->next->adr == adr) {
  4836.       mlink* blk_free=lnk->next;
  4837.       fassert(blk_free->id != -1);
  4838.       fassert( * ( (t_htsboundary*) ( (char*) adr - bsize ) ) == htsboundary );
  4839.       fassert( * ( (t_htsboundary*) ( (char*) adr + blk_free->len ) ) == htsboundary );
  4840.       lnk->next=lnk->next->next;
  4841.       free((void*) blk_free);
  4842.       //blk_free->id=-1;
  4843.       free((char*) adr - bsize);
  4844.       htsLocker(mallocMutex, 0);
  4845.       return;
  4846.     }
  4847.     lnk = lnk->next;
  4848.     fassert(lnk->next != NULL);
  4849.   }
  4850.   free(adr);
  4851.   htsLocker(mallocMutex, 0);
  4852. }
  4853. void* hts_realloc(void* adr,size_t len) {
  4854.   int bsize = sizeof(t_htsboundary);
  4855.   len += ((bsize - (len % bsize)) % bsize);  /* check alignement */
  4856.   if (adr != NULL) {
  4857.     mlink* lnk = &trmalloc;
  4858.     htsLocker(mallocMutex, 1);
  4859.     while(lnk->next != NULL)  {
  4860.       if (lnk->next->adr==adr) {
  4861.         {
  4862.           mlink* blk_free=lnk->next;
  4863.           fassert(blk_free->id != -1);
  4864.           fassert( * ( (t_htsboundary*) ( (char*) adr - bsize ) ) == htsboundary );
  4865.           fassert( * ( (t_htsboundary*) ( (char*) adr + blk_free->len ) ) == htsboundary );
  4866.         }
  4867.         adr = realloc((char*) adr - bsize, len + bsize * 2);
  4868.         fassert(adr != NULL);
  4869.         lnk->next->adr = (char*) adr + bsize;
  4870.         lnk->next->len = len;
  4871.         * ( (t_htsboundary*) ( (char*) adr ) ) 
  4872.           = * ( (t_htsboundary*) ( (char*) adr + len + bsize) ) 
  4873.           = htsboundary;
  4874.         htsLocker(mallocMutex, 0);
  4875.         return (char*) adr + bsize;
  4876.       }
  4877.       lnk = lnk->next;
  4878.       fassert(lnk->next != NULL);
  4879.     }
  4880.     htsLocker(mallocMutex, 0);
  4881.   }
  4882.   return hts_malloc(len);
  4883. }
  4884. mlink* hts_find(char* adr) {
  4885.   char* stkframe = (char*) &stkframe;
  4886.   mlink* lnk = &trmalloc;
  4887.   int bsize = sizeof(t_htsboundary);
  4888.   fassert(adr != NULL);
  4889.   if (!adr) {
  4890.     return NULL;
  4891.   }
  4892.   htsLocker(mallocMutex, 1);
  4893.   while(lnk->next != NULL) {
  4894.     if (adr >= lnk->next->adr && adr <= lnk->next->adr + lnk->next->len) {   /* found */
  4895.       htsLocker(mallocMutex, 0);
  4896.       return lnk->next;
  4897.     }
  4898.     lnk = lnk->next;
  4899.   }
  4900.   htsLocker(mallocMutex, 0);
  4901.   {
  4902.     int depl = (int) (adr - stkframe);
  4903.     if (depl < 0) depl = -depl;
  4904.     //fassert(depl < 512000);   /* near the stack frame.. doesn't look like malloc but stack variable */
  4905.     return NULL;
  4906.   }
  4907. }
  4908. // check the malloct() and calloct() trace stack
  4909. void  hts_freeall(void) {
  4910.   int bsize = sizeof(t_htsboundary);
  4911.   while(trmalloc.next) {
  4912. #if MEMDEBUG
  4913.     printf("* block %d\t not released: at %d\t (%d\t bytes)\n",trmalloc.next->id,trmalloc.next->adr,trmalloc.next->len);
  4914. #endif
  4915.     if (trmalloc.next->id != -1) {
  4916.       free((char*) trmalloc.next->adr - bsize);
  4917.     }
  4918.   }
  4919. }
  4920. #endif
  4921.  
  4922.  
  4923. // -- divers //
  4924.  
  4925. // cut path and project name
  4926. // patch also initial path
  4927. void cut_path(char* fullpath,char* path,char* pname) {
  4928.   path[0]=pname[0]='\0';
  4929.   if (strnotempty(fullpath)) {
  4930.     if ((fullpath[strlen(fullpath)-1]=='/') || (fullpath[strlen(fullpath)-1]=='\\'))
  4931.       fullpath[strlen(fullpath)-1]='\0';
  4932.     if (strlen(fullpath)>1) {
  4933.       char* a;
  4934.       while( (a=strchr(fullpath,'\\')) ) *a='/';     // remplacer par /
  4935.       a=fullpath+strlen(fullpath)-2;
  4936.       while( (*a!='/') && ( a > fullpath)) a--;
  4937.       if (*a=='/') a++;
  4938.       strcpybuff(pname,a);
  4939.       strncatbuff(path,fullpath,(int) (a - fullpath));
  4940.     }
  4941.   }
  4942. }
  4943.  
  4944.  
  4945.  
  4946. // -- Gestion protocole ftp --
  4947.  
  4948. #ifdef _WIN32
  4949. int ftp_available(void) {
  4950.   return 1;
  4951. }
  4952. #else
  4953. int ftp_available(void) {
  4954.   return 1;   // ok!
  4955.   //return 0;   // SOUS UNIX, PROBLEMESs
  4956. }
  4957. #endif
  4958.  
  4959.  
  4960. int hts_dgb_init = 0;
  4961. FILE* hts_dgb_init_fp = NULL;
  4962. HTSEXT_API void hts_debug(int level) {
  4963.   hts_dgb_init = level;
  4964.   if (hts_dgb_init > 0) {
  4965.     HTS_DBG("hts_debug() called");
  4966.   }
  4967. }
  4968.  
  4969. FILE *hts_dgb_(void) {
  4970.   if (hts_dgb_init_fp == NULL) {
  4971.     if ((hts_dgb_init & 0x80) == 0) {
  4972.       hts_dgb_init_fp = stderr;
  4973.     } else {
  4974. #ifdef _WIN32_WCE
  4975.       hts_dgb_init_fp = fopen("\\Temp\\hts-debug.txt", "wb");
  4976. #else
  4977.       hts_dgb_init_fp = fopen("hts-debug.txt", "wb");
  4978. #endif
  4979.       if (hts_dgb_init_fp != NULL) {
  4980.         fprintf(hts_dgb_init_fp, "* Creating file\r\n");
  4981.       }
  4982.     }
  4983.   }
  4984.   return hts_dgb_init_fp;
  4985. }
  4986.  
  4987. static int hts_init_ok = 0;
  4988. HTSEXT_API int hts_init(void) {
  4989.   const char *dbg_env;
  4990.   /* */
  4991.   if (hts_init_ok)
  4992.     return 1;
  4993.   hts_init_ok = 1;
  4994.  
  4995.   /* enable debugging ? */
  4996.   dbg_env = getenv("HTS_LOG");
  4997.   if (dbg_env != NULL && *dbg_env != 0) {
  4998.     int level = 0;
  4999.     if (sscanf(dbg_env, "%d", &level) == 1) {
  5000.       hts_debug(level);
  5001.     }
  5002.   }
  5003.  
  5004.   HTS_DBG("entering hts_init()");    /* debug */
  5005.  
  5006. #ifdef _WIN32_WCE
  5007. #ifndef HTS_CECOMPAT
  5008.   xceinit(L"");
  5009. #endif
  5010. #endif
  5011.  
  5012.   /* Init threads (lazy init) */
  5013.   htsthread_init();
  5014.  
  5015.   /* Ensure external modules are loaded */
  5016.   HTS_DBG("calling htspe_init()");    /* debug */
  5017.   htspe_init();  /* module load (lazy) */
  5018.  
  5019.   /* MD5 Auto-test */
  5020.   {
  5021.     char digest[32 + 2];
  5022.     const unsigned char* atest = (const unsigned char*)"MD5 Checksum Autotest";
  5023.     digest[0] = '\0';
  5024.     domd5mem(atest, strlen(atest), digest, 1); /* a42ec44369da07ace5ec1d660ba4a69a */
  5025.     if (strcmp(digest, "a42ec44369da07ace5ec1d660ba4a69a") != 0) {
  5026.       int fatal_broken_md5 = 0;
  5027.       assertf(fatal_broken_md5);
  5028.     }
  5029.   }
  5030.  
  5031.   HTS_DBG("initializing SSL");    /* debug */
  5032. #if HTS_USEOPENSSL
  5033.   /*
  5034.   Initialize the OpensSSL library
  5035.   */
  5036.   if (!openssl_ctx && SSL_is_available) {
  5037.     if (SSL_load_error_strings) SSL_load_error_strings();
  5038.     SSL_library_init();
  5039.     ///if (SSL_load_error_strings)  SSL_load_error_strings();
  5040.     //if (ERR_load_crypto_strings) ERR_load_crypto_strings();
  5041.     // if (ERR_load_SSL_strings)    ERR_load_SSL_strings(); ???!!!
  5042.     // OpenSSL_add_all_algorithms();
  5043.     openssl_ctx = SSL_CTX_new(SSLv23_client_method());
  5044.     if (!openssl_ctx) {
  5045.       fprintf(stderr, "fatal: unable to initialize TLS: SSL_CTX_new(SSLv23_client_method)\n");
  5046.       abortLog("unable to initialize TLS: SSL_CTX_new(SSLv23_client_method)");
  5047.       assertf("unable to initialize TLS" == NULL);
  5048.     }
  5049.   }
  5050. #endif
  5051.   
  5052.   HTS_DBG("ending hts_init()");    /* debug */
  5053.   return 1;
  5054. }
  5055.  
  5056. /* will not free thread env. */
  5057. HTSEXT_API int hts_uninit(void) {
  5058.   /* hts_init() is a lazy initializer, with limited a allocation (one or two mutexes) ;
  5059.   we won't free anything here as the .h semantic was never being very clear */
  5060.   return 1;
  5061. }
  5062.  
  5063. HTSEXT_API int hts_uninit_module(void) {
  5064.   if (!hts_init_ok)
  5065.     return 1;
  5066.   htsthread_uninit();
  5067.   htspe_uninit();
  5068.   hts_init_ok = 0;
  5069.   return 1;
  5070. }
  5071.  
  5072. HTSEXT_API int hts_log(httrackp *opt, const char* prefix, const char *msg) {
  5073.   if (opt->log != NULL) {
  5074.     fspc(opt, opt->log, prefix);
  5075.     fprintf(opt->log, "%s"LF, msg);
  5076.     return 0;
  5077.   }
  5078.   return 1;   /* Error */
  5079. }
  5080.  
  5081. HTSEXT_API void set_wrappers(httrackp *opt) {        // LEGACY
  5082. }
  5083.  
  5084. HTSEXT_API int plug_wrapper(httrackp *opt, const char *moduleName, const char* argv) {
  5085.   void* handle = openFunctionLib(moduleName);
  5086.   if (handle != NULL) {
  5087.     t_hts_plug plug = (t_hts_plug) getFunctionPtr(handle, "hts_plug");
  5088.     t_hts_unplug unplug = (t_hts_unplug) getFunctionPtr(handle, "hts_unplug");
  5089.     if (plug != NULL) {
  5090.       int ret = plug(opt, argv);
  5091.       if (hts_dgb_init > 0 && opt->log != NULL) {
  5092.         HTS_DBG("plugged module '%s' (return code=%d)" _ moduleName _ ret);
  5093.       }
  5094.       if (ret == 1) {   /* Success! */
  5095.         opt->libHandles.handles = (htslibhandle*) realloct(opt->libHandles.handles, ( opt->libHandles.count + 1 )*sizeof(htslibhandle));
  5096.         opt->libHandles.handles[opt->libHandles.count].handle = handle;
  5097.         opt->libHandles.handles[opt->libHandles.count].moduleName = strdupt(moduleName);
  5098.         opt->libHandles.count++;
  5099.         return 1;
  5100.       } else {
  5101.         HTS_DBG("* note: error while running entry point 'hts_plug' in %s"LF _ moduleName);
  5102.         if (unplug)
  5103.           unplug(opt);
  5104.       }
  5105.     } else {
  5106.       int last_errno = errno;
  5107.       HTS_DBG("* note: can't find entry point 'hts_plug' in %s: %s"LF _ moduleName _ strerror(last_errno));
  5108.     }
  5109.     closeFunctionLib(handle);
  5110.     return 0;
  5111.   } else {
  5112.     int last_errno = errno;
  5113.     HTS_DBG("* note: can't load %s: %s"LF _ moduleName _ strerror(last_errno));
  5114.   }
  5115.   return -1;
  5116. }
  5117.  
  5118. static void unplug_wrappers(httrackp *opt) {
  5119.   if (opt->libHandles.handles != NULL) {
  5120.     int i;
  5121.     for(i = 0 ; i < opt->libHandles.count ; i++) {
  5122.       if (opt->libHandles.handles[i].handle != NULL) {
  5123.         /* hts_unplug(), the dll exit point (finalizer) */
  5124.         t_hts_unplug unplug = (t_hts_unplug) getFunctionPtr(opt->libHandles.handles[i].handle, "hts_unplug");
  5125.         if (unplug != NULL)
  5126.           unplug(opt);
  5127.         closeFunctionLib(opt->libHandles.handles[i].handle);
  5128.         opt->libHandles.handles[i].handle = NULL;
  5129.       }
  5130.       if (opt->libHandles.handles[i].moduleName != NULL) {
  5131.         freet(opt->libHandles.handles[i].moduleName);
  5132.         opt->libHandles.handles[i].moduleName = NULL;
  5133.       }
  5134.     }
  5135.     freet(opt->libHandles.handles);
  5136.     opt->libHandles.handles = NULL;
  5137.     opt->libHandles.count = 0;
  5138.   }
  5139. }
  5140.  
  5141. int multipleStringMatch(const char *s, const char *match) {
  5142.   int ret = 0;
  5143.   String name = STRING_EMPTY;
  5144.   if (match  == NULL || s == NULL || *s == 0)
  5145.     return 0;
  5146.   for( ; *match != 0 ; match++) {
  5147.     StringClear(name);
  5148.     for( ; *match != 0 && *match != '\n' ; match++) {
  5149.       StringAddchar(name, *match);
  5150.     }
  5151.     if (StringLength(name) > 0 && strstr(s, StringBuff(name)) != NULL) {
  5152.       ret = 1;
  5153.       break ;
  5154.     }
  5155.   }
  5156.   StringFree(name);
  5157.   return ret;
  5158. }
  5159.  
  5160. HTSEXT_API httrackp *hts_create_opt(void) {
  5161. #ifdef _WIN32
  5162.   static const char *defaultModules[] = { 
  5163.     "htsswf", "htsjava", "httrack-plugin", NULL 
  5164.   };
  5165. #else
  5166.   static const char *defaultModules[] = { 
  5167.     "libhtsswf.so.1", "libhtsjava.so.2", "httrack-plugin", NULL 
  5168.   };
  5169. #endif
  5170.   httrackp *opt = malloc(sizeof(httrackp));
  5171.  
  5172.   /* default options */
  5173.   memset(opt, 0, sizeof(httrackp));
  5174.   opt->size_httrackp = sizeof(httrackp);
  5175.  
  5176.   /* mutexes */
  5177.   hts_mutexinit(&opt->state.lock);
  5178.  
  5179.     /* custom wrappers */
  5180.   opt->libHandles.count = 0;
  5181.  
  5182.     /* default settings */
  5183.  
  5184.     opt->wizard=2;   // wizard automatique
  5185.   opt->quiet=0;     // questions
  5186.   //  
  5187.   opt->travel=0;   // mΩme adresse
  5188.   opt->depth=9999; // mirror total par dΘfaut
  5189.   opt->extdepth=0; // mais pas α l'extΘrieur
  5190.   opt->seeker=1;   // down 
  5191.   opt->urlmode=2;  // relatif par dΘfaut
  5192.   opt->debug=0;    // pas de dΘbug en plus
  5193.   opt->getmode=3;  // linear scan
  5194.   opt->maxsite=-1; // taille max site (aucune)
  5195.   opt->maxfile_nonhtml=-1; // taille max fichier non html
  5196.   opt->maxfile_html=-1;    // idem pour html
  5197.   opt->maxsoc=4;     // nbre socket max
  5198.   opt->fragment=-1;  // pas de fragmentation
  5199.   opt->nearlink=0;   // ne pas prendre les liens non-html "adjacents"
  5200.   opt->makeindex=1;  // faire un index
  5201.   opt->kindex=0;     // index 'keyword'
  5202.   opt->delete_old=1; // effacer anciens fichiers
  5203.   opt->makestat=0;  // pas de fichier de stats
  5204.   opt->maketrack=0; // ni de tracking
  5205.   opt->timeout=120; // timeout par dΘfaut (2 minutes)
  5206.   opt->cache=1;     // cache prioritaire
  5207.   opt->shell=0;     // pas de shell par defaut
  5208.   opt->proxy.active=0;    // pas de proxy
  5209.   opt->user_agent_send=1; // envoyer un user-agent
  5210.   StringCopy(opt->user_agent, "Mozilla/4.5 (compatible; HTTrack 3.0x; Windows 98)");
  5211.   StringCopy(opt->referer, "");
  5212.   StringCopy(opt->from, "");
  5213.   opt->savename_83=0;     // noms longs par dΘfaut
  5214.   opt->savename_type=0;   // avec structure originale
  5215.   opt->savename_delayed=2;// hard delayed type (default)
  5216.   opt->delayed_cached=1;  // cached delayed type (default)
  5217.   opt->mimehtml=0;        // pas MIME-html
  5218.   opt->parsejava=HTSPARSE_DEFAULT; // parser classes
  5219.   opt->hostcontrol=0;     // PAS de control host pour timeout et traffic jammer
  5220.   opt->retry=2;           // 2 retry par dΘfaut
  5221.   opt->errpage=1;         // copier ou gΘnΘrer une page d'erreur en cas d'erreur (404 etc.)
  5222.   opt->check_type=1;      // vΘrifier type si inconnu (cgi,asp..) SAUF / considΘrΘ comme html
  5223.   opt->all_in_cache=0;    // ne pas tout stocker en cache
  5224.   opt->robots=2;          // traiter les robots.txt
  5225.   opt->external=0;        // liens externes normaux
  5226.   opt->passprivacy=0;     // mots de passe dans les fichiers
  5227.   opt->includequery=1;    // include query-string par dΘfaut
  5228.   opt->mirror_first_page=0;  // pas mode mirror links
  5229.   opt->accept_cookie=1;   // gΘrer les cookies
  5230.   opt->cookie=NULL;
  5231.   opt->http10=0;          // laisser http/1.1
  5232.   opt->nokeepalive = 0;   // pas keep-alive
  5233.   opt->nocompression=0;   // pas de compression
  5234.   opt->tolerant=0;        // ne pas accepter content-length incorrect
  5235.   opt->parseall=1;        // tout parser (tags inconnus, par exemple)
  5236.   opt->parsedebug=0;      // pas de mode dΘbuggage
  5237.   opt->norecatch=0;       // ne pas reprendre les fichiers effacΘs par l'utilisateur
  5238.   opt->verbosedisplay=0;  // pas d'animation texte
  5239.   opt->sizehack=0;        // size hack
  5240.   opt->urlhack=1;         // url hack (normalizer)
  5241.   StringCopy(opt->footer,HTS_DEFAULT_FOOTER);
  5242.   opt->ftp_proxy=1;       // proxy http pour ftp
  5243.   StringCopy(opt->filelist,"");
  5244.   StringCopy(opt->lang_iso,"en, *");
  5245.   StringCopy(opt->mimedefs,"\n"); // aucun filtre mime (\n IMPORTANT)
  5246.   StringClear(opt->mod_blacklist);
  5247.   //
  5248.   opt->log = stdout;
  5249.   opt->errlog = stderr;
  5250.   opt->flush = 1;         // flush sur les fichiers log
  5251.   //opt->aff_progress=0;
  5252.   opt->keyboard=0;
  5253.   //
  5254.   StringCopy(opt->path_html,"");
  5255.   StringCopy(opt->path_log,"");
  5256.   StringCopy(opt->path_bin,"");
  5257.   //
  5258. #if HTS_SPARE_MEMORY==0
  5259.   opt->maxlink=100000;    // 100,000 liens max par dΘfaut (400Kb)
  5260.   opt->maxfilter=200;     // 200 filtres max par dΘfaut
  5261. #else
  5262.   opt->maxlink=10000;     // 10,000 liens max par dΘfaut (40Kb)
  5263.   opt->maxfilter=50;      // 50 filtres max par dΘfaut
  5264. #endif
  5265.   opt->maxcache=1048576*32;  // a peu prΦs 32Mo en cache max -- OPTION NON PARAMETRABLE POUR L'INSTANT --
  5266.   //opt->maxcache_anticipate=256;  // maximum de liens α anticiper
  5267.   opt->maxtime=-1;        // temps max en secondes
  5268. #if HTS_USEMMS
  5269.     opt->mms_maxtime = 60*3600;        // max time for mms streams (one hour)
  5270. #endif
  5271.   opt->maxrate=25000;     // taux maxi
  5272.   opt->maxconn=5.0;       // nombre connexions/s
  5273.   opt->waittime=-1;       // wait until.. hh*3600+mm*60+ss
  5274.   //
  5275.   opt->exec="";
  5276.   opt->is_update=0;      // not an update (yet)
  5277.   opt->dir_topindex=0;   // do not built top index (yet)
  5278.   //
  5279.   opt->bypass_limits=0;  // enforce limits by default
  5280.   opt->state.stop=0;     // stopper
  5281.   opt->state.exit_xh=0;  // abort
  5282.  
  5283.   /* Alocated buffers */
  5284.  
  5285.     opt->callbacks_fun = (t_hts_htmlcheck_callbacks*) malloct(sizeof(t_hts_htmlcheck_callbacks));
  5286.     memset(opt->callbacks_fun, 0, sizeof(t_hts_htmlcheck_callbacks));
  5287.  
  5288.   /* Preload callbacks : java and flash parser, and the automatic user-defined callback */
  5289.  
  5290.   {
  5291.     int i;
  5292.     for(i = 0 ; defaultModules[i] != NULL ; i++) {
  5293.       int ret = plug_wrapper(opt, defaultModules[i], defaultModules[i]);
  5294.       if (ret == 0) {     /* Module aborted initialization */
  5295.         /* Ignored. */
  5296.       }
  5297.     }
  5298.   }
  5299.  
  5300.     return opt;
  5301. }
  5302.  
  5303. HTSEXT_API void hts_free_opt(httrackp *opt) {
  5304.   if (opt != NULL) {
  5305.  
  5306.     /* Alocated callbacks */
  5307.  
  5308.     if (opt->callbacks_fun != NULL) {
  5309.       int i;
  5310.       t_hts_htmlcheck_callbacks_item *items = (t_hts_htmlcheck_callbacks_item*) opt->callbacks_fun;
  5311.       const int size = (int) sizeof(t_hts_htmlcheck_callbacks) / sizeof(t_hts_htmlcheck_callbacks_item);
  5312.       assertf(sizeof(t_hts_htmlcheck_callbacks_item)*size == sizeof(t_hts_htmlcheck_callbacks));
  5313.  
  5314.       /* Free all linked lists */
  5315.       for(i = 0 ; i < size ; i++) {
  5316.         t_hts_callbackarg *carg, *next_carg;
  5317.         for(carg = items[i].carg ; carg != NULL && (next_carg = carg->prev.carg, carg != NULL) ; carg = next_carg ) {
  5318.           hts_free(carg);
  5319.         }
  5320.       }
  5321.  
  5322.       freet(opt->callbacks_fun);
  5323.       opt->callbacks_fun = NULL;
  5324.     }
  5325.  
  5326.     /* Close library handles */
  5327.     unplug_wrappers(opt);
  5328.  
  5329.     /* Cache */
  5330.     if (opt->state.dns_cache != NULL) {
  5331.       hts_cache_free(opt->state.dns_cache);
  5332.       opt->state.dns_cache = NULL;
  5333.     }
  5334.  
  5335.     /* Cancel chain */
  5336.     if (opt->state.cancel != NULL) {
  5337.       htsoptstatecancel *cancel;
  5338.       for(cancel = opt->state.cancel ; cancel != NULL ; ) {
  5339.         htsoptstatecancel *next = cancel->next;
  5340.         if (cancel->url != NULL) {
  5341.           freet(cancel->url);
  5342.         }
  5343.         freet(cancel);
  5344.         cancel = next;
  5345.       }
  5346.       opt->state.cancel = NULL;
  5347.     }
  5348.  
  5349.     /* Free strings */
  5350.  
  5351.     StringFree(opt->proxy.name);
  5352.     StringFree(opt->proxy.bindhost);
  5353.  
  5354.     StringFree(opt->savename_userdef);
  5355.     StringFree(opt->user_agent);
  5356.     StringFree(opt->referer);
  5357.     StringFree(opt->from);
  5358.     StringFree(opt->lang_iso);
  5359.     StringFree(opt->sys_com);
  5360.     StringFree(opt->mimedefs);
  5361.     StringFree(opt->filelist);
  5362.     StringFree(opt->urllist);
  5363.     StringFree(opt->footer);
  5364.     StringFree(opt->mod_blacklist);
  5365.  
  5366.     StringFree(opt->path_html);
  5367.     StringFree(opt->path_log);
  5368.     StringFree(opt->path_bin);
  5369.  
  5370.     /* mutexes */
  5371.     hts_mutexfree(&opt->state.lock);
  5372.  
  5373.     /* Free structure */
  5374.     free(opt);
  5375.   }
  5376. }
  5377.  
  5378. // defaut wrappers
  5379. static void __cdecl htsdefault_init(t_hts_callbackarg *carg) {
  5380. }
  5381. static void __cdecl htsdefault_uninit(t_hts_callbackarg *carg) {
  5382.   // hts_freevar();
  5383. }
  5384. static int __cdecl htsdefault_start(t_hts_callbackarg *carg, httrackp* opt) {
  5385.   return 1; 
  5386. }
  5387. static int __cdecl htsdefault_chopt(t_hts_callbackarg *carg, httrackp* opt) {
  5388.   return 1;
  5389. }
  5390. static int  __cdecl htsdefault_end(t_hts_callbackarg *carg, httrackp* opt) { 
  5391.   return 1; 
  5392. }
  5393. static int __cdecl htsdefault_preprocesshtml(t_hts_callbackarg *carg, httrackp *opt, char** html,int* len,const char* url_adresse,const char* url_fichier) {
  5394.   return 1;
  5395. }
  5396. static int __cdecl htsdefault_postprocesshtml(t_hts_callbackarg *carg, httrackp *opt, char** html,int* len,const char* url_adresse,const char* url_fichier) {
  5397.   return 1;
  5398. }
  5399. static int __cdecl htsdefault_checkhtml(t_hts_callbackarg *carg, httrackp *opt, char* html,int len,const char* url_adresse,const char* url_fichier) {
  5400.   return 1;
  5401. }
  5402. static int __cdecl htsdefault_loop(t_hts_callbackarg *carg, httrackp *opt, lien_back* back,int back_max,int back_index,int lien_n,int lien_tot,int stat_time,hts_stat_struct* stats) {    // appelΘ α chaque boucle de HTTrack
  5403.   return 1;
  5404. }
  5405. static const char* __cdecl htsdefault_query(t_hts_callbackarg *carg, httrackp *opt, const char* question) {
  5406.   return "";
  5407. }
  5408. static const char* __cdecl htsdefault_query2(t_hts_callbackarg *carg, httrackp *opt, const char* question) {
  5409.   return "";
  5410. }
  5411. static const char* __cdecl htsdefault_query3(t_hts_callbackarg *carg, httrackp *opt, const char* question) {
  5412.   return "";
  5413. }
  5414. static int __cdecl htsdefault_check(t_hts_callbackarg *carg, httrackp *opt, const char* adr,const char* fil,int status) {
  5415.   return -1;
  5416. }
  5417. static int __cdecl htsdefault_check_mime(t_hts_callbackarg *carg, httrackp *opt, const char* adr,const char* fil,const char* mime,int status) {
  5418.   return -1;
  5419. }
  5420. static void __cdecl htsdefault_pause(t_hts_callbackarg *carg, httrackp *opt, const char* lockfile) {
  5421.   while (fexist(lockfile)) {
  5422.     Sleep(1000);
  5423.   }
  5424. }
  5425. static void __cdecl htsdefault_filesave(t_hts_callbackarg *carg, httrackp *opt, const char* file) {
  5426. }
  5427. static void __cdecl htsdefault_filesave2(t_hts_callbackarg *carg, httrackp *opt, const char* adr, const char* file, const char* sav, int is_new, int is_modified, int not_updated) {
  5428. }
  5429. static int __cdecl htsdefault_linkdetected(t_hts_callbackarg *carg, httrackp *opt, char* link) {
  5430.   return 1;
  5431. }
  5432. static int __cdecl htsdefault_linkdetected2(t_hts_callbackarg *carg, httrackp *opt, char* link, const char* start_tag) {
  5433.   return 1;
  5434. }
  5435. static int __cdecl htsdefault_xfrstatus(t_hts_callbackarg *carg, httrackp *opt, lien_back* back) {
  5436.   return 1;
  5437. }
  5438. static int __cdecl htsdefault_savename(t_hts_callbackarg *carg, httrackp *opt, const char* adr_complete,const char* fil_complete,const char* referer_adr,const char* referer_fil,char* save) {
  5439.   return 1;
  5440. }
  5441. static int __cdecl htsdefault_sendhead(t_hts_callbackarg *carg, httrackp *opt, char* buff, const char* adr, const char* fil, const char* referer_adr, const char* referer_fil, htsblk* outgoing) {
  5442.   return 1;
  5443. }
  5444. static int __cdecl htsdefault_receivehead(t_hts_callbackarg *carg, httrackp *opt, char* buff, const char* adr, const char* fil, const char* referer_adr, const char* referer_fil, htsblk* incoming) {
  5445.   return 1;
  5446. }
  5447. static int __cdecl htsdefault_detect(t_hts_callbackarg *carg, httrackp *opt, htsmoduleStruct* str) {
  5448.   return 0;
  5449. }
  5450. static int __cdecl htsdefault_parse(t_hts_callbackarg *carg, httrackp *opt, htsmoduleStruct* str) {
  5451.   return 0;
  5452. }
  5453.  
  5454.  
  5455. /* Default internal dummy callbacks */
  5456. const t_hts_htmlcheck_callbacks default_callbacks = {
  5457.     { htsdefault_init, NULL },
  5458.     { htsdefault_uninit, NULL },
  5459.     { htsdefault_start, NULL },
  5460.     { htsdefault_end, NULL },
  5461.     { htsdefault_chopt, NULL },
  5462.     { htsdefault_preprocesshtml, NULL },
  5463.     { htsdefault_postprocesshtml, NULL },
  5464.     { htsdefault_checkhtml, NULL },
  5465.     { htsdefault_query, NULL },
  5466.     { htsdefault_query2, NULL },
  5467.     { htsdefault_query3, NULL },
  5468.     { htsdefault_loop, NULL },
  5469.     { htsdefault_check, NULL },
  5470.     { htsdefault_check_mime, NULL },
  5471.     { htsdefault_pause, NULL },
  5472.     { htsdefault_filesave, NULL },
  5473.     { htsdefault_filesave2, NULL },
  5474.     { htsdefault_linkdetected, NULL },
  5475.     { htsdefault_linkdetected2, NULL },
  5476.     { htsdefault_xfrstatus, NULL },
  5477.     { htsdefault_savename, NULL },
  5478.     { htsdefault_sendhead, NULL },
  5479.     { htsdefault_receivehead, NULL },
  5480.     { htsdefault_detect, NULL },
  5481.     { htsdefault_parse, NULL }
  5482. };
  5483.  
  5484. #define CHARCAST(A) ( (char*) (A) )
  5485. #define OFFSET_OF(TYPE, MEMBER) ( (size_t) ( CHARCAST(&(((TYPE*) NULL)->MEMBER)) - CHARCAST((TYPE*) NULL) ) )
  5486. #define CALLBACK_REF(name, fun) \
  5487.   { name, OFFSET_OF(t_hts_htmlcheck_callbacks, fun) }
  5488. #define MEMBER_OF(STRUCT, OFFSET, TYPE) ( * ((TYPE*)((char*)(STRUCT) + (OFFSET))) )
  5489.  
  5490. const t_hts_callback_ref default_callbacks_ref[] = {
  5491.     CALLBACK_REF("init", init),
  5492.     CALLBACK_REF("free", uninit),
  5493.     CALLBACK_REF("start", start),
  5494.     CALLBACK_REF("end", end),
  5495.     CALLBACK_REF("change-options", chopt),
  5496.     CALLBACK_REF("preprocess-html", preprocess),
  5497.     CALLBACK_REF("postprocess-html", postprocess),
  5498.     CALLBACK_REF("check-html", check_html),
  5499.     CALLBACK_REF("query", query),
  5500.     CALLBACK_REF("query2", query2),
  5501.     CALLBACK_REF("query3", query3),
  5502.     CALLBACK_REF("loop", loop),
  5503.     CALLBACK_REF("check-link", check_link),
  5504.     CALLBACK_REF("check-mime", check_mime),
  5505.     CALLBACK_REF("pause", pause),
  5506.     CALLBACK_REF("save-file", filesave),
  5507.     CALLBACK_REF("save-file2", filesave2),
  5508.     CALLBACK_REF("link-detected", linkdetected),
  5509.     CALLBACK_REF("link-detected2", linkdetected2),
  5510.     CALLBACK_REF("transfer-status", xfrstatus),
  5511.     CALLBACK_REF("save-name", savename),
  5512.     CALLBACK_REF("send-header", sendhead),
  5513.     CALLBACK_REF("receive-header", receivehead),
  5514.     { NULL, 0 }
  5515. };
  5516.  
  5517. size_t hts_get_callback_offs(const char *name) {
  5518.     const t_hts_callback_ref *ref;
  5519.     for(ref = &default_callbacks_ref[0] ; ref->name != NULL ; ref++) {
  5520.         if (strcmp(name, ref->name) == 0) {
  5521.             return ref->offset;
  5522.         }
  5523.     }
  5524.     return (size_t)(-1);
  5525. }
  5526.  
  5527. int hts_set_callback(t_hts_htmlcheck_callbacks *callbacks, const char *name, void *function) {
  5528.     size_t offs = hts_get_callback_offs(name);
  5529.     if (offs != (size_t) -1) {
  5530.         MEMBER_OF(callbacks, offs, void*) = function;
  5531.         return 0;
  5532.     }
  5533.     return 1;
  5534. }
  5535.  
  5536. void *hts_get_callback(t_hts_htmlcheck_callbacks *callbacks, const char *name) {
  5537.     size_t offs = hts_get_callback_offs(name);
  5538.     if (offs != (size_t) -1) {
  5539.         return MEMBER_OF(callbacks, offs, void*);
  5540.     }
  5541.     return NULL;
  5542. }
  5543.  
  5544. // end defaut wrappers
  5545.  
  5546. /* libc stubs */
  5547.  
  5548. HTSEXT_API char* hts_strdup(const char* str) {
  5549.   return strdup(str);
  5550. }
  5551.  
  5552. HTSEXT_API void* hts_malloc(size_t size) {
  5553.   return malloc(size);
  5554. }
  5555.  
  5556. HTSEXT_API void* hts_realloc(void* data, size_t size) {
  5557.   return realloc(data, size);
  5558. }
  5559.  
  5560. HTSEXT_API void hts_free(void* data) {
  5561.   free(data);
  5562. }
  5563.  
  5564. /* Dummy functions */
  5565. HTSEXT_API int hts_resetvar(void) {
  5566.     return 0;
  5567. }
  5568.  
  5569. // Fin
  5570.  
  5571.