Ejemplo n.º 1
0
bool CWebserverRequest::SendFile(const std::string path,const std::string filename)
{
	if( (tmpint = OpenFile(path, filename) ) != -1 )
	{							// Wenn Datei geöffnet werden konnte
		if (!SocketWrite("HTTP/1.0 200 OK\r\n"))
		{
			close(tmpint);
			return false;
		}
		HttpStatus = 200;

		if (!SocketWrite("Content-Type: " + GetContentType(FileExt) + "\r\n\r\n"))
		{
			close(tmpint);
			return false;
		}
		if (Method == M_HEAD) {
			close(tmpint);
			return true;
		}
		off_t start = 0;
		off_t end = lseek(tmpint,0,SEEK_END);
		int written = 0;
		if((written = sendfile(Socket,tmpint,&start,end)) == -1)
			perror("sendfile failed");
		close(tmpint);
		return true;
	}
	else
	{
		Send404Error();
		return false;
	}
}
Ejemplo n.º 2
0
/**	
	Performs an HTTP POST operation to the path at the address / port specified.  The actual post contents 
  are found read from a given buffer and the result is returned in the same buffer.
  @param address The IP address of the server to post to.
  @param port The port on the server you're connecting to. Usually 80 for HTTP.
  @param hostname A string specifying the name of the host to connect to.  When connecting to a server
  that does shared hosting, this will specify who to connect with.
  @param path The path on the server to post to.
	@param buffer A pointer to the buffer to write from and read back into.  
	@param buffer_length An integer specifying the number of bytes to write.
	@param buffer_size An integer specifying the actual size of the buffer.
  @return status.

  \par Example
  \code
  // we'll post a test message to www.makingthings.com/post/path
  int addr = IP_ADDRESS( 72, 249, 53, 185); // makingthings.com is 72.249.53.185
  int bufLength = 100;
  char myBuffer[bufLength];
  sprintf( myBuffer, "A test message to post" );
  int result = WebClient_Post( addr, 80, "www.makingthings.com", "/post/path", 
                                    myBuffer, strlen("A test message to post"), bufLength );
  \endcode
*/
int WebClient_Post( int address, int port, char* hostname, char* path, char* buffer, int buffer_length, int buffer_size )
{
  char* b = WebClient_InternalBuffer;
  int buffer_read = 0;
  int wrote = 0;
  void* s = Socket( address, port );  
  if ( s != NULL )
  { 
    int send_len = snprintf( b, WEBCLIENT_INTERNAL_BUFFER_SIZE, 
                                "POST %s HTTP/1.1\r\n%s%s%sContent-Type: text/plain\r\nContent-Length: %d\r\n\r\n", 
                                path, 
                                ( hostname != NULL ) ? "Host: " : "",
                                ( hostname != NULL ) ? hostname : "",
                                ( hostname != NULL ) ? "\r\n" : "",
                                buffer_length );
    if ( send_len > WEBCLIENT_INTERNAL_BUFFER_SIZE )
    {
      SocketClose( s );
      return CONTROLLER_ERROR_INSUFFICIENT_RESOURCES;
    }

    wrote = SocketWrite( s, b, send_len );
    if ( wrote == 0 )
    {
      SocketClose( s );
      return CONTROLLER_ERROR_WRITE_FAILED;
    }

    SocketWrite( s, buffer, buffer_length );
    
    int content_length = 0;
    int b_len;
    while ( ( b_len = SocketReadLine( s, b, WEBCLIENT_INTERNAL_BUFFER_SIZE ) ) )
    {
      if ( strncmp( b, "\r\n", 2 ) == 0 )
        break;
      if ( strncmp( b, "Content-Length", 14 ) == 0 )
        content_length = atoi( &b[ 16 ] );
    }
          
    if ( content_length > 0 && b_len > 0 )
    {
      char* bp = buffer;
      while ( ( b_len = SocketRead( s, bp, buffer_size - buffer_read ) ) )
      {
        buffer_read += b_len;
        bp += b_len;
        if ( buffer_read >= content_length )
          break;
      }
    }          

    SocketClose( s );
    return buffer_read;
  }
  else
    return CONTROLLER_ERROR_BAD_ADDRESS;
}
Ejemplo n.º 3
0
//-------------------------------------------------------------------------
void CWebserverRequest::Send404Error()
{
	SocketWrite("HTTP/1.0 404 Not Found\r\n");		//404 - file not found
	SocketWrite("Content-Type: text/plain\r\n\r\n");
	if (Method != M_HEAD) {
		SocketWrite("404 : File not found\n\nThe requested file was not found on this dbox ;)\n");
	}
	HttpStatus = 404;
}
Ejemplo n.º 4
0
//-------------------------------------------------------------------------
void CWebserverRequest::Send500Error()
{
	SocketWrite("HTTP/1.0 500 InternalError\r\n");		//500 - internal error
	SocketWrite("Content-Type: text/plain\r\n\r\n");
	if (Method != M_HEAD) {
		SocketWrite("500 : InternalError\n\nPerhaps some parameters missing ? ;)");
	}
	HttpStatus = 500;
}
Ejemplo n.º 5
0
void DurSocketPrint(Socket *skt, Dur dur)
{
  char buf[PHRASELEN];
  if (dur == DURNA) SocketWrite(skt, "na");
  else {
#ifdef _GNU_SOURCE
    snprintf(buf, PHRASELEN, "%ldsec", dur);
#else
    sprintf(buf, "%ldsec", dur);
#endif
    SocketWrite(skt, buf);
  }
}
Ejemplo n.º 6
0
void TsSocketPrint(Socket *skt, Ts *ts)
{
  char      buf[16];
  struct tm *tms;
  if (ts == NULL) { SocketWrite(skt, "NULL"); return; }
  if (ts->flag & TSFLAG_APPROX) SocketWrite(skt, "~");
  if (ts->flag & TSFLAG_TOD) {
    TodSocketPrint(skt, (Tod)ts->unixts);
    SocketWrite(skt, "tod");
  } else if (ts->flag & TSFLAG_DUR) {
    DurSocketPrint(skt, (Dur)ts->unixts);
  } else if (ts->unixts == UNIXTSNA) {
    SocketWrite(skt, "na");
  } else if (ts->unixts == UNIXTSNEGINF) {
    SocketWrite(skt, "-Inf");
  } else if (ts->unixts == UNIXTSPOSINF) {
    SocketWrite(skt, "Inf");
  } else {
    if (NULL == (tms = localtime(&ts->unixts))) {
      SocketWrite(skt, "ERROR");
    } else {
#ifdef _GNU_SOURCE
      snprintf(buf, 16, "%.4d%.2d%.2dT%.2d%.2d%.2d", 1900+tms->tm_year,
               tms->tm_mon+1, tms->tm_mday, tms->tm_hour, tms->tm_min,
               tms->tm_sec);
#else
      sprintf(buf, "%.4d%.2d%.2dT%.2d%.2d%.2d", 1900+tms->tm_year,
              tms->tm_mon+1, tms->tm_mday, tms->tm_hour, tms->tm_min,
              tms->tm_sec);
#endif
      SocketWrite(skt, buf);
    }
  }
}
Ejemplo n.º 7
0
	int PackWriter::HandleOutput(int fd) 
	{
		int n = SocketWrite(fd,_data+_pos,_size-_pos);
		if (n >= 0) 
		{
			_pos += n;
			if (_pos == _size)
			{
				free((void*)_data);
				_poller->DeRegisterWrite(fd);
				if (_poller->GetSocketState(fd) == Closed)
				{
					_poller->AddErrorFd(fd);
				}
				
			}
			
		}
		else
		{
			free((void*)_data);
			_poller->AddErrorFd(fd);
		}
		return 0;
	}
