blob: 73e9fda993d6697dd404572827499e0828ccb56d [file] [log] [blame]
commit-bot@chromium.org6d036c22014-04-09 18:59:44 +00001package main
2
3import (
4 "bytes"
5 "crypto/md5"
commit-bot@chromium.org282333f2014-04-14 14:54:07 +00006 "database/sql"
commit-bot@chromium.org6d036c22014-04-09 18:59:44 +00007 "encoding/base64"
8 "encoding/json"
9 "flag"
10 "fmt"
commit-bot@chromium.org282333f2014-04-14 14:54:07 +000011 _ "github.com/go-sql-driver/mysql"
commit-bot@chromium.orgc81d1c42014-04-14 18:53:10 +000012 _ "github.com/mattn/go-sqlite3"
13 htemplate "html/template"
commit-bot@chromium.org6d036c22014-04-09 18:59:44 +000014 "io/ioutil"
15 "log"
commit-bot@chromium.orgd04e1dd2014-04-19 13:55:50 +000016 "math/rand"
commit-bot@chromium.org6d036c22014-04-09 18:59:44 +000017 "net/http"
18 "os"
19 "os/exec"
20 "path/filepath"
commit-bot@chromium.orgc81d1c42014-04-14 18:53:10 +000021 "regexp"
commit-bot@chromium.org6d036c22014-04-09 18:59:44 +000022 "strings"
23 "text/template"
commit-bot@chromium.org06aca012014-04-14 20:12:08 +000024 "time"
commit-bot@chromium.org6d036c22014-04-09 18:59:44 +000025)
26
27const (
28 RESULT_COMPILE = `c++ -DSK_GAMMA_SRGB -DSK_GAMMA_APPLY_TO_A8 -DSK_SCALAR_TO_FLOAT_EXCLUDED -DSK_ALLOW_STATIC_GLOBAL_INITIALIZERS=1 -DSK_SUPPORT_GPU=0 -DSK_SUPPORT_OPENCL=0 -DSK_FORCE_DISTANCEFIELD_FONTS=0 -DSK_SCALAR_IS_FLOAT -DSK_CAN_USE_FLOAT -DSK_SAMPLES_FOR_X -DSK_BUILD_FOR_UNIX -DSK_USE_POSIX_THREADS -DSK_SYSTEM_ZLIB=1 -DSK_DEBUG -DSK_DEVELOPER=1 -I../../src/core -I../../src/images -I../../tools/flags -I../../include/config -I../../include/core -I../../include/pathops -I../../include/pipe -I../../include/effects -I../../include/ports -I../../src/sfnt -I../../include/utils -I../../src/utils -I../../include/images -g -fno-exceptions -fstrict-aliasing -Wall -Wextra -Winit-self -Wpointer-arith -Wno-unused-parameter -Wno-c++11-extensions -Werror -m64 -fno-rtti -Wnon-virtual-dtor -c ../../../cache/%s.cpp -o ../../../cache/%s.o`
commit-bot@chromium.orgd6cab4a2014-04-09 21:35:18 +000029 LINK = `c++ -m64 -lstdc++ -lm -o ../../../inout/%s -Wl,--start-group ../../../cache/%s.o obj/experimental/webtry/webtry.main.o obj/gyp/libflags.a libskia_images.a libskia_core.a libskia_effects.a obj/gyp/libjpeg.a obj/gyp/libwebp_dec.a obj/gyp/libwebp_demux.a obj/gyp/libwebp_dsp.a obj/gyp/libwebp_enc.a obj/gyp/libwebp_utils.a libskia_utils.a libskia_opts.a libskia_opts_ssse3.a libskia_ports.a libskia_sfnt.a -Wl,--end-group -lpng -lz -lgif -lpthread -lfontconfig -ldl -lfreetype`
commit-bot@chromium.orgc81d1c42014-04-14 18:53:10 +000030 DEFAULT_SAMPLE = `SkPaint p;
31p.setColor(SK_ColorRED);
32p.setAntiAlias(true);
33p.setStyle(SkPaint::kStroke_Style);
34p.setStrokeWidth(10);
35
36canvas->drawLine(20, 20, 100, 100, p);
37`
commit-bot@chromium.org4bd8fdc2014-04-15 00:43:51 +000038 // Don't increase above 2^16 w/o altering the db tables to accept something bigger than TEXT.
39 MAX_TRY_SIZE = 64000
commit-bot@chromium.org6d036c22014-04-09 18:59:44 +000040)
41
42var (
43 // codeTemplate is the cpp code template the user's code is copied into.
44 codeTemplate *template.Template = nil
45
commit-bot@chromium.org06aca012014-04-14 20:12:08 +000046 // indexTemplate is the main index.html page we serve.
47 indexTemplate *htemplate.Template = nil
48
commit-bot@chromium.org2dceeda2014-04-19 14:50:23 +000049 // iframeTemplate is the main index.html page we serve.
50 iframeTemplate *htemplate.Template = nil
51
commit-bot@chromium.orgd04e1dd2014-04-19 13:55:50 +000052 // recentTemplate is a list of recent images.
commit-bot@chromium.org06aca012014-04-14 20:12:08 +000053 recentTemplate *htemplate.Template = nil
commit-bot@chromium.org282333f2014-04-14 14:54:07 +000054
commit-bot@chromium.orgd04e1dd2014-04-19 13:55:50 +000055 // workspaceTemplate is the page for workspaces, a series of webtrys.
56 workspaceTemplate *htemplate.Template = nil
57
commit-bot@chromium.org282333f2014-04-14 14:54:07 +000058 // db is the database, nil if we don't have an SQL database to store data into.
59 db *sql.DB = nil
commit-bot@chromium.orgc81d1c42014-04-14 18:53:10 +000060
61 // directLink is the regex that matches URLs paths that are direct links.
commit-bot@chromium.org06aca012014-04-14 20:12:08 +000062 directLink = regexp.MustCompile("^/c/([a-f0-9]+)$")
63
commit-bot@chromium.org2dceeda2014-04-19 14:50:23 +000064 // iframeLink is the regex that matches URLs paths that are links to iframes.
65 iframeLink = regexp.MustCompile("^/iframe/([a-f0-9]+)$")
66
commit-bot@chromium.org06aca012014-04-14 20:12:08 +000067 // imageLink is the regex that matches URLs paths that are direct links to PNGs.
68 imageLink = regexp.MustCompile("^/i/([a-f0-9]+.png)$")
commit-bot@chromium.orgd04e1dd2014-04-19 13:55:50 +000069
commit-bot@chromium.org35ffc442014-04-22 19:32:06 +000070 // tryInfoLink is the regex that matches URLs paths that are direct links to data about a single try.
71 tryInfoLink = regexp.MustCompile("^/json/([a-f0-9]+)$")
72
commit-bot@chromium.orgd04e1dd2014-04-19 13:55:50 +000073 // workspaceLink is the regex that matches URLs paths for workspaces.
74 workspaceLink = regexp.MustCompile("^/w/([a-z0-9-]+)$")
75
76 // workspaceNameAdj is a list of adjectives for building workspace names.
77 workspaceNameAdj = []string{
78 "autumn", "hidden", "bitter", "misty", "silent", "empty", "dry", "dark",
79 "summer", "icy", "delicate", "quiet", "white", "cool", "spring", "winter",
80 "patient", "twilight", "dawn", "crimson", "wispy", "weathered", "blue",
81 "billowing", "broken", "cold", "damp", "falling", "frosty", "green",
82 "long", "late", "lingering", "bold", "little", "morning", "muddy", "old",
83 "red", "rough", "still", "small", "sparkling", "throbbing", "shy",
84 "wandering", "withered", "wild", "black", "young", "holy", "solitary",
85 "fragrant", "aged", "snowy", "proud", "floral", "restless", "divine",
86 "polished", "ancient", "purple", "lively", "nameless",
87 }
88
89 // workspaceNameNoun is a list of nouns for building workspace names.
90 workspaceNameNoun = []string{
91 "waterfall", "river", "breeze", "moon", "rain", "wind", "sea", "morning",
92 "snow", "lake", "sunset", "pine", "shadow", "leaf", "dawn", "glitter",
93 "forest", "hill", "cloud", "meadow", "sun", "glade", "bird", "brook",
94 "butterfly", "bush", "dew", "dust", "field", "fire", "flower", "firefly",
95 "feather", "grass", "haze", "mountain", "night", "pond", "darkness",
96 "snowflake", "silence", "sound", "sky", "shape", "surf", "thunder",
97 "violet", "water", "wildflower", "wave", "water", "resonance", "sun",
98 "wood", "dream", "cherry", "tree", "fog", "frost", "voice", "paper",
99 "frog", "smoke", "star",
100 }
commit-bot@chromium.org6d036c22014-04-09 18:59:44 +0000101)
102
103// flags
104var (
105 useChroot = flag.Bool("use_chroot", false, "Run the compiled code in the schroot jail.")
commit-bot@chromium.org282333f2014-04-14 14:54:07 +0000106 port = flag.String("port", ":8000", "HTTP service address (e.g., ':8000')")
commit-bot@chromium.org6d036c22014-04-09 18:59:44 +0000107)
108
109// lineNumbers adds #line numbering to the user's code.
110func LineNumbers(c string) string {
111 lines := strings.Split(c, "\n")
112 ret := []string{}
113 for i, line := range lines {
114 ret = append(ret, fmt.Sprintf("#line %d", i+1))
115 ret = append(ret, line)
116 }
117 return strings.Join(ret, "\n")
118}
119
120func init() {
commit-bot@chromium.org2dceeda2014-04-19 14:50:23 +0000121 rand.Seed(time.Now().UnixNano())
commit-bot@chromium.orgc81d1c42014-04-14 18:53:10 +0000122
commit-bot@chromium.org6d036c22014-04-09 18:59:44 +0000123 // Change the current working directory to the directory of the executable.
124 var err error
125 cwd, err := filepath.Abs(filepath.Dir(os.Args[0]))
126 if err != nil {
127 log.Fatal(err)
128 }
129 os.Chdir(cwd)
130
131 codeTemplate, err = template.ParseFiles(filepath.Join(cwd, "templates/template.cpp"))
132 if err != nil {
133 panic(err)
134 }
commit-bot@chromium.orgd04e1dd2014-04-19 13:55:50 +0000135 indexTemplate, err = htemplate.ParseFiles(
136 filepath.Join(cwd, "templates/index.html"),
137 filepath.Join(cwd, "templates/titlebar.html"),
138 )
commit-bot@chromium.org06aca012014-04-14 20:12:08 +0000139 if err != nil {
140 panic(err)
141 }
commit-bot@chromium.org2dceeda2014-04-19 14:50:23 +0000142 iframeTemplate, err = htemplate.ParseFiles(
143 filepath.Join(cwd, "templates/iframe.html"),
144 )
145 if err != nil {
146 panic(err)
147 }
commit-bot@chromium.orgd04e1dd2014-04-19 13:55:50 +0000148 recentTemplate, err = htemplate.ParseFiles(
149 filepath.Join(cwd, "templates/recent.html"),
150 filepath.Join(cwd, "templates/titlebar.html"),
151 )
152 if err != nil {
153 panic(err)
154 }
155 workspaceTemplate, err = htemplate.ParseFiles(
156 filepath.Join(cwd, "templates/workspace.html"),
157 filepath.Join(cwd, "templates/titlebar.html"),
158 )
commit-bot@chromium.org6d036c22014-04-09 18:59:44 +0000159 if err != nil {
160 panic(err)
161 }
commit-bot@chromium.org282333f2014-04-14 14:54:07 +0000162
163 // Connect to MySQL server. First, get the password from the metadata server.
164 // See https://developers.google.com/compute/docs/metadata#custom.
165 req, err := http.NewRequest("GET", "http://metadata/computeMetadata/v1/instance/attributes/password", nil)
166 if err != nil {
167 panic(err)
168 }
169 client := http.Client{}
170 req.Header.Add("X-Google-Metadata-Request", "True")
171 if resp, err := client.Do(req); err == nil {
172 password, err := ioutil.ReadAll(resp.Body)
173 if err != nil {
174 log.Printf("ERROR: Failed to read password from metadata server: %q\n", err)
175 panic(err)
176 }
177 // The IP address of the database is found here:
178 // https://console.developers.google.com/project/31977622648/sql/instances/webtry/overview
179 // And 3306 is the default port for MySQL.
commit-bot@chromium.org4bd8fdc2014-04-15 00:43:51 +0000180 db, err = sql.Open("mysql", fmt.Sprintf("webtry:%s@tcp(173.194.83.52:3306)/webtry?parseTime=true", password))
commit-bot@chromium.org282333f2014-04-14 14:54:07 +0000181 if err != nil {
182 log.Printf("ERROR: Failed to open connection to SQL server: %q\n", err)
183 panic(err)
184 }
185 } else {
commit-bot@chromium.orgd04e1dd2014-04-19 13:55:50 +0000186 log.Printf("INFO: Failed to find metadata, unable to connect to MySQL server (Expected when running locally): %q\n", err)
commit-bot@chromium.orgc81d1c42014-04-14 18:53:10 +0000187 // Fallback to sqlite for local use.
188 db, err = sql.Open("sqlite3", "./webtry.db")
189 if err != nil {
190 log.Printf("ERROR: Failed to open: %q\n", err)
191 panic(err)
192 }
193 sql := `CREATE TABLE webtry (
194 code TEXT DEFAULT '' NOT NULL,
195 create_ts TIMESTAMP DEFAULT CURRENT_TIMESTAMP NOT NULL,
196 hash CHAR(64) DEFAULT '' NOT NULL,
197 PRIMARY KEY(hash)
198 )`
commit-bot@chromium.orgd04e1dd2014-04-19 13:55:50 +0000199 _, err = db.Exec(sql)
200 log.Printf("Info: status creating sqlite table for webtry: %q\n", err)
201 sql = `CREATE TABLE workspace (
202 name CHAR(64) DEFAULT '' NOT NULL,
203 create_ts TIMESTAMP DEFAULT CURRENT_TIMESTAMP NOT NULL,
204 PRIMARY KEY(name)
205 )`
206 _, err = db.Exec(sql)
207 log.Printf("Info: status creating sqlite table for workspace: %q\n", err)
208 sql = `CREATE TABLE workspacetry (
209 name CHAR(64) DEFAULT '' NOT NULL,
210 create_ts TIMESTAMP DEFAULT CURRENT_TIMESTAMP NOT NULL,
211 hash CHAR(64) DEFAULT '' NOT NULL,
212 hidden INTEGER DEFAULT 0 NOT NULL,
213
214 FOREIGN KEY (name) REFERENCES workspace(name)
215 )`
216 _, err = db.Exec(sql)
217 log.Printf("Info: status creating sqlite table for workspace try: %q\n", err)
commit-bot@chromium.org282333f2014-04-14 14:54:07 +0000218 }
commit-bot@chromium.org6d036c22014-04-09 18:59:44 +0000219}
220
221// userCode is used in template expansion.
222type userCode struct {
223 UserCode string
commit-bot@chromium.org2dceeda2014-04-19 14:50:23 +0000224 Hash string
commit-bot@chromium.org6d036c22014-04-09 18:59:44 +0000225}
226
227// expandToFile expands the template and writes the result to the file.
228func expandToFile(filename string, code string, t *template.Template) error {
229 f, err := os.Create(filename)
230 if err != nil {
231 return err
232 }
233 defer f.Close()
commit-bot@chromium.orgc81d1c42014-04-14 18:53:10 +0000234 return t.Execute(f, userCode{UserCode: code})
commit-bot@chromium.org6d036c22014-04-09 18:59:44 +0000235}
236
237// expandCode expands the template into a file and calculate the MD5 hash.
238func expandCode(code string) (string, error) {
239 h := md5.New()
240 h.Write([]byte(code))
241 hash := fmt.Sprintf("%x", h.Sum(nil))
242 // At this point we are running in skia/experimental/webtry, making cache a
243 // peer directory to skia.
244 // TODO(jcgregorio) Make all relative directories into flags.
245 err := expandToFile(fmt.Sprintf("../../../cache/%s.cpp", hash), code, codeTemplate)
246 return hash, err
247}
248
249// response is serialized to JSON as a response to POSTs.
250type response struct {
251 Message string `json:"message"`
252 Img string `json:"img"`
commit-bot@chromium.orgc81d1c42014-04-14 18:53:10 +0000253 Hash string `json:"hash"`
commit-bot@chromium.org6d036c22014-04-09 18:59:44 +0000254}
255
256// doCmd executes the given command line string in either the out/Debug
257// directory or the inout directory. Returns the stdout, and stderr in the case
258// of a non-zero exit code.
259func doCmd(commandLine string, moveToDebug bool) (string, error) {
260 log.Printf("Command: %q\n", commandLine)
261 programAndArgs := strings.SplitN(commandLine, " ", 2)
262 program := programAndArgs[0]
263 args := []string{}
264 if len(programAndArgs) > 1 {
265 args = strings.Split(programAndArgs[1], " ")
266 }
267 cmd := exec.Command(program, args...)
268 abs, err := filepath.Abs("../../out/Debug")
269 if err != nil {
270 return "", fmt.Errorf("Failed to find absolute path to Debug directory.")
271 }
272 if moveToDebug {
273 cmd.Dir = abs
274 } else if !*useChroot { // Don't set cmd.Dir when using chroot.
275 abs, err := filepath.Abs("../../../inout")
276 if err != nil {
277 return "", fmt.Errorf("Failed to find absolute path to inout directory.")
278 }
279 cmd.Dir = abs
280 }
281 log.Printf("Run in directory: %q\n", cmd.Dir)
282 var stdOut bytes.Buffer
283 cmd.Stdout = &stdOut
284 var stdErr bytes.Buffer
285 cmd.Stderr = &stdErr
286 cmd.Start()
287 err = cmd.Wait()
288 message := stdOut.String()
289 log.Printf("StdOut: %s\n", message)
290 if err != nil {
291 log.Printf("Exit status: %s\n", err.Error())
292 log.Printf("StdErr: %s\n", stdErr.String())
293 message += stdErr.String()
294 return message, fmt.Errorf("Failed to run command.")
295 }
296 return message, nil
297}
298
299// reportError formats an HTTP error response and also logs the detailed error message.
300func reportError(w http.ResponseWriter, r *http.Request, err error, message string) {
301 m := response{
302 Message: message,
303 }
304 log.Printf("Error: %s\n%s", message, err.Error())
305 resp, err := json.Marshal(m)
306 if err != nil {
307 http.Error(w, "Failed to serialize a response", 500)
308 return
309 }
310 w.Write(resp)
311}
312
commit-bot@chromium.orgd04e1dd2014-04-19 13:55:50 +0000313func writeToDatabase(hash string, code string, workspaceName string) {
commit-bot@chromium.org282333f2014-04-14 14:54:07 +0000314 if db == nil {
315 return
316 }
317 if _, err := db.Exec("INSERT INTO webtry (code, hash) VALUES(?, ?)", code, hash); err != nil {
318 log.Printf("ERROR: Failed to insert code into database: %q\n", err)
319 }
commit-bot@chromium.orgd04e1dd2014-04-19 13:55:50 +0000320 if workspaceName != "" {
321 if _, err := db.Exec("INSERT INTO workspacetry (name, hash) VALUES(?, ?)", workspaceName, hash); err != nil {
322 log.Printf("ERROR: Failed to insert into workspacetry table: %q\n", err)
323 }
324 }
commit-bot@chromium.org282333f2014-04-14 14:54:07 +0000325}
326
commit-bot@chromium.org06aca012014-04-14 20:12:08 +0000327func cssHandler(w http.ResponseWriter, r *http.Request) {
328 http.ServeFile(w, r, "css/webtry.css")
329}
330
commit-bot@chromium.orgd04e1dd2014-04-19 13:55:50 +0000331func jsHandler(w http.ResponseWriter, r *http.Request) {
332 http.ServeFile(w, r, "js/run.js")
333}
334
commit-bot@chromium.org06aca012014-04-14 20:12:08 +0000335// imageHandler serves up the PNG of a specific try.
336func imageHandler(w http.ResponseWriter, r *http.Request) {
337 log.Printf("Image Handler: %q\n", r.URL.Path)
338 if r.Method != "GET" {
339 http.NotFound(w, r)
340 return
341 }
342 match := imageLink.FindStringSubmatch(r.URL.Path)
343 if len(match) != 2 {
344 http.NotFound(w, r)
345 return
346 }
347 filename := match[1]
348 http.ServeFile(w, r, fmt.Sprintf("../../../inout/%s", filename))
349}
350
351type Try struct {
commit-bot@chromium.orgc3b738a2014-04-21 17:36:44 +0000352 Hash string `json:"hash"`
353 CreateTS string `json:"create_ts"`
commit-bot@chromium.org06aca012014-04-14 20:12:08 +0000354}
355
356type Recent struct {
357 Tries []Try
358}
359
360// recentHandler shows the last 20 tries.
361func recentHandler(w http.ResponseWriter, r *http.Request) {
362 log.Printf("Recent Handler: %q\n", r.URL.Path)
363
364 var err error
365 rows, err := db.Query("SELECT create_ts, hash FROM webtry ORDER BY create_ts DESC LIMIT 20")
366 if err != nil {
367 http.NotFound(w, r)
368 return
369 }
370 recent := []Try{}
371 for rows.Next() {
372 var hash string
373 var create_ts time.Time
374 if err := rows.Scan(&create_ts, &hash); err != nil {
375 log.Printf("Error: failed to fetch from database: %q", err)
376 continue
377 }
378 recent = append(recent, Try{Hash: hash, CreateTS: create_ts.Format("2006-02-01")})
379 }
380 if err := recentTemplate.Execute(w, Recent{Tries: recent}); err != nil {
381 log.Printf("ERROR: Failed to expand template: %q\n", err)
382 }
383}
384
commit-bot@chromium.orgd04e1dd2014-04-19 13:55:50 +0000385type Workspace struct {
386 Name string
387 Code string
commit-bot@chromium.org35ffc442014-04-22 19:32:06 +0000388 Hash string
commit-bot@chromium.orgd04e1dd2014-04-19 13:55:50 +0000389 Tries []Try
390}
391
392// newWorkspace generates a new random workspace name and stores it in the database.
393func newWorkspace() (string, error) {
394 for i := 0; i < 10; i++ {
395 adj := workspaceNameAdj[rand.Intn(len(workspaceNameAdj))]
396 noun := workspaceNameNoun[rand.Intn(len(workspaceNameNoun))]
397 suffix := rand.Intn(1000)
398 name := fmt.Sprintf("%s-%s-%d", adj, noun, suffix)
399 if _, err := db.Exec("INSERT INTO workspace (name) VALUES(?)", name); err == nil {
400 return name, nil
401 } else {
402 log.Printf("ERROR: Failed to insert workspace into database: %q\n", err)
403 }
404 }
405 return "", fmt.Errorf("Failed to create a new workspace")
406}
407
408// getCode returns the code for a given hash, or the empty string if not found.
commit-bot@chromium.org35ffc442014-04-22 19:32:06 +0000409func getCode(hash string) (string, error) {
commit-bot@chromium.orgd04e1dd2014-04-19 13:55:50 +0000410 code := ""
411 if err := db.QueryRow("SELECT code FROM webtry WHERE hash=?", hash).Scan(&code); err != nil {
412 log.Printf("ERROR: Code for hash is missing: %q\n", err)
commit-bot@chromium.org35ffc442014-04-22 19:32:06 +0000413 return code, err
commit-bot@chromium.orgd04e1dd2014-04-19 13:55:50 +0000414 }
commit-bot@chromium.org35ffc442014-04-22 19:32:06 +0000415 return code, nil
commit-bot@chromium.orgd04e1dd2014-04-19 13:55:50 +0000416}
417
418func workspaceHandler(w http.ResponseWriter, r *http.Request) {
419 log.Printf("Workspace Handler: %q\n", r.URL.Path)
420 if r.Method == "GET" {
421 tries := []Try{}
422 match := workspaceLink.FindStringSubmatch(r.URL.Path)
423 name := ""
424 if len(match) == 2 {
425 name = match[1]
commit-bot@chromium.orgc3b738a2014-04-21 17:36:44 +0000426 rows, err := db.Query("SELECT create_ts, hash FROM workspacetry WHERE name=? ORDER BY create_ts", name)
commit-bot@chromium.orgd04e1dd2014-04-19 13:55:50 +0000427 if err != nil {
428 reportError(w, r, err, "Failed to select.")
429 return
430 }
431 for rows.Next() {
432 var hash string
433 var create_ts time.Time
434 if err := rows.Scan(&create_ts, &hash); err != nil {
435 log.Printf("Error: failed to fetch from database: %q", err)
436 continue
437 }
438 tries = append(tries, Try{Hash: hash, CreateTS: create_ts.Format("2006-02-01")})
439 }
440 }
441 var code string
commit-bot@chromium.org35ffc442014-04-22 19:32:06 +0000442 var hash string
commit-bot@chromium.orgd04e1dd2014-04-19 13:55:50 +0000443 if len(tries) == 0 {
444 code = DEFAULT_SAMPLE
445 } else {
commit-bot@chromium.org35ffc442014-04-22 19:32:06 +0000446 hash = tries[len(tries)-1].Hash
447 code, _ = getCode(hash)
commit-bot@chromium.orgd04e1dd2014-04-19 13:55:50 +0000448 }
commit-bot@chromium.org35ffc442014-04-22 19:32:06 +0000449 if err := workspaceTemplate.Execute(w, Workspace{Tries: tries, Code: code, Name: name, Hash: hash}); err != nil {
commit-bot@chromium.orgd04e1dd2014-04-19 13:55:50 +0000450 log.Printf("ERROR: Failed to expand template: %q\n", err)
451 }
452 } else if r.Method == "POST" {
453 name, err := newWorkspace()
454 if err != nil {
455 http.Error(w, "Failed to create a new workspace.", 500)
456 return
457 }
458 http.Redirect(w, r, "/w/"+name, 302)
459 }
460}
461
commit-bot@chromium.org4bd8fdc2014-04-15 00:43:51 +0000462// hasPreProcessor returns true if any line in the code begins with a # char.
463func hasPreProcessor(code string) bool {
464 lines := strings.Split(code, "\n")
465 for _, s := range lines {
466 if strings.HasPrefix(strings.TrimSpace(s), "#") {
467 return true
468 }
469 }
470 return false
471}
472
commit-bot@chromium.orgd04e1dd2014-04-19 13:55:50 +0000473type TryRequest struct {
474 Code string `json:"code"`
commit-bot@chromium.org35ffc442014-04-22 19:32:06 +0000475 Name string `json:"name"` // Optional name of the workspace the code is in.
commit-bot@chromium.orgd04e1dd2014-04-19 13:55:50 +0000476}
477
commit-bot@chromium.org2dceeda2014-04-19 14:50:23 +0000478// iframeHandler handles the GET and POST of the main page.
479func iframeHandler(w http.ResponseWriter, r *http.Request) {
480 log.Printf("IFrame Handler: %q\n", r.URL.Path)
481 if r.Method != "GET" {
482 http.NotFound(w, r)
483 return
484 }
485 match := iframeLink.FindStringSubmatch(r.URL.Path)
486 if len(match) != 2 {
487 http.NotFound(w, r)
488 return
489 }
490 hash := match[1]
491 if db == nil {
492 http.NotFound(w, r)
493 return
494 }
495 var code string
commit-bot@chromium.org35ffc442014-04-22 19:32:06 +0000496 code, err := getCode(hash)
497 if err != nil {
commit-bot@chromium.org2dceeda2014-04-19 14:50:23 +0000498 http.NotFound(w, r)
499 return
500 }
501 // Expand the template.
502 if err := iframeTemplate.Execute(w, userCode{UserCode: code, Hash: hash}); err != nil {
503 log.Printf("ERROR: Failed to expand template: %q\n", err)
504 }
505}
506
commit-bot@chromium.org35ffc442014-04-22 19:32:06 +0000507type TryInfo struct {
508 Hash string `json:"hash"`
509 Code string `json:"code"`
510}
511
512// tryInfoHandler returns information about a specific try.
513func tryInfoHandler(w http.ResponseWriter, r *http.Request) {
514 log.Printf("Try Info Handler: %q\n", r.URL.Path)
515 if r.Method != "GET" {
516 http.NotFound(w, r)
517 return
518 }
519 match := tryInfoLink.FindStringSubmatch(r.URL.Path)
520 if len(match) != 2 {
521 http.NotFound(w, r)
522 return
523 }
524 hash := match[1]
525 code, err := getCode(hash)
526 if err != nil {
527 http.NotFound(w, r)
528 return
529 }
530 m := TryInfo{
531 Hash: hash,
532 Code: code,
533 }
534 resp, err := json.Marshal(m)
535 if err != nil {
536 reportError(w, r, err, "Failed to serialize a response.")
537 return
538 }
539 w.Header().Set("Content-Type", "application/json")
540 w.Write(resp)
541}
542
commit-bot@chromium.org6d036c22014-04-09 18:59:44 +0000543// mainHandler handles the GET and POST of the main page.
544func mainHandler(w http.ResponseWriter, r *http.Request) {
commit-bot@chromium.org06aca012014-04-14 20:12:08 +0000545 log.Printf("Main Handler: %q\n", r.URL.Path)
commit-bot@chromium.org6d036c22014-04-09 18:59:44 +0000546 if r.Method == "GET" {
commit-bot@chromium.orgc81d1c42014-04-14 18:53:10 +0000547 code := DEFAULT_SAMPLE
commit-bot@chromium.orgc81d1c42014-04-14 18:53:10 +0000548 match := directLink.FindStringSubmatch(r.URL.Path)
commit-bot@chromium.org35ffc442014-04-22 19:32:06 +0000549 var hash string
commit-bot@chromium.org06aca012014-04-14 20:12:08 +0000550 if len(match) == 2 && r.URL.Path != "/" {
commit-bot@chromium.org35ffc442014-04-22 19:32:06 +0000551 hash = match[1]
commit-bot@chromium.orgc81d1c42014-04-14 18:53:10 +0000552 if db == nil {
553 http.NotFound(w, r)
554 return
555 }
556 // Update 'code' with the code found in the database.
557 if err := db.QueryRow("SELECT code FROM webtry WHERE hash=?", hash).Scan(&code); err != nil {
558 http.NotFound(w, r)
559 return
560 }
561 }
562 // Expand the template.
commit-bot@chromium.org35ffc442014-04-22 19:32:06 +0000563 if err := indexTemplate.Execute(w, userCode{UserCode: code, Hash: hash}); err != nil {
commit-bot@chromium.orgc81d1c42014-04-14 18:53:10 +0000564 log.Printf("ERROR: Failed to expand template: %q\n", err)
565 }
commit-bot@chromium.org6d036c22014-04-09 18:59:44 +0000566 } else if r.Method == "POST" {
567 w.Header().Set("Content-Type", "application/json")
commit-bot@chromium.org4bd8fdc2014-04-15 00:43:51 +0000568 buf := bytes.NewBuffer(make([]byte, 0, MAX_TRY_SIZE))
569 n, err := buf.ReadFrom(r.Body)
commit-bot@chromium.org6d036c22014-04-09 18:59:44 +0000570 if err != nil {
571 reportError(w, r, err, "Failed to read a request body.")
572 return
573 }
commit-bot@chromium.org4bd8fdc2014-04-15 00:43:51 +0000574 if n == MAX_TRY_SIZE {
575 err := fmt.Errorf("Code length equal to, or exceeded, %d", MAX_TRY_SIZE)
576 reportError(w, r, err, "Code too large.")
577 return
578 }
commit-bot@chromium.orgd04e1dd2014-04-19 13:55:50 +0000579 request := TryRequest{}
580 if err := json.Unmarshal(buf.Bytes(), &request); err != nil {
581 reportError(w, r, err, "Coulnd't decode JSON.")
582 return
583 }
584 if hasPreProcessor(request.Code) {
commit-bot@chromium.org4bd8fdc2014-04-15 00:43:51 +0000585 err := fmt.Errorf("Found preprocessor macro in code.")
586 reportError(w, r, err, "Preprocessor macros aren't allowed.")
587 return
588 }
commit-bot@chromium.orgd04e1dd2014-04-19 13:55:50 +0000589 hash, err := expandCode(LineNumbers(request.Code))
commit-bot@chromium.org6d036c22014-04-09 18:59:44 +0000590 if err != nil {
591 reportError(w, r, err, "Failed to write the code to compile.")
592 return
593 }
commit-bot@chromium.orgd04e1dd2014-04-19 13:55:50 +0000594 writeToDatabase(hash, request.Code, request.Name)
commit-bot@chromium.org6d036c22014-04-09 18:59:44 +0000595 message, err := doCmd(fmt.Sprintf(RESULT_COMPILE, hash, hash), true)
596 if err != nil {
597 reportError(w, r, err, "Failed to compile the code:\n"+message)
598 return
599 }
600 linkMessage, err := doCmd(fmt.Sprintf(LINK, hash, hash), true)
601 if err != nil {
602 reportError(w, r, err, "Failed to link the code:\n"+linkMessage)
603 return
604 }
605 message += linkMessage
606 cmd := hash + " --out " + hash + ".png"
607 if *useChroot {
608 cmd = "schroot -c webtry --directory=/inout -- /inout/" + cmd
609 } else {
610 abs, err := filepath.Abs("../../../inout")
611 if err != nil {
612 reportError(w, r, err, "Failed to find executable directory.")
613 return
614 }
615 cmd = abs + "/" + cmd
616 }
617
618 execMessage, err := doCmd(cmd, false)
619 if err != nil {
620 reportError(w, r, err, "Failed to run the code:\n"+execMessage)
621 return
622 }
623 png, err := ioutil.ReadFile("../../../inout/" + hash + ".png")
624 if err != nil {
625 reportError(w, r, err, "Failed to open the generated PNG.")
626 return
627 }
628
629 m := response{
630 Message: message,
631 Img: base64.StdEncoding.EncodeToString([]byte(png)),
commit-bot@chromium.orgc81d1c42014-04-14 18:53:10 +0000632 Hash: hash,
commit-bot@chromium.org6d036c22014-04-09 18:59:44 +0000633 }
634 resp, err := json.Marshal(m)
635 if err != nil {
636 reportError(w, r, err, "Failed to serialize a response.")
637 return
638 }
639 w.Write(resp)
640 }
641}
642
643func main() {
644 flag.Parse()
commit-bot@chromium.org06aca012014-04-14 20:12:08 +0000645 http.HandleFunc("/i/", imageHandler)
commit-bot@chromium.orgd04e1dd2014-04-19 13:55:50 +0000646 http.HandleFunc("/w/", workspaceHandler)
commit-bot@chromium.org06aca012014-04-14 20:12:08 +0000647 http.HandleFunc("/recent/", recentHandler)
commit-bot@chromium.org2dceeda2014-04-19 14:50:23 +0000648 http.HandleFunc("/iframe/", iframeHandler)
commit-bot@chromium.org35ffc442014-04-22 19:32:06 +0000649 http.HandleFunc("/json/", tryInfoHandler)
commit-bot@chromium.org06aca012014-04-14 20:12:08 +0000650 http.HandleFunc("/css/", cssHandler)
commit-bot@chromium.orgd04e1dd2014-04-19 13:55:50 +0000651 http.HandleFunc("/js/", jsHandler)
commit-bot@chromium.org35ffc442014-04-22 19:32:06 +0000652 // TODO Break out /c/ as it's own handler.
commit-bot@chromium.org6d036c22014-04-09 18:59:44 +0000653 http.HandleFunc("/", mainHandler)
commit-bot@chromium.org282333f2014-04-14 14:54:07 +0000654 log.Fatal(http.ListenAndServe(*port, nil))
commit-bot@chromium.org6d036c22014-04-09 18:59:44 +0000655}