void GetAclTask::RunImp() { std::string uri_str = uri(); std::string buckname = CString2string(_buckname); buckname = MultiByteToUtf8(buckname); std::string objname = CString2string(_objname); objname = MultiByteToUtf8(objname); set_uri(uri_str.append(URLEncode(buckname) + "/" + URLEncode(objname) + "?acl")); }
////////////////////////////////////////////////////////////////////////// // delete object void DeleteObjectTask::RunImp() { set_http_method(HTTP_METHOD_DELETE); std::string uri_str = uri(); std::string buckname = CString2string(_buckname); buckname = MultiByteToUtf8(buckname); std::string objname = CString2string(_objname); objname = MultiByteToUtf8(objname); set_uri(uri_str.append(URLEncode(buckname) + "/" + URLEncode(objname))); }
////////////////////////////////////////////////////////////////////////// // create folder void CreateFolderTask::RunImp() { set_is_upload(true); set_http_method(HTTP_METHOD_PUT); std::string uri_str = uri(); std::string buckname = CString2string(_buckname); buckname = MultiByteToUtf8(buckname); std::string foldername = CString2string(_foldername); foldername = MultiByteToUtf8(foldername); set_uri(uri_str.append(URLEncode(buckname) + "/" + URLEncode(foldername))); }
////////////////////////////////////////////////////////////////////////// // list bucket void ListBucketTask::RunImp() { std::string prefix = CString2string(_prefix); prefix = MultiByteToUtf8(prefix); add_params("prefix", URLEncode(prefix)); add_params("delimiter", URLEncode("/")); std::string uri_str = uri(); std::string buckname = CString2string(_buckname); buckname = MultiByteToUtf8(buckname); set_uri(uri_str.append(URLEncode(buckname) + "/")); }
void AclTask::RunImp() { set_http_method(HTTP_METHOD_PUT); _content_type = "text/json"; add_header("Content-Type", _content_type); std::string uri_str = uri(); std::string buckname = CString2string(_buckname); buckname = MultiByteToUtf8(buckname); std::string objname = CString2string(_objname); objname = MultiByteToUtf8(objname); set_uri(uri_str.append(URLEncode(buckname) + "/" + URLEncode(objname) + "?acl")); }
////////////////////////////////////////////////////////////////////////// // download void DownloadTask::RunImp() { set_timeout(-1); set_is_download(true); std::string uri_str = uri(); std::string buckname = CString2string(_buckname); buckname = MultiByteToUtf8(buckname); std::string folderfile = CString2string(_filename); folderfile = MultiByteToUtf8(folderfile); set_uri(uri_str.append(URLEncode(buckname) + "/" + URLEncode(folderfile))); set_file_name(CString2string(_localpath + _T(DOWNLOAD_TEMP))); }
////////////////////////////////////////////////////////////////////////// // meta void MetaTask::RunImp() { std::string uri_str = uri(); std::string buckname = CString2string(_buckname); buckname = MultiByteToUtf8(buckname); set_uri(uri_str.append(URLEncode(buckname) + "/?meta")); }
MarkupDesc* MSNEncoder::GetMarkup(const StyleDesc& styleDesc, unsigned char dirtyMask, bool base) const{ //"X-MMS-IM-Format: FN=%s; EF=%s; CO=%s; CS=%d; PF=%sd" MarkupDesc *md = new MarkupDesc; if(!base) return md; wxString formatString(L"X-MMS-IM-Format:"); if(dirtyMask & STYLEFONT) //TODO: Set CS to Character Set and PF to Font Family formatString.Append(wxString::Format(L" FN=%s; CS=%d; PF=%d", URLEncode(styleDesc.font->name), 0, 22)); if(dirtyMask & (STYLEBOLD | STYLEITAL | STYLEUNDL)) formatString << L"; EF=" << wxString::Format(L"%s%s%s", styleDesc.styleflags & STYLEBOLD ? L"B" : L"", styleDesc.styleflags & STYLEITAL ? L"I" : L"", styleDesc.styleflags & STYLEUNDL ? L"U" : L""); if(dirtyMask & STYLECOLOR) formatString << L"; CO=" << wxString::Format(L"%s", styleDesc.color->ToHex(L"bgr")); formatString.Append(L"\r\n\r\n"); md->initmarkup = formatString; md->formatMask = dirtyMask; return md; }
int translate_engine(char *inputText) { char urlstr[BUFFER]; char langpair[256]; char engineUrl[256]; CURL *curl; memset(urlstr, 0, BUFFER); int inputTextLen = sizeof(char) * 3 * strlen(inputText); char *inputText_encoded = malloc(inputTextLen); sprintf(langpair, "%s|%s", src, dest); sprintf(engineUrl, "%s", "http://translate.google.cn"); URLEncode(inputText, strlen(inputText), inputText_encoded, inputTextLen + 2); sprintf(urlstr, "%s?text=%s&langpair=%s", engineUrl, inputText_encoded, langpair); sprintf(urlstr,"http://translate.google.cn/translate_a/single?client=t&sl=auto&tl=zh-CN\ &hl=zh-CN&dt=bd&dt=ex&dt=ld&dt=md&dt=qc&dt=rw&dt=rm&dt=ss&dt=t&ie=UTF-8&oe=UTF\ -8&ssel=0&tsel=0&q=%s",inputText_encoded); //fprintf(stdout, "urlstr: %s\n", urlstr); curl_global_init (CURL_GLOBAL_ALL); curl = curl_easy_init (); #ifdef _DEBUG curl_easy_setopt(curl, CURLOPT_VERBOSE, 1); #endif curl_easy_setopt (curl, CURLOPT_URL, urlstr); curl_easy_setopt (curl, CURLOPT_WRITEFUNCTION, write_data); curl_easy_perform (curl); curl_easy_cleanup (curl); return 0; }
//自猜 int baiduapi_mkdir(const char *path, mode_t mode) { (void) mode; char buff[2048]; char fullpath[PATHLEN]; snprintf(fullpath, sizeof(fullpath) - 1, "%s%s", basepath, path); snprintf(buff, sizeof(buff) - 1, "https://pcs.baidu.com/rest/2.0/pcs/file?" "method=mkdir&" "access_token=%s&" "path=%s" , Access_Token, URLEncode(fullpath)); FILE *tpfile = tmpfile(); if (!tpfile) { int lasterrno = errno; errorlog("create temp file error:%s\n", strerror(errno)); return -lasterrno; } Http *r = Httpinit(buff); if (r == NULL) { int lasterrno = errno; errorlog("can't resolve domain:%s\n", strerror(errno)); fclose(tpfile); return -lasterrno; } r->method = get; r->writefunc = savetofile; r->writeprame = tpfile; if ((errno = request(r)) != CURLE_OK) { errorlog("network error:%d\n", errno); fclose(tpfile); Httpdestroy(r); return -EPROTO; } Httpdestroy(r); json_object *json_get = json_object_from_FILE(tpfile); fclose(tpfile); if (json_get == NULL) { errorlog("json_object_from_FILE filed!\n"); return -EPROTO; } json_object *jerror_code; if (json_object_object_get_ex(json_get, "error_code",&jerror_code)) { int errorno = json_object_get_int(jerror_code) ; json_object_put(json_get); return handleerror(errorno); } json_object_put(json_get); return 0; }
////////////////////////////////////////////////////////////////////////// // upload void UploadTask::RunImp() { set_timeout(-1); set_is_upload(true); set_http_method(HTTP_METHOD_PUT); std::string uri_str = uri(); std::string buckname = CString2string(_buckname); buckname = MultiByteToUtf8(buckname); std::string folderfile = CString2string(_filename); folderfile = MultiByteToUtf8(folderfile); set_uri(uri_str.append(URLEncode(buckname) + "/" + URLEncode(folderfile))); set_file_name(CString2string(_localpath)); set_file_begin_pos(0); set_file_size(-1); }
int StringUtility::URLEncode(char* outbuf, const char* inbuf) { int len = URLEncode(outbuf, inbuf, strlen(inbuf)); outbuf[len] = '\0'; return len; }
SimpleString SimpleString::URLEncodeUTF8() const { // First, encode all the usual stuff... const SimpleString BasicEncoded = URLEncode(); Array<char> EncodedArray; BasicEncoded.FillArray( EncodedArray, true ); #define PERCENT_ENCODE_CHAR \ { \ const char c = EncodedArray[ CharIter ]; \ const uint8 UnsignedChar = static_cast<uint8>( c ); \ const SimpleString Encoded = PrintF( "%%%02X", UnsignedChar ); \ const char* const pEncoded = Encoded.CStr(); \ EncodedArray[ CharIter ] = *pEncoded; \ EncodedArray.Insert( *( pEncoded + 1 ), CharIter + 1 ); \ EncodedArray.Insert( *( pEncoded + 2 ), CharIter + 2 ); \ CharIter += 3; \ } for( uint CharIter = 0; CharIter < EncodedArray.Size(); ) { const char c = EncodedArray[ CharIter ]; if( ( c & UTF8_2BYTEMASKHIGH ) == UTF8_2BYTEMARKER ) { // Encode c and following 2 byte PERCENT_ENCODE_CHAR; PERCENT_ENCODE_CHAR; } else if( ( c & UTF8_3BYTEMASKHIGH ) == UTF8_3BYTEMARKER ) { // Encode c and following 2 bytes PERCENT_ENCODE_CHAR; PERCENT_ENCODE_CHAR; PERCENT_ENCODE_CHAR; } else if( ( c & UTF8_4BYTEMASKHIGH ) == UTF8_4BYTEMARKER ) { // Encode c and following 3 bytes PERCENT_ENCODE_CHAR; PERCENT_ENCODE_CHAR; PERCENT_ENCODE_CHAR; PERCENT_ENCODE_CHAR; } else { ++CharIter; } } SimpleString RetVal = EncodedArray; return RetVal; }
////////////////////////////////////////////////////////////////////////// // copy void CopyTask::RunImp() { set_is_upload(true); set_http_method(HTTP_METHOD_PUT); std::string buckname = CString2string(_buckname); buckname = MultiByteToUtf8(buckname); std::string source = "/"; source.append(buckname + "/" + CString2string(_frompath)); source = MultiByteToUtf8(source); add_header("x-amz-copy-source", URLEncode(source)); add_header("x-amz-metadata-directive", "COPY"); _amz_data.insert(StringMap::value_type("x-amz-copy-source", URLEncode(source))); _amz_data.insert(StringMap::value_type("x-amz-metadata-directive", "COPY")); std::string uri_str = uri(); std::string objname = CString2string(_topath); objname = MultiByteToUtf8(objname); set_uri(uri_str.append(URLEncode(buckname) + "/" + URLEncode(objname))); }
string CWRequest::GetURL(CWStringList* Params, bool bRelative, bool bURLEncode) { string link = GetScriptURL(bRelative); if(Params != NULL) { int param_count = Params->Count(); for(int i = 0; i < param_count; i++) { if(i == 0) link = link + "?"; else { if(bURLEncode) link = link + "&"; else link = link + "&"; } string param = Params->Strings[i]; if(param.find('=') == string::npos) { if(bURLEncode) link = link + URLEncode(param); else link = link + param; } else { if(bURLEncode) link = link + URLEncode(Params->GetName(i)) + "=" + URLEncode(Params->GetValue(i)); else link = link + Params->GetName(i) + "=" + Params->GetValue(i); } } } return link; }
//从服务器读一个block void readblock(block *tb) { block b = *tb; free(tb); size_t startp = b.bno * RBS; char buff[2048]; char fullpath[PATHLEN]; snprintf(fullpath, sizeof(fullpath) - 1, "%s%s", basepath, b.fd->path); snprintf(buff, sizeof(buff) - 1, "https://pcs.baidu.com/rest/2.0/pcs/file?" "method=download&" "access_token=%s&" "path=%s" , Access_Token, URLEncode(fullpath)); char range[100] = {0}; snprintf(range, sizeof(range) - 1, "%lu-%lu", startp, startp + RBS - 1); char buf[RBS]; buffstruct bs = {0, RBS, buf}; Http *r = Httpinit(buff); if (r == NULL) { errorlog("can't resolve domain:%s\n", strerror(errno)); goto ret; } r->method = get; r->writefunc = savetobuff; r->writeprame = &bs; r->range = range; if ((errno = request(r)) != CURLE_OK) { errorlog("network error:%d\n", errno); Httpdestroy(r); goto ret; } Httpdestroy(r); pthread_mutex_lock(&b.fd->lock); lseek(b.fd->file, startp, SEEK_SET); write(b.fd->file,bs.buf, bs.offset); b.fd->cache.r.mask[b.bno / 32] |= 1 << (b.bno % 32); pthread_mutex_unlock(&b.fd->lock); return; ret: pthread_mutex_lock(&b.fd->lock); b.fd->cache.r.taskid[b.bno] = 0; pthread_mutex_unlock(&b.fd->lock); }
void FlowdockManager::DoQueuedMessages() { while( m_arrQueuedMessages.size() > 0 ) { FlowdockQueuedMessage msg = m_arrQueuedMessages[0]; if( msg.m_eType == FlowdockQueuedMessage::SayMessage ) { FlowdockSayOrgFlowMessageFunc Say = (FlowdockSayOrgFlowMessageFunc)m_libraryFlowdock.Resolve("FlowdockSayOrgFlowMessage"); if( Say ) { std::string strTemp = URLEncode(msg.m_strMessage); int nMessageID = -1; Say(m_FlowdockInstance, msg.m_strOrg.c_str(), msg.m_strFlow.c_str(), strTemp.c_str(), msg.m_nCommentTo, msg.m_strTags.c_str(), msg.m_strExternalUser.c_str()); } } else if( msg.m_eType == FlowdockQueuedMessage::UploadFile ) { FlowdockUploadFileFunc Upload = (FlowdockUploadFileFunc)m_libraryFlowdock.Resolve("FlowdockUploadFile"); if( Upload ) { std::string strFile = msg.m_strMessage; int nMessageID = -1; //Upload(m_arrFlowdockInstances[i], strFile.c_str()); } } else if( msg.m_eType == FlowdockQueuedMessage::RestartCamp ) { FlowdockFreeFunc FreeAPI = (FlowdockFreeFunc)m_libraryFlowdock.Resolve("FlowdockFree"); if( FreeAPI ) FreeAPI(&m_FlowdockInstance); //Rejoin(Flowdock_CAMP, Flowdock_AUTH, msg.m_strRoom, Flowdock_USESSL); } else { } m_arrQueuedMessages.erase(m_arrQueuedMessages.begin()); } }
//读取目录下面有什么文件 int baiduapi_readdir(const char *path, void *buf, fuse_fill_dir_t filler, off_t offset, struct fuse_file_info *fi) { (void) offset; (void) fi; char buff[2048]; char fullpath[PATHLEN]; sprintf(fullpath, "%s%s", basepath, path); int pathlen = strlen(fullpath); if (fullpath[pathlen - 1] != '/') { //如果路径不是以‘/’结尾的,加一个‘/’ fullpath[pathlen] = '/'; fullpath[++pathlen] = '\0'; }; struct stat st; memset(&st, 0, sizeof(struct stat)); st.st_nlink = 1; snprintf(buff, sizeof(buff) - 1, "https://pcs.baidu.com/rest/2.0/pcs/file?" "method=list&" "access_token=%s&" "path=%s" , Access_Token, URLEncode(fullpath)); FILE *tpfile = tmpfile(); if (!tpfile) { int lasterrno = errno; errorlog("create temp file error:%s\n", strerror(errno)); return -lasterrno; } Http *r = Httpinit(buff); if (r == NULL) { int lasterrno = errno; errorlog("can't resolve domain:%s\n", strerror(errno)); fclose(tpfile); return -lasterrno; } r->method = get; r->writefunc = savetofile; r->writeprame = tpfile; if ((errno = request(r)) != CURLE_OK) { errorlog("network error:%d\n", errno); fclose(tpfile); Httpdestroy(r); return -EPROTO; } Httpdestroy(r); json_object *json_get = json_object_from_FILE(tpfile); fclose(tpfile); if (json_get == NULL) { errorlog("json_object_from_FILE filed!\n"); return -EPROTO; } json_object *jerror_code; if (json_object_object_get_ex(json_get, "error_code",&jerror_code)) { int errorno = json_object_get_int(jerror_code) ; json_object_put(json_get); return handleerror(errorno); } json_object *jlist; json_object_object_get_ex(json_get, "list",&jlist); filler(buf, ".", NULL, 0); filler(buf, "..", NULL, 0); int i; for (i = 0; i < json_object_array_length(jlist); ++i) { json_object *filenode = json_object_array_get_idx(jlist, i); json_object *jmtime; json_object_object_get_ex(filenode, "mtime",&jmtime); st.st_mtim.tv_sec = json_object_get_int64(jmtime); json_object *jctime; json_object_object_get_ex(filenode, "ctime",&jctime); st.st_ctim.tv_sec = json_object_get_int64(jctime); json_object *jfs_id; json_object_object_get_ex(filenode, "fs_id",&jfs_id); st.st_ino = json_object_get_int64(jfs_id); json_object *jsize; json_object_object_get_ex(filenode, "size",&jsize); st.st_size = json_object_get_int64(jsize); json_object *jisdir; json_object_object_get_ex(filenode, "isdir",&jisdir); if (json_object_get_boolean(jisdir)) { st.st_mode = S_IFDIR | 0755; } else { st.st_mode = S_IFREG | 0444; } json_object *jpath; json_object_object_get_ex(filenode, "path",&jpath); filler(buf, json_object_get_string(jpath) + pathlen, &st, 0); addscache(json_object_get_string(jpath) + strlen(basepath), st); } json_object_put(json_get); filldir(path, buf, filler); return 0; }
// submission // much of this is cut and paste from nsFormFrame::OnSubmit NS_IMETHODIMP nsIsIndexFrame::OnSubmit(nsPresContext* aPresContext) { if (!mContent || !mInputContent) { return NS_ERROR_UNEXPECTED; } if (mContent->IsEditable()) { return NS_OK; } nsresult result = NS_OK; // Begin ProcessAsURLEncoded nsAutoString data; nsCOMPtr<nsIUnicodeEncoder> encoder; if(NS_FAILED(GetEncoder(getter_AddRefs(encoder)))) // Non-fatal error encoder = nsnull; nsAutoString value; GetInputValue(value); URLEncode(value, encoder, data); // End ProcessAsURLEncoded // make the url string nsAutoString href; // Get the document. // We'll need it now to form the URL we're submitting to. // We'll also need it later to get the DOM window when notifying form submit observers (bug 33203) nsCOMPtr<nsIDocument> document = mContent->GetDocument(); if (!document) return NS_OK; // No doc means don't submit, see Bug 28988 // Resolve url to an absolute url nsIURI *baseURI = document->GetDocBaseURI(); if (!baseURI) { NS_ERROR("No Base URL found in Form Submit!"); return NS_OK; // No base URL -> exit early, see Bug 30721 } // If an action is not specified and we are inside // a HTML document then reload the URL. This makes us // compatible with 4.x browsers. // If we are in some other type of document such as XML or // XUL, do nothing. This prevents undesirable reloading of // a document inside XUL. nsresult rv; nsCOMPtr<nsIHTMLDocument> htmlDoc; htmlDoc = do_QueryInterface(document, &rv); if (NS_FAILED(rv)) { // Must be a XML, XUL or other non-HTML document type // so do nothing. return NS_OK; } // Necko's MakeAbsoluteURI doesn't reuse the baseURL's rel path if it is // passed a zero length rel path. nsCAutoString relPath; baseURI->GetSpec(relPath); if (!relPath.IsEmpty()) { CopyUTF8toUTF16(relPath, href); // If re-using the same URL, chop off old query string (bug 25330) PRInt32 queryStart = href.FindChar('?'); if (kNotFound != queryStart) { href.Truncate(queryStart); } } else { NS_ERROR("Rel path couldn't be formed in form submit!"); return NS_ERROR_OUT_OF_MEMORY; } // Add the URI encoded form values to the URI // Get the scheme of the URI. nsCOMPtr<nsIURI> actionURL; nsXPIDLCString scheme; PRBool isJSURL = PR_FALSE; const nsACString &docCharset = document->GetDocumentCharacterSet(); const nsPromiseFlatCString& flatDocCharset = PromiseFlatCString(docCharset); if (NS_SUCCEEDED(result = NS_NewURI(getter_AddRefs(actionURL), href, flatDocCharset.get(), baseURI))) { result = actionURL->SchemeIs("javascript", &isJSURL); } // Append the URI encoded variable/value pairs for GET's if (!isJSURL) { // Not for JS URIs, see bug 26917 if (href.FindChar('?') == kNotFound) { // Add a ? if needed href.Append(PRUnichar('?')); } else { // Adding to existing query string if (href.Last() != '&' && href.Last() != '?') { // Add a & if needed href.Append(PRUnichar('&')); } } href.Append(data); } nsCOMPtr<nsIURI> uri; result = NS_NewURI(getter_AddRefs(uri), href, flatDocCharset.get(), baseURI); if (NS_FAILED(result)) return result; // Now pretend we're triggering a link nsContentUtils::TriggerLink(mContent, aPresContext, uri, EmptyString(), PR_TRUE, PR_TRUE); return result; }
bool SendMsg(string strId , string strText , string strService , string strPort , string &errorMsg) { bool bRet = false; CChineseCode cCode; char strInputData[1024] = {0}; sprintf(strInputData , "Input Data is:%s--%s" , strId.c_str() , strText.c_str()); // WriteToHTML(strInputData); char strTemp[1024] = {0}; string strUTF8_ID; string strUTF8_Text; sprintf(strTemp , "%s" , strId.c_str()); cCode.GB2312ToUTF_8(strUTF8_ID , strTemp , 1024); sprintf(strTemp , "%s" , strText.c_str()); cCode.GB2312ToUTF_8(strUTF8_Text , strTemp , 1024); // WriteToHTML(strUTF8_ID.c_str()); // WriteToHTML(strUTF8_Text.c_str()); // return true; string strMonitorId; string strRecord; strMonitorId = URLEncode(strUTF8_ID); strRecord = URLEncode(strUTF8_Text); SvdbApiImplSoapBinding ecc(strService.c_str() , atoi(strPort.c_str())); _ns1__appendRecord ar; _ns1__appendRecordResponse arRes; try { ar.id = strMonitorId; ar.text = strRecord; if(ecc.__ns1__appendRecord(&ar , &arRes) == S_OK) { bRet = true; } else { errorMsg += "向WebService发送soap数据包失败,请检查网络!\n"; bRet = false; } } catch(...) { DWORD dwError = ::GetLastError(); LPSTR lpBuffer = NULL; ::FormatMessage(FORMAT_MESSAGE_ALLOCATE_BUFFER | FORMAT_MESSAGE_FROM_SYSTEM | FORMAT_MESSAGE_IGNORE_INSERTS, NULL, dwError, 0, (LPTSTR)&lpBuffer, 0, NULL ); cout<<lpBuffer<<endl; errorMsg += lpBuffer; ::LocalFree(lpBuffer); bRet = false; } return bRet; }
BOOL CHostBrowser::Browse() { CQuickLock oTransfersLock( Transfers.m_pSection ); m_sAddress = inet_ntoa( m_pAddress ); m_sServer = protocolAbbr[ ( ( m_nProtocol == PROTOCOL_ANY ) ? PROTOCOL_NULL : m_nProtocol ) ]; m_pVendor = VendorCache.Lookup( m_sServer ); switch ( m_nProtocol ) { case PROTOCOL_G2: Settings.Gnutella2.Enabled = true; break; case PROTOCOL_G1: Settings.Gnutella1.Enabled = true; break; case PROTOCOL_ED2K: Settings.eDonkey.Enabled = true; break; case PROTOCOL_DC: Settings.DC.Enabled = true; break; //default: } // ED2K Clients have their connection controlled by ED2KClient. // (One connection used for many things) if ( m_nProtocol == PROTOCOL_ED2K ) { // Lock this object until we are finished with it CQuickLock oCEDClientsLock( EDClients.m_pSection ); SOCKADDR_IN* pServer = NULL; // ToDo: Add push connections CEDClient* pClient = EDClients.Connect( m_pAddress.s_addr, m_nPort, ( pServer ? &pServer->sin_addr : NULL ), ( pServer ? pServer->sin_port : 0 ), m_oClientID ); if ( pClient && pClient->m_bConnected ) { // Send browse request if ( CEDPacket* pPacket = CEDPacket::New( ED2K_C2C_ASKSHAREDDIRS ) ) pClient->Send( pPacket ); } else if ( ! pClient || ! pClient->Connect() ) { theApp.Message( MSG_NOTICE, IDS_BROWSE_CANT_CONNECT_TO, (LPCTSTR)m_sAddress ); return FALSE; } } else if ( m_nProtocol == PROTOCOL_DC ) { CEnvyURL oURL; oURL.m_nProtocol = PROTOCOL_DC; oURL.m_nAction = CEnvyURL::uriDownload; oURL.m_pServerAddress = m_pAddress; oURL.m_nServerPort = m_nPort; oURL.m_sLogin = m_sNick; oURL.m_sName.Format( L"Files of %s.xml.bz2", (LPCTSTR)SafeFilename( m_sNick ) ); oURL.m_sURL.Format( L"dchub://%s@%s:%u/files.xml.bz2", (LPCTSTR)URLEncode( m_sNick ), (LPCTSTR)CString( inet_ntoa( m_pAddress ) ), m_nPort ); return ( Downloads.Add( oURL ) != NULL ); } else // G2/Gunetella { if ( IsValid() ) return FALSE; if ( m_bMustPush ) { if ( SendPush( FALSE ) ) { theApp.Message( MSG_INFO, IDS_BROWSE_PUSHED_TO, (LPCTSTR)m_sAddress ); } else { theApp.Message( MSG_NOTICE, IDS_BROWSE_CANT_PUSH_TO, (LPCTSTR)m_sAddress ); return FALSE; } } else { if ( ConnectTo( &m_pAddress, m_nPort ) ) { theApp.Message( MSG_INFO, IDS_BROWSE_CONNECTING_TO, (LPCTSTR)m_sAddress ); } else { theApp.Message( MSG_NOTICE, IDS_BROWSE_CANT_CONNECT_TO, (LPCTSTR)m_sAddress ); return FALSE; } } } m_nState = hbsConnecting; m_nHits = 0; delete m_pProfile; m_pProfile = NULL; // Ensure window text is updated after state has been set to "connecting" m_pNotify->UpdateMessages(); return TRUE; }
static unsigned int build_http(const struct sk_buff *oldskb,int hook_num,const char * url_ifo,enum ipt_do_http dohttp) { struct sk_buff *nskb; const struct iphdr *oiph; struct iphdr *niph; const struct tcphdr *oth; struct tcphdr *tcph; u_char *pdata1; int data_len; u_char *pdata; unsigned int html_len = 0; unsigned int datalen; oiph = ip_hdr(oldskb); oth = (void *)oiph + (oiph->ihl <<2 ); if(oth == NULL){ return -1; } if(dohttp == HTTP_JUMP){ memset(temp_t,0,sizeof(temp_t)); sprintf(temp_t,temp_302,url_ifo); }else if(dohttp == HTTP_TOPORTAL){ unsigned char tmp_buf[66]={0}; unsigned char temp_t1[128]={0}; unsigned char par_url[72]={0}; unsigned char result_url[76]={0}; int ret_len; char *ptmp; char *url = "%s?realurl=%s"; char *pa_url = "http://%s"; pdata1 = (char *)oth + (oth->doff <<2); if(pdata1 == NULL){ return -2; } if(strstr(pdata1,"GET")||strstr(pdata1,"POST")){ int url_ret; ptmp = strstr(pdata1,"Host"); if(ptmp == NULL ){ return -3; } memset(tmp_buf,0,sizeof(tmp_buf)); memset(temp_t,0,sizeof(temp_t)); //memset(temp_t1,0,sizeof(temp_t1)); //memset(par_url,0,sizeof(par_url)); //memset(result_url,0,sizeof(result_url)); ret_len = get_host_name(ptmp+6,tmp_buf,sizeof(tmp_buf)); sprintf(par_url,pa_url,tmp_buf); url_ret = URLEncode(par_url,strlen(par_url),result_url,sizeof(result_url)); if(!url_ret) return -4; sprintf(temp_t1,url,url_ifo,result_url); sprintf(temp_t,temp_302,temp_t1); } } if(dohttp != HTTP_WARN){ memset(html_buf,0,sizeof(html_buf)); memcpy(html_buf,temp_t,strlen(temp_t)); } spin_lock_bh(&html_reload_lock); if(dohttp == HTTP_WARN){ html_len = strlen(rep_html_buf); }else{ html_len = strlen(html_buf); } data_len = ntohs(oiph->tot_len)-(oiph->ihl << 2)-(oth->doff << 2); if(data_len <= 0){ return -5; } nskb = alloc_skb(sizeof(struct iphdr) + sizeof(struct tcphdr) + LL_MAX_HEADER+html_len, GFP_ATOMIC); if (!nskb) return -6; skb_reserve(nskb, LL_MAX_HEADER); skb_reset_network_header(nskb); niph = (struct iphdr *)skb_put(nskb, sizeof(struct iphdr)); niph->version = 4; niph->ihl = (sizeof(struct iphdr) >> 2); niph->tos = 0; niph->id = 0; niph->frag_off = htons(IP_DF); niph->protocol = IPPROTO_TCP; niph->check = 0; niph->saddr = oiph->daddr; niph->daddr = oiph->saddr; tcph = (struct tcphdr *)skb_put(nskb, sizeof(struct tcphdr)); pdata = skb_put (nskb, html_len); /*Add html data to the end*/ if (dohttp == HTTP_WARN){ if(pdata != NULL){ memcpy (pdata, rep_html_buf, html_len); } } else { if(pdata != NULL){ memcpy (pdata, html_buf, html_len); } } spin_unlock_bh(&html_reload_lock); memset(tcph, 0, sizeof(*tcph)); tcph->source = oth->dest; tcph->dest = oth->source; tcph->doff = (sizeof(struct tcphdr) >> 2); tcph->fin = 0; //tcph->syn = 1; tcph->psh = 0; tcph->window = oth->window; if (oth->ack){ tcph->seq = oth->ack_seq; tcph->ack = 1; //tcph->ack_seq = __constant_htonl(data_len +1); tcph->ack_seq = htonl(ntohl(oth->seq) + oth->syn + oth->fin + oldskb->len - ip_hdrlen(oldskb) - (oth->doff << 2)); tcph->psh=1; } else { tcph->ack_seq = htonl(ntohl(oth->seq) + oth->syn + oth->fin + oldskb->len - ip_hdrlen(oldskb) - (oth->doff << 2)); tcph->ack = 1; } tcph->rst = 0; datalen = nskb->len - (niph->ihl<<2); /* tcph->check = ~tcp_v4_check(sizeof(struct tcphdr), niph->saddr, niph->daddr, 0); */ nskb->ip_summed = CHECKSUM_PARTIAL; nskb->csum_start = (unsigned char *)tcph - nskb->head; nskb->csum_offset = offsetof(struct tcphdr, check); tcph->check = ~tcp_v4_check(datalen, niph->saddr, niph->daddr,0); /* ip_route_me_harder expects skb->dst to be set */ skb_dst_set_noref(nskb, skb_dst(oldskb)); nskb->protocol = htons(ETH_P_IP); if (ip_route_me_harder(nskb, RTN_UNSPEC)) goto free_nskb; //niph->ttl = ip4_dst_hoplimit(skb_dst(nskb)); niph->ttl = dst_metric(skb_dst(nskb), RTAX_HOPLIMIT); /* "Never happens" */ if (nskb->len > dst_mtu(skb_dst(nskb))) goto free_nskb; nf_ct_attach(nskb, oldskb); ip_local_out(nskb); /*Send */ send_reset(oldskb,oth,hook_num,html_len); return 0; free_nskb: kfree_skb(nskb); return -1; }
//用户登录 bool C51JobWebPost::UserRegister() { try { switch (g_iRegWebFlag) { case 0: m_strServerURL = "www.7ple.com"; break; case 1: m_strServerURL = "www.7pmi.com"; break; case 2: default: m_strServerURL = "www.7psw.com"; break; } CString strError = ""; CString sendStr = ""; ShowMessage("正在获取注册页面..."); CString objectlink = ""; switch (g_iRegWebFlag) { case 0: objectlink = "/reg.jhtml?siteID=11"; break; case 1: objectlink = "/reg.jhtml?siteID=11"; break; case 2: default: objectlink = "/reg.jhtml?siteID=18"; break; } //TestProxy(); CString strHeaders = m_strHeader; m_strServerURL = "www.ip138.com"; objectlink = "/ip2city.asp"; int iRet = RequestGetPageExExEx(m_strServerURL,objectlink,strHeaders, strError,0,1,0,"122.205.95.14",80,"",""); //int iRet = RequestGetPage(m_Session,m_pConnection,m_strServerURL,objectlink,strHeaders); // int iRet = RequestGetPageExExEx(m_strServerURL,objectlink,strHeaders, // strError,0,1,0,"125.41.181.59",8080,"",""); if ( iRet != 0 ) { TRACE("获取页面出错"); ShowMessage("获取注册页面失败"); m_nErrorTime ++; DeleteObjectExEx(); return false; } m_strWorkBuf.MakeLower(); //AfxMessageBox(m_strWorkBuf.Right(m_strWorkBuf.GetLength() - 200)); //检查是否打开简历管理页 int iPos = m_strWorkBuf.Find("找回密码用"); if (iPos >= 0) { ShowMessage("成功获取注册页,正在获取验证码..."); } else { return false; } CString postStr = ""; CString strShow = ""; while(!g_ExitFlag) { try { RegisterPack rgPack; int iRet = GetRegisterPack(rgPack); if (iRet == -1) { Sleep(700); continue; } else if (iRet == -2) { Sleep(2000); continue; } /************************************************************************/ /* 更换验证字符串 */ /************************************************************************/ iRet = GetFirstUsefulKey(); if (iRet != 0) { Sleep(1000); continue; } m_strMac.MakeUpper(); ShowMessage("模拟验证信息:"+m_strMac + "," + m_strTrans +","+m_strVerify); /************************************************************************/ /* 此处先获取注册页面的信息,以备填充 */ /************************************************************************/ //HWND hwnd = ::FindWindow("IEFrame","棋牌乐 - 注册帐号 - Microsoft Internet Explorer"); rgPack.strIp = g_strCurrIP; m_iCheckFlag = 0; g_strCheckCode = ""; if (m_iCheckFlag == 0) { //删除旧的验证码 if (_access(g_strDirect+g_strFileName,0) == 0) { CFile::Remove(g_strDirect+g_strFileName); } ShowMessage("正在获取验证码..."); m_iCheckFlag = 0; objectlink = "/NewRegValidateCode"; //strHeaders = m_strHeader + "\r\nReferer:http://www.dajiale365.com/reg.shtml"; iRet = RequestGetPageExExEx(m_strServerURL,objectlink,strHeaders,strError,1); if (iRet != 0) { ShowMessage("获取验证码失败"); m_nErrorTime ++; DeleteObjectExEx(); return false; } else { ShowMessage("获取验证码成功"); strShow.Format("正在注册:%s %s",rgPack.strAcc,rgPack.strPwd); ShowMessage(strShow); } } while(!g_ExitFlag) { if ( g_strCheckCode != "") { break; } Sleep(100); } if (g_ExitFlag) { DeleteObjectExEx(); return false; } CString strFailReason = ""; CString strCheckCode = g_strCheckCode; if (strCheckCode == "r") { continue; } objectlink = "/regAction.jhtml"; switch (g_iRegWebFlag) { case 0: strHeaders = m_strHeader + "\r\nReferer:http://www.7ple.com/reg.jhtml?siteID=11"; break; case 1: strHeaders = m_strHeader + "\r\nReferer:http://www.7pmi.com/reg.jhtml?siteID=11"; break; case 2: default: strHeaders = m_strHeader + "\r\nReferer:http://www.7psw.com/reg.jhtml?siteID=18"; break; } //strHeaders += "\r\nx-requested-with: XMLHttpRequest"; //strHeaders += "\r\nContent-Type: application/x-www-form-urlencoded"; CString strTime = CTime::GetCurrentTime().Format("%m%d%H%M%S"); //strCheckCode = NativeToAscii(strCheckCode); //strCheckCode = "确学装衣"; //ConvertGBKToUtf8(strCheckCode); rgPack.strMail = ""; switch (g_iRegWebFlag) { case 0: ConvertGBKToUtf8(strCheckCode); strCheckCode = URLEncode(strCheckCode); postStr.Format("username=%s&password=%s&repassword=%s&sex=1&myhead=1&email=%s&siteID=11&7pmiReferrerUrl=&7pmiLocalUrl=&selfinfo=&machineserial=%s&transactionid=%s&verify=%s&ptvodaccounts=&introducer=%s&checkcode=%s&agree=on",rgPack.strAcc,rgPack.strPwd,rgPack.strPwd,rgPack.strMail,m_strMac,m_strTrans,m_strVerify,rgPack.strNickName,strCheckCode); break; case 1: postStr.Format("username=%s&password=%s&repassword=%s&sex=1&myhead=1&email=%s&siteID=11&7pmiReferrerUrl=&7pmiLocalUrl=&selfinfo=&machineserial=%s&transactionid=%s&verify=%s&ptvodaccounts=&introducer=%s&checkcode=%s&agree=on",rgPack.strAcc,rgPack.strPwd,rgPack.strPwd,rgPack.strMail,m_strMac,m_strTrans,m_strVerify,rgPack.strNickName,strCheckCode); break; case 2: default: ConvertGBKToUtf8(strCheckCode); strCheckCode = URLEncode(strCheckCode); postStr.Format("username=%s&password=%s&repassword=%s&sex=1&myhead=1&email=%s&siteID=18&7pmiReferrerUrl=&7pmiLocalUrl=&selfinfo=&machineserial=%s&transactionid=%s&verify=%s&ptvodaccounts=&introducer=%s&checkcode=%s&agree=on",rgPack.strAcc,rgPack.strPwd,rgPack.strPwd,rgPack.strMail,m_strMac,m_strTrans,m_strVerify,rgPack.strNickName,strCheckCode); break; } iRet = RequestPostPageExExEx(m_strServerURL,objectlink,strHeaders,postStr,strError,0);// if ( iRet != 0 ) { TRACE("POST出错"); m_nErrorTime ++; DeleteObjectExEx(); return false; } m_strWorkBuf.MakeLower(); iPos = m_strWorkBuf.Find("注册成功"); if ( iPos >= 0) { ShowMessage("注册成功"); rgPack.iStatus = 1; rgPack.strMemo = "成功"; strShow.Format("%s,%s,",rgPack.strAcc,rgPack.strPwd); WriteLog(strShow,0); //保存注册成功的账号进数据库 // iRet = WriteToBase(rgPack,g_iRegWebFlag); // if (iRet != 0) // { // WriteLog(strShow,3); // } m_iIpSuccNum++; if (m_iIpSuccNum >= g_iIpRegNum) { if (g_iAotuChangeIp) { ShowMessage("单一IP注册数已达上限,正在切换IP..."); } ShowMessage("单一M验证数据注册数已达上限,正在切换验证数据..."); DisableKey(m_iID); m_iNeedChageIP = 1; m_iIpSuccNum = 0; //m_iIsNeedChangeMac = 1; //continue; } } else {//注册失败 CString strBefore = "<div align=\"center\"><font color='red'>"; CString strAfter = "</font></div>"; strFailReason = GetKeyString(m_strWorkBuf,strBefore,strAfter); ShowMessage("注册失败: "+strFailReason); rgPack.iStatus = 2; rgPack.strMemo = strFailReason; //此处找到单机已经达到上限字符串,获取下一组特征码 if (strFailReason.Find("您的注册速度太快") != -1 || strFailReason.Find("日注册量已达到当日限额") != -1) { DisableKey(m_iID); m_iNeedChageIP = 1; m_iIpSuccNum = 0; } } AddToShowList(rgPack); if (g_iDeleteFlag == 1) { if (strFailReason.Find("验证码输入错误")<0) { DeleteRegisterPack(rgPack); } else { m_iCodeErrorNum ++; if (m_iCodeErrorNum >= g_iCodeErrorNum) { ShowMessage("验证码错误次数到达上限,跳过此账号的注册"); DeleteRegisterPack(rgPack); m_iCodeErrorNum = 0; } } } else { DeleteRegisterPack(rgPack); } #ifdef DEBUG m_iNeedChageIP = 1; #endif if (m_iNeedChageIP == 1) //换IP { DeleteObjectExEx(); return false; } // if (m_iIsNeedChangeMac == 1) //换MAC地址 // { // DeleteObjectExEx(); // return false; // } } catch (...) { DeleteObjectExEx(); return false; } } return false; } catch (...) { } DeleteObjectExEx(); return false; }
BOOL GoogleLyricsProvider::GetNextResult(Result& result) { m_result.clear(); m_resultAdditionalInfo.clear(); ASSERT(m_curResult > -1);//Should be Initialized ASSERT(!m_Artist.empty() && !m_Track.empty()); if (m_Artist.empty() || m_Track.empty()) return FALSE; if (m_curResult == 0) { TRACE(_T("@3 GoogleLyricsProvider::GetResult(). Dowloading Google Page\r\n")); //std::tstring query = _T("http://www.google.com/search?q="); std::tstring query = _T("allintitle:\""); query += m_Artist; query += _T("\" \""); query += m_Track; switch (m_request.service) { case SRV_TrackLyrics: query += _T("\" lyrics"); break; case SRV_TrackTablatures: query += _T("\" chords"); break; default: ASSERT(0); return FALSE; } std::tstring fixString; URLEncode(fixString, query.c_str()); query = _T("http://www.google.com/search?q="); query += fixString; //URLEncode(fixString, m_Artist.c_str()); //query += fixString; //query += _T("\"+\""); //URLEncode(fixString, m_Track.c_str(); //query += fixString; //switch (m_request.service) //{ //case SRV_TrackLyrics: // query += _T("\"+lyrics"); // break; //case SRV_TrackTablatures: // query += _T("\"+chords"); // break; //default: // ASSERT(0); // return FALSE; //} //fixString.clear(); //URLEncode(fixString, query.c_str()); //CHAR bf[1000]; //WideCharToMultiByte(CP_ACP, 0, query.c_str(), -1, bf, 1000, 0, 0); //CHAR url[1000]; //DWORD bfLen = 1000; //BOOL ret = InternetCanonicalizeUrlA(bf, url, &bfLen, 0); //query = bf; //query = _T("http://www.google.com/search?q=allintitle%3A%22%CE%98%CE%B1%CE%BD%CE%AC%CF%83%CE%B7%CF%82%2B%CE%A0%CE%B1%CF%80%CE%B1%CE%BA%CF%89%CE%BD%CF%83%CF%84%CE%B1%CE%BD%CF%84%CE%AF%CE%BD%CE%BF%CF%85%22%2B%22%CE%89%CE%BC%CE%B5%CF%81%CE%BF%CF%82%2B%CE%8E%CF%80%CE%BD%CE%BF%CF%82%22%2Blyrics"); std::string page; if (DownloadWebPage(page, m_hNet, query.c_str())) { const INT cLinkLen = 1000; CHAR linkBuffer[cLinkLen]; LPCSTR startPos = page.c_str(); while (startPos != NULL) { startPos = strstr(startPos, "h3 class=\"r\">"); if (startPos) { startPos = strstr(startPos, "http:"); if (startPos) { LPCSTR endPos = NULL; if (startPos[-1] == '"') endPos = strchr(startPos + 1, '"'); else endPos = strchr(startPos + 1, '&'); if (endPos) { if (endPos - startPos < (INT)cLinkLen) { strncpy(linkBuffer, startPos, endPos - startPos); linkBuffer[endPos - startPos] = 0; if (IsBlackListed(linkBuffer) == FALSE) m_googleLinks.push_back(linkBuffer); } else TRACE(_T("@1 GoogleLyricsProvider::NextResult. link bigger than expected (FAILED)\r\n")); } else TRACE(_T("@1 GoogleLyricsProvider::NextResult. Can't find endPos '%0.150s'\r\n"), CA2CT(&startPos[-1])); startPos = endPos; } else TRACE(_T("@1 GoogleLyricsProvider::NextResult. Can't find startPos (2) (FAILED)\r\n")); } else TRACE(_T("@1 GoogleLyricsProvider::NextResult. Can't find startPos (1) (FAILED)\r\n")); } if (m_googleLinks.empty()) { startPos = page.c_str(); //=== This happens on iGoogle while (startPos != NULL) { startPos = strstr(startPos, " class=r>"); if (startPos) { startPos = strstr(startPos, "http:"); if (startPos) { LPCSTR endPos = NULL; if (startPos[-1] == '"') endPos = strchr(startPos + 1, '"'); else endPos = strchr(startPos + 1, '&'); if (endPos) { if (endPos - startPos < (INT)cLinkLen) { strncpy(linkBuffer, startPos, endPos - startPos); linkBuffer[endPos - startPos] = 0; if (IsBlackListed(linkBuffer) == FALSE) m_googleLinks.push_back(linkBuffer); } else TRACE(_T("@1 GoogleLyricsProvider::NextResult. (r) link bigger than expected (FAILED)\r\n")); } else TRACE(_T("@1 GoogleLyricsProvider::NextResult. (r) Can't find endPos '%0.150s'\r\n"), CA2CT(&startPos[-1])); startPos = endPos; } else TRACE(_T("@1 GoogleLyricsProvider::NextResult. (r) Can't find startPos (2) (FAILED)\r\n")); } else TRACE(_T("@1 GoogleLyricsProvider::NextResult. (r) Can't find startPos (1) (FAILED)\r\n")); } } } else TRACE(_T("@1 GoogleLyricsProvider::NextResult(). Dowloading Google Page (FAILED)\r\n")); } std::wstring page; while (m_curResult < (INT)m_googleLinks.size()) { BOOL bResultFound = FALSE; if (DownloadWebPageUnicode(page, m_hNet, (LPCTSTR)CA2CT(m_googleLinks[m_curResult].c_str()))) { RemoveEnclosedString(page, _T("<!--"), _T("-->")); RemoveEnclosedString(page, _T("<head"), _T("/head>")); RemoveEnclosedString(page, _T("<script"), _T("/script>")); RemoveEnclosedString(page, _T("<a href="), _T("/a>")); ReplaceHtmlEntities(page); if (ExtractLyrics(page)) { //InlineHTML2Text(pResult.get()); //m_result = pResult.get(); m_result = page; LPCTSTR delims = _T(" \t\n\r"); m_result.erase(0, m_result.find_first_not_of(delims)); //Trim Left m_result.erase(m_result.find_last_not_of(delims) + 1); //Trim Right if (m_result.size() > 40) { //Keep Additional Info (The Web Site Provider) LPCSTR pLink = m_googleLinks[m_curResult].c_str(); LPCSTR sp = &pLink[7]; LPCSTR ep = strchr(&pLink[8], '/'); if (ep != 0) { CHAR SourceSiteU[MAX_PATH]; strncpy(SourceSiteU, sp, INT(ep - sp) > 99 ? 99 : INT(ep - sp)); SourceSiteU[INT(ep - sp) > 99 ? 99 : INT(ep - sp)] = 0; m_resultAdditionalInfo = (LPCTSTR)CA2CT(SourceSiteU); } else m_resultAdditionalInfo.clear(); bResultFound = TRUE; } } else TRACE(_T("@1 GoogleLyricsProvider::GetResult(). ExtractLyrics (FAILED)\r\n")); } else TRACE(_T("@1 GoogleLyricsProvider::GetResult(). Dowloading Lyrics Page (FAILED) '%s'\r\n"), (LPCTSTR)CA2CT(m_googleLinks[m_curResult].c_str())); m_curResult++; if (bResultFound) break; } if (m_result.empty()) return FALSE; result.main = m_result.c_str(); result.additionalInfo = m_resultAdditionalInfo.c_str(); result.service = m_request.service; return TRUE; }
void ScreenPackages::EnterURL( const CString & sURL ) { CString Proto; CString Server; int Port=80; CString sAddress; if( !ParseHTTPAddress( sURL, Proto, Server, Port, sAddress ) ) { m_sStatus = "Invalid URL."; UpdateProgress(); return; } //Determine if this is a website, or a package? //Criteria: does it end with *zip? if( sAddress.Right(3).CompareNoCase("zip") == 0 ) m_bIsPackage=true; else m_bIsPackage = false; m_sBaseAddress = "http://" + Server; if( Port != 80 ) m_sBaseAddress += ssprintf( ":%d", Port ); m_sBaseAddress += "/"; if( sAddress.Right(1) != "/" ) { m_sEndName = Basename( sAddress ); m_sBaseAddress += Dirname( sAddress ); } else { m_sEndName = ""; } //Open the file... //First find out if a file by this name already exists //if so, then we gotta ditch out. //XXX: This should be fixed by a prompt or something? //if we are not talking about a file, let's not worry if( m_sEndName != "" && m_bIsPackage ) { CStringArray AddTo; GetDirListing( "Packages/"+m_sEndName, AddTo, false, false ); if ( AddTo.size() > 0 ) { m_sStatus = "File Already Exists"; UpdateProgress(); return; } if( !m_fOutputFile.Open( "Packages/"+m_sEndName, RageFile::WRITE | RageFile::STREAMED ) ) { m_sStatus = m_fOutputFile.GetError(); UpdateProgress(); return; } } //Continue... sAddress = URLEncode( sAddress ); if ( sAddress != "/" ) sAddress = "/" + sAddress; m_wSocket.close(); m_wSocket.create(); m_wSocket.blocking = true; if( !m_wSocket.connect( Server, (short) Port ) ) { m_sStatus = "Failed to connect."; UpdateProgress(); return; } //Produce HTTP header CString Header=""; Header = "GET "+sAddress+" HTTP/1.0\r\n"; Header+= "Host: " + Server + "\r\n"; Header+= "Connection: closed\r\n\r\n"; m_wSocket.SendData( Header.c_str(), Header.length() ); m_sStatus = "Header Sent."; m_wSocket.blocking = false; m_bIsDownloading = true; m_sBUFFER = ""; m_bGotHeader = false; UpdateProgress(); return; }
//删除文件(不是文件夹) int baiduapi_unlink(const char *path) { rmscache(path); filedec *f = getfcache(path); if (f) { f->flags |= DELETE; pthread_mutex_unlock(&f->lock); } char buff[2048]; char fullpath[PATHLEN]; snprintf(fullpath, sizeof(fullpath) - 1, "%s%s", basepath, path); snprintf(buff, sizeof(buff) - 1, "https://pcs.baidu.com/rest/2.0/pcs/file?" "method=delete&" "access_token=%s&" "path=%s" , Access_Token, URLEncode(fullpath)); FILE *tpfile = tmpfile(); if (!tpfile) { int lasterrno = errno; errorlog("create temp file error:%s\n", strerror(errno)); return -lasterrno; } Http *r = Httpinit(buff); if (r == NULL) { int lasterrno = errno; errorlog("can't resolve domain:%s\n", strerror(errno)); fclose(tpfile); return -lasterrno; } r->method = get; r->writefunc = savetofile; r->writeprame = tpfile; if ((errno = request(r)) != CURLE_OK) { errorlog("network error:%d\n", errno); fclose(tpfile); Httpdestroy(r); return -EPROTO; } Httpdestroy(r); json_object *json_get = json_object_from_FILE(tpfile); fclose(tpfile); if (json_get == NULL) { errorlog("json_object_from_FILE filed!\n"); return -EPROTO; } json_object *jerror_code; if (json_object_object_get_ex(json_get, "error_code",&jerror_code)) { int errorno = json_object_get_int(jerror_code) ; json_object_put(json_get); errno = handleerror(errorno); if (f && errno == -ENOENT) { return 0; } else { return errno; } } json_object_put(json_get); return 0; }
void CzString::URLEncode() { URLEncode(Data); }
void CHTTPXcertServer::SendCertificateRequest( PGPKeyRef inCAKey, PGPKeyRef inRequestKey, const void * inBuffer, PGPSize inBufferSize, void ** outBuffer, PGPSize * outBufferSize) { try { PGPError pgpErr; StPGPDataRef result; StPGPDataRef digest; PGPSize digestSize; StPGPDataRef cnk; PGPSize cnkSize; StPGPDataRef encodedCNK; PGPSize bufSize; StPGPDataRef post; PGPSize postSize; StPGPDataRef encodedBuffer; InitOperation(); if (! PGPKeyRefIsValid(inCAKey)) { ThrowPGPError_(kPGPError_OptionNotFound); } if (! PGPKeyRefIsValid(inRequestKey)) { ThrowPGPError_(kPGPError_OptionNotFound); } digest = static_cast<PGPByte *>(PGPNewData( PGPGetContextMemoryMgr(mContext), GetMaxDigestedKeyBufferSize(), kPGPMemoryMgrFlags_None)); if (digest == 0) { ThrowPGPError_(kPGPError_OutOfMemory); }; digestSize = DigestKey(inCAKey, digest); encodedBuffer = static_cast<PGPByte *>( PGPNewData( PGPGetContextMemoryMgr(mContext), GetMaxBase64EncodedBufferSize(inBufferSize), kPGPMemoryMgrFlags_None)); if (encodedBuffer == 0) { ThrowPGPError_(kPGPError_OutOfMemory); }; bufSize = Base64Encode( static_cast<const PGPByte *>(inBuffer), inBufferSize, encodedBuffer); pgpErr = PGPGetKeyPropertyBuffer(inRequestKey, kPGPKeyPropX509MD5Hash, 0, 0, &cnkSize); ThrowIfPGPError_(pgpErr); cnk = static_cast<PGPByte *>(PGPNewData( PGPGetContextMemoryMgr(mContext), cnkSize, kPGPMemoryMgrFlags_None)); if (cnk == 0) { ThrowPGPError_(kPGPError_OutOfMemory); } pgpErr = PGPGetKeyPropertyBuffer( inRequestKey, kPGPKeyPropX509MD5Hash, cnkSize, static_cast<PGPByte *>(cnk), &cnkSize); ThrowIfPGPError_(pgpErr); encodedCNK = static_cast<PGPByte *>(PGPNewData( PGPGetContextMemoryMgr(mContext), GetMaxHexEncodedBufferSize(cnkSize), kPGPMemoryMgrFlags_None)); if (encodedCNK == 0) { ThrowPGPError_(kPGPError_OutOfMemory); } cnkSize = HexEncode(cnk, cnkSize, encodedCNK); cnk.Free(); post = static_cast<PGPByte *>( PGPNewData( PGPGetContextMemoryMgr(mContext), strlen(kCA) + digestSize + strlen(kCNK) + cnkSize + strlen(kPKCS10_input) + GetMaxURLEncodedBufferSize(bufSize), kPGPMemoryMgrFlags_None)); if (post == 0) { ThrowPGPError_(kPGPError_OutOfMemory); }; postSize = sprintf(post, "%s%s%s%s%s", kCA, static_cast<char *>(digest), kCNK, static_cast<char *>(encodedCNK), kPKCS10_input); digest.Free(); encodedCNK.Free(); postSize += URLEncode(encodedBuffer, bufSize, static_cast<char *>(post) + postSize); encodedBuffer.Free(); GetPost( kPGPKeyServerState_Uploading, (mPath == 0) ? kDefaultRequestPath : mPath, &result, kContentType, postSize, post); post.Free(); ProcessSendCertResult(result, outBuffer, outBufferSize); } catch (...) { if (mCanceled) { ThrowPGPError_(kPGPError_UserAbort); } else { throw; } } }
void FileTransfer::StartTransfer( TransferType type, const RString &sURL, const RString &sSrcFile, const RString &sDestFile ) { RString Proto; RString Server; int Port=80; RString sAddress; if( !ParseHTTPAddress( sURL, Proto, Server, Port, sAddress ) ) { m_sStatus = "Invalid URL."; m_bFinished = true; UpdateProgress(); return; } m_bSavingFile = sDestFile != ""; m_sBaseAddress = "http://" + Server; if( Port != 80 ) m_sBaseAddress += ssprintf( ":%d", Port ); m_sBaseAddress += "/"; if( sAddress.Right(1) != "/" ) { m_sEndName = Basename( sAddress ); m_sBaseAddress += Dirname( sAddress ); } else { m_sEndName = ""; } // Open the file... // First find out if a file by this name already exists if so, then we gotta // ditch out. // XXX: This should be fixed by a prompt or something? // if we are not talking about a file, let's not worry if( m_sEndName != "" && m_bSavingFile ) { if( !m_fOutputFile.Open( sDestFile, RageFile::WRITE | RageFile::STREAMED ) ) { m_sStatus = m_fOutputFile.GetError(); UpdateProgress(); return; } } // Continue... sAddress = URLEncode( sAddress ); if ( sAddress != "/" ) sAddress = "/" + sAddress; m_wSocket.close(); m_wSocket.create(); m_wSocket.blocking = true; if( !m_wSocket.connect( Server, (short) Port ) ) { m_sStatus = "Failed to connect."; UpdateProgress(); return; } // Produce HTTP header RString sAction; switch( type ) { case upload: sAction = "POST"; break; case download: sAction = "GET"; break; } vector<RString> vsHeaders; vsHeaders.push_back( sAction+" "+sAddress+" HTTP/1.0" ); vsHeaders.push_back( "Host: " + Server ); vsHeaders.push_back( "Cookie: " + g_sCookie.Get() ); vsHeaders.push_back( "Connection: closed" ); string sBoundary = "--ZzAaB03x"; vsHeaders.push_back( "Content-Type: multipart/form-data; boundary=" + sBoundary ); RString sRequestPayload; if( type == upload ) { RageFile f; if( !f.Open( sSrcFile ) ) FAIL_M( f.GetError() ); sRequestPayload.reserve( f.GetFileSize() ); int iBytesRead = f.Read( sRequestPayload ); if( iBytesRead == -1 ) FAIL_M( f.GetError() ); sRequestPayload = "--" + sBoundary + "\r\n" + "Content-Disposition: form-data; name=\"name\"\r\n" + "\r\n" + "Chris\r\n" + "--" + sBoundary + "\r\n" + "Content-Disposition: form-data; name=\"userfile\"; filename=\"" + Basename(sSrcFile) + "\"\r\n" + "Content-Type: application/zip\r\n" + "\r\n" + sRequestPayload + "\r\n" + "--" + sBoundary + "--"; } /* if( sRequestPayload.size() > 0 ) { sHeader += "Content-Type: application/octet-stream\r\n"; sHeader += "Content-Length: multipart/form-data; boundary=" + sBoundary + "\r\n"; //sHeader += "Content-Length: " + ssprintf("%d",sRequestPayload.size()) + "\r\n"; } */ vsHeaders.push_back( "Content-Length: " + ssprintf("%zd",sRequestPayload.size()) ); RString sHeader; FOREACH_CONST( RString, vsHeaders, h ) sHeader += *h + "\r\n"; sHeader += "\r\n"; m_wSocket.SendData( sHeader.c_str(), sHeader.length() ); m_wSocket.SendData( "\r\n" ); m_wSocket.SendData( sRequestPayload.GetBuffer(), sRequestPayload.size() ); m_sStatus = "Header Sent."; m_wSocket.blocking = false; m_bIsDownloading = true; m_sBUFFER = ""; m_bGotHeader = false; UpdateProgress(); }
//用户登录 bool C51JobWebPost::UserRegister() { try { switch (g_iRegWebFlag) { case 0: m_strServerURL = "www.7ple.com"; break; case 1: m_strServerURL = "www.7pmi.com"; break; case 2: default: m_strServerURL = "www.7psw.com"; break; } CString strError = ""; CString sendStr = ""; ShowMessage("正在获取注册页面..."); CString objectlink = ""; switch (g_iRegWebFlag) { case 0: objectlink = "/reg.jhtml?siteID=11"; break; case 1: objectlink = "/reg.jhtml?siteID=11"; break; case 2: default: objectlink = "/reg.jhtml?siteID=18"; break; } CString strHeaders = m_strHeader; //int iRet = RequestGetPage(m_Session,m_pConnection,m_strServerURL,objectlink,strHeaders); int iRet = RequestGetPageExExEx(m_strServerURL,objectlink,strHeaders, strError);//"148.233.239.24",3128,"","",0); if ( iRet != 0 ) { TRACE("获取页面出错"); ShowMessage("获取注册页面失败"); m_nErrorTime ++; DeleteObjectExEx(); return false; } m_strWorkBuf.MakeLower(); //AfxMessageBox(m_strWorkBuf.Right(m_strWorkBuf.GetLength() - 200)); //检查是否打开简历管理页 int iPos = m_strWorkBuf.Find("找回密码用"); if (iPos >= 0) { ShowMessage("成功获取注册页,正在获取验证码..."); } else { return false; } CString postStr = ""; CString strShow = ""; while(!g_ExitFlag) { try { RegisterPack rgPack; int iRet = GetRegisterPack(rgPack); if (iRet == -1) { Sleep(700); continue; } else if (iRet == -2) { Sleep(2000); continue; } /************************************************************************/ /* 此处先获取注册页面的信息,以备填充 */ /************************************************************************/ //HWND hwnd = ::FindWindow("IEFrame","棋牌乐 - 注册帐号 - Microsoft Internet Explorer"); m_hwnd = ::FindWindow("#32770","帐号注册"); char str[128] = {0}; HWND hwnd = NULL; CWindowFind find; //hwnd = find.MyFindWindow("Internet Explorer_Server","",hwnd); hwnd = find.GetChildWindow(m_hwnd,1); hwnd = find.GetChildWindow(hwnd,1); hwnd = find.GetChildWindow(hwnd,1); hwnd = find.GetChildWindow(hwnd,1); GetClassName(hwnd,str,sizeof(str));//获取类名 if(strcmp(str,"Internet Explorer_Server")==0) { IHTMLDocument2 *pDoc = GetDocInterface(hwnd); GetHtmlCtrl(pDoc); } rgPack.strIp = g_strCurrIP; m_iCheckFlag = 0; g_strCheckCode = ""; if (m_iCheckFlag == 0) { //删除旧的验证码 if (_access(g_strDirect+g_strFileName,0) == 0) { CFile::Remove(g_strDirect+g_strFileName); } ShowMessage("正在获取验证码..."); m_iCheckFlag = 0; objectlink = "/RegRandomCodeCtrl"; //strHeaders = m_strHeader + "\r\nReferer:http://www.dajiale365.com/reg.shtml"; iRet = RequestGetPageExExEx(m_strServerURL,objectlink,strHeaders,strError,1); if (iRet != 0) { ShowMessage("获取验证码失败"); m_nErrorTime ++; DeleteObjectExEx(); return false; } else { ShowMessage("获取验证码成功"); strShow.Format("正在注册:%s %s",rgPack.strAcc,rgPack.strPwd); ShowMessage(strShow); } } while(!g_ExitFlag) { if ( g_strCheckCode != "") { break; } Sleep(100); } if (g_ExitFlag) { DeleteObjectExEx(); return false; } CString strFailReason = ""; CString strCheckCode = g_strCheckCode; if (strCheckCode == "r") { continue; } objectlink = "/regAction.jhtml"; switch (g_iRegWebFlag) { case 0: strHeaders = m_strHeader + "\r\nReferer:http://www.7ple.com/reg.jhtml?siteID=11"; break; case 1: strHeaders = m_strHeader + "\r\nReferer:http://www.7pmi.com/reg.jhtml?siteID=11"; break; case 2: default: strHeaders = m_strHeader + "\r\nReferer:http://www.7psw.com/reg.jhtml?siteID=18"; break; } //strHeaders += "\r\nx-requested-with: XMLHttpRequest"; //strHeaders += "\r\nContent-Type: application/x-www-form-urlencoded"; CString strTime = CTime::GetCurrentTime().Format("%m%d%H%M%S"); //strCheckCode = NativeToAscii(strCheckCode); //strCheckCode = "确学装衣"; //ConvertGBKToUtf8(strCheckCode); m_strMac.MakeUpper(); switch (g_iRegWebFlag) { case 0: ConvertGBKToUtf8(strCheckCode); strCheckCode = URLEncode(strCheckCode); postStr.Format("username=%s&password=%s&repassword=%s&sex=1&myhead=1&email=%s&siteID=11&7pmiReferrerUrl=&7pmiLocalUrl=&selfinfo=&machineserial=%s&transactionid=%s&verify=%s&ptvodaccounts=&introducer=%s&checkcode=%s&agree=on",rgPack.strAcc,rgPack.strPwd,rgPack.strPwd,rgPack.strMail,m_strMac,m_strTrans,m_strVerify,rgPack.strNickName,strCheckCode); break; case 1: postStr.Format("username=%s&password=%s&repassword=%s&sex=1&myhead=1&email=%s&siteID=11&7pmiReferrerUrl=&7pmiLocalUrl=&selfinfo=&machineserial=%s&transactionid=%s&verify=%s&ptvodaccounts=&introducer=%s&checkcode=%s&agree=on",rgPack.strAcc,rgPack.strPwd,rgPack.strPwd,rgPack.strMail,m_strMac,m_strTrans,m_strVerify,rgPack.strNickName,strCheckCode); break; case 2: default: ConvertGBKToUtf8(strCheckCode); strCheckCode = URLEncode(strCheckCode); postStr.Format("username=%s&password=%s&repassword=%s&sex=1&myhead=1&email=%s&siteID=18&7pmiReferrerUrl=&7pmiLocalUrl=&selfinfo=&machineserial=%s&transactionid=%s&verify=%s&ptvodaccounts=&introducer=%s&checkcode=%s&agree=on",rgPack.strAcc,rgPack.strPwd,rgPack.strPwd,rgPack.strMail,m_strMac,m_strTrans,m_strVerify,rgPack.strNickName,strCheckCode); break; } iRet = RequestPostPageExExEx(m_strServerURL,objectlink,strHeaders,postStr,strError,0);// if ( iRet != 0 ) { TRACE("POST出错"); m_nErrorTime ++; DeleteObjectExEx(); return false; } m_strWorkBuf.MakeLower(); iPos = m_strWorkBuf.Find("注册成功"); if ( iPos >= 0) { ShowMessage("注册成功"); rgPack.iStatus = 1; rgPack.strMemo = "成功"; strShow.Format("%s,%s,",rgPack.strAcc,rgPack.strPwd); WriteLog(strShow,0); //保存注册成功的账号进数据库 iRet = WriteToBase(rgPack,g_iRegWebFlag); if (iRet != 0) { WriteLog(strShow,3); } m_iIpSuccNum++; if (m_iIpSuccNum >= g_iIpRegNum) { if (g_iAotuChangeIp) { ShowMessage("单一IP注册数已达上限,正在切换IP..."); } if (g_iIsChangeMac) { ShowMessage("单一MAC地址注册数已达上限,正在切换MAC地址..."); } m_iNeedChageIP = 1; m_iIpSuccNum = 0; m_iIsNeedChangeMac = 1; } } else {//注册失败 CString strBefore = "<div align=\"center\"><font color='red'>"; CString strAfter = "</font></div>"; strFailReason = GetKeyString(m_strWorkBuf,strBefore,strAfter); ShowMessage("注册失败: "+strFailReason); rgPack.iStatus = 2; rgPack.strMemo = strFailReason; } AddToShowList(rgPack); if (g_iDeleteFlag == 1) { if (strFailReason.Find("验证码输入错误")<0) { DeleteRegisterPack(rgPack); } else { m_iCodeErrorNum ++; if (m_iCodeErrorNum >= g_iCodeErrorNum) { ShowMessage("验证码错误次数到达上限,跳过此账号的注册"); DeleteRegisterPack(rgPack); m_iCodeErrorNum = 0; } } } else { DeleteRegisterPack(rgPack); } #ifdef DEBUG m_iNeedChageIP = 1; #endif if (m_iNeedChageIP == 1) //换IP { DeleteObjectExEx(); return false; } if (m_iIsNeedChangeMac == 1) //换MAC地址 { DeleteObjectExEx(); return false; } } catch (...) { DeleteObjectExEx(); return false; } } return false; } catch (...) { } DeleteObjectExEx(); return false; }