File: http.ec

package info (click to toggle)
ecere-sdk 0.44.15-1
  • links: PTS
  • area: main
  • in suites: sid, stretch
  • size: 97,712 kB
  • ctags: 54,695
  • sloc: ansic: 593,042; makefile: 12,250; yacc: 4,955; lex: 707; objc: 259; python: 252; xml: 102
file content (236 lines) | stat: -rw-r--r-- 6,181 bytes parent folder | download | duplicates (2)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
import "ecere"

static const char * indexNames[] =
{
   "index.html",
   "index.htm",
   "home.html",
   "home.htm",
   "welcome.html",
   "welcome.htm",
   "default.html",
   "default.htm"
};

#define NUM_INDEX    (sizeof(indexNames) / sizeof(char *))

static void WriteFileName(File f, const char * fileName)
{
   byte ch;
   int c;
   for(c = 0; (ch = fileName[c]); c++)
   {
      if(ch <= 32 || ch > 128)
      {
         byte nibble;
         f.Putc('%');
         nibble = (ch & 0xF0) >> 4;
         f.Putc((char)((nibble > 9) ? (nibble - 10 + 'a') : (nibble + '0')));
         nibble = ch & 0x0F;
         f.Putc((char)((nibble > 9) ? (nibble - 10 + 'a') : (nibble + '0')));
      }
      else
         f.Putc(ch);
   }
}

#define CONTENT_PATH   "."

static void CreateDirectoryListing(File f, char * directory)
{
   FileListing listing { directory };

   f.Puts("<HTML><HEAD></HEAD><BODY>\r\n");

   if(directory[0] && directory[1] && (directory[1] != ':' || (directory[2] && directory[3])))
      f.Puts("<A HREF=../>../</A><BR>\r\n");

   while(listing.Find())
   {
      f.Puts("<A HREF=");
      WriteFileName(f, listing.name);
      if(listing.stats.attribs.isDirectory)
         f.Puts("/");
      f.Puts(">");
      f.Puts(listing.name);
      f.Puts("</A><BR>\r\n");
   }

   f.Puts("\r\n</BODY></HTML>\r\n");
}

static const char * GetString(const char * string, const char * what, int count)
{
   int c;
   bool result = true;
   for(c = 0; what[c]; c++)
   {
      if((count && c >= count) || (string[c] != what[c] && tolower(string[c]) != tolower(what[c])))
         return null;
   }
   return string + c;
}

class HTTPClient : Socket
{
   File f;
   bool close;

   #define ishexdigit(x) (isdigit(x) || (x >= 'a' && x<='f') || (x >= 'A' && x <= 'F'))

   uint OnReceive(const byte * buffer, uint count)
   {
      int c;
      for(c = 0; c<count-1; c++)
      {
         if(buffer[c] == '\r' && buffer[c+1] == '\n')
            break;
      }
      if(c<count)
      {
         const char * string = (const char *)buffer;

         if((string = GetString(string, "GET ", count)))
         {
            char reply[1024];
            char path[MAX_LOCATION];
            char addedPath[MAX_LOCATION];
            int d, i;
            FileAttribs attribs;
            int len = 0;

            strcpy(path, CONTENT_PATH);

            for(d = c; d > 0 && string[d] != ' '; d--);
            for(i = 0; i<d; i++)
            {
               if(string[i] == '%' && ishexdigit(string[i+1]) && ishexdigit(string[i+2]))
               {
                  char digits[3];
                  digits[0] = string[i+1];
                  digits[1] = string[i+2];
                  digits[2] = '\0';
                  addedPath[len++] = (byte)strtol(digits, null, 16);
                  i += 2;
               }
               else
                  addedPath[len++] = string[i];
               addedPath[len] = '\0';
            }

            PathCat(path, addedPath+1);

            attribs = FileExists(path);

            if(attribs.isDirectory)
            {
               if(addedPath[len-1] != '/')
               {
                  strcpy(reply, "HTTP/1.1 301 Moved Permantently\r\n");

                  strcat(reply, "Location: ");
                  strcat(reply, addedPath);
                  strcat(reply, "/\r\n");
                  strcat(reply, "Content-Length: 0\r\n\r\n");
               }
               else
               {
                  int i;
                  char indexFile[MAX_LOCATION];
                  for(i = 0; i<NUM_INDEX; i++)
                  {
                     strcpy(indexFile, path);
                     PathCat(indexFile, indexNames[i]);
                     if(FileExists(indexFile).isFile)
                     {
                        f = FileOpen(indexFile, read);
                        break;
                     }
                  }
                  // List contents if we didn't find an index
                  if(i == NUM_INDEX)
                  {
                     f = TempFile {};
                     if(f)
                     {
                        CreateDirectoryListing(f, path);
                        f.Seek(0, start);
                     }
                  }
               }
            }
            else if(attribs.isFile)
               f = FileOpen(path, read);
            else
               strcpy(reply, "HTTP/1.1 404 Not Found\r\nContent-Length: 0\r\n\r\n");

            if(f)
            {
               char extension[MAX_EXTENSION];
               uint size = f.GetSize();
               sprintf(reply, "HTTP/1.1 200 OK\r\n");

               GetExtension(addedPath, extension);
               if(attribs.isDirectory || !strcmp(extension, "html") || !strcmp(extension, "htm"))
                  strcat(reply, "Content-Type: text/html\r\n");
               else
                  strcat(reply, "Content-Type: text/plain\r\n");
               sprintf(strchr(reply, 0), "Content-Length: %d\r\n\r\n", size);
            }
            SendString(reply);
         }
         return c+2;
      }
      return count;
   }
}

class HTTPServer : Service
{
   void OnAccept()
   {
      HTTPClient { this };
   }
}

class HTTPApplication : GuiApplication
{
   bool Init()
   {
      httpServer.Start();
      return true;
   }

   bool Cycle(bool idle)
   {
      bool result = true;
      HTTPClient client, next;
      for(client = (HTTPClient)httpServer.firstClient; client; client = next)
      {
         next = (HTTPClient)client.next;
         if(client.f)
         {
            #define PACKETSIZE      65536

            static byte buffer[PACKETSIZE];
            int read = client.f.Read(buffer, 1, PACKETSIZE);

            if(read)
               client.Send(buffer, read);
            if(client.f.Eof())
            {
               delete client.f;
               if(client.close)
                  client.Disconnect(0);
            }

            result = true;
         }
      }
      return result;
   }
}

HTTPServer httpServer { port = 8080 };

Window serverWindow { size = Size { 320, 200 }, text = "ECERE HTTP Server", hasMinimize = true, hasClose = true };