Ejemplo n.º 8
0
static BOOL Init(void)
{
	struct system_t *pSystemInfo = &gSystemInfo;

	//初始化audio info结构体
	if(!InitAudioStruct(pSystemInfo,TRUE))
	{
		DBGE((TEXT("[System DLL] init struct err.\r\n")));
		return FALSE;
	}

	if (!CreateClientSocket(9980))
	{
		DBGE((TEXT("[System DLL] audio create client socket err.\r\n")));
		return FALSE;
	}

	pSystemInfo->bInit = TRUE;

	BYTE buf[2] = {0x01,0x01};
	SocketWrite(buf,2);

	DBGI((TEXT("\r\n[System DLL] Init OK time:")));
	DBGI((TEXT(__TIME__)));
	DBGI((TEXT(" data:")));
	DBGI((TEXT(__DATE__)));
	DBGI((TEXT("\r\n")));

	return TRUE;
}
Ejemplo n.º 9
0
OSStatus SocketWrite(
	SSLConnectionRef 	connection,
	const void	 		*data, 
	size_t 				*dataLength)	/* IN/OUT */ 
{
	size_t		bytesSent = 0;
	int			sock = (int)((long)connection);
	int 		length;
	size_t		dataLen = *dataLength;
	const UInt8 *dataPtr = (UInt8 *)data;
	OSStatus	ortn;
	
	if(oneAtATime && (*dataLength > 1)) {
		size_t i;
		size_t outLen;
		size_t thisMove;
		
		outLen = 0;
		for(i=0; i<dataLen; i++) {
			thisMove = 1;
			ortn = SocketWrite(connection, dataPtr, &thisMove);
			outLen += thisMove;
			dataPtr++;  
			if(ortn) {
				return ortn;
			}
		}
		return noErr;
	}
	*dataLength = 0;

    do {
        length = write(sock, 
				(char*)dataPtr + bytesSent, 
				dataLen - bytesSent);
    } while ((length > 0) && 
			 ( (bytesSent += length) < dataLen) );
	
	if(length <= 0) {
		int theErr = errno;
		switch(theErr) {
			case EAGAIN:
				ortn = errSSLWouldBlock; break;
			case EPIPE:
				ortn = errSSLClosedAbort; break;
			default:
				dprintf(("SocketWrite: write(%u) error %d\n", 
					  (unsigned)(dataLen - bytesSent), theErr));
				ortn = ioErr;
				break;
		}
	}
	else {
		ortn = noErr;
	}
	tprintf("SocketWrite", dataLen, bytesSent, dataPtr);
	*dataLength = bytesSent;
	return ortn;
}
Ejemplo n.º 10
0
void TodSocketPrint(Socket *skt, Tod tod)
{
  long	hour, min, sec;
  char  buf[7];
  if (tod == TODNA) SocketWrite(skt, "na");
  else {
    hour = tod / 3600;
    min = (tod - 3600*hour)/60;
    sec = tod % 60;
#ifdef _GNU_SOURCE
    snprintf(buf, 7, "%.2ld%.2ld%.2ld", hour, min, sec);
#else
    sprintf(buf, "%.2ld%.2ld%.2ld", hour, min, sec);
#endif
    SocketWrite(skt, buf);
  }
}
Ejemplo n.º 11
0
void CWebserverRequest::Send302(char const *URI)
{
	printf("HTTP/1.0 302 Moved Permanently\r\nLocation: %s\r\nContent-Type: text/html\r\n\r\n",URI);
	if (Method != M_HEAD) {
		SocketWrite("<html><head><title>Object moved</title></head><body>");
		printf("302 : Object moved.<brk>If you dont get redirected click <a href=\"%s\">here</a></body></html>\n",URI);
	}
	HttpStatus = 302;
}
Ejemplo n.º 12
0
Archivo: remote.c Proyecto: aburch/ug
static void IFInvPolymark (short n, SHORT_POINT *points)
{
  BUFSTART;
  BUFINT(DC_InvPolymark);
  BUFINT(n);
  BUFEND;

  SocketWrite(theSocket, (char *)points, sizeof(SHORT_POINT)*n);
}
Ejemplo n.º 13
0
Archivo: remote.c Proyecto: aburch/ug
static void IFInversePolyline (SHORT_POINT *points, INT n)
{
  BUFSTART;
  BUFINT(DC_InversePolyline);
  BUFINT(n);
  BUFEND;

  SocketWrite(theSocket, (char *)points, sizeof(SHORT_POINT)*n);
}
Ejemplo n.º 14
0
Archivo: remote.c Proyecto: aburch/ug
static void IFErasePolygon (SHORT_POINT *points, INT n)
{
  BUFSTART;
  BUFINT(DC_ErasePolygon);
  BUFINT(n);
  BUFEND;

  SocketWrite(theSocket, (char *)points, sizeof(SHORT_POINT)*n);
}
Ejemplo n.º 15
0
//-------------------------------------------------------------------------
bool CWebserverRequest::HandleUpload()				// momentan broken 
{
	int t = 0;
//	FILE *output;
//	int count = 0;

	SocketWrite("HTTP/1.1 100 Continue \r\n\r\n");		// Erstmal weitere Daten anfordern

	if(HeaderList["Content-Length"] != "")
	{
		dprintf("Contenlaenge gefunden\n");
		long contentsize = atol(HeaderList["Content-Length"].c_str());
		dprintf("Contenlaenge :%ld\n",contentsize);
		char *buffer2 =(char *) malloc(contentsize);
		if(!buffer2)
		{
			dprintf("Kein Speicher für upload\n");
			return false;
		}
		long long gelesen = 0;
		dprintf("Buffer ok Groesse:%ld\n",contentsize);
		while(gelesen < contentsize)
		{
			t = read(Socket,&buffer2[gelesen],contentsize-gelesen);
			if(t <= 0)
				dprintf("nix mehr\n");
			gelesen += t;
			dprintf("gelesen %lld\n",gelesen);
		}
		dprintf("fertig\n");
		FILE *out = fopen("/var/tmp/test.ausgabe","w");
		if(out != NULL)
		{
			fwrite(buffer2,gelesen,1,out);
			fclose(out);
		}
		else
			dprintf("nicht geschreiben\n");
		free(buffer2);
		
		if(gelesen == contentsize)
		{
			dprintf("Upload komplett gelesen: %ld bytes\n",contentsize);
			return true;
		} 
		else
		{
			dprintf("Upload konnte nicht komplett gelesen werden  %ld bytes\n",contentsize);
			return false;
		}
	}
	else
	{
		dprintf("Content-Length ist nicht in der HeaderListe\n");
		return false;
	}
}
Ejemplo n.º 16
0
OSStatus SocketWrite(
					 SSLConnectionRef   connection,
					 const void       *data, 
					 size_t         *dataLength)  /* IN/OUT */ 
{
	UInt32    bytesSent = 0;
	int      sock = (int)connection;
	int     length;
	UInt32    dataLen = (UInt32) *dataLength;
	const UInt8 *dataPtr = (UInt8 *)data;
	OSStatus  ortn;
	
	if(oneAtATime && (*dataLength > 1)) {
		UInt32 i;
		UInt32 outLen;
		size_t thisMove;
		
		outLen = 0;
		for(i=0; i<dataLen; i++) {
			thisMove = 1;
			ortn = SocketWrite(connection, dataPtr, &thisMove);
			outLen += thisMove;
			dataPtr++;  
			if(ortn) {
				return ortn;
			}
		}
		return noErr;
	}
	*dataLength = 0;
	
    do {
        length = (int) write(sock, 
					   (char*)dataPtr + bytesSent, 
					   dataLen - bytesSent);
    } while ((length > 0) && 
			 ( (bytesSent += length) < dataLen) );
	
	if(length <= 0) {
		if(errno == EAGAIN) {
			ortn = errSSLWouldBlock;
		}
		else {
			ortn = ioErr;
		}
	}
	else {
		ortn = noErr;
	}
	tprintf("SocketWrite", dataLen, bytesSent, dataPtr);
	*dataLength = bytesSent;
	return ortn;
}
Ejemplo n.º 17
0
abyss_bool
ConnWrite(TConn *      const connectionP,
          const void * const buffer,
          uint32_t     const size) {

    abyss_bool failed;

    SocketWrite(connectionP->socketP, buffer, size, &failed);

    traceSocketWrite(connectionP, buffer, size, failed);

    if (!failed)
        connectionP->outbytes += size;

    return !failed;
}
Ejemplo n.º 18
0
bool File::WriteData(const void* d, int size)
{
	if(mode & FILEWRITE)
	{
		switch(srctype)
		{
		case MODE_MYFILE:
		case MODE_EXTFILE:
			return FileWrite(file,d,size);
		case MODE_MYDATA:		//resize if buffer's not big enough
			if(datapos + size > datasize) {
				int a=datapos+size,b=datasize*2;
				ResizeDataBuffer(Max(a,b));
			}
			memcpy(datafile+datapos, d, size);
			datapos += size;
			return true;
		case MODE_EXTDATA:
			if(datapos + size > datasize)
				return false;
			memcpy(datafile+datapos, d, size);
			datapos += size;
			return true;
		case MODE_TCPSOCKET:
		case MODE_UDPSOCKET:
		  {
		    const char* msg = (const char*)d;
		    int totalsent = 0;
		    while(totalsent < size) {
		      int n = SocketWrite(socket,msg+totalsent,size-totalsent);
		      if(n < 0) {
			perror("File(socket) SocketWrite");
			return false;
		      }
		      if(n == 0) {
			printf("File(socket): SocketWrite returned %d, what does it mean?\n",n);
			ThreadSleep(0.001);
		      }
		      totalsent += n;
		    }
		    assert(totalsent == size);
		    return true;
		  }
		}
	}
	return false;
}
Ejemplo n.º 19
0
void connection::MyWrite(const std::string &buf)
{
	switch (connection_type) {
	case connection_http:
	case connection_websocket:
		// we dont send data anymore in websocket closing state
		boost::unique_lock<boost::mutex>(writeMutex);
		if (write_in_progress) {
			// write in progress, add to queue
			writeQ.push(buf);
		}
		else {
			SocketWrite(buf);
		}
		break;
	}
}
Ejemplo n.º 20
0
int ConnWriteFlush(TConn *c)
{
        uint32 size = 0;

	/* sanity */
	if (!c) {
		return FALSE;
	}

        size = c->out_bufferpos;

        if( size ) {
                c->outbytes+=size;
                c->out_bufferpos = 0;
                return SocketWrite(&(c->socket),c->out_buffer,size);
        }
        return( 1 );
}
Ejemplo n.º 21
0
bool CWebserverRequest::ParseFile(string file,CStringList params)		// replace all parameters if file
{
	FILE * f;
	char zeile[1024];
	if(RequestCanceled)
		return false;
	if((f = fopen(file.c_str(),"r")) == NULL)
	{
		aprintf("Parse file open error: '%s'\n",file.c_str());
		return false;
	}
	while(!feof(f))
	{
		if(fgets(zeile,sizeof(zeile),f))
		{
			SocketWrite(ParseLine(zeile,params));
		}
	};
	fclose(f);
	return true;
}
Ejemplo n.º 22
0
void connection::handle_write(const boost::system::error_code& error, size_t bytes_transferred)
{
	boost::unique_lock<boost::mutex>(writeMutex);
	write_buffer.clear();
	write_in_progress = false;
	if (!error) {
		if (!writeQ.empty()) {
			std::string buf = writeQ.front();
			writeQ.pop();
			SocketWrite(buf);
		}
		else if (!keepalive_) {
			connection_manager_.stop(shared_from_this());
		}
	}
	if (!error && keepalive_) {
	status_ = ENDING_WRITE;
		// if a keep-alive connection is requested, we read the next request
		reset_abandoned_timeout();
	} else {
		connection_manager_.stop(shared_from_this());
	}
}
Ejemplo n.º 23
0
int ConnWrite(TConn *c,const void *buffer,uint32 size)
{
	/* sanity */
	if (!c || !buffer) {
		return FALSE;
	}

        /* overflow -> flush buffer */
        if( c->out_bufferpos+size >= BUFFER_SIZE )
                ConnWriteFlush( c );

        /* size "large" -> empty space and write direct */
        if( size >= BUFFER_SIZE/2 ) {
                if( c->out_bufferpos )
                        ConnWriteFlush( c );
                return( SocketWrite( &(c->socket),buffer,size ) );
        }

        /* size fits so copy it in */
        memmove( c->out_buffer+c->out_bufferpos,buffer,size );
        c->out_bufferpos += size;

        return( 1 );
}
Ejemplo n.º 24
0
//-------------------------------------------------------------------------
void CWebserverRequest::SendError()
{
	SocketWrite("error");
}
Ejemplo n.º 25
0
//-------------------------------------------------------------------------
void CWebserverRequest::SendOk()
{
	SocketWrite("ok");
}
Ejemplo n.º 26
0
//-------------------------------------------------------------------------
bool CWebserverRequest::SendResponse()
{
	RewriteURL();		// Erst mal die URL umschreiben

	if(Path.compare("/control/") == 0)						// api for external programs
	{
		return Parent->WebDbox->ControlAPI->Execute(this);
	}
	else if(Path.compare("/bouquetedit/") == 0)				// bouquetedit api
	{
		return Parent->WebDbox->BouqueteditAPI->Execute(this);
	}
	else if(Path.compare("/fb/") == 0)						// webbrowser api
	{
		return Parent->WebDbox->WebAPI->Execute(this);
	}
	else
	{
	// Normale Datei										//normal file
		if( (tmpint = OpenFile(Path,Filename) ) != -1 )		// Testen ob Datei auf Platte geöffnet werden kann
		{											// Wenn Datei geöffnet werden konnte
			if (!SocketWrite("HTTP/1.0 200 OK\r\n"))
			{
				close(tmpint);
				return false;
			}
			HttpStatus = 200;
			if( FileExt == "" )		// Anhand der Dateiendung den Content bestimmen
				ContentType = "text/html";
			else
			{
				if(  (FileExt.compare("html") == 0) || (FileExt.compare("htm") == 0) )
					ContentType = "text/html";
				else if(FileExt.compare("gif") == 0)
					ContentType = "image/gif";
				else if((FileExt.compare("png") == 0) || (FileExt.compare("PNG") == 0) )
					ContentType = "image/png";
				else if( (FileExt.compare("jpg") == 0) || (FileExt.compare("JPG") == 0) )
					ContentType = "image/jpeg";
				else if( (FileExt.compare("css") == 0) || (FileExt.compare("CSS") == 0) )
					ContentType = "text/css";
				else if(FileExt.compare("xml") == 0)
					ContentType = "text/xml";
				else
					ContentType = "text/plain";

			}
			if (!SocketWrite("Content-Type: " + ContentType + "\r\n\r\n"))
			{
				close(tmpint);
				return false;
			}
			if (Method != M_HEAD) {
				SendOpenFile(tmpint);
			}
			else {
				close(tmpint);
			}
		}
		else
		{											// Wenn Datei nicht geöffnet werden konnte
			Send404Error();							// 404 Error senden
		}
		return true;
	}
}
Ejemplo n.º 27
0
void CWebserverRequest::SendPlainHeader(string contenttype)
{
	SocketWrite("HTTP/1.0 200 OK\r\nContent-Type: " + contenttype + "\r\n\r\n");
	HttpStatus = 200;
}
Ejemplo n.º 28
0
bool CWebserverRequest::HandleUpload()	
{
	int t,y = 0;

	SocketWrite("HTTP/1.1 100 Continue \r\n\r\n");		// Erstmal weitere Daten anfordern

	if(HeaderList["Content-Length"] != "")
	{
		remove(UPLOAD_TMP_FILE);
		// Get Multipart Upload
		//--------------------------------
		aprintf("Contenlaenge gefunden\n");
		long contentsize = atol(HeaderList["Content-Length"].c_str());
		aprintf("Contenlaenge :%ld\n",contentsize);
		char *buffer2 =(char *) malloc(contentsize);
		if(!buffer2)
		{
			aprintf("Kein Speicher für upload\n");
			return false;
		}
		long long gelesen = 0;
		aprintf("Buffer ok Groesse:%ld\n",contentsize);
		fcntl(Socket, F_SETFL, fcntl(Socket,F_GETFL)|O_NONBLOCK); //Non blocking
		while(gelesen < contentsize)
		{
			if(y > 500)
			{
				aprintf("y read Abbruch\n");
				break;
			}
			aprintf("vor %lld noch %lld",gelesen,contentsize-gelesen);
			t = read(Socket,&buffer2[gelesen],contentsize-gelesen);//Test -1
			aprintf("nach read t%d\n",t);
			if(t!=-1)//EAGAIN =-1
			{
				if(t <= 0)
				{
					aprintf("nix mehr\n");
					break;
				}
				gelesen += t;
				y=0; 
			}
			else
				y++;
		}
		aprintf("fertig\n");
		if(gelesen == contentsize)
		{
			// Extract Upload File
			//--------------------------------
			std::string marker;
			std::string buff;
			buff = std::string(buffer2, gelesen);
			free(buffer2);

			int pos = 0;
			if((pos = buff.find("\r\n")) > 0)	// find marker
			{
				marker = buff.substr(0,pos-1);
				buff = buff.substr(pos+1,buff.length() - (pos+1)); // snip
			}		
			if((pos = buff.find("Content-Type")) > 0) // Multipart File
			{
				buff = buff.substr(pos+1,buff.length() - (pos+1)); // snip
			}		
			if((pos = buff.find("\r\n\r\n")) > 0) // Multipart File - Start offset
			{
				buff = buff.substr(pos+4,buff.length() - (pos+4)); // snip
			}		
			if((pos = buff.find(marker)) > 0)// find marker after file
			{
				buff= buff.substr(0,pos-2); // snip "\r\n"+marker
			}		
			aprintf("write");
			
			// Write Upload Extract file
			//--------------------------------
			FILE *out = fopen(UPLOAD_TMP_FILE,"w"); // save tmp & mem - open here => File=0 tmp=Socket-space
			if(out != NULL)
			{
				fwrite(buff.c_str(),buff.length(),1,out);
				fclose(out);
			}
			else
				aprintf("nicht geschrieben\n");
		}
		if(gelesen == contentsize)
		{
			aprintf("Upload komplett gelesen: %ld bytes\n",contentsize);
			return true;
		}
		else
		{
			aprintf("Upload konnte nicht komplett gelesen werden  %ld bytes\n",contentsize);
			return false;
		}
	}
	else
	{
		aprintf("Content-Length ist nicht in der HeaderListe\n");
		return false;
	}
}
Ejemplo n.º 29
0
bool CWebserverRequest::ParseRequest()
{
	int ende;

	if(rawbuffer_len > 0 )
	{
		if((ende = rawbuffer.find_first_of('\n')) == 0)
		{
			aprintf("ParseRequest: End of line not found\n");
			Send500Error();
			return false;
		}
		std::string zeile1 = rawbuffer.substr(0,ende-1);

		if(ParseFirstLine(zeile1))
		{
			unsigned int i;
			for(i = 0; ((rawbuffer[i] != '\n') || (rawbuffer[i+2] != '\n')) && (i < rawbuffer.length());i++);
			int headerende = i;
//			dprintf("headerende: %d buffer_len: %d\n",headerende,rawbuffer_len);
			if(headerende == 0)
			{
				aprintf("ParseRequest: no headers found\n");
				Send500Error();
				return false;
			}
			std::string header = rawbuffer.substr(ende+1,headerende - ende - 2);
			ParseHeader(header);
			Host = HeaderList["Host"];
			if(Method == M_POST) // TODO: Und testen ob content = formdata
			{
				std::string t = "multipart/form-data; boundary=";
				if(HeaderList["Content-Type"].compare(0,t.length(),t) == 0)
				{
//					SocketWriteLn("Sorry, momentan broken\n");
					Boundary = "--" + HeaderList["Content-Type"].substr(t.length(),HeaderList["Content-Type"].length() - t.length());
					aprintf("Boundary: '%s'\n",Boundary.c_str());
//					if((headerende + 3) < rawbuffer_len)
//						ParseBoundaries(rawbuffer.substr(headerende + 3,rawbuffer_len - (headerende + 3)));
					HandleUpload();
				}
				else if(HeaderList["Content-Type"].compare("application/x-www-form-urlencoded") == 0)
				{
//					dprintf("Form Daten in Parameter String\n");
					if((headerende + 3) < rawbuffer_len)
					{
						std::string params = rawbuffer.substr(headerende + 3,rawbuffer_len - (headerende + 3));
						if(params[params.length()-1] == '\n')
							params.substr(0,params.length() -2);
						ParseParams(params);
					}
				}

				dprintf("Method Post !\n");
			}


			return true;
		}
		else {
			SocketWrite("HTTP/1.0 501 Not implemented\r\n");
			SocketWrite("Content-Type: text/plain\r\n\r\n");
			SocketWrite("501 : Request-Method not implemented.\n");
			HttpStatus = 501;
			aprintf("501 : Request-Method not implemented.\n");
			return false;
		}
	}
	else
	{
		aprintf("rawbuffer_len = %ld\n",rawbuffer_len);
		return false;
	}
}
Ejemplo n.º 30
0
//-------------------------------------------------------------------------
bool CWebserverRequest::ParseRequest()
{
int ende;
	if(rawbuffer_len > 0 )
	{
		if((ende = rawbuffer.find_first_of('\n')) == 0)
		{
			aprintf("ParseRequest: End of line not found\n");
			Send500Error();
			return false;
		}
		string zeile1 = rawbuffer.substr(0,ende-1);

		if(ParseFirstLine(zeile1))
		{
			unsigned int i;
			for(i = 0; ((rawbuffer[i] != '\n') || (rawbuffer[i+2] != '\n')) && (i < rawbuffer.length());i++);
			int headerende = i;
//			dprintf("headerende: %d buffer_len: %d\n",headerende,rawbuffer_len);
			if(headerende == 0)
			{
				aprintf("ParseRequest: no headers found\n");
				Send500Error();
				return false;
			}
			string header = rawbuffer.substr(ende+1,headerende - ende - 2);
			ParseHeader(header);
			Host = HeaderList["Host"];
			if(Method == M_POST) // TODO: Und testen ob content = formdata
			{				

				string t = "multipart/form-data; boundary=";
				if(HeaderList["Content-Type"].compare(0,t.length(),t) == 0)
				{
					SocketWriteLn("Sorry, momentan broken\n");
					/*Boundary = "--" + HeaderList["Content-Type"].substr(t.length(),HeaderList["Content-Type"].length() - t.length());
					dprintf("Boundary: '%s'\n",Boundary.c_str());
					if((headerende + 3) < rawbuffer_len)
						ParseBoundaries(rawbuffer.substr(headerende + 3,rawbuffer_len - (headerende + 3)));
					HandleUpload();*/
				}			
				else if(HeaderList["Content-Type"].compare("application/x-www-form-urlencoded") == 0)
				{
					dprintf("Form Daten in Parameter String\n");
					if((headerende + 3) < rawbuffer_len)
					{
						string params = rawbuffer.substr(headerende + 3,rawbuffer_len - (headerende + 3));
						if(params[params.length()-1] == '\n')
							params.substr(0,params.length() -2);
						ParseParams(params);
					}
				}
				
				dprintf("Method Post !\n");
			}

/*
			if(Method == M_POST) // TODO: Und testen ob content = formdata
			{
				if( (ende + 3) < rawbuffer + rawbuffer_len)
				{
//					Parent->Debug("Post Parameter vorhanden\n");
					anfang = ende + 3;
					Param_String = string(anfang,rawbuffer + rawbuffer_len - anfang);
					dprintf("Post Param_String: %s\n",Param_String.c_str());
					ParseParams(Param_String);
				}
				if(HeaderList->GetIndex("Content-Type") != -1)
				{
					dprintf("Content-Type: %s\n",HeaderList->GetValue(HeaderList->GetIndex("Content-Type")));
					if(strcasecmp("application/x-www-form-urlencoded",HeaderList->GetValue(HeaderList->GetIndex("Content-Type"))) == 0)
						dprintf("Form Daten in Parameter String\n");
					if(strstr(HeaderList->GetValue(HeaderList->GetIndex("Content-Type")),"multipart/form-data") != 0)
					{
						char * boundary;
						boundary = strstr(HeaderList->GetValue(HeaderList->GetIndex("Content-Type")),"boundary=");
						if(boundary)
						{
							boundary += strlen("boundary=");

							dprintf("boundary : %s\n",boundary);
							Upload = new TUpload(this);
							Upload->Boundary = new TString(boundary);
							Boundary = new TString(boundary);
							dprintf("Form Daten in Parameter String und Datei upload\nBoundary: %ld\n",Boundary);
						}
					}					
				}
			}
*/
			return true;
		}
		else {
			SocketWrite("HTTP/1.0 501 Not implemented\r\n");
			SocketWrite("Content-Type: text/plain\r\n\r\n");
			SocketWrite("501 : Request-Method not implemented.\n");
			HttpStatus = 501;
//			dprintf("501 : Request-Method not implemented.\n");
			return false;
		}
	}
	return false;
}