コード例 #1
0
ファイル: test7.C プロジェクト: vishalmistry/imitate
void prepareTestCase6(procType proc_type, BPatch_thread *thread, forkWhen when)
{
   const int TN = 6;

   if(proc_type == Parent_p  &&  when == PostFork) {
      BPatch_image *parImage = thread->getImage();

      BPatch_variableExpr *var7_6p = 
	 parImage->findVariable("globalVariable7_6");
      if(doError(TN, (var7_6p==NULL),
		 "  Unable to locate variable globalVariable7_6\n")) return;

      BPatch_arithExpr a_expr7_6p(BPatch_plus, *var7_6p, BPatch_constExpr(5));
      BPatch_arithExpr b_expr7_6p(BPatch_assign, *var7_6p, a_expr7_6p);
      thread->oneTimeCode(b_expr7_6p);
   } else if(proc_type == Child_p  &&  when == PostFork) {
      BPatch_image *childImage = thread->getImage();

      BPatch_variableExpr *var7_6c = 
	 childImage->findVariable("globalVariable7_6");
      if(doError(TN, (var7_6c==NULL),
		 "  Unable to locate variable globalVariable7_6\n")) return;

      BPatch_arithExpr a_expr7_6c(BPatch_plus, *var7_6c, BPatch_constExpr(9));
      BPatch_arithExpr b_expr7_6c(BPatch_assign, *var7_6c, a_expr7_6c);
      thread->oneTimeCode(b_expr7_6c);
   }
}
コード例 #2
0
ファイル: wbind.c プロジェクト: Ukusbobra/open-watcom-v2
static long CopyFile( int in, int out, char *infile, char *outfile )
{
    unsigned    size;
    unsigned    len;
    unsigned    bufsize;
    long        totalsize;
    void        *buff;

    buff = myAlloc( IO_BUFF );
    bufsize = IO_BUFF;
    totalsize = 0L;
    for( ;; ) {
        size = read( in, buff, bufsize );
        if( size == 0 ) {
            break;
        }

        if( size == -1 ) {
            doError( "Error reading file \"%s\"", infile );
        }
        len = write( out, buff, size );
        if( len != size ) {
            doError( "Error writing file \"%s\"", outfile );
        }
        totalsize += len;
        if( (unsigned) size != bufsize ) {
            break;
        }
    }
    free( buff );
    return( totalsize );
}
コード例 #3
0
bool ElogThreadSubmit::doResponseError( const char* response ) {
  QString strError;
  char str[80];
  
  if (strstr(response, "302 Found")) {
    if (strstr(response, "Location:")) {
      if (strstr(response, "wpwd")) {
        doError( tr2i18n("Failed to add ELOG entry: invalid password") );
      } else if (strstr(response, "wusr")) {
        doError( tr2i18n("Failed to add ELOG entry: invalid user name") );
      } else {
        strncpy(str, strstr(response, "Location:") + 10, sizeof(str));
        if (strchr(str, '?')) {
          *strchr(str, '?') = 0;
        }
        if (strchr(str, '\n')) {
          *strchr(str, '\n') = 0;
        }
        if (strchr(str, '\r')) {
          *strchr(str, '\r') = 0;
        }
        
        if (strrchr(str, '/')) {
          strError = tr2i18n("Successfully added ELOG entry: ID=%1\n").arg( strrchr(str, '/') + 1 );
          doError( strError, KstDebug::Notice );
        } else {
          strError = tr2i18n("Successfully added ELOG entry: ID=%1\n").arg( str );
          doError( strError, KstDebug::Notice );
        }
      }
    } else {
      doError( tr2i18n("Successfully added ELOG entry"), KstDebug::Notice );
    }
  } else if (strstr(response, "Logbook Selection"))
    doError( tr2i18n("Failed to add ELOG entry: no logbook specified") );
  else if (strstr(response, "enter password")) {
    doError( tr2i18n("Failed to add ELOG entry: missing or invalid password") );
  }
  else if (strstr(response, "form name=form1")) {
    doError( tr2i18n("Failed to add ELOG entry: missing or invalid user name/password") );
  }
  else if (strstr(response, "Error: Attribute")) {
    strncpy(str, strstr(response, "Error: Attribute") + 20, sizeof(str));
    if (strchr(str, '<')) {
      *strchr(str, '<') = 0;
    }
    strError = tr2i18n("Failed to add ELOG entry: missing required attribute \"%1\"").arg( str );
    doError( strError );
  } else {
    doError( tr2i18n("Failed to add ELOG entry: error transmitting message") ); 
  }
  
  return TRUE;
}
コード例 #4
0
ファイル: nbd-server.c プロジェクト: madpenguin/VDCCloud
void doAccept(int listener)
{
	int net,f,sock;
	fd_set rfds;
	struct sockaddr_storage addrin;
	socklen_t addrinlen=sizeof(addrin);

	doLog("Enter ACCEPT");
	while(1) {
		FD_ZERO(&rfds);
		FD_SET(listener, &rfds);
		if(select(listener+1, &rfds, NULL, NULL, NULL)>0) {
			if(FD_ISSET(listener, &rfds)) {
				if ((sock=accept(listener, (struct sockaddr *) &addrin, &addrinlen)) < 0) {
					doError("Error on ACCEPT");
					continue;
				}
				f = fork();
				if(f<0) { printf("Fork error [err=%d]\n",errno); exit(1); }
				if(f==0) {
					syslog(LOG_INFO,"Forkd new process with id = %d",getpid());
					setsid();
					for (f=getdtablesize();f>=0;--f) if(f!=sock) close(f);
					f=open("/dev/null",O_RDWR); dup(f); dup(f); umask(027); chdir("/tmp/");
					doSession(sock);
					close(sock);
					syslog(LOG_INFO,"Process with pid %d terminated",getpid());
					exit(0);
				}
				close(sock);
			}
		}	
	}
	doLog("Exit ACCEPT");
}
コード例 #5
0
ファイル: test7.C プロジェクト: vishalmistry/imitate
void prepareTestCase9(procType proc_type, BPatch_thread *thread, forkWhen when)
{
   const int TN = 9;

   if(proc_type == Parent_p  &&  when == PreFork) {
      BPatch_image *parImage = thread->getImage();
      var7_9p = thread->malloc(*(parImage->findType("int")));
      if(doError(TN, (var7_9p==NULL),
		 "  Unable to malloc variable in parent\n")) return;

      BPatch_arithExpr a_expr7_9p(BPatch_assign, *var7_9p,
				  BPatch_constExpr(10));
      thread->oneTimeCode(a_expr7_9p);
   } else if(proc_type == Parent_p  &&  when == PostFork) {
      // can't delete var7_9p here, since then the getInheritedVariable
      // would be operating on a freed variable
   } else if(proc_type == Child_p  &&  when == PostFork) {
      var7_9c = thread->getInheritedVariable(*var7_9p);
      parentThread->free(*var7_9p);

      BPatch_image *childImage = thread->getImage();

      BPatch_Vector<BPatch_function *> found_funcs;
      const char *inFunction = "func7_9";
      if ((NULL == childImage->findFunction(inFunction, found_funcs, 1)) || !found_funcs.size()) {
	fprintf(stderr, "    Unable to find function %s\n",
		inFunction);
	exit(1);
      }
      
      if (1 < found_funcs.size()) {
	fprintf(stderr, "%s[%d]:  WARNING  : found %d functions named %s.  Using the first.\n", 
		__FILE__, __LINE__, found_funcs.size(), inFunction);
      }
      
      BPatch_Vector<BPatch_point *> *points7_9c = found_funcs[0]->findPoint(BPatch_entry);

      if(doError(TN, !points7_9c || ((*points7_9c).size() == 0),
		 "  Unable to find entry point to \"func7_9\".\n")) return;
      BPatch_point *point7_9c = (*points7_9c)[0];

      BPatch_arithExpr a_expr7_9c(BPatch_plus, *var7_9c, BPatch_constExpr(5));
      BPatch_arithExpr b_expr7_9c(BPatch_assign, *var7_9c, a_expr7_9c);

      thread->insertSnippet(b_expr7_9c, *point7_9c, BPatch_callBefore);
   }
}
コード例 #6
0
ファイル: wbind.c プロジェクト: Ukusbobra/open-watcom-v2
static void *myAlloc( size_t amount )
{
    void        *tmp;

    tmp = malloc( amount );
    if( tmp == NULL ) {
        doError("Out of memory!");
    }
    return( tmp );
}
コード例 #7
0
ファイル: steam.cpp プロジェクト: scharsig/keenportfolio
/*!
  \brief Connects the \p reply object with it's slots here.

  \param reply The \c QNetworkReply object to connect to everything.
*/
void
Steam::connectReply( QNetworkReply *reply )
{
  if( ! reply )
    return;

  connect( reply, SIGNAL( downloadProgress( qint64, qint64 ) ), this,
    SLOT( doDownloadProgress( qint64, qint64 ) ) );
  connect( reply, SIGNAL( error( QNetworkReply::NetworkError ) ), this,
    SLOT( doError() ) );
  connect( reply, SIGNAL( finished() ), this, SLOT( doFinished() ) );
}
コード例 #8
0
ファイル: test7.C プロジェクト: vishalmistry/imitate
void prepareTestCase1(procType proc_type, BPatch_thread *thread, forkWhen when)
{
   static BPatchSnippetHandle *parSnippetHandle1;
   
   if(proc_type == Parent_p  &&  when == PreFork) {
       BPatch_image *parImage = thread->getImage();
       
       BPatch_Vector<BPatch_function *> found_funcs;
       const char *inFunction = "func7_1";
       if ((NULL == parImage->findFunction(inFunction, found_funcs, 1)) || !found_funcs.size()) {
           fprintf(stderr, "    Unable to find function %s\n",
                   inFunction);
           exit(1);
       }
       
       if (1 < found_funcs.size()) {
           fprintf(stderr, "%s[%d]:  WARNING  : found %d functions named %s.  Using the first.\n", 
                   __FILE__, __LINE__, found_funcs.size(), inFunction);
       }
       
       BPatch_Vector<BPatch_point *> *point7_1p = found_funcs[0]->findPoint(BPatch_entry);
       
       if(doError(1, !point7_1p || ((*point7_1p).size() == 0),
                  "  Unable to find entry point to \"func7_1\".\n")) return;
       
       BPatch_variableExpr *var7_1p = 
       parImage->findVariable("globalVariable7_1");
       if(doError(1, (var7_1p==NULL),
                  "  Unable to locate variable globalVariable7_1\n")) return;
       
       BPatch_arithExpr expr7_1p(BPatch_assign, *var7_1p,BPatch_constExpr(321));
       
       parSnippetHandle1 =
       thread->insertSnippet(expr7_1p, *point7_1p, BPatch_callBefore);
       if(doError(1, (parSnippetHandle1 == NULL),
                  "  Unable to insert snippet into parent for test 1\n")) return;
   } else if(proc_type == Parent_p  &&  when == PostFork) {
       thread->deleteSnippet(parSnippetHandle1);
   }
}
コード例 #9
0
void ElogThreadSubmit::run( ) {
  int status, sock, error;
  
  error = makeConnection( &sock, &status );
  if( status == 0 ) {
    doTransmit( sock );
    close( sock );
  }
  else {
    switch( error ) {
      case -1:
        doError( tr2i18n("Failed to add ELOG entry: failed to connect to host.") );          	      		  break;
      case -2:
        doError( tr2i18n("Failed to add ELOG entry: failed to get host name.") );          	      		  break;
      case -3:
        doError( tr2i18n("Failed to add ELOG entry: failed to create socket.") );
        break;
      case -4:
        doError( tr2i18n("Failed to add ELOG entry: failed to get host by address.") );
        break;
      case -5:
        doError( tr2i18n("Failed to add ELOG entry: failed to get host by name.") );          	      		  break;
      default:
        doError( tr2i18n("Failed to add ELOG entry: unknown error.") );
        break;
    }
  }
}
コード例 #10
0
ファイル: test7.C プロジェクト: vishalmistry/imitate
void prepareTestCase4(procType proc_type, BPatch_thread *thread, forkWhen when)
{
   const int TN = 4;
   static BPatchSnippetHandle *parSnippetHandle4;

   if(proc_type == Child_p  &&  when == PostFork) {
      BPatch_image *childImage = thread->getImage();

      BPatch_Vector<BPatch_function *> found_funcs;
      const char *inFunction = "func7_4";
      if ((NULL == childImage->findFunction(inFunction, found_funcs, 1)) || !found_funcs.size()) {
	fprintf(stderr, "    Unable to find function %s\n",
		inFunction);
	exit(1);
      }
      
      if (1 < found_funcs.size()) {
	fprintf(stderr, "%s[%d]:  WARNING  : found %d functions named %s.  Using the first.\n", 
		__FILE__, __LINE__, found_funcs.size(), inFunction);
      }
      
      BPatch_Vector<BPatch_point *> *points7_4c = found_funcs[0]->findPoint(BPatch_entry);
      if(doError(TN, !points7_4c || ((*points7_4c).size() == 0),
		 "  Unable to find entry point to \"func7_4\".\n")) return;
      BPatch_point *point7_4c = (*points7_4c)[0];

      BPatch_variableExpr *var7_4c = 
	 childImage->findVariable("globalVariable7_4");
      if(doError(TN, (var7_4c==NULL),
		 "  Unable to locate variable globalVariable7_4\n")) return;

      BPatch_arithExpr a_expr7_4c(BPatch_plus, *var7_4c,BPatch_constExpr(211));
      BPatch_arithExpr b_expr7_4c(BPatch_assign, *var7_4c, a_expr7_4c);
      parSnippetHandle4 =
	thread->insertSnippet(b_expr7_4c, *point7_4c, BPatch_callBefore);
   }
}
コード例 #11
0
ファイル: sync_pollable.cpp プロジェクト: dshatrov/mycpp
void
SyncPollable::processError ()
{
    stateMutex.lock ();

    if (processingInput  ||
	processingOutput ||
	processingError)
    {
	errorDirty = true;
    } else
	doError ();

    stateMutex.unlock ();
}
コード例 #12
0
ファイル: extconn.cpp プロジェクト: 52M/openlitespeed
int ExtConn::onError()
{
    int error = errno;
    int ret = getSockError(&error);
    if ((ret == -1) || (error != 0))
    {
        if (ret != -1)
            errno = error;
    }
    LS_DBG_L(this, "ExtConn::onError()");
    if (error != 0)
    {
        m_iState = CLOSING;
        doError(error);
    }
    else
        onRead();
    return LS_FAIL;
}
コード例 #13
0
bool WebsocketServlet_impl::doPost(acl::HttpServletRequest& req,
	acl::HttpServletResponse& res)
{
	res.setContentType("text/html; charset=utf-8")	// 设置响应字符集
		.setContentEncoding(false)		// 设置是否压缩数据
		.setChunkedTransferEncoding(true);	// 采用 chunk 传输方式

	const char* ip = req.getLocalAddr();
	if (ip == NULL || *ip == 0)
	{
		logger_error("getLocalAddr error");
		return false;
	}
	unsigned short port = req.getLocalPort();
	if (port == 0)
	{
		logger_error("getLocalPort error");
		return false;
	}

	acl::string local_addr;
	local_addr << ip << ":" << port;

	printf("getLocalAddr: %s\r\n", local_addr.c_str());

	acl::string html_file;
	html_file << "www/upload.html";
	acl::string buf;
	if (acl::ifstream::load(html_file, &buf) == false)
	{
		logger_error("load %s error %s",
			html_file.c_str(), acl::last_serror());
		return doError(req, res);
	}

	buf << "<script>g_url='ws://" << local_addr << "/'</script>";

	// 发送 http 响应体,因为设置了 chunk 传输模式,所以需要多调用一次
	// res.write 且两个参数均为 0 以表示 chunk 传输数据结束
	return res.write(buf) && res.write(NULL, 0);
}
コード例 #14
0
ファイル: http_servlet.cpp プロジェクト: LazyPlanet/acl
bool http_servlet::doPost(acl::HttpServletRequest& req,
	acl::HttpServletResponse& res)
{
	res.setContentType("text/html; charset=utf-8")	// 设置响应字符集
		.setContentEncoding(true)		// 设置是否压缩数据
		.setChunkedTransferEncoding(false);	// 采用 chunk 传输方式

	acl::string html_file;
	html_file << var_cfg_html_path << "/client.html";
	acl::string buf;
	if (acl::ifstream::load(html_file, &buf) == false)
	{
		logger_error("load %s error %s",
			html_file.c_str(), acl::last_serror());
		return doError(req, res);
	}

	// 发送 http 响应体,因为设置了 chunk 传输模式,所以需要多调用一次
	// res.write 且两个参数均为 0 以表示 chunk 传输数据结束
	return res.write(buf) && res.write(NULL, 0);
}
コード例 #15
0
ファイル: sync_pollable.cpp プロジェクト: dshatrov/mycpp
void
SyncPollable::doInput ()
{
    processingInput = true;
    inputDirty = false;
    stateMutex.unlock ();

    for (;;) {
	pollable->processInput ();

	stateMutex.lock ();

	if (processingError) {
	    if (errorDirty) {
		processingInput = false;
		return;
	    }

	    /* If we are processing an error,
	     * then output and input processing threads
	     * have already collapsed into one thread,
	     * and we have to call output handlers
	     * from within input handlers, and vice versa. */

	    if (processingOutput == false)
		if (outputDirty)
		    doOutput ();
	} else
	    if (errorDirty)
		doError ();

	if (inputDirty == false) {
	    processingInput = false;
	    return;
	}

	inputDirty = false;
	stateMutex.unlock ();
    }
}
コード例 #16
0
ファイル: test_fork_8.C プロジェクト: cuviper/testsuite
static int mutatorTest(BPatch *bpatch, BPatch_thread *appThread)
{
    if ( !setupMessaging(&msgid) )
    {
       passedTest = false;
       return passedTest;
    }

    parentThread = appThread;

    initialPreparation(parentThread);
    /* ok, do the fork */;
                         parentThread->getProcess()->continueExecution();

    /* the rest of the execution occurs in postForkFunc() */
    /* Secondary test: we should not have to manually continue
       either parent or child at any point */

    while ( !parentThread->getProcess()->isTerminated() )
    {
       bpatch->waitForStatusChange();
    }

    // At this point if childThread == NULL the postfork handler failed
    // to run.  Fail gracefully instead of segfaulting on 
    // childThread->isTerminated()
    if (doError(&passedTest, childThread == NULL,
             "childThread == NULL: postForkFunc must not have run\n") )
    {
       return passedTest;
    }
    
    while ( !childThread->getProcess()->isTerminated() )
    {
       bpatch->waitForStatusChange();
    }

    return passedTest;
}
コード例 #17
0
ファイル: wbind.c プロジェクト: Ukusbobra/open-watcom-v2
void FindExtender( char *extname, char *winext )
{
    char        *watcom;

    _searchenv( extname, "PATH", winext );
    if( winext[0] == '\0' ) {
        watcom = getenv( "WATCOM" );
        if( watcom != NULL ) {
            strcpy( winext, watcom );
#if defined( __UNIX__ )
            strcat( winext, "/binw/" );
#else
            strcat( winext, "\\binw\\" );
#endif
            strcat( winext, extname );
            if( access( winext, R_OK ) == -1 ) {
                winext[0] = '\0';               // indicate file not found
            }
        }
        if( winext[0] == '\0' ) {
            doError( "Could not find \"%s\" in your path", extname );
        }
    }
}
コード例 #18
0
void CWizXmlRpcEventLoop::on_replyError(QNetworkReply::NetworkError error)
{
    doError(error);
    //
    quit();
}
コード例 #19
0
ファイル: HttpServlet.cpp プロジェクト: 10jschen/acl
bool HttpServlet::doRun(session& session, socket_stream* stream /* = NULL */,
	bool body_parse /* = true */, int body_limit /* = 102400 */)
{
	socket_stream* in;
	socket_stream* out;
	bool cgi_mode;

	if (stream == NULL)
	{
		// 数据流为空,则当 CGI 模式处理,将标准输入输出
		// 作为数据流
		stream = NEW socket_stream();
		(void) stream->open(ACL_VSTREAM_IN);
		in = stream;

		stream = NEW socket_stream();
		(void) stream->open(ACL_VSTREAM_OUT);
		out = stream;
		cgi_mode = true;
	}
	else
	{
		in = out = stream;
		cgi_mode = false;
	}

	// req/res 采用栈变量,减少内存分配次数

	HttpServletResponse res(*out);
	HttpServletRequest req(res, session, *in, local_charset_,
		body_parse, body_limit);

	if (rw_timeout_ >= 0)
		req.setRwTimeout(rw_timeout_);

	res.setCgiMode(cgi_mode);

	bool  ret;

	http_method_t method = req.getMethod();
	if (method == HTTP_METHOD_GET)
		ret = doGet(req, res);
	else if (method == HTTP_METHOD_POST)
		ret = doPost(req, res);
	else if (method == HTTP_METHOD_PUT)
		ret = doPut(req, res);
	else if (method == HTTP_METHOD_CONNECT)
		ret = doConnect(req, res);
	else if (method == HTTP_METHOD_PURGE)
		ret = doPurge(req, res);
	else
	{
		ret = false; // 有可能是IO失败或未知方法
		http_request_error_t n = req.getLastError();
		if (n == HTTP_REQ_ERR_METHOD)
			doUnknown(req, res);
		else
			doError(req, res);
	}

	if (in != out)
	{
		// 如果是标准输入输出流,则需要先将数据流与标准输入输出解绑,
		// 然后才能释放数据流对象,数据流内部会自动判断流句柄合法性
		// 这样可以保证与客户端保持长连接
		in->unbind();
		out->unbind();
		delete in;
		delete out;
	}

	return ret;
}
コード例 #20
0
ファイル: HttpServlet.cpp プロジェクト: LazyPlanet/acl
bool HttpServlet::start()
{
	socket_stream* in;
	socket_stream* out;
	bool cgi_mode;

	bool first = first_;
	if (first_)
		first_ = false;

	if (stream_ == NULL)
	{
		// 数据流为空,则当 CGI 模式处理,将标准输入输出
		// 作为数据流
		in = NEW socket_stream();
		in->open(ACL_VSTREAM_IN);

		out = NEW socket_stream();
		out->open(ACL_VSTREAM_OUT);
		cgi_mode = true;
	}
	else
	{
		in = out = stream_;
		cgi_mode = false;
	}

	// 在 HTTP 长连接重复请求情况下,以防万一,需要首先删除请求/响应对象
	delete req_;
	delete res_;

	res_ = NEW HttpServletResponse(*out);
	req_ = NEW HttpServletRequest(*res_, *session_, *in, local_charset_,
			 parse_body_enable_, parse_body_limit_);

	// 设置 HttpServletRequest 对象
	res_->setHttpServletRequest(req_);

	if (rw_timeout_ >= 0)
		req_->setRwTimeout(rw_timeout_);

	res_->setCgiMode(cgi_mode);

	string method_s(32);
	http_method_t method = req_->getMethod(&method_s);

	// 根据请求的值自动设定是否需要保持长连接
	if (!cgi_mode)
		res_->setKeepAlive(req_->isKeepAlive());

	bool  ret;

	switch (method)
	{
	case HTTP_METHOD_GET:
		if (upgradeWebsocket(*req_, *res_))
		{
			if (res_->sendHeader() == false)
			{
				logger_error("sendHeader error!");
				return false;
			}
			ret = doWebsocket(*req_, *res_);
		} else
			ret = doGet(*req_, *res_);
		break;
	case HTTP_METHOD_POST:
		ret = doPost(*req_, *res_);
		break;
	case HTTP_METHOD_PUT:
		ret = doPut(*req_, *res_);
		break;
	case HTTP_METHOD_CONNECT:
		ret = doConnect(*req_, *res_);
		break;
	case HTTP_METHOD_PURGE:
		ret = doPurge(*req_, *res_);
		break;
	case HTTP_METHOD_DELETE:
		ret = doDelete(*req_, *res_);
		break;
	case  HTTP_METHOD_HEAD:
		ret = doHead(*req_, *res_);
		break;
	case HTTP_METHOD_OPTION:
		ret = doOptions(*req_, *res_);
		break;
	case HTTP_METHOD_PROPFIND:
		ret = doPropfind(*req_, *res_);
		break;
	case HTTP_METHOD_OTHER:
		ret = doOther(*req_, *res_, method_s.c_str());
		break;
	default:
		ret = false; // 有可能是IO失败或未知方法
		if (req_->getLastError() == HTTP_REQ_ERR_METHOD)
			doUnknown(*req_, *res_);
		else if (first)
			doError(*req_, *res_);
		break;
	}

	if (in != out)
	{
		// 如果是标准输入输出流,则需要先将数据流与标准输入输出解绑,
		// 然后才能释放数据流对象,数据流内部会自动判断流句柄合法性
		// 这样可以保证与客户端保持长连接
		in->unbind();
		out->unbind();
		delete in;
		delete out;
	}

	return ret;
}
コード例 #21
0
ファイル: HttpServlet.cpp プロジェクト: lunlun1992/acl
bool HttpServlet::doRun(dbuf_pool* dbuf)
{
	socket_stream* in;
	socket_stream* out;
	bool cgi_mode;

	bool first = first_;
	if (first_)
		first_ = false;

	if (stream_ == NULL)
	{
		// 数据流为空,则当 CGI 模式处理,将标准输入输出
		// 作为数据流
		in = NEW socket_stream();
		in->open(ACL_VSTREAM_IN);

		out = NEW socket_stream();
		out->open(ACL_VSTREAM_OUT);
		cgi_mode = true;
	}
	else
	{
		in = out = stream_;
		cgi_mode = false;
	}

	// req/res 采用栈变量,减少内存分配次数

	HttpServletResponse res(*out, dbuf);
	HttpServletRequest req(res, *session_, *in, local_charset_,
		parse_body_enable_, parse_body_limit_, dbuf);

	// 设置 HttpServletRequest 对象
	res.setHttpServletRequest(&req);

	if (rw_timeout_ >= 0)
		req.setRwTimeout(rw_timeout_);

	res.setCgiMode(cgi_mode);

	string method_s(32);
	http_method_t method = req.getMethod(&method_s);

	// 根据请求的值自动设定是否需要保持长连接
	if (!cgi_mode)
		res.setKeepAlive(req.isKeepAlive());

	bool  ret;

	switch (method)
	{
	case HTTP_METHOD_GET:
		ret = doGet(req, res);
		break;
	case HTTP_METHOD_POST:
		ret = doPost(req, res);
		break;
	case HTTP_METHOD_PUT:
		ret = doPut(req, res);
		break;
	case HTTP_METHOD_CONNECT:
		ret = doConnect(req, res);
		break;
	case HTTP_METHOD_PURGE:
		ret = doPurge(req, res);
		break;
	case HTTP_METHOD_DELETE:
		ret = doDelete(req, res);
		break;
	case  HTTP_METHOD_HEAD:
		ret = doHead(req, res);
		break;
	case HTTP_METHOD_OPTION:
		ret = doOptions(req, res);
		break;
	case HTTP_METHOD_PROPFIND:
		ret = doPropfind(req, res);
		break;
	case HTTP_METHOD_OTHER:
		ret = doOther(req, res, method_s.c_str());
		break;
	default:
		ret = false; // 有可能是IO失败或未知方法
		if (req.getLastError() == HTTP_REQ_ERR_METHOD)
			doUnknown(req, res);
		else if (first)
			doError(req, res);
		break;
	}

	if (in != out)
	{
		// 如果是标准输入输出流,则需要先将数据流与标准输入输出解绑,
		// 然后才能释放数据流对象,数据流内部会自动判断流句柄合法性
		// 这样可以保证与客户端保持长连接
		in->unbind();
		out->unbind();
		delete in;
		delete out;
	}

	// 返回给上层调用者:true 表示继续保持长连接,否则表示需断开连接
	return ret && req.isKeepAlive()
		&& res.getHttpHeader().get_keep_alive();
}
コード例 #22
0
ファイル: WeiboDialog.cpp プロジェクト: BIbiLion/PhotoKit
	void setupUi(WeiboDialog *ui) {
		QObject::connect(api, SIGNAL(error(QString)), ui, SLOT(doError(QString)));
        QObject::connect(api, SIGNAL(loginOk()), ui, SLOT(loginDone()));
        ui->resize(qApp->desktop()->width()/2 - 11, qApp->desktop()->height() -22);
	}
