00001
00002 #include <sys/types.h>
00003 #include <sys/stat.h>
00004 #include <unistd.h>
00005 #include <errno.h>
00006 #include <Utility.h>
00007 #include <Uid.h>
00008 #include "RowoHandler.h"
00009 #include "InjectSocket.h"
00010
00011
00012
00013
00014 InjectSocket::InjectSocket(ISocketHandler& h)
00015 :HTTPSocket(h)
00016 ,m_is_server(false)
00017 ,m_content_length(0)
00018 ,m_file(NULL)
00019 {
00020 }
00021
00022
00023 InjectSocket::~InjectSocket()
00024 {
00025 if (m_file)
00026 fclose(m_file);
00027 }
00028
00029
00030 void InjectSocket::OnConnect()
00031 {
00032 struct stat st;
00033 if (stat(m_filename.c_str(),&st) == -1)
00034 {
00035 Handler().LogError(this, "stat", errno, strerror(errno), LOG_LEVEL_FATAL);
00036 SetCloseAndDelete();
00037 return;
00038 }
00039 std::string request;
00040 request += "PUT " + m_filename + " HTTP/1.0\n";
00041 request += "Content-type: text/xml\n";
00042 request += "Content-length: " + Utility::l2string(st.st_size) + "\n";
00043 request += "Connection: close\n";
00044 request += "\n";
00045 Send( request );
00046 FILE *fil;
00047 if ((fil = fopen(m_filename.c_str(),"rb")) != NULL)
00048 {
00049 char buf[1000];
00050 size_t n;
00051 while ((n = fread(buf,1,1000,fil)) > 0)
00052 {
00053 SendBuf(buf, n);
00054 }
00055 fclose(fil);
00056 }
00057 }
00058
00059
00060 void InjectSocket::OnAccept()
00061 {
00062 m_is_server = true;
00063 }
00064
00065
00066 void InjectSocket::OnFirst()
00067 {
00068 }
00069
00070
00071 void InjectSocket::OnHeader(const std::string& key,const std::string& value)
00072 {
00073
00074 if (!strcasecmp(key.c_str(),"content-type"))
00075 {
00076 if (strcasecmp(value.c_str(),"text/xml"))
00077 {
00078 Handler().LogError(this, "OnHeader", 0, "content-type not text/xml", LOG_LEVEL_FATAL);
00079 SetCloseAndDelete();
00080 }
00081 else
00082 m_filename = GetUrl();
00083 }
00084 else
00085 if (!strcasecmp(key.c_str(),"content-length"))
00086 {
00087 m_content_length = atoi(value.c_str());
00088 }
00089 }
00090
00091
00092 void InjectSocket::OnHeaderComplete()
00093 {
00094
00095 if (m_filename.size() && m_is_server)
00096 {
00097 Uid random;
00098 m_filename = random.GetUid() + ".xml";
00099 m_file = fopen(m_filename.c_str(),"wb");
00100 }
00101 }
00102
00103
00104 void InjectSocket::OnData(const char *buf,size_t sz)
00105 {
00106
00107 if (m_file)
00108 fwrite(buf,1,sz,m_file);
00109
00110 m_content_length -= sz;
00111 if (m_content_length <= 0)
00112 {
00113 fclose(m_file);
00114 m_file = NULL;
00115 SetCloseAndDelete();
00116 static_cast<RowoHandler&>(Handler()).InjectRobot(m_filename);
00117 unlink(m_filename.c_str());
00118 }
00119 }
00120
00121