int TcpSocketImpl::Recv(string &s) { char tmpbuf[MAXRECV]; int status=::recv(_socket,tmpbuf,MAXRECV,0); s.erase(); if (status==SOCKET_ERROR) { #if defined(linux) status=errno; #if defined(DEBUG) && defined(FileLogDebugDefined) ostringstream ostr; ostr<<"TcpSocketImpl::Recv(const &string): 'recv' received error "<<status<<".\n"; FileLogDebug(ostr.str()); #endif if (status>0) status=-status; #elif defined(WIN32) status=WSAGetLastError(); #if defined(DEBUG) && defined(FileLogDebugDefined) ostringstream ostr; ostr<<"TcpSocketImpl::Recv(const &string): 'recv' received error "<<status<<".\n"; FileLogDebug(ostr.str()); #endif if (status>0) status=-status; #else #error "TcpSocketImpl::Recv: Cannot return the appropriate error code." #endif return status; } else if ( status == 0 ) { #if defined(DEBUG) && defined(FileLogDebugDefined) ostringstream ostr; ostr<<"TcpSocketImpl::Recv(const &string): 'recv' received 0 bytes.\n"; FileLogDebug(ostr.str()); #endif return 0; } else { #if defined(DEBUG) && defined(FileLogDebugDefined) ostringstream ostr; ostr<<"TcpSocketImpl::Recv(const &string): 'recv' received "<<status<<" bytes:\n"; for (int i=0; i<status; i++) { int hexvalue; char *p=(char *) &hexvalue; hexvalue=Byte2Hex(tmpbuf[i]); ostr<<p[0]<<p[1]<<" "; } FileLogDebug(ostr.str()); #endif s.append(tmpbuf,status); return status; } }
int CScriptBuilder::ExtractDeclaration(int pos, string &declaration, int &type) { declaration = ""; type = 0; int start = pos; std::string token; int len = 0; asETokenClass t = asTC_WHITESPACE; // Skip white spaces and comments do { pos += len; t = engine->ParseToken(&modifiedScript[pos], modifiedScript.size() - pos, &len); } while ( t == asTC_WHITESPACE || t == asTC_COMMENT ); // We're expecting, either a class, interface, function, or variable declaration if( t == asTC_KEYWORD || t == asTC_IDENTIFIER ) { token.assign(&modifiedScript[pos], len); if( token == "interface" || token == "class" ) { // Skip white spaces and comments do { pos += len; t = engine->ParseToken(&modifiedScript[pos], modifiedScript.size() - pos, &len); } while ( t == asTC_WHITESPACE || t == asTC_COMMENT ); if( t == asTC_IDENTIFIER ) { type = 1; declaration.assign(&modifiedScript[pos], len); pos += len; return pos; } } else { // For function declarations, store everything up to the start of the statement block // For variable declaration store everything up until the first parenthesis, assignment, or end statement. // We'll only know if the declaration is a variable or function declaration when we see the statement block, or absense of a statement block. int varLength = 0; declaration.append(&modifiedScript[pos], len); pos += len; for(; pos < (int)modifiedScript.size();) { t = engine->ParseToken(&modifiedScript[pos], modifiedScript.size() - pos, &len); if( t == asTC_KEYWORD ) { token.assign(&modifiedScript[pos], len); if( token == "{" ) { // We've found the end of a function signature type = 2; return pos; } if( token == "=" || token == ";" ) { // We've found the end of a variable declaration. if( varLength != 0 ) declaration.resize(varLength); type = 3; return pos; } else if( token == "(" && varLength == 0 ) { // This is the first parenthesis we encounter. If the parenthesis isn't followed // by a statement block, then this is a variable declaration, in which case we // should only store the type and name of the variable, not the initialization parameters. varLength = (int)declaration.size(); } } declaration.append(&modifiedScript[pos], len); pos += len; } } } return start; }
INT32 CJSKMakeInvoice::FPSC_Proc(UINT8 czlx, UINT32 &fpzx, string &strInvInfo, string &strErr) { INT8 sqlbuf[128]; CInvServ invServ; CInvHead invHead; INT32 retcode = JSK_SUCCESS; INT32 errcode = 0; string tmpErr(""); // CJSKDeclareProc::DelUploadInv(); memset(sqlbuf, 0, sizeof(sqlbuf)); sprintf(sqlbuf, "where UP_FLAG=0 or UP_FLAG=1 "); invServ.m_filter.append(sqlbuf); invServ.Requery(); errcode = invServ.LoadOneRecord(); DBG_PRINT(("errcode = %d", errcode)); if(errcode == SQLITE_OK) { if((invServ.m_code=="") || (invServ.m_InvNo==0)) errcode = SQLITE_DONE; } if(errcode != SQLITE_OK) { retcode = CJSKInfoFunc::GetFirstOffInvInfo(&invHead, tmpErr); if((invHead.m_fpdm=="") || (invHead.m_fphm==0)) retcode = JSK_FAILURE; if(retcode != JSK_SUCCESS) { g_globalArgLib->m_pthreadFlag = 0; g_globalArgLib->m_InvServNum = 0; retcode = JSK_COMMON_ERR_NO; strErr = "所有发票都已上传!"; return retcode; } memset(sqlbuf, 0, sizeof(sqlbuf)); sprintf(sqlbuf, "where FPDM='%s' and FPHM=%u ", invHead.m_fpdm.c_str(), invHead.m_fphm); DBG_PRINT(("sqlbuf = %s", sqlbuf)); invServ.m_filter.append(sqlbuf); invServ.Requery(); if(invServ.LoadOneRecord() == SQLITE_OK) { if(invServ.m_upFlag == INV_UPLOAD_FLAG2) { g_globalArgLib->m_pthreadFlag = 0; retcode = JSK_COMMON_ERR_NO; strErr = "发票上传错误,请核对!"; return retcode; } } invServ.m_code = invHead.m_fpdm; invServ.m_InvNo = invHead.m_fphm; invServ.m_fpsyh = invHead.m_fpsyh; } UINT32 invLen = 0; fpzx = 1; //发票张数 memset(sqlbuf, 0, sizeof(sqlbuf)); sprintf(sqlbuf, "where FPDM='%s' and FPHM=%u ", invServ.m_code.c_str(), invServ.m_InvNo); DBG_PRINT(("sqlbuf = %s", sqlbuf)); invHead.m_filter.append(sqlbuf); retcode = invHead.Load(); if(retcode != SQLITE_OK) { DBG_PRINT(("here query from JSK")); invHead.m_fpdm = invServ.m_code; invHead.m_fphm = invServ.m_InvNo; invHead.m_fpsyh = invServ.m_fpsyh; retcode = CJSKInfoFunc::GetInvDetailInfoNO(&invHead, g_invInfo, invLen, strErr); if(retcode != JSK_SUCCESS) { return retcode; } // if(invHead.Save() != SQLITE_OK) // { // retcode = JSK_COMMON_ERR_NO; // strErr = "发票信息保存数据库错误"; // return retcode; // } } else { DBG_PRINT(("here query from DB success")); //将invHead类转换成string类型输出 CJSKInfoFunc::MutexLock(); CJSKInfoFunc::InvDetail2Data(&invHead, g_invInfo, invLen); CJSKInfoFunc::MutexUnlock(); DBG_PRINT(("invLen = %u", invLen)); } DBG_PRINT(("invLen = %u", invLen)); AddInvDetail2Data(&invHead, g_invInfo, invLen); strInvInfo.append((INT8 *)g_invInfo); DBG_PRINT(("invLen = %u", invLen)); //更新上传标志 invServ.m_upFlag = INV_UPLOAD_FLAG1; DBG_PRINT(("sqlbuf = %s", sqlbuf)); invServ.Update(sqlbuf, &invServ.m_upFlag, NULL); return JSK_SUCCESS; }
void exportToGMSH (const vector<Point>& points, const vector<Edge>& mesh0Edges, const vector<Edge>& mesh1Edges, string dir) { ofstream out; dir.append ("/exprtGMSH.geo"); out.open (dir.c_str()); vector <vector <int> > ptConn ((points.size()+1)); if (out.is_open()) { out << "Mesh.Algorithm = 6;" << endl; for (int i=0; i<points.size(); ++i) { out << "Point("; out << i; out << ") = {"; out << points[i].dim[0]; out << ","; out << points[i].dim[1]; out << ","; out << points[i].dim[2]; out << "};" << endl; } //--------------------------------------------- { int start, end; start = 0; end = start + mesh0Edges.size(); for (int e=start; e<end; ++e) // e for edge { int p0 = mesh0Edges[e-start].t[0] ; int p1 = mesh0Edges[e-start].t[1]; ptConn[p0].push_back(e); ptConn[p1].push_back(e); } start = mesh0Edges.size(); end = start + mesh1Edges.size(); for (int e=start; e<end; ++e) { int p0 = mesh1Edges[e-start].t[0]; int p1 = mesh1Edges[e-start].t[1]; ptConn[p0].push_back(e); ptConn[p1].push_back(e); } } //--------------------------------------------- out << "Line("; out << 0; out << ") = {"; out << mesh0Edges[0].t[0]; out << ","; out << mesh0Edges[0].t[1]; out << "};" << endl; int last = mesh0Edges[0].t[1]; int iLastEdge = 0; for (int i=0; i<mesh0Edges.size()-1; ++i) { // find the edge that last belongs for (int j=0; j<2; ++j) { if ( ptConn[last][j] != iLastEdge ) { // found j for iOtherEdge int iOtherEdge = ptConn[last][j]; iLastEdge = iOtherEdge; // find iOtherEdge.t != it1 for (int k=0; k<2; ++k) { if ( mesh0Edges[iOtherEdge].t[k] != last ) { // found k for iOtherEdge.t != it1 out << "Line("; out << i+1; out << ") = {"; out << last; out << ","; out << mesh0Edges[iOtherEdge].t[k]; out << "};" << endl; last = mesh0Edges[iOtherEdge].t[k]; break; } } break; } } } out << "Line("; out << mesh0Edges.size(); out << ") = {"; out << mesh1Edges[0].t[0]; out << ","; out << mesh1Edges[0].t[1]; out << "};" << endl; last = mesh1Edges[0].t[1]; iLastEdge = mesh0Edges.size(); for (int i=0; i<mesh1Edges.size()-1; ++i) { // find the edge that last belongs for (int j=0; j<2; ++j) { if ( ptConn[last][j] != iLastEdge ) { // found j for iOtherEdge int iOtherEdge = ptConn[last][j] - mesh0Edges.size(); iLastEdge = ptConn[last][j]; // find iOtherEdge.t != it1 for (int k=0; k<2; ++k) { if ( mesh1Edges[iOtherEdge].t[k] != last ) { // found k for iOtherEdge.t != it1 out << "Line("; out << i+1 + mesh0Edges.size(); out << ") = {"; out << last; out << ","; out << mesh1Edges[iOtherEdge].t[k]; out << "};" << endl; last = mesh1Edges[iOtherEdge].t[k]; break; } } break; } } } out << "Line Loop(1) = {"; for (int i=0; i<mesh0Edges.size(); ++i) { out << i; if (i < mesh0Edges.size()-1) { out << ","; } } out << "};" << endl; out << "Line Loop(2) = {"; for (int i=mesh0Edges.size(); i<mesh0Edges.size()+mesh1Edges.size(); ++i) { out << i; if (i < mesh0Edges.size()+mesh1Edges.size()-1) { out << ","; } } out << "};" << endl; out << "Plane Surface(1) = {1,2};"; out.close(); } else { cout << "could not open file in AFT::exportToGMSH()" << endl; exit(-2); } }
Book(string theISBNNum,string theName,string theAuthor,string theDate) { //ISNB格式检查 if(theISBNNum.length()<6) { cout<<"ISBN码输入格式有误"<<endl; return; } if((int)theISBNNum[0]<'0' || (int)theISBNNum[0]>'9' || (int)theISBNNum[2]<'0' || (int)theISBNNum[2]>'9' ||(int)theISBNNum[4]<'0' || (int)theISBNNum[4]>'9' ||(((int)theISBNNum[6]<'0' || (int)theISBNNum[6]>'9') &&((char)theISBNNum[6]>'z'||(char)theISBNNum[6]<'a') &&((char)theISBNNum[6]>'Z'||(char)theISBNNum[6]<'A'))) { cout<<"ISBN码输入格式有误"<<endl; return; } //日期检查 if(theDate.length()<8) { cout<<"日期输入格式有误"<<endl; return; } if(theDate.length()==8) { if(DateFormat1(theDate)) { char month0=theDate[4]; char month1=theDate[5]; int month=((int)month0-48)*10+((int)month1-48); char day0=theDate[6]; char day1=theDate[7]; //int day=((int)day0-48)*10+((int)*day1-48); //修改日期格式 theDate[4]='-'; theDate[5]=month0; theDate[6]=month1; theDate[7]='-'; theDate.append(&day0); theDate.append(&day1); cout<<"theDate="<<theDate<<endl; } else { cout<<"日期输入格式有误"<<endl; return; } } else if(theDate.length()==10) { if(DateFormat2(theDate)) { } else { cout<<"日期输入格式有误"<<endl; return; } } else if(theDate.length()>10) { cout<<"日期输入格式有误"<<endl; return; } ISBNNum=theISBNNum; name=theName; author=theAuthor; pblsDate=theDate; //初始化时默认未借出 isOut=false; }
int main(int argc, char *argv[]) { //clear the master and temp sets FD_ZERO(&master); FD_ZERO(&controlSocks); char c; int hSocket; uint16_t number=0; uint64_t lastAnnounceTime=0; Reconnector reconnector; set_terminate(terminateFcn); void (*prev_fn)(int); prev_fn = signal (SIGINT,terminateFcn); if (prev_fn==SIG_ERR) makeLog(LOG_ERR,"Main: Unable to set termination funtion"); while ((c = getopt (argc, argv, "fvc:")) != -1) switch (c) { case 'f': fflag = true; break; case 'v': vflag = true; break; case 'c': configFile = optarg; break; case '?': if (optopt == 'c') fprintf (stderr, "Main: Option -%c requires an argument.\n", optopt); else if (isprint (optopt)) fprintf (stderr, "Main: Unknown option `-%c'.\n", optopt); else fprintf (stderr, "Main: Unknown option character `\\x%x'.\n", optopt); return 1; default: abort (); } Config config; readConfig(config); makeLog(LOG_DEBUG,"Read configuration"); if (!pidFile.empty()) { makeLog(LOG_DEBUG,"Main: Checking pid file: %s",pidFile.c_str()); ifstream pidfile(pidFile.c_str()); if (pidfile.is_open()) { char line[20]; int otherpid; pidfile.getline(line,sizeof(line)); sscanf(line,"%u",&otherpid); if (kill(otherpid,0)==0) { makeLog(LOG_ERR,"Main: Other instance is running: %d",otherpid); pidFile=""; terminate(); } pidfile.close(); } } // makeLog(LOG_DEBUG,"PID check finished"); if (!fflag) daemon (0,1); if (!pidFile.empty()) { ofstream pidfile; pidfile.open(pidFile.c_str()); pidfile << getpid(); pidfile << "\n"; pidfile.close(); } if (listeningArgs.proto.compare("tcp")==0) { //get the listener if(listener.init(AF_INET, SOCK_STREAM, 0) == -1) { makeLog(LOG_ERR,"Listener: Unable to create socket"); exit(1); } listener.peer.set_in(listeningArgs.host,listeningArgs.port); if (listener.connect() < 0) { makeLog(LOG_ERR,"Listener: Cannot connect: %s;",strerror(errno)); reconnector.add(&listener,reconnectListener,NULL); } else { // add the listener to the master set listener.updatefdmax(&fdmax); makeLog(LOG_INFO,"Listener: Connected to %s:%d;",listeningArgs.host.c_str(),listeningArgs.port); } FD_SET(listener.getHandle(), &master); } else { const bool mcast=((inet_addr(listeningArgs.host.c_str()) & MCAST_MASK) == MCAST_ADDR); //get the listener if(listener.init(AF_INET, SOCK_DGRAM, 0) == -1) { makeLog(LOG_ERR,"Listener: Server-socket() error lol!"); terminate(); } makeLog(LOG_INFO,"Listener: Server-socket() is OK..."); //"address already in use" error message if(listener.setsockopt(SOL_SOCKET, SO_REUSEADDR, &yes, sizeof(int)) == -1) { makeLog(LOG_ERR,"Listener: Setsockopt error: %s",strerror(errno)); terminate(); } makeLog(LOG_INFO,"Listener: Setsockopt() is OK..."); // bind listener.local.set_in(listeningArgs.host,listeningArgs.port); if(listener.bind() == -1) { makeLog(LOG_ERR,"Listener: Unable to bind: %s",strerror(errno)); terminate(); } if (mcast) { ip_mreq imreq; imreq.imr_multiaddr.s_addr = inet_addr(listeningArgs.host.c_str()); imreq.imr_interface.s_addr = INADDR_ANY; // use DEFAULT interface // JOIN multicast group on default interface int status = listener.setsockopt(IPPROTO_IP, IP_ADD_MEMBERSHIP, (const void *)&imreq, sizeof(struct ip_mreq)); makeLog(LOG_INFO,"Listener: Joining multicast %s",listeningArgs.host.c_str()); } makeLog(LOG_INFO,"Listener: ready udp://%s:%d",listeningArgs.host.c_str(),listeningArgs.port); // add the listener to the master set FD_SET(listener.getHandle(), &master); listener.updatefdmax(&fdmax); } if(control.init(AF_INET, SOCK_DGRAM, 0) == -1) { makeLog(LOG_ERR,"Control: Unable to create socket: %s",strerror(errno)); terminate(); } if (controlArgs.host.empty()) { control.local.set_in("",controlArgs.port); if (control.bind()>=0) makeLog(LOG_INFO,"Control: Listening on *:%d",controlArgs.port); else { makeLog(LOG_INFO,"Control: Unable to bind socket for udp port %d: %s",controlArgs.port,strerror(errno)); exit(0); } } else { makeLog(LOG_INFO,"Control: NAT mode"); if (controlArgs.proto.compare("tcp")==0) { } else { control.peer.set_in(controlArgs.host,controlArgs.port); } } #ifdef CONTROL_THREAD FD_SET(control.getHandle(), &controlSocks); control.updatefdmax(&fdmax); #else FD_SET(control.getHandle(), &master); control.updatefdmax(&fdmax); #endif if(sender.init(AF_INET, SOCK_DGRAM, 0) == -1) { makeLog(LOG_ERR,"Streamer: Unable to create socket: %s",strerror(errno)); terminate(); } if (streamingArgs.proto.compare("tcp")==0) { } else { sender.peer.set_in(streamingArgs.host,streamingArgs.port); makeLog(LOG_INFO,"Streamer: Peer port was set up %s:%d",streamingArgs.host.c_str(),streamingArgs.port); } #ifdef CONTROL_THREAD FD_SET(sender .getHandle(), &controlSocks); sender.updatefdmax(&fdmax); #else FD_SET(sender.getHandle(), &master); sender.updatefdmax(&fdmax); #endif if (!listeningArgs.copyHost.empty()) { if(copier.init(AF_INET, SOCK_DGRAM, 0) == -1) { makeLog(LOG_ERR,"Copier: Unable to create socket: %s",strerror(errno)); } copier.peer.set_in(listeningArgs.copyHost,listeningArgs.copyPort); makeLog(LOG_INFO,"Copier: Resend data to: %s",copier.peer.toString().c_str()); FD_SET(copier.getHandle(), &master); copier.updatefdmax(&fdmax); } openlog("ict-receiver", LOG_PID|LOG_CONS, LOG_USER); sendingSuspended=streamingArgs.suspendOnStart; if (int errcode=pthread_create(&cleaningThread,NULL,&cleaningFcn,&cleaningArgs)) { makeLog(LOG_ERR,"Cleaner: Unable to create thread: %s",strerror(errno)); } if (streamingArgs.bitrate) { if(pipe(mypipe) < 0) { makeLog(LOG_ERR,"Streamer: Unable to create pipe %s",strerror(errno)); } if (int errcode=pthread_create(&streamingThread,NULL,&streamingFcn,&streamingArgs)) { makeLog(LOG_ERR,"Streamer: Unable to create thread: %s",strerror(errno)); } } if (int errcode=pthread_create(&keepingThread,NULL,&keepingFcn,NULL)) { makeLog(LOG_ERR,"Keeper: Unable to create thread: %s",strerror(errno)); } #ifdef CONTROL_THREAD if (int errcode=pthread_create(&controlThread,NULL,&controlThreadFcn,&controlArgs)) { makeLog(LOG_ERR,"Control: Unable to create thread: %s",strerror(errno)); } #endif sendControl("START"); timeval timeout={10,0}; //sec,usec // loop for(;;) { // copy it fd_set read_fds = master; int readCnt=select(fdmax+1, &read_fds, NULL, NULL, &timeout); if( readCnt == -1 ) { makeLog(LOG_ERR,"Main: select error: %s",strerror(errno)); exit(1); } reconnector.tryReconnect(10); if ( readCnt > 0 ) { //run through the existing connections looking for data to be read for(hSocket = 0; hSocket <= fdmax; hSocket++) { if(FD_ISSET(hSocket, &read_fds)) { // we got one... if(listener.handles(hSocket)) { // buffer for client data ictDatagram_t ictDatagram; int recvlen = listener.recv(ictDatagram.data(), listeningArgs.mtu, 0); if (recvlen>0) { if (copier.inited()) { copier.write(ictDatagram.data(),recvlen); } ictDatagram.setDataLength(recvlen); if (!sendingSuspended) { ictDatagram.setTime(getMNow()); ictDatagram.setNumber(number); pushDatagram (ictDatagram); if (streamingArgs.bitrate) { // makeLog(LOG_DEBUG,"Writenumber: %u",number); write(mypipe[1],&number,sizeof(number)); // outQueue.push_back ( number ); } else { int sentcount=sender.send(ictDatagram,ictDatagram.size(),0); } number++; } else {//if suspended uint64_t now=getMNow(); if (now-lastAnnounceTime>30*1000) { sender.send("UU",2,0); lastAnnounceTime=now; } } //if suspended } //if recvLen>0 else if (recvlen==0){//Client must be reconnected!!!! if (listeningArgs.proto.compare("tcp")==0) { FD_CLR(listener.getHandle(),&master); if (listener.isConnected()) { listener.reinit(); } /* if (listener.connect()==0) { makeLog(LOG_INFO,"Listener: Connected"); } else { makeLog(LOG_INFO,"Listener: Reconnect failed"); sleep(10); } */ reconnector.add(&listener,reconnectListener,NULL); makeLog(LOG_INFO,"Listener: Disconnected"); } } //if recvlen==0 } //if sock is listener #ifndef CONTROL_THREAD if (control.handles(hSocket)) { char cmsg[1500]; int recvlen = control.recv((void*)cmsg,sizeof(cmsg),0); if (recvlen>0) { makeLog(LOG_DEBUG,"Processing control from main"); controlStr.append(cmsg,recvlen); processControls(controlStr,control); } } if (sender.handles(hSocket)) { char cmsg[1500]; int recvlen = sender.recv(cmsg,sizeof(cmsg),0); if (recvlen>0) { makeLog(LOG_DEBUG,"Processing control from main"); controlStr.append(cmsg,recvlen); processControls(controlStr,sender); } } #endif } }//for }//if readCnt>0 } closelog(); return 0; }
MyProfile(string n) { name.append(n); }
int http_client::read_response_body(string& out, bool clean, int* real_size) { if (real_size) *real_size = 0; if (body_finish_) return (last_ret_); if (stream_ == NULL) { logger_error("connect null"); disconnected_ = true; return -1; } ACL_VSTREAM* vstream = stream_->get_vstream(); if (vstream == NULL) { logger_error("connect stream null"); disconnected_ = true; return -1; } if (hdr_res_ == NULL) { logger_error("response header not get yet"); disconnected_ = true; return -1; } if (res_ == NULL) res_ = http_res_new(hdr_res_); if (clean) out.clear(); int saved_count = (int) out.length(); char buf[8192]; SKIP_GZIP_HEAD_AGAIN: // 对于有 GZIP 头数据,可能需要重复读 int ret = (int) http_res_body_get_sync(res_, vstream, buf, sizeof(buf)); if (zstream_ == NULL) { if (ret > 0) { out.append(buf, ret); if (real_size) *real_size = ret; } else { body_finish_ = true; // 表示数据已经读完 if (ret < 0) disconnected_ = true; last_ret_ = ret; } return ret; } if (ret <= 0) { if (zstream_->unzip_finish(&out) == false) { logger_error("unzip_finish error"); return -1; } last_ret_ = ret; // 记录返回值 body_finish_ = true; // 表示数据已经读完且解压缩完毕 if (ret < 0) disconnected_ = true; return (int) out.length() - saved_count; } if (real_size) (*real_size) += ret; // 需要先跳过 gzip 头 if (gzip_header_left_ >= ret) { gzip_header_left_ -= ret; goto SKIP_GZIP_HEAD_AGAIN; } int n; if (gzip_header_left_ > 0) { n = gzip_header_left_; gzip_header_left_ = 0; } else n = 0; if (zstream_->unzip_update(buf + n, ret - n, &out) == false) { logger_error("unzip_update error"); return -1; } return (int) out.length() - saved_count; }
bool http_client::body_gets(string& out, bool nonl /* = true */, size_t* size /* = NULL */) { if (buf_ == NULL) buf_ = new string(4096); size_t len, size_saved = out.length(); // 首先判断是否已经读完 HTTP 数据体 if (body_finish_) { if (buf_->empty()) { if (size) *size = 0; return false; } // 当读缓冲区数据非空时,先尝试从中获取一行数据 if (buf_->scan_line(out, nonl, &len) == true) { if (size) *size = out.length() - size_saved; return true; } // 如果不能读到完整行数据且 HTTP 数据体读完的情况下则将读 // 缓冲区内的数据都拷贝至目标缓冲区 out.append(buf_); buf_->clear(); if (size) *size = out.length() - size_saved; return true; } // 继续读 HTTP 数据体,并尝试从中读取一行数据 len = 0; while (true) { if (!buf_->empty()) { if (buf_->scan_line(out, nonl, &len) == true) { if (size) *size = out.length() - size_saved; return true; } // 为了减少下次循环时调用 scan_line 的字符串查找次数, // 将读缓冲区中的数据先拷贝至目标缓冲区中 len += buf_->length(); out.append(buf_); buf_->clear(); } if (body_finish_) { if (size) *size = len; return len > 0 ? true : false; } if (read_body(*buf_, false) <= 0) body_finish_ = true; else body_finish_ = false; } }
bool mycompare(string X, string Y) { string XY = X.append(Y); string YX = Y.append(X); return XY.compare(YX)>0?true:false; }
string operator+(string a,string b) { return b.append(a); }
void Bed5Interval::printNull(string &outBuf) const { Bed3Interval::printNull(outBuf); outBuf.append("\t.\t-1", 5); }
int main(int argc, char **argv) //lat, long, res, filename, waterDrop, baseHeight { int point; float lat; float lng; int res; int stepSize = 1; int tile_n; int tile_w; int waterDrop = -2; //millimeters int baseHeight = 2; //millimeters //float true_verticalscale = 92.7; //meters/arcsecond at equator float verticalscale = 23.2; //true_verticalscale gives models that are too flat to be interesting lat = atof(argv[1]); //Latitude of NW corner printf("Using latitude: %f\n",lat); globalLat = 3.1415926*lat/180; lng = atof(argv[2]); //Longitude of NW corner printf("Using longitude: %f\n",lng); res = atoi(argv[3]); //arcseconds/tick in model if(res%3!=0){ //must be a multiple of 3 printf("Bad resolution\n"); return 0; } res = res/3; //SRTM data already has a resolution of 3 arcseconds if(res>15){ stepSize = 8; }else if(res>12){ stepSize = 4; }else if(res>9){ stepSize = 2; } printf("Stepsize: %i\n",stepSize); printf("Using resolution %i\n",res); //Arc height = 40*res/stepSize; width = 40*res/stepSize; hList.resize(width*height,0); savefile.append(std::string(argv[4])); printf("Saving to '%s'\n",savefile.c_str()); waterDrop = atoi(argv[5]); baseHeight = atoi(argv[6]); getTile(lat,lng,0); //-------Find starting file index--------------- float n = (lat-floor(lat))*3600; float e = (lng-floor(lng))*3600; int i = 1201-(int)(n/(3)); int j = (int)(e/(3)); int tilesOffsetX = 10000; //how much the secondary x tiles should be offset in x, 10000 means only one tile is used int tilesOffsetY = 10000; //how much the secondary x tiles should be offset in x, 10000 means only one tile is used if(i+height*stepSize>1200){ printf("Extra tile in y"); tilesOffsetY = (1200-i); getTile(lat-1.0,lng,2); } if(j+width*stepSize>1200){ printf("Extra tile in x"); tilesOffsetX = (1200-j); getTile(lat,lng+1.0,1); if(tilesOffsetY!=10000){ getTile(lat-1.0,lng+1.0,3); } } point = j+i*1201; //the file index of the NW corner //------------Open file and read data into array---------------------------- int h; char number [2]; int whichTile; int tileX; int tileY; ifstream file; int openTile = -1;; for(int y = 0; y < height*stepSize; y+=stepSize){ for(int x = 0; x < width*stepSize; x+=stepSize){ tileX = x; tileY = y; if(x<=tilesOffsetX && y<=tilesOffsetY){ //simplify this with bitwise logic? whichTile = 0; point = j+i*1201; } if(x>tilesOffsetX && y<=tilesOffsetY){ whichTile = 1; tileX = x-tilesOffsetX; point = i*1201; } if(x<=tilesOffsetX && y>tilesOffsetY){ whichTile = 2; tileY = y-tilesOffsetY; point = j; } if(x>tilesOffsetX && y>tilesOffsetY){ whichTile = 3; tileX = x-tilesOffsetX; tileY = y-tilesOffsetY; point = 0; } if(openTile!=whichTile){ //printf("%s",tiles[whichTile].c_str()); openTile = whichTile; file.close(); file.open(tiles[whichTile].c_str(),ios::in|ios::binary); } file.seekg((point+tileX+tileY*1201)*2,ios::beg); file.read(number,2); h = number[1]; if(h<0){ h = h+255; } h+= number[0]*256; if(h==0){ h=-waterDrop*verticalscale; } //If a void exists, marks it as -100 if(h<-100){ h=-verticalscale*100*stepSize; } //rotate model to correct orientation //hList.at((height-1-y)*width+x) = h/(verticalscale*res); //cast verticalscale to int for COOl effect! hList.at((height-1-y/stepSize)*width+x/stepSize) = h/(verticalscale*stepSize)+baseHeight; //+baseHeight so that the bottom of the model does not bleed through to the top } } writeSTLfromArray(); return 0; }
string function(string &s, const string &pre, const string &suf) { s.insert(s.begin(), pre.begin(), pre.end()); s.append(suf); return s; }
//Receive String of length sock_length bool SocketHandler::RecvLength( string &sock_inT, unsigned int sock_lengthT ) { if ( RecvBuf.size() >= sock_lengthT ) { sock_inT.append( RecvBuf.substr( 0, sock_lengthT ) ); RecvBuf.erase( 0, sock_lengthT ); return true; } char buffer[MAXRECV+1]; ssize_t buffer_count; unsigned int received = 0; if ( RecvBuf.size() > (ssize_t)0 ) { sock_inT.append( RecvBuf ); received += RecvBuf.size(); RecvBuf = ""; } for(;;) { Timeout.tv_sec = RECVTIMEOUT; Timeout.tv_usec = 0; FD_ZERO(&checkfd); FD_SET(sock_fd,&checkfd); int ret = select_eintr(sock_fd+1, &checkfd, NULL, NULL, &Timeout); if ( ret <= 0 ) { return false; } while ((buffer_count = ::recv(sock_fd, buffer, MAXRECV, 0)) < 0 && errno == EINTR); if ( buffer_count < 1 ) { return false; } if ( received + buffer_count >= sock_lengthT ) { string Rest; Rest.append( buffer, buffer_count ); unsigned int needed = sock_lengthT - received; sock_inT.append( Rest.substr( 0, needed ) ); if ( Rest.size() > needed ) RecvBuf.append( Rest.substr( needed ) ); return true; } sock_inT.append( buffer, buffer_count ); received += buffer_count; } return true; }
void MyTcpSocket::detectErrorBind(int* errCode,string& errMsg) { *errCode = WSAGetLastError(); if ( *errCode == WSANOTINITIALISED ) errMsg.append("A successful WSAStartup must occur before using this function."); else if ( *errCode == WSAENETDOWN ) errMsg.append("The network subsystem has failed."); else if ( *errCode == WSAEADDRINUSE ) { errMsg.append("A process on the machine is already bound to the same\n"); errMsg.append("fully-qualified address and the socket has not been marked\n"); errMsg.append("to allow address re-use with SO_REUSEADDR. For example,\n"); errMsg.append("IP address and port are bound in the af_inet case"); } else if ( *errCode == WSAEADDRNOTAVAIL ) errMsg.append("The specified address is not a valid address for this machine."); else if ( *errCode == WSAEFAULT ) { errMsg.append("The name or the namelen parameter is not a valid part of\n"); errMsg.append("the user address space, the namelen parameter is too small,\n"); errMsg.append("the name parameter contains incorrect address format for the\n"); errMsg.append("associated address family, or the first two bytes of the memory\n"); errMsg.append("block specified by name does not match the address family\n"); errMsg.append("associated with the socket descriptor s."); } else if ( *errCode == WSAEINPROGRESS ) { errMsg.append("A blocking Windows Sockets 1.1 call is in progress, or the\n"); errMsg.append("service provider is still processing a callback function."); } else if ( *errCode == WSAEINVAL ) errMsg.append("The socket is already bound to an address. "); else if ( *errCode == WSAENOBUFS ) errMsg.append("Not enough buffers available, too many connections."); else if ( *errCode == WSAENOTSOCK ) errMsg.append("The descriptor is not a socket."); else errMsg.append("unknown problems!"); }
//void LMParser::parseCNFString(string formula,vector<PredicateSymbol*> predicateList) void LMParser::parseCNFString(string formula,fstream& filestr) { //apend multiple lines char* buf = new char[1024]; size_t pos; while(1) { pos = formula.find(WEIGHTSEPARATOR); if(pos!=string::npos) break; else { filestr.getline(buf,1024); string s(buf); s.erase( remove(s.begin(), s.end(), ' '), s.end() ); formula.append(s); } } delete[] buf; //extract the weight string weight = formula.substr(pos+2); stringstream convert(weight); double wt; convert >> wt; formula = formula.substr(0,pos); //cout<<wt<<endl; vector<string> clauseStrings; LStringConversionUtils::tokenize(formula,clauseStrings,ANDOPERATOR); vector<WClause*> CNF; for(int i=0;i<clauseStrings.size();i++) { //If clause starts with a paranthesis if(clauseStrings[i].find(LEFTPRNTH)==0) { //eliminate the first and last paranthesis clauseStrings[i] = clauseStrings[i].substr(1,clauseStrings[i].size()-2); } vector<string> atomStrings; LStringConversionUtils::tokenize(clauseStrings[i],atomStrings,OROPERATOR); vector<vector<string> > sTermsList(atomStrings.size()); //sign of an atom vector<bool> sign(atomStrings.size()); //index into the predicate symbols vector<int> predicateSymbolIndex(atomStrings.size()); for(int j=0;j<atomStrings.size();j++) { //find opening and closing braces int startpos=atomStrings[j].find(LEFTPRNTH); string predicateName = atomStrings[j].substr(0,startpos); if(predicateName.find(NOTOPERATOR)==0) { //negation predicateName = predicateName.substr(1,predicateName.size()); sign[j]=true; } for(int k=0;k<mln.symbols.size();k++) { //found the predicate if(mln.symbols[k]->symbol.compare(predicateName)==0) { predicateSymbolIndex[j] = k; break; } } int endpos=atomStrings[j].find(RIGHTPRNTH); string termsString = atomStrings[j].substr(startpos+1,endpos-startpos-1); vector<string> terms; LStringConversionUtils::tokenize(termsString,terms,COMMASEPARATOR); sTermsList[j]=terms; //check if the number of terms is equal to the declared predicate if(terms.size()!=mln.symbols[predicateSymbolIndex[j]]->variable_types.size()) { cout<<"Error! Number/domain of terms in the predicate delcaration does not match in formula::"<<predicateName.c_str()<<endl; exit(-1); } } //create required terms vector<vector<LvrTerm*> > iTermsList(atomStrings.size()); for(int j=0;j<atomStrings.size();j++) { //for each term of atom i, check if it has already appeared in previous atoms of clause vector<LvrTerm*> iTerms(sTermsList[j].size()); for(int k=0;k<sTermsList[j].size();k++) { int domainIndex = predicateDomainMap[predicateSymbolIndex[j]].at(k); //if term is a constant must be a unique term if(isTermConstant(sTermsList[j].at(k))) { //find the id of the term int id=-1; for(int m=0;m<domainList[domainIndex]->values.size();m++) { if(domainList[domainIndex]->values[m].compare(sTermsList[j].at(k))==0) { id=m; break; } } if(id==-1) { cout<<"Constant does not match predicate's domain::"<<domainList[domainIndex]->name<<endl; exit(-1); } iTerms[k] = new LvrTerm(0,id); } else { int domainSize = domainList[domainIndex]->values.size(); bool isExistingTerm = false; int atomIndex=-1; int termIndex=-1; //check in term lists for atoms 0 to j; for(int m=0;m<j;m++) { for(int n=0;n<sTermsList[m].size();n++) { if((sTermsList[m])[n].compare((sTermsList[j])[k])==0) { //check if the domains of the matched variables are the same int atomSymbolIndex1 = predicateSymbolIndex[m]; int atomId1 = mln.symbols[atomSymbolIndex1]->id; int domainListIndex1 = predicateDomainMap[atomId1].at(n); int atomSymbolIndex2 = predicateSymbolIndex[j]; int atomId2 = mln.symbols[atomSymbolIndex2]->id; int domainListIndex2 = predicateDomainMap[atomId2].at(k); if(domainList[domainListIndex1]->name.compare(domainList[domainListIndex2]->name)!=0) { cout<<"Error! variables do not match type ::"<<atomStrings[j]<<"("<<domainList[domainListIndex1]->name<<", "<<domainList[domainListIndex2]->name<<")"<<endl; exit(-1); } //variable is repeated, use the term created for atom m, term n isExistingTerm = true; atomIndex = m; termIndex = n; break; } } if(isExistingTerm) break; } if(isExistingTerm) { //use the terms created for previous atoms iTerms[k] = (iTermsList[atomIndex])[termIndex]; } else { //create a new LvrTerm iTerms[k] = create_new_term(domainSize); } } } iTermsList[j] = iTerms; }//j atoms WClause* newClause = create_new_clause(predicateSymbolIndex,sign,iTermsList); newClause->weight = LogDouble(wt,false); CNF.push_back(newClause); }//i clauses int formulaStartIndex = mln.clauses.size(); for(int i=0;i<CNF.size();i++) { mln.clauses.push_back(CNF[i]); } int formulaEndIndex = mln.clauses.size(); mln.formulas.push_back(new Formula(formulaStartIndex,formulaEndIndex,LogDouble(wt,false))); }
void MyTcpSocket::detectErrorRecv(int* errCode,string& errMsg) { *errCode = WSAGetLastError(); if ( *errCode == WSANOTINITIALISED ) errMsg.append("A successful WSAStartup must occur before using this function."); else if ( *errCode == WSAENETDOWN ) errMsg.append("The network subsystem has failed."); else if ( *errCode == WSAEFAULT ) errMsg.append("The buf parameter is not completely contained in a valid part of the user address space."); else if ( *errCode == WSAENOTCONN ) errMsg.append("The socket is not connected."); else if ( *errCode == WSAEINTR ) errMsg.append("The (blocking) call was canceled through WSACancelBlockingCall."); else if ( *errCode == WSAEINPROGRESS ) { errMsg.append("A blocking Windows Sockets 1.1 call is in progress, or the\n"); errMsg.append("service provider is still processing a callback function."); } else if ( *errCode == WSAENETRESET ) { errMsg.append("The connection has been broken due to the keep-alive activity\n"); errMsg.append("detecting a failure while the operation was in progress."); } else if ( *errCode == WSAENOTSOCK ) errMsg.append("The descriptor is not a socket."); else if ( *errCode == WSAEOPNOTSUPP ) { errMsg.append("MSG_OOB was specified, but the socket is not stream-style\n"); errMsg.append("such as type SOCK_STREAM, out-of-band data is not supported\n"); errMsg.append("in the communication domain associated with this socket, or\n"); errMsg.append("the socket is unidirectional and supports only send operations."); } else if ( *errCode == WSAESHUTDOWN ) { errMsg.append("The socket has been shut down; it is not possible to recv on a\n"); errMsg.append("socket after shutdown has been invoked with how set to SD_RECEIVE or SD_BOTH."); } else if ( *errCode == WSAEWOULDBLOCK ) errMsg.append("The socket is marked as nonblocking and the receive operation would block."); else if ( *errCode == WSAEMSGSIZE ) errMsg.append("The message was too large to fit into the specified buffer and was truncated."); else if ( *errCode == WSAEINVAL ) { errMsg.append("The socket has not been bound with bind, or an unknown flag\n"); errMsg.append("was specified, or MSG_OOB was specified for a socket with\n"); errMsg.append("SO_OOBINLINE enabled or (for byte stream sockets only) len was zero or negative."); } else if ( *errCode == WSAECONNABORTED ) { errMsg.append("The virtual circuit was terminated due to a time-out or\n"); errMsg.append("other failure. The application should close the socket as it is no longer usable."); } else if ( *errCode == WSAETIMEDOUT ) { errMsg.append("The connection has been dropped because of a network\n"); errMsg.append("failure or because the peer system failed to respond."); } else if ( *errCode == WSAECONNRESET ) { errMsg.append("The virtual circuit was reset by the remote side executing a\n"); errMsg.append("\"hard\" or \"abortive\" close. The application should close\n"); errMsg.append("the socket as it is no longer usable. On a UDP datagram socket\n"); errMsg.append("this error would indicate that a previous send operation\n"); errMsg.append("resulted in an ICMP \"Port Unreachable\" message."); } else errMsg.append("unknown problems!"); }
string reqp::get_url( thrd* p_thrd, string s_req, map_string &map_params ) { auto unsigned int pos; string s_ret ( "" ); string s_vars( "" ); auto int i_request; i_request= ( s_req.find("GET",0) != string::npos ) ? RQ_GET : RQ_POST; if ( i_request == RQ_POST ) return "OFFBYTE"; pos = s_req.find( "HTTP", 0 ); if( i_request == RQ_GET ) s_ret.append( s_req.substr( 5, pos-6 ) ); else s_ret.append( s_req.substr( 6, pos-7 ) ); // remove ".." from the request. do { pos = s_ret.find( "../", 0 ); if ( pos == string::npos ) break; s_ret.replace( pos, pos+2, "" ); } while( true ); // do not add the string behind "?" tp s_ret and add all params behind "?" to map_params. if( i_request == RQ_GET ) pos = s_ret.find( "?", 0 ); else pos = s_req.find("\r\n\r\n", 0); auto string s_params( "" ); if ( pos != string::npos ) { if( i_request == RQ_GET ) s_params.append( s_ret.substr( pos+1, s_ret.length() -pos-1 ) ); else s_params = s_req.substr( pos+4, s_req.length() -pos-1 ); s_ret = s_ret.substr( 0, pos ); } if ( i_request == RQ_POST && s_params.empty() ) { char c_req[READBUF]; if ( read ( p_thrd->get_sock() , c_req, READBUF ) <= 0 ) return "OFFBYTE"; s_params = string( strstr( c_req, "event" ) ); } auto unsigned int pos2; do { pos = s_params.find( "=", 0 ); if ( pos == string::npos ) break; pos2 = s_params.find( "&", 0 ); if ( pos2 == string::npos ) { auto string sValue( s_params.substr(pos+1, s_params.length()-pos-1) ); auto string tmpstr( url_decode(sValue) ); map_params[ s_params.substr( 0, pos ) ] = tmpstr; break; } auto string s_temp= s_params.substr( pos+1, pos2-pos-1 ); map_params[ s_params.substr( 0, pos ) ] = url_decode(s_temp); s_params = s_params.substr( pos2+1, s_params.length()-pos2-1 ); } while( true ); #ifdef VERBOSE wrap::system_message( REQUEST + s_ret ); #endif if ( s_ret.empty() ) s_ret = wrap::CONF->get_elem( "HTML_START_SITE" ); map_params["request"] = s_ret; return s_ret; }
void MyTcpSocket::detectErrorConnect(int* errCode,string& errMsg) { *errCode = WSAGetLastError(); if ( *errCode == WSANOTINITIALISED ) errMsg.append("A successful WSAStartup must occur before using this function."); else if ( *errCode == WSAENETDOWN ) errMsg.append("The network subsystem has failed."); else if ( *errCode == WSAEADDRINUSE ) { errMsg.append("The socket's local address is already in use and the socket\n"); errMsg.append("was not marked to allow address reuse with SO_REUSEADDR. This\n"); errMsg.append("error usually occurs when executing bind, but could be delayed\n"); errMsg.append("until this function if the bind was to a partially wild-card\n"); errMsg.append("address (involving ADDR_ANY) and if a specific address needs\n"); errMsg.append("to be committed at the time of this function."); } else if ( *errCode == WSAEINTR ) errMsg.append("The (blocking) Windows Socket 1.1 call was canceled through WSACancelBlockingCall."); else if ( *errCode == WSAEINPROGRESS ) { errMsg.append("A blocking Windows Sockets 1.1 call is in progress, or\n"); errMsg.append("the service provider is still processing a callback function."); } else if ( *errCode == WSAEALREADY ) { errMsg.append("A nonblocking connect call is in progress on the specified socket.\n"); errMsg.append("Note In order to preserve backward compatibility, this error is\n"); errMsg.append("reported as WSAEINVAL to Windows Sockets 1.1 applications that\n"); errMsg.append("link to either WINSOCK.DLL or WSOCK32.DLL."); } else if ( *errCode == WSAEADDRNOTAVAIL ) errMsg.append("The remote address is not a valid address (such as ADDR_ANY)."); else if ( *errCode == WSAEAFNOSUPPORT ) errMsg.append("Addresses in the specified family cannot be used with this socket."); else if ( *errCode == WSAECONNREFUSED ) errMsg.append("The attempt to connect was forcefully rejected."); else if ( *errCode == WSAEFAULT ) { errMsg.append("The name or the namelen parameter is not a valid part of\n"); errMsg.append("the user address space, the namelen parameter is too small,\n"); errMsg.append("or the name parameter contains incorrect address format for\n"); errMsg.append("the associated address family."); } else if ( *errCode == WSAEINVAL ) { errMsg.append("The parameter s is a listening socket, or the destination\n"); errMsg.append("address specified is not consistent with that of the constrained\n"); errMsg.append("group the socket belongs to."); } else if ( *errCode == WSAEISCONN ) errMsg.append("The socket is already connected (connection-oriented sockets only)."); else if ( *errCode == WSAENETUNREACH ) errMsg.append("The network cannot be reached from this host at this time."); else if ( *errCode == WSAENOBUFS ) errMsg.append("No buffer space is available. The socket cannot be connected."); else if ( *errCode == WSAENOTSOCK ) errMsg.append("The descriptor is not a socket."); else if ( *errCode == WSAETIMEDOUT ) errMsg.append("Attempt to connect timed out without establishing a connection."); else if ( *errCode == WSAEWOULDBLOCK ) { errMsg.append("The socket is marked as nonblocking and the connection\n"); errMsg.append("cannot be completed immediately."); } else if ( *errCode == WSAEACCES ) { errMsg.append("Attempt to connect datagram socket to broadcast address failed\n"); errMsg.append("because setsockopt option SO_BROADCAST is not enabled."); } else errMsg.append("unknown problems!"); }
void setName(string n) { name.clear(); name.append(n); }
void MyTcpSocket::detectErrorAccept(int* errCode,string& errMsg) { *errCode = WSAGetLastError(); if ( *errCode == WSANOTINITIALISED ) errMsg.append("A successful WSAStartup must occur before using this FUNCTION."); else if ( *errCode == WSAENETDOWN ) errMsg.append("The network subsystem has failed."); else if ( *errCode == WSAEFAULT ) errMsg.append("The addrlen parameter is too small or addr is not a valid part of the user address space."); else if ( *errCode == WSAEINTR ) errMsg.append("A blocking Windows Sockets 1.1 call was canceled through WSACancelBlockingCall."); else if ( *errCode == WSAEINPROGRESS ) { errMsg.append("A blocking Windows Sockets 1.1 call is in progress, or the\n"); errMsg.append("service provider is still processing a callback function."); } else if ( *errCode == WSAEINVAL ) errMsg.append("The listen function was not invoked prior to accept."); else if ( *errCode == WSAEMFILE ) errMsg.append("The queue is nonempty upon entry to accept and there are no descriptors available."); else if ( *errCode == WSAENOBUFS ) errMsg.append("No buffer space is available."); else if ( *errCode == WSAENOTSOCK ) errMsg.append("The descriptor is not a socket."); else if ( *errCode == WSAEOPNOTSUPP ) errMsg.append("The referenced socket is not a type that supports connection-oriented service."); else if ( *errCode == WSAEWOULDBLOCK ) errMsg.append("The socket is marked as nonblocking and no connections are present to be accepted."); else errMsg.append("unknown problems!"); }
string CCBitmapConvert::GenBmpPicPath(string strSrcPath) { int iPos = strSrcPath.rfind('.'); return strSrcPath.append(".bmp"); }
void MyTcpSocket::detectErrorListen(int* errCode,string& errMsg) { *errCode = WSAGetLastError(); if ( *errCode == WSANOTINITIALISED ) errMsg.append("A successful WSAStartup must occur before using this function."); else if ( *errCode == WSAENETDOWN ) errMsg.append("The network subsystem has failed."); else if ( *errCode == WSAEADDRINUSE ) { errMsg.append("The socket's local address is already in use and the socket was\n"); errMsg.append("not marked to allow address reuse with SO_REUSEADDR. This error\n"); errMsg.append("usually occurs during execution of the bind function, but could\n"); errMsg.append("be delayed until this function if the bind was to a partially\n"); errMsg.append("wild-card address (involving ADDR_ANY) and if a specific address\n"); errMsg.append("needs to be \"committed\" at the time of this function."); } else if ( *errCode == WSAEINPROGRESS ) { errMsg.append("A blocking Windows Sockets 1.1 call is in progress, or the service\n"); errMsg.append("provider is still processing a callback function."); } else if ( *errCode == WSAEINVAL ) errMsg.append("The socket has not been bound with bind."); else if ( *errCode == WSAEISCONN ) errMsg.append("The socket is already connected."); else if ( *errCode == WSAEMFILE ) errMsg.append("No more socket descriptors are available."); else if ( *errCode == WSAENOBUFS ) errMsg.append("No buffer space is available."); else if ( *errCode == WSAENOTSOCK ) errMsg.append("The descriptor is not a socket."); else if ( *errCode == WSAEOPNOTSUPP ) errMsg.append("The referenced socket is not of a type that supports the listen operation."); else errMsg.append("unknown problems!"); }
// Exercise 9.45 string add_pre_and_suffix(string name, string const& pre, string const& su) { name.insert(name.begin(), pre.cbegin(), pre.cend()); return name.append(su); }
void MyTcpSocket::detectErrorSend(int* errCode,string& errMsg) { *errCode = WSAGetLastError(); if ( *errCode == WSANOTINITIALISED ) errMsg.append("A successful WSAStartup must occur before using this function."); else if ( *errCode == WSAENETDOWN ) errMsg.append("The network subsystem has failed."); else if ( *errCode == WSAEACCES ) { errMsg.append("The requested address is a broadcast address,\n"); errMsg.append("but the appropriate flag was not set. Call setsockopt\n"); errMsg.append("with the SO_BROADCAST parameter to allow the use of the broadcast address."); } else if ( *errCode == WSAEINTR ) { errMsg.append("A blocking Windows Sockets 1.1 call was canceled\n"); errMsg.append("through WSACancelBlockingCall."); } else if ( *errCode == WSAEINPROGRESS ) { errMsg.append("A blocking Windows Sockets 1.1 call is in progress,\n"); errMsg.append("or the service provider is still processing a callback function."); } else if ( *errCode == WSAEFAULT ) { errMsg.append("The buf parameter is not completely contained in a\n"); errMsg.append("valid part of the user address space."); } else if ( *errCode == WSAENETRESET ) { errMsg.append("The connection has been broken due to the keep-alive\n"); errMsg.append("activity detecting a failure while the operation was in progress."); } else if ( *errCode == WSAENOBUFS ) errMsg.append("No buffer space is available."); else if ( *errCode == WSAENOTCONN ) errMsg.append("The socket is not connected."); else if ( *errCode == WSAENOTSOCK ) errMsg.append("The descriptor is not a socket."); else if ( *errCode == WSAEOPNOTSUPP ) { errMsg.append("MSG_OOB was specified, but the socket is not stream-style\n"); errMsg.append("such as type SOCK_STREAM, out-of-band data is not supported\n"); errMsg.append("in the communication domain associated with this socket,\n"); errMsg.append("or the socket is unidirectional and supports only receive operations."); } else if ( *errCode == WSAESHUTDOWN ) { errMsg.append("The socket has been shut down; it is not possible to send\n"); errMsg.append("on a socket after shutdown has been invoked with how set\n"); errMsg.append("to SD_SEND or SD_BOTH."); } else if ( *errCode == WSAEWOULDBLOCK ) errMsg.append("The socket is marked as nonblocking and the requested operation would block.\n"); else if ( *errCode == WSAEMSGSIZE ) { errMsg.append("The socket is message oriented, and the message is larger\n"); errMsg.append("than the maximum supported by the underlying transport."); } else if ( *errCode == WSAEHOSTUNREACH ) errMsg.append("The remote host cannot be reached from this host at this time."); else if ( *errCode == WSAEINVAL ) { errMsg.append("The socket has not been bound with bind, or an unknown flag\n"); errMsg.append("was specified, or MSG_OOB was specified for a socket with SO_OOBINLINE enabled."); } else if ( *errCode == WSAECONNABORTED ) { errMsg.append("The virtual circuit was terminated due to a time-out or \n"); errMsg.append("other failure. The application should close the socket as it is no longer usable."); } else if ( *errCode == WSAECONNRESET ) { errMsg.append("The virtual circuit was reset by the remote side executing a \"hard\" \n"); errMsg.append("or \"abortive\" close. For UPD sockets, the remote host was unable to\n"); errMsg.append("deliver a previously sent UDP datagram and responded with a\n"); errMsg.append("\"Port Unreachable\" ICMP packet. The application should close\n"); errMsg.append("the socket as it is no longer usable."); } else if ( *errCode == WSAETIMEDOUT ) { errMsg.append("The connection has been dropped, because of a network failure\n"); errMsg.append("or because the system on the other end went down without notice."); } else errMsg.append("unknown problems!"); }
void gen_text_pattern(int text_len, int pattern_len, string& text, string& pattern) { text = gen_string(text_len); pattern = gen_string(pattern_len); pattern.append(1, 'z'); }
//Receive String - Maximal MAXRECV //sock_del = false : Do not delete Data from Socket ssize_t SocketHandler::Recv( string &sock_inT, bool sock_delT, int timeout ) { if ( RecvBuf.size() > (ssize_t)0 ) { sock_inT.append( RecvBuf ); if ( sock_delT == true ) { ssize_t tempsize = RecvBuf.size(); RecvBuf = ""; return tempsize; } return RecvBuf.size(); } char buffer[MAXRECV+1]; ssize_t buffer_count; int ret; if ( timeout != -1 ) { Timeout.tv_sec = timeout; } else { Timeout.tv_sec = RECVTIMEOUT; } Timeout.tv_usec = 0; FD_ZERO(&checkfd); FD_SET(sock_fd,&checkfd); ret = select_eintr(sock_fd+1, &checkfd, NULL, NULL, &Timeout); if (ret <= 0) { return -1; } while ((buffer_count = ::recv(sock_fd, buffer, MAXRECV, 0)) < 0) { if (errno == EINTR) continue; return -1; } if ( sock_delT == false ) { RecvBuf.append( buffer, buffer_count ); } if ( buffer_count == 0 ) { return 0; } sock_inT.append( buffer, buffer_count ); return buffer_count; }
void makeTmpDir(void) { char adbfsTemplate[]="/tmp/adbfs-XXXXXX"; tempDirPath.assign(mkdtemp(adbfsTemplate)); tempDirPath.append("/"); atexit(&cleanupTmpDir); }
bool ProfileDB::internalMatchProfile(Profile* profile, vector<Capability>& requiredCapabilites, vector<Capability>& optionalCapabilites, string& matchToken) { bool match = true; // When can we NOT reuse a specific runtime? // Only if fragmentation is set to BUILDTIME and if either a) one supports the capability and // the other does not OR b) the capability value differs. // So we add strings to create a unique match token for every // runtime that need be built for (vector<Capability>::iterator capability = requiredCapabilites.begin(); capability != requiredCapabilites.end(); capability++) { Capability matchedCapability = profile->getCapability( capability->getName()); CapabilityState matchedState = matchedCapability.getState(); // Ok, so we don't support this, bail out! if (matchedState == NOT_IMPLEMENTED || matchedState == UNSUPPORTED) { match = false; } Fragmentation fragmentation = matchedCapability.getFragmentation(); string valueStr = fragmentation == BUILDTIME ? matchedCapability.getValue() : ""; matchToken.append(valueStr); matchToken.append("|"); } // So, the optional capabilities are matched in a different way. // We add stuff to the matchTokens string to produce a string that // is unique to the optional capabilities being matched. for (vector<Capability>::iterator capability = optionalCapabilites.begin(); capability != optionalCapabilites.end(); capability++) { Capability matchedCapability = profile->getCapability( capability->getName()); CapabilityState matchedState = matchedCapability.getState(); Fragmentation fragmentation = matchedCapability.getFragmentation(); string valueStr = fragmentation == BUILDTIME ? matchedCapability.getValue() : ""; bool capSupported = fragmentation == BUILDTIME && (matchedState == NOT_IMPLEMENTED || matchedState == UNSUPPORTED); matchToken.append((capSupported ? "+" : "-") + valueStr); matchToken.append("|"); } // Finally we add PROPERTIES of the runtime which are buildtime fragmented. // For example, different device types or icon sizes should always generate // a unique runtime. set<string> allCapabilities = profile->getCapabilities(); for (set<string>::iterator allCapabilitesIt = allCapabilities.begin(); allCapabilitesIt != allCapabilities.end(); allCapabilitesIt++) { string capabilityName = *allCapabilitesIt; Capability capability = profile->getCapability(capabilityName); if (capability.getType() == "property") { Fragmentation fragmentation = capability.getFragmentation(); string valueStr = fragmentation == BUILDTIME ? capability.getValue() : "-"; matchToken.append(valueStr); matchToken.append("|"); } } return match; }