コード例 #23
0
ファイル: llerror_tut.cpp プロジェクト: Nora28/imprudence
	static void doAll() { doDebug(); doInfo(); doWarn(); doError(); }
コード例 #24
0
void ElogThreadSubmit::doTransmit(int sock) {
  KstELOGCaptureStruct captureStruct;
  QByteArray	byteArrayCapture;
  QBuffer bufferCapture( byteArrayCapture );
  QByteArray	byteArrayConfigure;
  QTextStream textStreamConfigure( byteArrayConfigure, IO_ReadWrite );
  QByteArray	byteArrayDebugInfo;
  QTextStream textStreamDebugInfo( byteArrayDebugInfo, IO_ReadWrite );
  QCustomEvent eventCapture(KstELOGCaptureEvent);
  QCustomEvent eventConfigure(KstELOGConfigureEvent);
  QCustomEvent eventDebugInfo(KstELOGDebugInfoEvent);
  QStringList::iterator it;
  QStringList	strListAttributes;
  QStringList	strListAttribute;
  QString strSplit( "\n" );
  QString strSplitAttribute( "=" );
  QString strUserName;
  QString strUserPassword;
  QString strWritePassword;
  QString strLogbook;
  QString strAttributes;
  QString strText;
  bool bIncludeCapture;
  bool bIncludeConfiguration;
  bool bIncludeDebugInfo;
  bool bSubmitAsHTML;
  bool bSuppressEmail;
  char* content;
  char request[100000];
  char response[100000];
  char boundary[80], str[80], *p;
  int i, n, header_length, content_length;
  int iAttachment = 0;

  bIncludeCapture   		= _elog->entry()->includeCapture();
  bIncludeConfiguration = _elog->entry()->includeConfiguration();
  bIncludeDebugInfo     = _elog->entry()->includeDebugInfo();
  content_length 			  = 100000;
  
  if( bIncludeCapture ) {  
    captureStruct.pBuffer     = &bufferCapture;
    captureStruct.iWidth      = _elog->configuration()->captureWidth();
    captureStruct.iHeight     = _elog->configuration()->captureHeight();
    eventCapture.setData( &captureStruct );
    QApplication::sendEvent( (QObject*)_elog->app()->viewObject(), (QEvent*)&eventCapture );
    content_length += byteArrayCapture.size();
  }
  
  if( bIncludeConfiguration ) {
    eventConfigure.setData( &textStreamConfigure );
    QApplication::sendEvent( (QObject*)_elog->app(), (QEvent*)&eventConfigure );
    content_length += byteArrayConfigure.size();
  }
  
  if( bIncludeDebugInfo ) {
    eventDebugInfo.setData( &textStreamDebugInfo );
    QApplication::sendEvent( (QObject*)_elog->app(), (QEvent*)&eventDebugInfo );
    content_length += byteArrayDebugInfo.size();
  }
  
  content = (char*)malloc(content_length);
  if (content != NULL) {
    strUserName 					= _elog->configuration()->userName();
    strUserPassword 			= _elog->configuration()->userPassword();
    strWritePassword			= _elog->configuration()->writePassword();
    strLogbook  					= _elog->configuration()->name();
    bSubmitAsHTML    		  = _elog->configuration()->submitAsHTML();
    bSuppressEmail    		= _elog->configuration()->suppressEmail();
    strAttributes     		= _elog->entry()->attributes();
    strText     					= _elog->entry()->text();
    
    srand((unsigned) time(NULL));
    sprintf(boundary, "---------------------------%04X%04X%04X", rand(), rand(), rand());
    strcpy(content, boundary);
    strcat(content, "\r\nContent-Disposition: form-data; name=\"cmd\"\r\n\r\nSubmit\r\n");
    
    //
    // add the attributes...
    //
    addAttribute( content, boundary, "unm", strUserName, false );
    addAttribute( content, boundary, "upwd", strUserPassword, true );
    addAttribute( content, boundary, "exp", strLogbook, false );
    
    strListAttributes = QStringList::split( strSplit, strAttributes, FALSE ); 
    for ( it = strListAttributes.begin(); it != strListAttributes.end(); ++it ) {
      strListAttribute = QStringList::split( strSplitAttribute, *it, FALSE );
      if( strListAttribute.count() == 2 ) {
        addAttribute( content, boundary, 
                      strListAttribute.first().stripWhiteSpace().ascii(),
                      strListAttribute.last().stripWhiteSpace(), false );
      }
    }
    if( bSubmitAsHTML ) {
      addAttribute( content, boundary, "html", "1", false );      
    }
    if( bSuppressEmail ) {
      addAttribute( content, boundary, "suppress", "1", false );      
    }
    addAttribute( content, boundary, "Text", strText, false );
    sprintf( content + strlen(content), "%s\r\n", boundary );

    content_length = strlen(content);
    p = content + content_length;
    
    //
    // add the attachments...
    //
    if( bIncludeCapture ) {
      iAttachment++;
      addAttachment( &content_length, &p, boundary, &byteArrayCapture, iAttachment, "Capture.png" );
    }
    if( bIncludeConfiguration ) {
      iAttachment++;
      addAttachment( &content_length, &p, boundary, &byteArrayConfigure, iAttachment, "Configure.kst" );
    }
    if( bIncludeDebugInfo ) {
      iAttachment++;
      addAttachment( &content_length, &p, boundary, &byteArrayDebugInfo, iAttachment, "DebugInfo.txt" );
    }

    strcpy(request, "POST /");
    if (!strLogbook.isEmpty()) {
      sprintf(request + strlen(request), "%s/", strLogbook.ascii());
    }
    strcat(request, " HTTP/1.0\r\n");
    
    sprintf(request + strlen(request), "Content-Type: multipart/form-data; boundary=%s\r\n", boundary);
    sprintf(request + strlen(request), "Host: %s\r\n", _host_name);
    sprintf(request + strlen(request), "User-Agent: ELOG\r\n");
    sprintf(request + strlen(request), "Content-Length: %d\r\n", content_length);
    
    if (!strWritePassword.isEmpty()) {
      base64_encode(strWritePassword.ascii(), str);
      sprintf(request + strlen(request), "Cookie: wpwd=%s\r\n", str);
    }

    strcat(request, "\r\n");
    
    header_length = strlen(request);
    
    send(sock, request, header_length, 0);
    send(sock, content, content_length, 0);
    
    //
    // handle the response...
    //
    i = recv(sock, response, 10000, 0);
    if (i >= 0) {    
      n = i;
      while (i > 0) {
        i = recv(sock, response + n, 10000, 0);
        if (i > 0) {
          n += i;
        }
      }
      response[n] = 0;
      
      doResponseError(response);
    }
    else
    {
      doError( tr2i18n("ELOG entry: unable to receive response"), KstDebug::Notice );
    }
  }
}
コード例 #25
0
void CWizAutoTimeOutEventLoop::on_replyError(QNetworkReply::NetworkError error)
{
    doError(error);
    //
    quit();
}
コード例 #26
0
ファイル: nbd-server.c プロジェクト: madpenguin/VDCCloud
void doSession(int sock)
{
	struct nbd_request request;
	struct nbd_reply reply;
	char buffer[1024*132];
	int readlen,bytes;
	int running = True;
	int db;

	doLog("Enter SESSION");
	doConnectionMade(sock);
	if(db=doNegotiate(sock)) {
	
		doLog("Processing DATA requests ...");
        		        
		do {
            
			getBytes(sock,&request,sizeof(request));
			off = ntohll(request.from);
			cmd = ntohl(request.type) & NBD_CMD_MASK_COMMAND;
			len = ntohl(request.len);
			reply.magic = htonl(NBD_REPLY_MAGIC);
			reply.error = 0;
			memcpy(reply.handle, request.handle, sizeof(reply.handle));
			
			if(debug) {	
				snprintf(pbuf,sizeof(pbuf),"%s - block [%04llx] %ld blocks, off=%lld, len=%ld",	
					cmds[cmd],						
					(long long unsigned int)(off/1024),		
					(long unsigned int)(len/1024),			
					(long long unsigned int)off,(long unsigned int)len	
				);								
				doLog(pbuf);							
			}	
			switch(cmd) {
				case NBD_READ:
					putBytes(sock,&reply,sizeof(reply));									
					if(lseek(db,off,SEEK_SET)==-1) running = doError("SEEK");
					while( len > 0 ) {
						readlen = len > sizeof(buffer)?sizeof(buffer):len;
						//syslog(LOG_ERR,"READ: %d, %lld %ld",db,(unsigned long long)off,(unsigned long) len);
						bytes = read(db,&buffer,readlen);
						if( bytes != readlen ) running = doError("READ");
						else putBytes(sock,&buffer,readlen);
						len -= readlen;
					}
				break;
                
			case NBD_WRITE:
				if(lseek(db,off,SEEK_SET)==-1) running = doError("SEEK");
				while( len > 0 ) {
					readlen = len > sizeof(buffer)?sizeof(buffer):len;
				        getBytes(sock,&buffer,readlen);
					bytes = write(db,&buffer,readlen);
					if( bytes != readlen ) running = doError("WRITE");
					len -= readlen;
				}
				putBytes(sock,&reply,sizeof(reply));
				break;
            
			case NBD_CLOSE:
				running = False;
				break;
			
			case NBD_TRIM:
				// FIXME :: TRIM Code needed
				putBytes(sock,&reply,sizeof(reply));
				break;
				
			case NBD_FLUSH:
				// FIXME :: FLUSH Code needed
				putBytes(sock,&reply,sizeof(reply));
				break;
                
			default:
				doError("Unknown Command");
			}	
		} while( running );          
	}
	if(db) close(db);
	doLog("Exit SESSION");
}
コード例 #27
0
ファイル: wbind.c プロジェクト: Ukusbobra/open-watcom-v2
int main( int argc, char *argv[] )
{
    int             in, out, i, rcparm = 0, pcnt;
    int             Rflag = FALSE, nflag = FALSE;
    int             uflag = FALSE;
    int             dllflag = FALSE;
    char            *wext = NULL;
    long            tsize = 0;
    char            drive[_MAX_DRIVE], dir[_MAX_DIR], fname[_MAX_FNAME];
    char            ext[_MAX_EXT];
    char            rex[_MAX_PATH];
    char            exe[_MAX_PATH];
    char            dll[_MAX_PATH];
    char            res[_MAX_PATH];
    char            winext[_MAX_PATH];
    char            rc[256];
    long            totalsize;
    const char      **arglist;
    char            *path = NULL;
    int             currarg,len;
    simple_header   re;
    long            exelen;
    char            *desc = NULL;

    /*
     * get parms
     */
    if( argc < 2 ) {
        doUsage( NULL );
    }
    currarg=1;
    while( currarg < argc ) {
#ifdef __UNIX__
        if( argv[ currarg ][0] == '-' ) {
#else
        if( argv[ currarg ][0] == '/' || argv[ currarg ][0] == '-' ) {
#endif
            len = strlen( argv[ currarg ] );
            for( i=1; i<len; i++ ) {
                switch( argv[ currarg ][i] ) {
                case '?': doUsage( NULL );
                case 'D':
                    currarg++;
                    desc = argv[ currarg ];
                    break;
                case 's':
                    currarg++;
                    wext = argv[ currarg ];
                    break;
                case 'q':
                    quietFlag = TRUE;
                    break;
                case 'u':
                    uflag = TRUE;
                    break;
                case 'n':
                    nflag = TRUE;
                    break;
                case 'd':
                    dllflag = TRUE;
                    break;
                case 'R': case 'r':
                    Rflag=TRUE;
                    rcparm = currarg+1;
                    if( rcparm == argc ) {
                        doUsage("must specify resource compiler command line" );
                    }
                    break;
                }
            }
            if( Rflag ) {
                break;
            }
        } else {
            if( path != NULL ) {
                doUsage( "Only one executable may be specified" );
            }
            path = argv[ currarg ];
        }
        currarg++;
    }
    if( path == NULL ) {
        doUsage( "No executable to bind" );
    }
    doBanner();

    /*
     * get files to use
     */
    _splitpath( path, drive, dir, fname, ext );
    _makepath( rex, drive, dir, fname, ".rex" );
    if( dllflag ) {
        _makepath( dll, drive, dir, fname, ".dll" );
    }
    _makepath( exe, drive, dir, fname, ".exe" );
    _makepath( res, drive, dir, fname, "" );

    /*
     * do the unbind
     */
    if( uflag ) {
        if( ext[0] == 0 ) {
            path = exe;
        }
        in = open( path, O_RDONLY | O_BINARY );
        if( in < 0 ) {
            doError( "Could not open %s", path );
        }
        out = open( rex, O_CREAT | O_TRUNC | O_WRONLY | O_BINARY, PMODE_RWX );
        if( out < 0 ) {
            doError( "Could not open %s", rex );
        }
        lseek( in, MAGIC_OFFSET, SEEK_SET );
        read( in, &exelen, sizeof( unsigned_32 ) );
        lseek( in, exelen, SEEK_SET );
        read( in, &re, sizeof( re ) );
        if( re.signature != ('M' & ('Q' << 8)) ) {
            doError( "Not a bound Open Watcom 32-bit Windows application" );
        }
        lseek( in, exelen, SEEK_SET );
        CopyFile( in, out, path, rex );
        close( in );
        close( out );
        myPrintf( ".rex file %s created", rex );
        exit( 0 );
    }

    if( wext == NULL ) {
        if( dllflag ) {
            FindExtender( "w386dll.ext", winext );
        } else {
            FindExtender( "win386.ext", winext );
        }
    } else {
        strcpy( winext, wext );
    }
    if( dllflag ) {
        myPrintf("Loading 32-bit Windows DLL Supervisor \"%s\"\n",winext );
    } else {
        myPrintf("Loading 32-bit Windows Supervisor \"%s\"\n",winext );
    }

    /*
     * open files
     */
    in = open( winext, O_RDONLY | O_BINARY );
    if( in < 0 )  {
        doError( "Could not open %s", winext );
    }
    out = open( exe, O_CREAT | O_TRUNC|O_WRONLY | O_BINARY, PMODE_RWX );
    if( out < 0 )  {
        doError( "Could not open %s", exe );
    }

    /*
     * copy extender over
     */
    CopyFile( in, out, winext, exe );
    close( in );
    close( out );

    /*
     * run the resource compiler
     */
    if( !nflag ) {
        myPrintf( "Invoking the resource compiler...\n" );
        if( Rflag ) {
            strcpy( rc, RC_STR );
            arglist = myAlloc( sizeof(char *) *(argc-rcparm +3) );
            pcnt = 1;
            for( i=rcparm;i<argc;i++ ) {
                arglist[pcnt++] = argv[i];
                strcat( rc," " );
                strcat( rc, argv[i] );
            }
        } else {
            sprintf( rc, RC_STR " %s", res );
            arglist = myAlloc( sizeof(char *) * 3 );
            arglist[1] = res;
            pcnt = 2;
        }
        arglist[0] = RC_STR;
        arglist[pcnt] = NULL;

        myPrintf( "%s\n",rc );
        i = spawnvp( P_WAIT, RC_STR, arglist );
        if( i == -1 ) {
            remove( exe );
            switch( errno ) {
            case E2BIG:
                doError( "Argument list too big. Resource compiler step failed." );
                break;
            case ENOENT:
                doError( "Could not find " RC_STR ".exe." );
                break;
            case ENOMEM:
                doError( "Not enough memory. Resource compiler step failed." );
                break;
            }
            doError( "Unknown error %d, resource compiler step failed.", errno );
        }
        if( i != 0 ) {
            remove( exe );
            errPrintf( "Resource compiler failed, return code = %d\n", i );
            exit( i );
        }
    }

    /*
     * copy the rex file onto the end
     */
    in = open( rex, O_RDONLY | O_BINARY );
    if( in < 0 )  {
        doError( "Could not open %s", rex );
    }
    out = open( exe, O_RDWR | O_BINARY );
    if( out < 0 )  {
        doError( "Could not open %s", exe );
    }
    lseek( out, 0, SEEK_END );
    tsize = tell( out );

    totalsize = CopyFile( in, out, rex, exe );
    close( in );

    /*
     * noodle the file: change name, and then
     * write the file size into the old exe header (for
     * use by the loader)
     */
    lseek( out, MAGIC_OFFSET, SEEK_SET );
    write( out, &tsize, sizeof( tsize ) );
    len = strlen( fname );
    memset( &fname[len],' ',8-len );
    updateNHStuff( out, fname, desc );
    close( out );
    if( dllflag ) {
        remove( dll );
        rename( exe,dll );
        myPrintf("Created \"%s\" (%ld + %ld = %ld bytes)\n", dll,
                tsize,totalsize, tsize+totalsize );
    } else {
        myPrintf("Created \"%s\" (%ld + %ld = %ld bytes)\n", exe,
                tsize,totalsize, tsize+totalsize );
    }

    return( 0 );
} /* main */
コード例 #28
0
ファイル: test7.C プロジェクト: vishalmistry/imitate
void prepareTestCase3(procType proc_type, BPatch_thread *thread, forkWhen when)
{
   static BPatchSnippetHandle *parSnippetHandle3;

   if(proc_type == Parent_p  &&  when == PreFork) {
      BPatch_image *parImage = thread->getImage();

      BPatch_Vector<BPatch_function *> found_funcs;
      const char *inFunction = "func7_3";
      if ((NULL == parImage->findFunction(inFunction, found_funcs, 1)) || !found_funcs.size()) {
	fprintf(stderr, "    Unable to find function %s\n",
		inFunction);
	exit(1);
      }
      
      if (1 < found_funcs.size()) {
	fprintf(stderr, "%s[%d]:  WARNING  : found %d functions named %s.  Using the first.\n", 
		__FILE__, __LINE__, found_funcs.size(), inFunction);
      }
      
      BPatch_Vector<BPatch_point *> *points7_3p = found_funcs[0]->findPoint(BPatch_entry);

      if(doError(3, !points7_3p || ((*points7_3p).size() == 0),
		 "  Unable to find entry point to \"func7_3\".\n")) return;
      BPatch_point *point7_3p = (*points7_3p)[0];

      BPatch_variableExpr *var7_3p = 
	 parImage->findVariable("globalVariable7_3");
      if(doError(3, (var7_3p==NULL),
		 "  Unable to locate variable globalVariable7_3\n")) return;

      BPatch_arithExpr expr7_3p(BPatch_assign, *var7_3p,BPatch_constExpr(642));

      parSnippetHandle3 =
	 thread->insertSnippet(expr7_3p, *point7_3p, BPatch_callBefore);
   } else if(proc_type == Parent_p  &&  when == PostFork) {
      bool result = thread->deleteSnippet(parSnippetHandle3);
      if(result == false) {
	 fprintf(stderr, "  error, couldn't delete snippet\n");
	 passedTest[3] = false;
	 return;
      }
   } else if(proc_type == Child_p  &&  when == PostFork) {
      BPatch_image *childImage = thread->getImage();

      BPatch_Vector<BPatch_function *> found_funcs;
      const char *inFunction = "func7_3";
      if ((NULL == childImage->findFunction(inFunction, found_funcs, 1)) || !found_funcs.size()) {
	fprintf(stderr, "    Unable to find function %s\n",
		inFunction);
	exit(1);
      }
      
      if (1 < found_funcs.size()) {
	fprintf(stderr, "%s[%d]:  WARNING  : found %d functions named %s.  Using the first.\n", 
		__FILE__, __LINE__, found_funcs.size(), inFunction);
      }
      
      BPatch_Vector<BPatch_point *> *points7_3c = found_funcs[0]->findPoint(BPatch_entry);
      
      if(doError(3, !points7_3c || ((*points7_3c).size() == 0),
		 "  Unable to find entry point to \"func7_3\".\n")) return;
      BPatch_point *point7_3c = (*points7_3c)[0];

      BPatch_Vector<BPatchSnippetHandle *> childSnippets =
	 point7_3c->getCurrentSnippets();
      if(doError(3, (childSnippets.size()==0),
		 " No snippets were found at func7_3\n")) return;

      for(unsigned i=0; i<childSnippets.size(); i++) {
	 bool result = thread->deleteSnippet(childSnippets[i]);
	 if(result == false) {
	    fprintf(stderr, "  error, couldn't delete snippet\n");
	    passedTest[3] = false;
	    return;
	 }
      }
   }
}
コード例 #29
0
ファイル: HttpServlet.cpp プロジェクト: 2202877/acl
bool HttpServlet::doRun(session& session, socket_stream* stream /* = NULL */)
{
	socket_stream* in;
	socket_stream* out;
	bool cgi_mode;

	if (stream == NULL)
	{
		// 数据流为空,则当 CGI 模式处理,将标准输入输出
		// 作为数据流
		stream = NEW socket_stream();
		(void) stream->open(ACL_VSTREAM_IN);
		in = stream;

		stream = NEW socket_stream();
		(void) stream->open(ACL_VSTREAM_OUT);
		out = stream;
		cgi_mode = true;
	}
	else
	{
		in = out = stream;
		cgi_mode = false;
	}

	// req/res 采用栈变量,减少内存分配次数

	HttpServletResponse res(*out);
	HttpServletRequest req(res, session, *in, local_charset_,
		parse_body_enable_, parse_body_limit_);

	if (rw_timeout_ >= 0)
		req.setRwTimeout(rw_timeout_);

	res.setCgiMode(cgi_mode);

	bool  ret;

	http_method_t method = req.getMethod();

	switch (method)
	{
	case HTTP_METHOD_GET:
		ret = doGet(req, res);
		break;
	case HTTP_METHOD_POST:
		ret = doPost(req, res);
		break;
	case HTTP_METHOD_PUT:
		ret = doPut(req, res);
		break;
	case HTTP_METHOD_CONNECT:
		ret = doConnect(req, res);
		break;
	case HTTP_METHOD_PURGE:
		ret = doPurge(req, res);
		break;
	case HTTP_METHOD_DELETE:
		ret = doDelete(req, res);
		break;
	case  HTTP_METHOD_HEAD:
		ret = doHead(req, res);
		break;
	case HTTP_METHOD_OPTION:
		ret = doOption(req, res);
		break;
	default:
		ret = false; // 有可能是IO失败或未知方法
		if (req.getLastError() == HTTP_REQ_ERR_METHOD)
			doUnknown(req, res);
		else
			doError(req, res);
		break;
	}

	if (in != out)
	{
		// 如果是标准输入输出流,则需要先将数据流与标准输入输出解绑,
		// 然后才能释放数据流对象,数据流内部会自动判断流句柄合法性
		// 这样可以保证与客户端保持长连接
		in->unbind();
		out->unbind();
		delete in;
		delete out;
	}

	return ret;
}
コード例 #30
0
ファイル: nbd-server.c プロジェクト: madpenguin/VDCCloud
int doNegotiate(int sock)
{
    struct {
	        volatile uint64_t magic __attribute__((packed));
	        volatile uint32_t opts  __attribute__((packed));
	} nbd;
    
	uint32_t flags;    
	uint32_t len;
	uint32_t opt;
	
	char 	*name;	
	char 	path[256];
	int 	status = False;
	int 	working = True;
	int	db;

	getBytes(sock,&flags,sizeof(flags));
	flags = htonl(flags);
	
	doLog("Enter NEGOTIATION");
	
	do {
		getBytes(sock,&nbd,sizeof(nbd));
		if(nbd.magic != htonll(OPTS_MAGIC)) {
			doError("Bad MAGIC from Client");
			status = False;
			working = False;	
			break;
		}
		opt = ntohl(nbd.opts);
		switch( opt )
		{
			case NBD_OPT_EXPORT_NAME:                
				getBytes(sock,&len,sizeof(len));
				len = ntohl(len);
				name = malloc(len+1);
				name[len]=0;
				getBytes(sock,name,len);
				syslog(LOG_INFO,"Incoming name = %s",name);
		
				sprintf(path,"/dev/vols/blocks/%s",name);
				db = open(path,O_RDWR|O_EXCL);
				if( db == -1) {
					sprintf(path,"/dev/vols/blocks/%s1",name);
					db = open(path,O_RDWR|O_EXCL);
					if( db ==-1) {
						doError("Unable to open BLOCK DEVICE");
						doError(path);
						status = False;
						working = False;
						break;
					}
				}
				if(db != -1) { syslog(LOG_INFO,"Opened [%s] with descriptor [%d]",path,db); }
				working = False;
				status = True;
				free(name);
				break;
	
			/*case NBD_OPT_LIST:
				doLog("Received LIST from client");
				getBytes(&len,sizeof(len));
				len=ntohl(len);
				if(len) sendReply(opt, NBD_REP_ERR_INVALID, 0, NULL);    
                
				char buf[128];
				char *ptr = (char*)&buf;
                
				len = htonl(4);
				memcpy(ptr,&len,sizeof(len));
				ptr += sizeof(len);
				memcpy(ptr,"demo",4);
				sendReply(opt, NBD_REP_SERVER, 8, buf);
				sendReply(opt, NBD_REP_ACK, 0, NULL);
				break; */
	
			case NBD_OPT_ABORT:
				doLog("Received ABORT from client");
				status = False;
				working = False;
				break;
	
			default:
				doError("Unknown command");
				break;
		}
	} while( working );
	
	if(!status) return False;
	
	
	int64_t size = 0;
	ioctl(db, BLKGETSIZE, &size);
	syslog(LOG_INFO,"Device Size = %lld\n",(unsigned long long)size);
	size = htonll(size*512);
	int16_t small = htons(1);
	char zeros[124];
	memset(zeros,0,sizeof(zeros));
	putBytes(sock,&size,sizeof(size));
	putBytes(sock,&small,sizeof(small));
	putBytes(sock,&zeros,sizeof(zeros));
	doLog("Exit NEGOTIATION [Ok]");
	return db;
}