O meu squid esta habilitado , e o mysql tambem.
O que pode esta errado ?
- File:
Brazilfw 3.0.256
2 Link Adsl Velox 1mpbs cada
Load Balance
Smart Route com regras dividindo a banda
Squid ativado
Mysql ativado
Qos Ativado
Brazilfw 3.0.256
2 Link Adsl Velox 1mpbs cada
Load Balance
Smart Route com regras dividindo a banda
Squid ativado
Mysql ativado
Qos Ativado
Quando diz que o relatório zerou você quer dizer que o cache foi excluído ou você não vê nada no cache? De qualquer forma verifique o funcionamento do mysql, pois o relatório é mostrado pelos dados que estão no banco de dados.adrianollima escreveu:O meu relatório zerou
adrianollima escreveu:Quando diz que o relatório zerou você quer dizer que o cache foi excluído ou você não vê nada no cache? De qualquer forma verifique o funcionamento do mysql, pois o relatório é mostrado pelos dados que estão no banco de dados.adrianollima escreveu:O meu relatório zerou
Um abraço.
brunovescovi escreveu:Boa noite, pessoal.
Este tópico é a continuação desde: http://www.brazilfw.com.br/forum/viewtopic.php?f=77&t=81695
Deixo em destaque o assunto dos últimos posts do tópico antigo. Por favor, leiam a patir do post abaixo até no final antes de iniciar a participação aqui:
http://www.brazilfw.com.br/forum/viewtopic.php?f=77&t=81695&p=282649#p282603
Continuem postando os resultados aqui para melhorarmos sempre.
Um abraço.
O source do plugin do youtube é esse:gerardonoh escreveu:Espero puedan publica el codigo o rehacer el plugin de youtube
#include <iostream>
#include <cstring>
#include <vector>
#include "../utils.cpp"
using namespace std;
// use this line to compile
// g++ -I. -fPIC -shared -g -o plugin.so plugin.cpp
string get_videoid(string url){
vector<string> resultado,valor;
string retorna = "";
SearchReplace(url,"?","&");
stringexplode(url, "/", &resultado);
if (resultado.size() > 1){
url = resultado.at(1);
resultado.clear();
stringexplode(url, "&", &resultado);
for (int i=0; i <= resultado.size()-1;i++){
valor.clear();
stringexplode(resultado.at(i), "=", &valor);
if (valor.at(0) == "id" || valor.at(0) == "video_id") {
retorna = valor.at(1);
break;
}
}
}
return retorna;
}
// o regex retorna a parte do texto encontrada na linha
//regex_match(regex,texto);
extern "C" resposta getmatch(const string url) {
resposta r;
r.file = get_videoid(url);
if ( !r.file.empty() and
((url.find(".googlevideo.com") != string::npos) or (url.find(".youtube.com") != string::npos) or
(regex_match("74\\.125\\.(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\\.(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)", url) != "")) and
(url.find("videoplayback") != string::npos) and
(url.find("begin=") == string::npos)
) {
r.match = true;
r.domain = "youtube";
r.file += ".flv";
} else {
r.match = false;
}
return r;
}
brunovescovi escreveu:O source completo do bfwcache será disponibilizado logo que sair a próxima versão. A próxima versão já está em testes pela equipe de Beta Testers e assim que aprovada será lançada.
if (valor.at(0) == "id" || valor.at(0) == "video_id") {
retorna = valor.at(1);
// break; aqui cancel el brak para que revice si esta con range=1123-2342
}
//parche
if (valor.at(0) == "range"){
retorna2 = valor.at(1);
retorna += retorna2; // aqui le sumo el rango para que genere el noombre de asrchivo
break;
No Squid 3.1.18 do BFW 3.0.256 a funcionalidade url_rewrite_program não é suportada.gerardonoh escreveu:esto hace como url_rewrite_program de bfwcache que realmente es un parent proxy
O que vem nativo é decisão estratégica do Woshman, que é o developer do BFW 3.x. Eu nunca cheguei a perguntar a ele pessoalmente, mas certamente ele conhece os prós e contras e no final decidiu pelo squid 3 ao invés do squid 2.7 ou lusca.gildope escreveu:porque o BFW3 usa o SQUID3
gerardonoh escreveu:esto hace como url_rewrite_program de bfwcache que realmente es un parent proxy
## BFWCACHE ##
acl bfwcache_lst url_regex -i "/etc/brazilfw/custom/bfwcache.acl"
never_direct allow bfwcache_lst
cache deny bfwcache_lst
cache_peer 127.0.0.1 parent 8080 0 proxy-only no-digest
dead_peer_timeout 2 seconds
cache_peer_access 127.0.0.1 allow bfwcache_lst
cache_peer_access 127.0.0.1 deny all
y por lo de corregir el problema no lo afirmo si no que espero que funcione ya que no tengo el codigo completo de bfwcache por que falta el utils.cpp que alo mejor ya tiene correciones, esperemos aque alguien le este dando seguimiento al problema , al igual el los vodoes que dan problemas traen una cadena como esta key=yes si en el plugin pueden validarlo y evita cachearlo seria bueno como indicas mientras se le da solucion ya que con el url_rewrite_program storeurl.pl que indican en una parte del foro que fue publicado para darle solucion temporal al youtbe no funciona en brazilfw256 no logra subir el squid. en el ejemplo que das de la url del video este en particular se cachearia correctamente ya que no tiene el key=yes ni range=1234-6789.
#include <iostream>
#include <cstring>
#include <vector>
#include "../utils.cpp"
using namespace std;
// use this line to compile
// g++ -I. -fPIC -shared -g -o plugin.so plugin.cpp
string get_videoid(string url){
vector<string> resultado,valor;
string retorna = "";
SearchReplace(url,"?","&");
stringexplode(url, "/", &resultado);
if (resultado.size() > 1){
url = resultado.at(1);
resultado.clear();
stringexplode(url, "&", &resultado);
for (int i=0; i <= resultado.size()-1;i++){
valor.clear();
stringexplode(resultado.at(i), "=", &valor);
//parche
if (valor.at(0) == "range"){
//si el Url del video tiene range entonces dar un resultado en retorna que luego pueda convertirse en un cache miss
retorna = ""; // 0 = cache miss
break;
}
}
}
return retorna;
}
// o regex retorna a parte do texto encontrada na linha
//regex_match(regex,texto);
extern "C" resposta getmatch(const string url) {
resposta r;
r.file = get_videoid(url);
// al tener una condicion para analizar !r.file.empty() , y nuestra funcion get_videoid retornar vacio al detectar range se hace cache miss y todo queda OK
if ( !r.file.empty() and
((url.find(".googlevideo.com") != string::npos) or (url.find(".youtube.com") != string::npos) or
(regex_match("74\\.125\\.(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\\.(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)", url) != "")) and
(url.find("videoplayback") != string::npos) and
(url.find("begin=") == string::npos)
) {
r.match = true;
r.domain = "youtube";
r.file += ".flv";
} else {
r.match = false;
}
return r;
}
Não é o ideal, mas é uma boa solução até encontrarmos a definitiva.yoboss escreveu:Solo hacer cache de vídeos que no vengan con range
Vou fazer uma adaptação segundo a sua sugestão, mas desse jeito o valor de "resposta" sempre será vazio, uma vez que você retirou essa parte:yoboss escreveu:
- Código: Selecionar todos
//parche
if (valor.at(0) == "range"){
//si el Url del video tiene range entonces dar un resultado en retorna que luego pueda convertirse en un cache miss
retorna = ""; // 0 = cache miss
break;
Mas vou fazer a junção das duas funções (da original e da sua). Parabéns pela iniciativa e muito obrigado pela idéia.brunovescovi escreveu:
- Código: Selecionar todos
if (valor.at(0) == "id" || valor.at(0) == "video_id") {
retorna = valor.at(1);
break;
#include <iostream>
#include <cstring>
#include <vector>
#include "../utils.cpp"
using namespace std;
// use this line to compile
// g++ -I. -fPIC -shared -g -o plugin.so plugin.cpp
string get_videoid(string url){
vector<string> resultado,valor;
string retorna = "";
SearchReplace(url,"?","&");
stringexplode(url, "/", &resultado);
if (resultado.size() > 1){
url = resultado.at(1);
resultado.clear();
stringexplode(url, "&", &resultado);
for (int i=0; i <= resultado.size()-1;i++){
valor.clear();
stringexplode(resultado.at(i), "=", &valor);
if (valor.at(0) == "range"){
//si el Url del video tiene range entonces dar un resultado en retorna que luego pueda convertirse en un cache miss y romper el bucle
retorna = ""; // 0 = cache miss
break;
}
if (valor.at(0) == "id" || valor.at(0) == "video_id") {
retorna = valor.at(1);
break;
}
}
}
}
return retorna;
}
// o regex retorna a parte do texto encontrada na linha
//regex_match(regex,texto);
extern "C" resposta getmatch(const string url) {
resposta r;
r.file = get_videoid(url);
// al tener una condicion para analizar !r.file.empty() , y nuestra funcion get_videoid retornar vacio al detectar range se hace cache miss y todo queda OK
if ( !r.file.empty() and
((url.find(".googlevideo.com") != string::npos) or (url.find(".youtube.com") != string::npos) or
(regex_match("74\\.125\\.(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\\.(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)", url) != "")) and
(url.find("videoplayback") != string::npos) and
(url.find("begin=") == string::npos)
) {
r.match = true;
r.domain = "youtube";
r.file += ".flv";
} else {
r.match = false;
}
return r;
}
if (valor.at(0) == "range"){
//si el Url del video tiene range entonces dar un resultado en retorna que luego pueda convertirse en un cache miss y romper el bucle
retorna = ""; // 0 = cache miss
break;
}
if (valor.at(0) == "id" || valor.at(0) == "video_id") {
retorna = valor.at(1);
break;
}
#include <iostream>
#include <cstring>
#include <vector>
#include "../utils.cpp"
using namespace std;
// use this line to compile
// g++ -I. -fPIC -shared -g -o plugin.so plugin.cpp
string get_videoid(string url){
vector<string> resultado,valor;
string retorna = "";
string retorna2 = "";
SearchReplace(url,"?","&");
stringexplode(url, "/", &resultado);
if (resultado.size() > 1){
url = resultado.at(1);
resultado.clear();
stringexplode(url, "&", &resultado);
for (int i=0; i <= resultado.size()-1;i++){
valor.clear();
stringexplode(resultado.at(i), "=", &valor);
if (valor.at(0) == "cm2" || valor.at(0) == "id" || valor.at(0) == "video_id" || valor.at(0) == "range" || valor.at(0) == "fmt" || valor.at(0) == "itag" || valor.at(0) == "begin") {
retorna +=valor.at(1);
// break;
}
//**parche
//if (valor.at(0) == "range"){
//retorna2 = valor.at(1);
//retorna += retorna2;
//retorna="";
//break;
//}
}
}
return retorna;
}
// o regex retorna a parte do texto encontrada na linha
//regex_match(regex,texto);
extern "C" resposta getmatch(const string url) {
resposta r;
r.file = get_videoid(url);
if(url.find("noflv=") != string::npos && url.find("ptk=") == string::npos){
r.match = false;
}else{
if ( !r.file.empty() and
((url.find(".googlevideo.com") != string::npos) or (url.find(".youtube.com") != string::npos) or
(regex_match("74\\.125\\.(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\\.(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)", url) != "")) and
(url.find("videoplayback") != string::npos) and
(url.find("begin") == string::npos) ) {
r.match = true;
r.domain = "youtube";
r.file += ".flv";
} else {
r.match = false;
}
}
return r;
}
#include <iostream>
#include <cstring>
#include <vector>
#include "../utils.cpp"
using namespace std;
string get_videoid(string url){
vector<string> resultado,valor;
string retorna = "";
SearchReplace(url,"?","&");
stringexplode(url, "/", &resultado);
if (resultado.size() > 1){
url = resultado.at(1);
resultado.clear();
stringexplode(url, "&", &resultado);
for (int i=0; i <= resultado.size()-1;i++){
valor.clear();
stringexplode(resultado.at(i), "=", &valor);
// si el Url del video tiene range entonces dar un resultado en retorna que luego pueda convertirse en un cache miss y romper el bucle
// Se a URL do vídeo possui range, então retorna um resultado que vai ser entendido como MISS e interrompe o loop
if (valor.at(0) == "range"){
retorna = ""; // 0 = cache miss
break;
}
if (valor.at(0) == "id" || valor.at(0) == "video_id") {
retorna = valor.at(1);
break;
}
}
}
return retorna;
}
extern "C" resposta getmatch(const string url) {
resposta r;
r.file = get_videoid(url);
// al tener una condicion para analizar !r.file.empty(), y nuestra funcion get_videoid retornar vacio al detectar range se hace cache miss y todo queda OK
// a checagem de r.file.empty() agora serve para apontar cache miss: (01) se não encontrar id e (02) se encontrar range.
if ( !r.file.empty() and
((url.find(".googlevideo.com") != string::npos) or (url.find(".youtube.com") != string::npos) or
(regex_match("74\\.125\\.(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\\.(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)", url) != "")) and
(url.find("videoplayback") != string::npos) and
(url.find("begin=") == string::npos)) {
r.match = true;
r.domain = "youtube";
r.file += ".flv";
} else {
r.match = false;
}
return r;
}
gerardonoh escreveu:buenas tardes: aqui pongo un parche que estoy probando al igual seria abueno ver el codigo de util.cpp
void SearchReplace(string &source, string search, string replace) {
string::size_type position = source.find(search);
while (position != string::npos) {
source.replace(position, search.size(), replace);
position = source.find(search);
}
}
void stringexplode(string str, string separator, vector<string>* results) {
size_t found;
found = str.find_first_of(separator);
while (found != string::npos) {
if (found > 0) {
results->push_back(str.substr(0, found));
}
str = str.substr(found + 1);
found = str.find_first_of(separator);
}
if (str.length() > 0) {
results->push_back(str);
}
}
string regex_match(string er, string line) {
int error;
regmatch_t match;
regex_t reg;
if ((regcomp(®, er.c_str(), REG_EXTENDED | REG_NEWLINE)) == 0) {
error = regexec(®, line.c_str(), 1, &match, 0);
if (error == 0) {
//cout << "Tamanho: " << line.size() << " Inicio: " << match.rm_so << " Fim: " << match.rm_eo << endl;
return line.substr(match.rm_so, match.rm_eo - match.rm_so);
} else {
return "";
}
} else {
return "";
}
}
Também concordo, mas as duas sugestões dadas até agora são medidas paleativas. A primeira é a versão compilada que coloquei aqui. A segunda vamos aguardar o autor analizar as funções aqui apresentadas do arquivo utils.cpp para que esteja mais sólida, então compilamos para testar também. De qualquer forma todas essas idéias e sugestões são fundamentais para chegarmos a uma solução final que seja satisfatória para todos.yoboss escreveu:El problema es que el cache va subir mucho muy grande, podríamos tener 50 veces el mismo vídeo en cache, la solución de no hacer cache de los vídeos partidos me gusta mas.
Que opina la gente?
gerardonoh escreveu:Seria bueno subir los archivos .cpp para que sirva de apoyo y hacer mas plugins
/*
* (c) Copyright 2009 Joaquim Pedro França Simão (osmano807) <osmano807@gmail.com>. Some Rights Reserved.
* @autor Joaquim Pedro França Simão (osmano807) <osmano807@gmail.com>
*/
#include <iostream>
#include <cstring>
#include <string>
#include <vector>
#include "../utils.cpp"
using namespace std;
// use this line to compile
// g++ -I. -fPIC -shared -g -o 4shared.com.so 4shared.com.cpp
string get_filename(string url) {
vector<string> resultado;
if (url.find("?") != string::npos) {
stringexplode(url, "?", &resultado);
stringexplode(resultado.at(resultado.size()-2), "/", &resultado);
return resultado.at(resultado.size()-1);
} else {
stringexplode(url, "/", &resultado);
return resultado.at(resultado.size()-1);
}
}
extern "C" resposta getmatch(const string url) {
resposta r;
if ( (url.find(".4shared.com/download/") != string::npos)
) {
r.file = get_filename(url);
if (!r.file.empty()) {
r.match = true;
r.domain = "4shared";
} else {
r.match = false;
}
} else {
r.match = false;
}
return r;
}
return r;
O plugin do facebook não é nativo deste addon. O uso é por conta e risco de cada um. Não temos condições de tratar aqui sobre plugins que não estão na versão original.adrianollima escreveu:olá ! Meus clientes estão reclamando de uma coisa que só percebi hoje, a imagem no facebook fica em má qualidade ou seja em baixa resolução, como não mexo muito não percebi, e hoje entrei só pra ver e realmente eles tem razão, alguém mais percebeu isso ? ou é só comigo ?
O arquivo que chama os plugins é este abaixo:yoboss escreveu: bruno plz si pudieras postear parte del código en donde se acceda a la db seria de mucha utilidad
#include "connectiontohttp2.h"
#include "logfile.h"
#include "utils.h"
#include "params.h"
#include "database_mysql.h"
#include "x64compat.h"
#include <stdio.h>
#include <iostream>
#include <vector>
#include <dlfcn.h>
#include <cstdlib>
#include <sstream>
extern int LL; //LogLevel
void ConnectionToHTTP2::Cache() {
msghit = "MISS";
hit = downloading = r.match = rewrited = resuming = passouheader = general = etag = false;
filesize = filedownloaded = filesended = partial = expiration = 0;
if (LL > 0) LogFile::AccessMessage("Url %s%s\n", domain.c_str(), request.c_str());
string domaintmp = getdomain(domain + request);
string pluginpath = pluginsdir + domaintmp + ".so";
if (file_exists(pluginpath)) {
if (LL > 0) LogFile::AccessMessage("Loading plugin %s\n", pluginpath.c_str());
void* handle = dlopen(pluginpath.c_str(), RTLD_LAZY);
if (!handle) {
if (LL > 0) LogFile::ErrorMessage("Cannot open library: %s\n", dlerror());
}
typedef resposta(*plugin_t)(string);
plugin_t plugin = (plugin_t) dlsym(handle, "getmatch");
if (!plugin) {
if (LL > 0) LogFile::ErrorMessage("Cannot load symbol: %s\n", dlerror());
dlclose(handle);
} else { // Plugin carregado corretamente, ok para atribuir valores ao struc
r = plugin(domain + request);
if (LL > 0) LogFile::AccessMessage("Resposta Match %d Domain %s File %s\n", r.match, r.domain.c_str(), r.file.c_str());
}
}
if (r.match) {
subdir = ConvertChar(r.file);
completepath = cachedir + r.domain;
completefilepath = completepath + "/" + subdir + "/" + r.file;
if (LL > 1) LogFile::AccessMessage("Arquivo: %s\n", string(completefilepath).c_str());
if (r.domain == "rewrite") {
r.match = false;
rewrited = true;
if (LL > 1) LogFile::AccessMessage("Rewrite: %s%s \n", r.file.c_str());
} else if (!file_exists(completefilepath)) {
if (disk_use(completepath) <= cache_limit) {
// cria diretorios e etc
if (!file_exists(completepath + "/" + subdir + "/")) {
mkdir_p(completepath + "/" + subdir + "/");
}
domaindb.set("INSERT INTO bfwcache (domain, file, size, downloaded, requested, last_request) VALUES ('" + r.domain + "', '" + domaindb.sqlconv(r.file) + "', 0, now(),0,now());");
if (LL > 0) LogFile::AccessMessage("MISS: Domain: %s File: %s\n", r.domain.c_str(), r.file.c_str());
} else {
LogFile::ErrorMessage("Cache limit (%d/%d) %s%s\n", cache_limit, disk_use(completepath), cachedir.c_str(), r.domain.c_str());
}
} else if (file_exists(completefilepath)) {
if (domaindb.get("SELECT size FROM bfwcache WHERE file='" + domaindb.sqlconv(r.file) + "' and domain='" + r.domain + "';") != 0) {
LogFile::ErrorMessage("erro select mysql: %s\n", domaindb.getError().c_str());
r.match = hit = false;
}
filesize = atol(domaindb.get("size", 1).c_str());
if (LL > 1) LogFile::AccessMessage("Size db: "LLD" File size: "LLD" Timeout: %d\n", filesize, file_size(completefilepath), (now() - file_getmodif(completefilepath)));
if (domaindb.get_num_rows() == 0) // se nao existir o registro do arquivo do db
{
domaindb.set("INSERT INTO bfwcache (domain, file, size, downloaded, requested, last_request) VALUES ('" + r.domain + "', '" + domaindb.sqlconv(r.file) + "', 0, now(),0,now());");
if (LL > 0) LogFile::AccessMessage("MISS DB: Domain: %s File: %s\n", r.domain.c_str(), r.file.c_str());
} else if (
((now() - file_getmodif(completefilepath)) < 10)
&&
(
(filesize > file_size(completefilepath)) || (filesize == 0)
)
) {
if (Params::GetConfigBool(UpperCase(r.domain) + "_NODOWN")) {
if (LL > 1) LogFile::AccessMessage("Concorrencia cancelada: Domain: %s File: %s\n", r.domain.c_str(), r.file.c_str());
r.match = false; // pega direto do site
} else {
hit = true;
downloading = true;
if (LL > 0) LogFile::AccessMessage("HIT DOWN: Domain: %s File: %s\n", r.domain.c_str(), r.file.c_str());
msghit = "HIT";
}
} else if (filesize == file_size(completefilepath)) {
hit = true;
downloading = false;
domaindb.set("UPDATE bfwcache SET requested=requested+1, last_request=now() WHERE file='" + domaindb.sqlconv(r.file) + "' and domain='" + r.domain + "';");
if (LL > 0) LogFile::AccessMessage("HIT!: Domain: %s File: %s\n", r.domain.c_str(), r.file.c_str());
msghit = "HIT";
} else if (Params::GetConfigBool(UpperCase(r.domain) + "_NORESUME") && filesize > 0) { // o arquivo foi baixado parcialmente
if (disk_use(completepath) <= cache_limit) {
hit = resuming = downloading = true;
downloader.ClearVars();
downloader.SetDomainAndPort(domain, port);
if (LL > 0) LogFile::AccessMessage("HIT RESUME: Domain: %s File: %s\n", r.domain.c_str(), r.file.c_str());
msghit = "HIT";
} else {
LogFile::ErrorMessage("Cache limit (%d/%d) %s%s\n", cache_limit, disk_use(completepath), cachedir.c_str(), r.domain.c_str());
}
}
domaindb.clear();
}
}
}
bool ConnectionToHTTP2::SetDomainAndPort(string domainT, int portT, string requestT) {
//if (LL>1) LogFile::AccessMessage("Passando pelo SetDomainAndPort \n");
if (!domaindb.connected)
if (domaindb.open(Params::GetConfigString("MYSQL_HOST"), Params::GetConfigString("MYSQL_USER"), Params::GetConfigString("MYSQL_PASS"), Params::GetConfigString("MYSQL_DB")) != 0) {
LogFile::ErrorMessage("erro conexao mysql: %s\n", domaindb.getError().c_str());
Close();
}
domain = domainT;
request = requestT;
port = portT;
pluginsdir = Params::GetConfigString("PLUGINSDIR");
cachedir = Params::GetConfigString("CACHEDIR");
cache_limit = Params::GetConfigInt("CACHE_LIMIT");
Cache();
if (hit)
return true;
else
return ConnectionToHTTP::SetDomainAndPort(domain, port);
}
bool ConnectionToHTTP2::ConnectToServer() {
//if (LL>1) LogFile::AccessMessage("Passando pelo ConnectToServer \n");
if (rewrited) return true;
if (resuming) {
if (!downloader.ConnectToServer()) {
if (LL > 0) LogFile::AccessMessage("downloader nao conectou\n");
Close();
}
}
if (hit) return true;
else return ConnectionToHTTP::ConnectToServer();
}
bool ConnectionToHTTP2::SendHeader(string header, bool ConnectionClose, string requestT) {
//if (LL>1) LogFile::AccessMessage("Passando pelo SendHeader \n");
if (passouheader) {
if (cachefile.is_open()) cachefile.close();
if (outfile.is_open()) outfile.close();
if ((filesended < filesize) && ((r.match && !hit) || (r.match && resuming)))
file_setmodif(completefilepath, 1);
downloader.Close();
if (LL > 1) LogFile::AccessMessage("Novo header, chamando Cache()\n");
request = requestT;
Cache();
}
if (!passouheader) passouheader = true;
if (rewrited) return true;
if (resuming) {
vector<string> lines;
char linha[5000];
string headertmp = "";
stringexplode(header, "\r\n", &lines);
for (unsigned int i = 0; i <= lines.size() - 1; ++i) {
if (i == lines.size() - 1) {
sprintf(linha, "Range: bytes="LLD"-"LLD"\r\n", file_size(completefilepath), filesize);
} else {
sprintf(linha, "%s\r\n", lines.at(i).c_str());
}
headertmp.append(linha);
}
if (LL > 1) LogFile::AccessMessage("header req down (%s%s)\n %s \n", domain.c_str(), request.c_str(), headertmp.c_str());
downloader.SendHeader(headertmp, true);
}
if (hit && (header.find("If-None-Match") != string::npos)) etag = true;
if (hit) {
if (!downloading && !resuming) {
vector<string> lines;
stringexplode(header, "\r\n", &lines);
for (unsigned int i = 1; i <= lines.size() - 1; ++i) {
if (lines.at(i).find("Range: bytes=") == 0) {
//pegar o valor do range, trabalhando só com o inicio do arquivo
partial = atoi(lines.at(i).substr(13, lines.at(1).length() - 13 - lines.at(i).find("-")).c_str());
break;
}
}
}
return true;
} else return ConnectionToHTTP::SendHeader(header, ConnectionClose);
}
string ConnectionToHTTP2::GetIP() {
//if (LL>1) LogFile::AccessMessage("Passando pelo GetIP \n");
if (hit || rewrited) return "0.0.0.0";
else return ConnectionToHTTP::GetIP();
}
bool ConnectionToHTTP2::ReadHeader(string &headerT) {
//if (LL>1) LogFile::AccessMessage("Passando pelo ReadHeader \n");
if (resuming) {
string headertmp = "";
if (downloader.GetResponse() == 0) downloader.ReadHeader(headertmp);
downloader.AnalyseHeader(headertmp);
if (LL > 1) LogFile::AccessMessage("header downloader (%d)(%s%s)\n%s\n", downloader.GetResponse(), domain.c_str(), request.c_str(), headertmp.c_str());
if ((downloader.GetResponse() == 302) || (downloader.GetResponse() == 303)) {
if (LL > 0) LogFile::AccessMessage("redirect resume: %d\n", downloader.GetResponse());
headerT = headertmp;
hit = resuming = downloading = false;
rewrited = true;
return true;
} else if (downloader.GetResponse() != 206) {
if (LL > 0) LogFile::AccessMessage("resume fail: %d\n", downloader.GetResponse());
return false;
}
}
if (rewrited) {
stringstream tmp;
tmp.str("");
tmp << "HTTP/1.0 302 Moved\r\n";
tmp << "Location: http://" << r.file << "\r\n";
tmp << "Content-Length: 0\r\n";
tmp << "Connection: close\r\n\r\n";
headerT = tmp.str();
return true;
} else if (hit && etag) {
stringstream tmp;
tmp.str("");
tmp << "HTTP/1.0 304 Not Modified\r\n";
tmp << "Connection: close\r\n\r\n";
headerT = tmp.str();
rewrited = true;
r.match = hit = false;
return true;
} else if (hit) {
stringstream tmp;
tmp.str("");
if (partial == 0)
tmp << "HTTP/1.0 200 OK\r\n";
else
tmp << "HTTP/1.0 206 Partial\r\n";
//tmp << "Content-Disposition: attachment; filename=\"" + r.file + "\"\r\n";
if (getFileExtension(r.file) == "SWF")
tmp << "Content-Type: application/x-shockwave-flash\r\n";
else if (getFileExtension(r.file) == "FLV")
tmp << "Content-Type: video/x-flv\r\n";
else
tmp << "Content-Type: application/octet-stream\r\n";
tmp << "Content-Length: ";
tmp << filesize - partial;
tmp << "\r\n";
if (partial > 0) {
tmp << "Accept-Ranges: bytes\r\n";
tmp << "Content-Range: bytes " << partial << "-" << (filesize - 1) << "/" << filesize << "\r\n";
}
tmp << "X-Cache: HIT from BFW Cache\r\n";
tmp << "BFW Cache: HIT FROM " << r.domain << "\r\n";
headerT = tmp.str();
return true;
} else return ConnectionToHTTP::ReadHeader(headerT);
}
bool ConnectionToHTTP2::AnalyseHeader(string &linesT) {
//if (LL>1) LogFile::AccessMessage("Passando pelo AnalyseHeader \n");
if (hit) return true;
else return ConnectionToHTTP::AnalyseHeader(linesT);
}
bool ConnectionToHTTP2::IsItKeepAlive() {
//if (LL>1) LogFile::AccessMessage("Passando pelo IsItKeepAlive \n");
if (hit) return true;
else return ConnectionToHTTP::IsItKeepAlive();
}
int64_t ConnectionToHTTP2::GetContentLength() {
//if (LL>1) LogFile::AccessMessage("Passando pelo GetContentLength \n");
if (hit)
return filesize;
else {
int64_t ContentLengthReference;
ContentLengthReference = ConnectionToHTTP::GetContentLength();
if (r.match) {
if (ContentLengthReference > 0) {
if (general) {
domaindb.set("UPDATE bfwcache SET size=" + itoa(ContentLengthReference) + " WHERE file='" + domaindb.sqlconv(subdir + "/" + r.file) + "' and domain='" + r.domain + "';");
} else {
domaindb.set("UPDATE bfwcache SET size=" + itoa(ContentLengthReference) + " WHERE file='" + domaindb.sqlconv(r.file) + "' and domain='" + r.domain + "';");
}
}
filesize = ContentLengthReference;
if (((ContentLengthReference < Params::GetConfigInt(getFileExtension(getFileName(request)) + "_MIN") || (ContentLengthReference > Params::GetConfigInt(getFileExtension(getFileName(request)) + "_MAX") && Params::GetConfigInt(getFileExtension(getFileName(request)) + "_MAX") > 0)) && general) ||
(ContentLengthReference < Params::GetConfigInt(UpperCase(r.domain) + "_MIN") || (ContentLengthReference > Params::GetConfigInt(UpperCase(r.domain) + "_MAX") && Params::GetConfigInt(UpperCase(r.domain) + "_MAX") > 0))) {
r.match = general = false;
if (LL > 0) LogFile::AccessMessage("MAXMIN CANCEL: Domain: %s File: %s Size: "LLD"\n", r.domain.c_str(), r.file.c_str(), filesize);
}
}
return ContentLengthReference;
}
}
bool ConnectionToHTTP2::IsItChunked() {
//if (LL>1) LogFile::AccessMessage("Passando pelo IsItChunked \n");
if (hit) return false;
else return ConnectionToHTTP::IsItChunked();
}
string ConnectionToHTTP2::PrepareHeaderForBrowser() {
//if (LL>1) LogFile::AccessMessage("Passando pelo PrepareHeaderForBrowser \n");
if (hit) {
string header;
ReadHeader(header);
return header;
} else if (r.match) {
timerecord = time(NULL);
stringstream tmp;
tmp.str("");
tmp << ConnectionToHTTP::PrepareHeaderForBrowser();
tmp << "BFW Cache: MISS FROM " << r.domain << "\r\n";
return tmp.str();
} else return ConnectionToHTTP::PrepareHeaderForBrowser();
}
int ConnectionToHTTP2::GetResponse() {
//if (LL>1) LogFile::AccessMessage("Passando pelo GetResponse \n");
int retorno;
if (hit) retorno = 200;
else if (!hit && r.match) {
retorno = ConnectionToHTTP::GetResponse();
if (retorno != 200) {
r.match = hit = resuming = false;
}
} else retorno = ConnectionToHTTP::GetResponse();
return retorno;
}
bool ConnectionToHTTP2::CheckForData(int timeout) {
//if (LL>1) LogFile::AccessMessage("Passando pelo CheckForData \n");
if (hit) return false;
else return ConnectionToHTTP::CheckForData(timeout);
}
ssize_t ConnectionToHTTP2::ReadBodyPart(string &bodyT, bool Chunked) {
//if (LL>1) LogFile::AccessMessage("Passando pelo ReadBodyPart \n");
if (rewrited) {
bodyT.append("\r\n", 2);
return 2;
}
ssize_t BodyLength = 0;
if (resuming) {
string bodyTmp = "";
BodyLength = downloader.ReadBodyPart(bodyTmp, Chunked);
if (!outfile.is_open()) {
outfile.open(string(completefilepath).c_str(), ios::out | ios::app | ios::binary);
}
if (BodyLength > 0)
outfile.write(bodyTmp.c_str(), BodyLength);
if ((time(NULL) - timerecord2) > 1) {
if (LL > 1) LogFile::AccessMessage("resumindo... %d \n", BodyLength);
outfile.flush();
file_setmodif(completefilepath);
}
}
if (hit) {
BodyLength = 0;
int tbuffer = MAXRECV;
char memblock[MAXRECV];
memset(memblock, '\0', sizeof (memblock));
bodyT = "";
while (BodyLength == 0) {
if (!cachefile.is_open()) {
cachefile.open(string(completefilepath).c_str(), ios::in | ios::binary);
if (partial > 0) cachefile.seekg(partial);
timeout = timerecord = time(NULL);
}
if (downloading) {
if ((time(NULL) - timerecord) > 1) {
filedownloaded = file_size(completefilepath);
timerecord = time(NULL);
if (LL > 1) LogFile::AccessMessage("atualizando... %s tbuffer: %d downloaded: "LLD" filesize: "LLD" \n", r.file.c_str(), tbuffer, filedownloaded, filesize);
}
if ((filesended + MAXRECV) > filedownloaded) {
tbuffer = filedownloaded - filesended;
} else if (filedownloaded == filesize) {
downloading = false;
tbuffer = MAXRECV;
if (LL > 1) LogFile::AccessMessage("acabou o download, nao precisa ajustar tbuffer %s \n", r.file.c_str());
} else tbuffer = MAXRECV;
}
if (cachefile.eof()) {
if (LL > 0) LogFile::AccessMessage("EOF: %s\n", r.file.c_str());
BodyLength = 0;
cachefile.close();
break;
}
if (tbuffer > 0) {
cachefile.read(memblock, tbuffer);
BodyLength = cachefile.gcount();
if (BodyLength > 0) {
filesended += BodyLength;
bodyT.append(memblock, BodyLength);
timeout = time(NULL);
} else usleep(rand() % 300000);
} else usleep(rand() % 300000);
if ((time(NULL) - timeout) >= 5) {
if (LL > 0) LogFile::AccessMessage("TIMEOUT: %s\n", r.file.c_str());
BodyLength = -1;
cachefile.close();
break;
}
if (filesended == filesize) {
cachefile.close();
break;
}
}
return BodyLength;
} else {
ssize_t BodyLength;
BodyLength = ConnectionToHTTP::ReadBodyPart(bodyT, Chunked);
if (r.match) {
if (!cachefile.is_open()) {
cachefile.open(string(completefilepath).c_str(), ios::out | ios::binary);
}
if (BodyLength > 0) {
cachefile.write(bodyT.c_str(), BodyLength);
filesended += BodyLength;
if ((time(NULL) - timerecord) > 1) {
cachefile.flush();
file_setmodif(completefilepath);
timerecord = time(NULL);
}
}
}
return BodyLength;
}
}
void ConnectionToHTTP2::Close() {
//if (LL>1) LogFile::AccessMessage("Passando pelo Close\n");
domaindb.close();
if (cachefile.is_open()) cachefile.close();
if (outfile.is_open()) outfile.close();
if ((filesended < filesize) && ((r.match && !hit) || (r.match && resuming)))
file_setmodif(completefilepath, 1);
downloader.Close();
ConnectionToHTTP::Close();
}
string UpperCase(string CaseString) {
string::const_iterator si = CaseString.begin();
string::size_type j = 0;
string::size_type e = CaseString.size();
while (j < e) {
CaseString[j++] = toupper(*si++);
}
return CaseString;
}
void stringexplode(string str, string separator, vector<string>* results) {
size_t found;
found = str.find_first_of(separator);
while (found != string::npos) {
if (found > 0) {
results->push_back(str.substr(0, found));
}
str = str.substr(found + 1);
found = str.find_first_of(separator);
}
if (str.length() > 0) {
results->push_back(str);
}
}
string getdomain(string url) {
if (regex_match("^74\\.125\\.(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\\.(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?$)", url) != "") return "youtube.com";
vector<string> resultado;
if (!url.empty()) {
stringexplode(url, "/", &resultado);
if (resultado.size() > 1) {
url = resultado.at(0);
}
resultado.clear();
stringexplode(url, ".", &resultado);
if (resultado.size() > 1) {
if ((resultado.at(resultado.size() - 2)).size() <= 3 &&
(resultado.at(resultado.size() - 1)).size() <= 3) {
return resultado.at(resultado.size() - 3) + "." + resultado.at(resultado.size() - 2) + "." + resultado.at(resultado.size() - 1);
} else {
return resultado.at(resultado.size() - 2) + "." + resultado.at(resultado.size() - 1);
}
} else return url;
} else return "";
}
bool file_exists(string strFilename) {
struct stat stFileInfo;
if (stat(strFilename.c_str(), &stFileInfo) == 0) {
return true;
} else {
return false;
}
}
int64_t file_size(string szFileName) {
struct stat fileStat;
int err = stat(szFileName.c_str(), &fileStat);
if (0 != err) return -1;
return (int64_t) fileStat.st_size;
}
void mkdir_p(const string &pathname) {
umask(0);
if (mkdir(pathname.c_str(), 0777) < 0) {
if (errno == ENOENT) {
// If we couldn't make the whole directory because of ENOENT (a
// parent directory doesn't exist), then try recursively to make
// the immediate parent directory.
size_t slash = pathname.rfind('/');
if (slash != string::npos) {
string prefix = pathname.substr(0, slash);
mkdir_p(prefix);
mkdir(pathname.c_str(), 0777);
}
}
}
}
string regex_match(string er, string line) {
int error;
regmatch_t match;
regex_t reg;
if ((regcomp(®, er.c_str(), REG_EXTENDED | REG_NEWLINE)) == 0) {
error = regexec(®, line.c_str(), 1, &match, 0);
if (error == 0) {
//cout << "Tamanho: " << line.size() << " Inicio: " << match.rm_so << " Fim: " << match.rm_eo << endl;
return line.substr(match.rm_so, match.rm_eo - match.rm_so);
} else {
return "";
}
} else {
return "";
}
}
string itoa(int val) {
char res[1024];
sprintf(res, "%d", val);
string str = string(res);
return str;
}
double now() {
struct timeval tv;
gettimeofday(&tv, 0);
return tv.tv_sec + tv.tv_usec / 1e6;
}
long file_getmodif(string szFileName) {
struct stat fileStat;
int err = stat(szFileName.c_str(), &fileStat);
if (0 != err) return 0;
return fileStat.st_mtime;
}
int file_setmodif(string szFileName, long fdate) {
struct utimbuf fmtime;
if (fdate > 0) {
fmtime.actime = fdate + 10;
fmtime.modtime = fdate + 10;
return utime(szFileName.c_str(), &fmtime);
} else {
static struct timespec newtime;
fmtime.actime = newtime.tv_sec;
fmtime.modtime = newtime.tv_sec;
return utime(szFileName.c_str(), &fmtime);
}
}
string ConvertChar(string lineT) {
string line = "";
for (unsigned int i = 0; i < lineT.length(); i++) {
switch (lineT[i]) {
case 'a':
line += "1";
break;
case 'b':
line += "2";
break;
case 'c':
line += "3";
break;
case 'd':
line += "4";
break;
case 'e':
line += "5";
break;
case 'f':
line += "6";
break;
case 'g':
line += "7";
break;
case 'h':
line += "8";
break;
case 'i':
line += "9";
break;
case 'j':
line += "10";
break;
case 'k':
line += "11";
break;
case 'l':
line += "12";
break;
case 'm':
line += "13";
break;
case 'n':
line += "14";
break;
case 'o':
line += "15";
break;
case 'p':
line += "16";
break;
case 'q':
line += "17";
break;
case 'r':
line += "18";
break;
case 's':
line += "19";
break;
case 't':
line += "20";
break;
case 'u':
line += "21";
break;
case 'v':
line += "22";
break;
case 'w':
line += "23";
break;
case 'x':
line += "24";
break;
case 'y':
line += "25";
break;
case 'z':
line += "26";
break;
default:
if (isdigit(lineT[i]))
line += lineT[i];
else
line += "27";
break;
}
}
unsigned long resultado = 0;
string tempstr = "";
if (line.length() <= 3)
line += "282930";
for (unsigned int fff = 3; fff < line.length(); fff += 3) {
tempstr = line.substr(0, fff);
resultado += atoi(tempstr.c_str());
line = line.substr(fff + 1);
}
tempstr = itoa(resultado);
if (tempstr.length() > 3)
tempstr = tempstr.substr(tempstr.length() - 3);
string updir = itoa(atoi(tempstr.substr(1, 1).c_str()) + atoi(tempstr.substr(2, 2).c_str()));
if (updir.size() > 1)
updir = updir.substr(1, 1);
/* END! */
lineT = "";
lineT += updir;
lineT += "/";
lineT += tempstr[0];
lineT += "_";
lineT += tempstr.substr(1);
return lineT;
}
int disk_use(string path) {
double bfree, btotal = 0;
struct statvfs fiData;
if ((statvfs(path.c_str(), &fiData)) < 0) {
return -1;
} else {
bfree = (((double) fiData.f_frsize) * ((double) fiData.f_bfree));
btotal = (((double) fiData.f_frsize) * ((double) fiData.f_blocks));
return ((btotal - bfree) / btotal)*100;
}
}
const string getFileExtension(string file) {
size_t pos = file.find_last_of(".");
if (pos != string::npos)
return UpperCase(file.substr(pos + 1));
else
return UpperCase(file);
}
const string getFileName(string file) {
size_t pos = file.find_last_of("/");
if (pos != string::npos) {
return file.substr(pos + 1);
//file = file.substr(pos + 1);
//pos = file.find_last_of("?");
//if (pos != string::npos)
// return file.substr(0,pos);
//else
// return file;
} else
return file;
}
Não quebrou regra, não, Adriano. Só avisei que não tem como dar suporte aqui pelo fórum. Só podemos tratar aqui o que passou pelos testes e foi homologado.adrianollima escreveu:me desculpa se quebrei alguma regra do fórum
brunovescovi escreveu:Dei uma ajeitada no source do plugin do youtube de acordo com as sugestões aqui apresentadas para apontar MISS caso tenha range. Compilei e testei aqui em 64 bits.
Não sei se funcionou 100% como o esperado porque fiz poucos testes, mas percebi que ao ver alguns vídeos, a informação era acrescentada ao relatório, e às vezes não era acrescentada, ou seja, tudo indica que realmente tem vídeos que está fazendo cache e outros não, justamente como o esperado.
Mas gostaria da ajuda dos senhores para testar essa alteração. O plugin compilado para 32 bits está no link abaixo:
http://www.brazilfw.com.br/users/brunovescovi/addons/3.0/bfwcache/youtube.com.so
gildope escreveu:O plugin do youtube que Bruno passou para testar, está dando erros quando se acessa o vídeo cacheado. "Ocorreu um erro, tente mais tarde".
reginaldo escreveu: gildope escreveu:O plugin do youtube que Bruno passou para testar, está dando erros quando se acessa o vídeo cacheado. "Ocorreu um erro, tente mais tarde".
Você zerou o cache depois que colocou o novo plugin?
adrianollima escreveu:olá ! Meus clientes estão reclamando de uma coisa que só percebi hoje, a imagem no facebook fica em má qualidade ou seja em baixa resolução, como não mexo muito não percebi, e hoje entrei só pra ver e realmente eles tem razão, alguém mais percebeu isso ? ou é só comigo ?
yoboss escreveu:Pruevas de hoy:
Descubrí que si compilo algo en Ubuntu y luego lo traigo a Brazil FW este ejecutable no hace nada
luego también descubrí que existe un build tree para poder compilar programas para brazilFW
así que estoy descargando Devian 5 y luego intentare instalar ese build tree, y compilar algo..
Estoy por el camino correcto ???
mkdir build-treeBFW3
rsync -DHlravzptg --delete www.brazilfw.com.br::brazilfw ./build-treeBFW3
Voltar para Certified Addons of Project BFW
Usuários navegando neste fórum: Nenhum usuário registrado e 2 visitantes