blob: 6aa186ced857df902d0277462d543ba9bb2655e6 [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"),
commit-bot@chromium.org90041922014-04-22 21:13:45 +0000138 filepath.Join(cwd, "templates/content.html"),
commit-bot@chromium.orgd04e1dd2014-04-19 13:55:50 +0000139 )
commit-bot@chromium.org06aca012014-04-14 20:12:08 +0000140 if err != nil {
141 panic(err)
142 }
commit-bot@chromium.org2dceeda2014-04-19 14:50:23 +0000143 iframeTemplate, err = htemplate.ParseFiles(
144 filepath.Join(cwd, "templates/iframe.html"),
commit-bot@chromium.org90041922014-04-22 21:13:45 +0000145 filepath.Join(cwd, "templates/content.html"),
commit-bot@chromium.org2dceeda2014-04-19 14:50:23 +0000146 )
147 if err != nil {
148 panic(err)
149 }
commit-bot@chromium.orgd04e1dd2014-04-19 13:55:50 +0000150 recentTemplate, err = htemplate.ParseFiles(
151 filepath.Join(cwd, "templates/recent.html"),
152 filepath.Join(cwd, "templates/titlebar.html"),
153 )
154 if err != nil {
155 panic(err)
156 }
157 workspaceTemplate, err = htemplate.ParseFiles(
158 filepath.Join(cwd, "templates/workspace.html"),
159 filepath.Join(cwd, "templates/titlebar.html"),
commit-bot@chromium.org90041922014-04-22 21:13:45 +0000160 filepath.Join(cwd, "templates/content.html"),
commit-bot@chromium.orgd04e1dd2014-04-19 13:55:50 +0000161 )
commit-bot@chromium.org6d036c22014-04-09 18:59:44 +0000162 if err != nil {
163 panic(err)
164 }
commit-bot@chromium.org282333f2014-04-14 14:54:07 +0000165
166 // Connect to MySQL server. First, get the password from the metadata server.
167 // See https://developers.google.com/compute/docs/metadata#custom.
168 req, err := http.NewRequest("GET", "http://metadata/computeMetadata/v1/instance/attributes/password", nil)
169 if err != nil {
170 panic(err)
171 }
172 client := http.Client{}
173 req.Header.Add("X-Google-Metadata-Request", "True")
174 if resp, err := client.Do(req); err == nil {
175 password, err := ioutil.ReadAll(resp.Body)
176 if err != nil {
177 log.Printf("ERROR: Failed to read password from metadata server: %q\n", err)
178 panic(err)
179 }
180 // The IP address of the database is found here:
181 // https://console.developers.google.com/project/31977622648/sql/instances/webtry/overview
182 // And 3306 is the default port for MySQL.
commit-bot@chromium.org4bd8fdc2014-04-15 00:43:51 +0000183 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 +0000184 if err != nil {
185 log.Printf("ERROR: Failed to open connection to SQL server: %q\n", err)
186 panic(err)
187 }
188 } else {
commit-bot@chromium.orgd04e1dd2014-04-19 13:55:50 +0000189 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 +0000190 // Fallback to sqlite for local use.
191 db, err = sql.Open("sqlite3", "./webtry.db")
192 if err != nil {
193 log.Printf("ERROR: Failed to open: %q\n", err)
194 panic(err)
195 }
196 sql := `CREATE TABLE webtry (
197 code TEXT DEFAULT '' NOT NULL,
198 create_ts TIMESTAMP DEFAULT CURRENT_TIMESTAMP NOT NULL,
199 hash CHAR(64) DEFAULT '' NOT NULL,
200 PRIMARY KEY(hash)
201 )`
commit-bot@chromium.orgd04e1dd2014-04-19 13:55:50 +0000202 _, err = db.Exec(sql)
203 log.Printf("Info: status creating sqlite table for webtry: %q\n", err)
204 sql = `CREATE TABLE workspace (
205 name CHAR(64) DEFAULT '' NOT NULL,
206 create_ts TIMESTAMP DEFAULT CURRENT_TIMESTAMP NOT NULL,
207 PRIMARY KEY(name)
208 )`
209 _, err = db.Exec(sql)
210 log.Printf("Info: status creating sqlite table for workspace: %q\n", err)
211 sql = `CREATE TABLE workspacetry (
212 name CHAR(64) DEFAULT '' NOT NULL,
213 create_ts TIMESTAMP DEFAULT CURRENT_TIMESTAMP NOT NULL,
214 hash CHAR(64) DEFAULT '' NOT NULL,
215 hidden INTEGER DEFAULT 0 NOT NULL,
216
217 FOREIGN KEY (name) REFERENCES workspace(name)
218 )`
219 _, err = db.Exec(sql)
220 log.Printf("Info: status creating sqlite table for workspace try: %q\n", err)
commit-bot@chromium.org282333f2014-04-14 14:54:07 +0000221 }
commit-bot@chromium.org6d036c22014-04-09 18:59:44 +0000222}
223
224// userCode is used in template expansion.
225type userCode struct {
commit-bot@chromium.org90041922014-04-22 21:13:45 +0000226 Code string
227 Hash string
commit-bot@chromium.org6d036c22014-04-09 18:59:44 +0000228}
229
230// expandToFile expands the template and writes the result to the file.
231func expandToFile(filename string, code string, t *template.Template) error {
232 f, err := os.Create(filename)
233 if err != nil {
234 return err
235 }
236 defer f.Close()
commit-bot@chromium.org90041922014-04-22 21:13:45 +0000237 return t.Execute(f, userCode{Code: code})
commit-bot@chromium.org6d036c22014-04-09 18:59:44 +0000238}
239
240// expandCode expands the template into a file and calculate the MD5 hash.
241func expandCode(code string) (string, error) {
242 h := md5.New()
243 h.Write([]byte(code))
244 hash := fmt.Sprintf("%x", h.Sum(nil))
245 // At this point we are running in skia/experimental/webtry, making cache a
246 // peer directory to skia.
247 // TODO(jcgregorio) Make all relative directories into flags.
248 err := expandToFile(fmt.Sprintf("../../../cache/%s.cpp", hash), code, codeTemplate)
249 return hash, err
250}
251
252// response is serialized to JSON as a response to POSTs.
253type response struct {
254 Message string `json:"message"`
commit-bot@chromium.org90041922014-04-22 21:13:45 +0000255 StdOut string `json:"stdout"`
commit-bot@chromium.org6d036c22014-04-09 18:59:44 +0000256 Img string `json:"img"`
commit-bot@chromium.orgc81d1c42014-04-14 18:53:10 +0000257 Hash string `json:"hash"`
commit-bot@chromium.org6d036c22014-04-09 18:59:44 +0000258}
259
260// doCmd executes the given command line string in either the out/Debug
commit-bot@chromium.org15b29812014-04-28 14:56:32 +0000261// directory or the inout directory. Returns the stdout and stderr.
commit-bot@chromium.org6d036c22014-04-09 18:59:44 +0000262func doCmd(commandLine string, moveToDebug bool) (string, error) {
263 log.Printf("Command: %q\n", commandLine)
264 programAndArgs := strings.SplitN(commandLine, " ", 2)
265 program := programAndArgs[0]
266 args := []string{}
267 if len(programAndArgs) > 1 {
268 args = strings.Split(programAndArgs[1], " ")
269 }
270 cmd := exec.Command(program, args...)
271 abs, err := filepath.Abs("../../out/Debug")
272 if err != nil {
273 return "", fmt.Errorf("Failed to find absolute path to Debug directory.")
274 }
275 if moveToDebug {
276 cmd.Dir = abs
277 } else if !*useChroot { // Don't set cmd.Dir when using chroot.
278 abs, err := filepath.Abs("../../../inout")
279 if err != nil {
280 return "", fmt.Errorf("Failed to find absolute path to inout directory.")
281 }
282 cmd.Dir = abs
283 }
284 log.Printf("Run in directory: %q\n", cmd.Dir)
commit-bot@chromium.org15b29812014-04-28 14:56:32 +0000285 message, err := cmd.CombinedOutput()
286 log.Printf("StdOut + StdErr: %s\n", string(message))
commit-bot@chromium.org6d036c22014-04-09 18:59:44 +0000287 if err != nil {
288 log.Printf("Exit status: %s\n", err.Error())
commit-bot@chromium.org15b29812014-04-28 14:56:32 +0000289 return string(message), fmt.Errorf("Failed to run command.")
commit-bot@chromium.org6d036c22014-04-09 18:59:44 +0000290 }
commit-bot@chromium.org15b29812014-04-28 14:56:32 +0000291 return string(message), nil
commit-bot@chromium.org6d036c22014-04-09 18:59:44 +0000292}
293
294// reportError formats an HTTP error response and also logs the detailed error message.
295func reportError(w http.ResponseWriter, r *http.Request, err error, message string) {
commit-bot@chromium.org90041922014-04-22 21:13:45 +0000296 log.Printf("Error: %s\n%s", message, err.Error())
297 http.Error(w, message, 500)
298}
299
300// reportTryError formats an HTTP error response in JSON and also logs the detailed error message.
301func reportTryError(w http.ResponseWriter, r *http.Request, err error, message, hash string) {
commit-bot@chromium.org6d036c22014-04-09 18:59:44 +0000302 m := response{
303 Message: message,
commit-bot@chromium.org90041922014-04-22 21:13:45 +0000304 Hash: hash,
commit-bot@chromium.org6d036c22014-04-09 18:59:44 +0000305 }
306 log.Printf("Error: %s\n%s", message, err.Error())
307 resp, err := json.Marshal(m)
308 if err != nil {
309 http.Error(w, "Failed to serialize a response", 500)
310 return
311 }
312 w.Write(resp)
313}
314
commit-bot@chromium.orgd04e1dd2014-04-19 13:55:50 +0000315func writeToDatabase(hash string, code string, workspaceName string) {
commit-bot@chromium.org282333f2014-04-14 14:54:07 +0000316 if db == nil {
317 return
318 }
319 if _, err := db.Exec("INSERT INTO webtry (code, hash) VALUES(?, ?)", code, hash); err != nil {
320 log.Printf("ERROR: Failed to insert code into database: %q\n", err)
321 }
commit-bot@chromium.orgd04e1dd2014-04-19 13:55:50 +0000322 if workspaceName != "" {
323 if _, err := db.Exec("INSERT INTO workspacetry (name, hash) VALUES(?, ?)", workspaceName, hash); err != nil {
324 log.Printf("ERROR: Failed to insert into workspacetry table: %q\n", err)
325 }
326 }
commit-bot@chromium.org282333f2014-04-14 14:54:07 +0000327}
328
commit-bot@chromium.org06aca012014-04-14 20:12:08 +0000329func cssHandler(w http.ResponseWriter, r *http.Request) {
330 http.ServeFile(w, r, "css/webtry.css")
331}
332
commit-bot@chromium.orgd04e1dd2014-04-19 13:55:50 +0000333func jsHandler(w http.ResponseWriter, r *http.Request) {
334 http.ServeFile(w, r, "js/run.js")
335}
336
commit-bot@chromium.org06aca012014-04-14 20:12:08 +0000337// imageHandler serves up the PNG of a specific try.
338func imageHandler(w http.ResponseWriter, r *http.Request) {
339 log.Printf("Image Handler: %q\n", r.URL.Path)
340 if r.Method != "GET" {
341 http.NotFound(w, r)
342 return
343 }
344 match := imageLink.FindStringSubmatch(r.URL.Path)
345 if len(match) != 2 {
346 http.NotFound(w, r)
347 return
348 }
349 filename := match[1]
350 http.ServeFile(w, r, fmt.Sprintf("../../../inout/%s", filename))
351}
352
353type Try struct {
commit-bot@chromium.orgc3b738a2014-04-21 17:36:44 +0000354 Hash string `json:"hash"`
355 CreateTS string `json:"create_ts"`
commit-bot@chromium.org06aca012014-04-14 20:12:08 +0000356}
357
358type Recent struct {
359 Tries []Try
360}
361
362// recentHandler shows the last 20 tries.
363func recentHandler(w http.ResponseWriter, r *http.Request) {
364 log.Printf("Recent Handler: %q\n", r.URL.Path)
365
366 var err error
367 rows, err := db.Query("SELECT create_ts, hash FROM webtry ORDER BY create_ts DESC LIMIT 20")
368 if err != nil {
369 http.NotFound(w, r)
370 return
371 }
372 recent := []Try{}
373 for rows.Next() {
374 var hash string
375 var create_ts time.Time
376 if err := rows.Scan(&create_ts, &hash); err != nil {
377 log.Printf("Error: failed to fetch from database: %q", err)
378 continue
379 }
380 recent = append(recent, Try{Hash: hash, CreateTS: create_ts.Format("2006-02-01")})
381 }
382 if err := recentTemplate.Execute(w, Recent{Tries: recent}); err != nil {
383 log.Printf("ERROR: Failed to expand template: %q\n", err)
384 }
385}
386
commit-bot@chromium.orgd04e1dd2014-04-19 13:55:50 +0000387type Workspace struct {
388 Name string
389 Code string
commit-bot@chromium.org35ffc442014-04-22 19:32:06 +0000390 Hash string
commit-bot@chromium.orgd04e1dd2014-04-19 13:55:50 +0000391 Tries []Try
392}
393
394// newWorkspace generates a new random workspace name and stores it in the database.
395func newWorkspace() (string, error) {
396 for i := 0; i < 10; i++ {
397 adj := workspaceNameAdj[rand.Intn(len(workspaceNameAdj))]
398 noun := workspaceNameNoun[rand.Intn(len(workspaceNameNoun))]
399 suffix := rand.Intn(1000)
400 name := fmt.Sprintf("%s-%s-%d", adj, noun, suffix)
401 if _, err := db.Exec("INSERT INTO workspace (name) VALUES(?)", name); err == nil {
402 return name, nil
403 } else {
404 log.Printf("ERROR: Failed to insert workspace into database: %q\n", err)
405 }
406 }
407 return "", fmt.Errorf("Failed to create a new workspace")
408}
409
410// getCode returns the code for a given hash, or the empty string if not found.
commit-bot@chromium.org35ffc442014-04-22 19:32:06 +0000411func getCode(hash string) (string, error) {
commit-bot@chromium.orgd04e1dd2014-04-19 13:55:50 +0000412 code := ""
413 if err := db.QueryRow("SELECT code FROM webtry WHERE hash=?", hash).Scan(&code); err != nil {
414 log.Printf("ERROR: Code for hash is missing: %q\n", err)
commit-bot@chromium.org35ffc442014-04-22 19:32:06 +0000415 return code, err
commit-bot@chromium.orgd04e1dd2014-04-19 13:55:50 +0000416 }
commit-bot@chromium.org35ffc442014-04-22 19:32:06 +0000417 return code, nil
commit-bot@chromium.orgd04e1dd2014-04-19 13:55:50 +0000418}
419
420func workspaceHandler(w http.ResponseWriter, r *http.Request) {
421 log.Printf("Workspace Handler: %q\n", r.URL.Path)
422 if r.Method == "GET" {
423 tries := []Try{}
424 match := workspaceLink.FindStringSubmatch(r.URL.Path)
425 name := ""
426 if len(match) == 2 {
427 name = match[1]
commit-bot@chromium.orgc3b738a2014-04-21 17:36:44 +0000428 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 +0000429 if err != nil {
430 reportError(w, r, err, "Failed to select.")
431 return
432 }
433 for rows.Next() {
434 var hash string
435 var create_ts time.Time
436 if err := rows.Scan(&create_ts, &hash); err != nil {
437 log.Printf("Error: failed to fetch from database: %q", err)
438 continue
439 }
440 tries = append(tries, Try{Hash: hash, CreateTS: create_ts.Format("2006-02-01")})
441 }
442 }
443 var code string
commit-bot@chromium.org35ffc442014-04-22 19:32:06 +0000444 var hash string
commit-bot@chromium.orgd04e1dd2014-04-19 13:55:50 +0000445 if len(tries) == 0 {
446 code = DEFAULT_SAMPLE
447 } else {
commit-bot@chromium.org35ffc442014-04-22 19:32:06 +0000448 hash = tries[len(tries)-1].Hash
449 code, _ = getCode(hash)
commit-bot@chromium.orgd04e1dd2014-04-19 13:55:50 +0000450 }
commit-bot@chromium.org35ffc442014-04-22 19:32:06 +0000451 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 +0000452 log.Printf("ERROR: Failed to expand template: %q\n", err)
453 }
454 } else if r.Method == "POST" {
455 name, err := newWorkspace()
456 if err != nil {
457 http.Error(w, "Failed to create a new workspace.", 500)
458 return
459 }
460 http.Redirect(w, r, "/w/"+name, 302)
461 }
462}
463
commit-bot@chromium.org4bd8fdc2014-04-15 00:43:51 +0000464// hasPreProcessor returns true if any line in the code begins with a # char.
465func hasPreProcessor(code string) bool {
466 lines := strings.Split(code, "\n")
467 for _, s := range lines {
468 if strings.HasPrefix(strings.TrimSpace(s), "#") {
469 return true
470 }
471 }
472 return false
473}
474
commit-bot@chromium.orgd04e1dd2014-04-19 13:55:50 +0000475type TryRequest struct {
476 Code string `json:"code"`
commit-bot@chromium.org35ffc442014-04-22 19:32:06 +0000477 Name string `json:"name"` // Optional name of the workspace the code is in.
commit-bot@chromium.orgd04e1dd2014-04-19 13:55:50 +0000478}
479
commit-bot@chromium.org2dceeda2014-04-19 14:50:23 +0000480// iframeHandler handles the GET and POST of the main page.
481func iframeHandler(w http.ResponseWriter, r *http.Request) {
482 log.Printf("IFrame Handler: %q\n", r.URL.Path)
483 if r.Method != "GET" {
484 http.NotFound(w, r)
485 return
486 }
487 match := iframeLink.FindStringSubmatch(r.URL.Path)
488 if len(match) != 2 {
489 http.NotFound(w, r)
490 return
491 }
492 hash := match[1]
493 if db == nil {
494 http.NotFound(w, r)
495 return
496 }
497 var code string
commit-bot@chromium.org35ffc442014-04-22 19:32:06 +0000498 code, err := getCode(hash)
499 if err != nil {
commit-bot@chromium.org2dceeda2014-04-19 14:50:23 +0000500 http.NotFound(w, r)
501 return
502 }
503 // Expand the template.
commit-bot@chromium.org90041922014-04-22 21:13:45 +0000504 if err := iframeTemplate.Execute(w, userCode{Code: code, Hash: hash}); err != nil {
commit-bot@chromium.org2dceeda2014-04-19 14:50:23 +0000505 log.Printf("ERROR: Failed to expand template: %q\n", err)
506 }
507}
508
commit-bot@chromium.org35ffc442014-04-22 19:32:06 +0000509type TryInfo struct {
510 Hash string `json:"hash"`
511 Code string `json:"code"`
512}
513
514// tryInfoHandler returns information about a specific try.
515func tryInfoHandler(w http.ResponseWriter, r *http.Request) {
516 log.Printf("Try Info Handler: %q\n", r.URL.Path)
517 if r.Method != "GET" {
518 http.NotFound(w, r)
519 return
520 }
521 match := tryInfoLink.FindStringSubmatch(r.URL.Path)
522 if len(match) != 2 {
523 http.NotFound(w, r)
524 return
525 }
526 hash := match[1]
527 code, err := getCode(hash)
528 if err != nil {
529 http.NotFound(w, r)
530 return
531 }
532 m := TryInfo{
533 Hash: hash,
534 Code: code,
535 }
536 resp, err := json.Marshal(m)
537 if err != nil {
538 reportError(w, r, err, "Failed to serialize a response.")
539 return
540 }
541 w.Header().Set("Content-Type", "application/json")
542 w.Write(resp)
543}
544
commit-bot@chromium.org90041922014-04-22 21:13:45 +0000545func cleanCompileOutput(s, hash string) string {
546 old := "../../../cache/" + hash + ".cpp:"
547 log.Printf("INFO: replacing %q\n", old)
548 return strings.Replace(s, old, "usercode.cpp:", -1)
549}
550
commit-bot@chromium.org6d036c22014-04-09 18:59:44 +0000551// mainHandler handles the GET and POST of the main page.
552func mainHandler(w http.ResponseWriter, r *http.Request) {
commit-bot@chromium.org06aca012014-04-14 20:12:08 +0000553 log.Printf("Main Handler: %q\n", r.URL.Path)
commit-bot@chromium.org6d036c22014-04-09 18:59:44 +0000554 if r.Method == "GET" {
commit-bot@chromium.orgc81d1c42014-04-14 18:53:10 +0000555 code := DEFAULT_SAMPLE
commit-bot@chromium.orgc81d1c42014-04-14 18:53:10 +0000556 match := directLink.FindStringSubmatch(r.URL.Path)
commit-bot@chromium.org35ffc442014-04-22 19:32:06 +0000557 var hash string
commit-bot@chromium.org06aca012014-04-14 20:12:08 +0000558 if len(match) == 2 && r.URL.Path != "/" {
commit-bot@chromium.org35ffc442014-04-22 19:32:06 +0000559 hash = match[1]
commit-bot@chromium.orgc81d1c42014-04-14 18:53:10 +0000560 if db == nil {
561 http.NotFound(w, r)
562 return
563 }
564 // Update 'code' with the code found in the database.
565 if err := db.QueryRow("SELECT code FROM webtry WHERE hash=?", hash).Scan(&code); err != nil {
566 http.NotFound(w, r)
567 return
568 }
569 }
570 // Expand the template.
commit-bot@chromium.org90041922014-04-22 21:13:45 +0000571 if err := indexTemplate.Execute(w, userCode{Code: code, Hash: hash}); err != nil {
commit-bot@chromium.orgc81d1c42014-04-14 18:53:10 +0000572 log.Printf("ERROR: Failed to expand template: %q\n", err)
573 }
commit-bot@chromium.org6d036c22014-04-09 18:59:44 +0000574 } else if r.Method == "POST" {
575 w.Header().Set("Content-Type", "application/json")
commit-bot@chromium.org4bd8fdc2014-04-15 00:43:51 +0000576 buf := bytes.NewBuffer(make([]byte, 0, MAX_TRY_SIZE))
577 n, err := buf.ReadFrom(r.Body)
commit-bot@chromium.org6d036c22014-04-09 18:59:44 +0000578 if err != nil {
commit-bot@chromium.org90041922014-04-22 21:13:45 +0000579 reportTryError(w, r, err, "Failed to read a request body.", "")
commit-bot@chromium.org6d036c22014-04-09 18:59:44 +0000580 return
581 }
commit-bot@chromium.org4bd8fdc2014-04-15 00:43:51 +0000582 if n == MAX_TRY_SIZE {
583 err := fmt.Errorf("Code length equal to, or exceeded, %d", MAX_TRY_SIZE)
commit-bot@chromium.org90041922014-04-22 21:13:45 +0000584 reportTryError(w, r, err, "Code too large.", "")
commit-bot@chromium.org4bd8fdc2014-04-15 00:43:51 +0000585 return
586 }
commit-bot@chromium.orgd04e1dd2014-04-19 13:55:50 +0000587 request := TryRequest{}
588 if err := json.Unmarshal(buf.Bytes(), &request); err != nil {
commit-bot@chromium.org90041922014-04-22 21:13:45 +0000589 reportTryError(w, r, err, "Coulnd't decode JSON.", "")
commit-bot@chromium.orgd04e1dd2014-04-19 13:55:50 +0000590 return
591 }
592 if hasPreProcessor(request.Code) {
commit-bot@chromium.org4bd8fdc2014-04-15 00:43:51 +0000593 err := fmt.Errorf("Found preprocessor macro in code.")
commit-bot@chromium.org90041922014-04-22 21:13:45 +0000594 reportTryError(w, r, err, "Preprocessor macros aren't allowed.", "")
commit-bot@chromium.org4bd8fdc2014-04-15 00:43:51 +0000595 return
596 }
commit-bot@chromium.orgd04e1dd2014-04-19 13:55:50 +0000597 hash, err := expandCode(LineNumbers(request.Code))
commit-bot@chromium.org6d036c22014-04-09 18:59:44 +0000598 if err != nil {
commit-bot@chromium.org90041922014-04-22 21:13:45 +0000599 reportTryError(w, r, err, "Failed to write the code to compile.", hash)
commit-bot@chromium.org6d036c22014-04-09 18:59:44 +0000600 return
601 }
commit-bot@chromium.orgd04e1dd2014-04-19 13:55:50 +0000602 writeToDatabase(hash, request.Code, request.Name)
commit-bot@chromium.org6d036c22014-04-09 18:59:44 +0000603 message, err := doCmd(fmt.Sprintf(RESULT_COMPILE, hash, hash), true)
604 if err != nil {
commit-bot@chromium.org90041922014-04-22 21:13:45 +0000605 message = cleanCompileOutput(message, hash)
606 reportTryError(w, r, err, message, hash)
commit-bot@chromium.org6d036c22014-04-09 18:59:44 +0000607 return
608 }
609 linkMessage, err := doCmd(fmt.Sprintf(LINK, hash, hash), true)
610 if err != nil {
commit-bot@chromium.org90041922014-04-22 21:13:45 +0000611 linkMessage = cleanCompileOutput(linkMessage, hash)
612 reportTryError(w, r, err, linkMessage, hash)
commit-bot@chromium.org6d036c22014-04-09 18:59:44 +0000613 return
614 }
615 message += linkMessage
616 cmd := hash + " --out " + hash + ".png"
617 if *useChroot {
618 cmd = "schroot -c webtry --directory=/inout -- /inout/" + cmd
619 } else {
620 abs, err := filepath.Abs("../../../inout")
621 if err != nil {
commit-bot@chromium.org90041922014-04-22 21:13:45 +0000622 reportTryError(w, r, err, "Failed to find executable directory.", hash)
commit-bot@chromium.org6d036c22014-04-09 18:59:44 +0000623 return
624 }
625 cmd = abs + "/" + cmd
626 }
627
628 execMessage, err := doCmd(cmd, false)
629 if err != nil {
commit-bot@chromium.org90041922014-04-22 21:13:45 +0000630 reportTryError(w, r, err, "Failed to run the code:\n"+execMessage, hash)
commit-bot@chromium.org6d036c22014-04-09 18:59:44 +0000631 return
632 }
633 png, err := ioutil.ReadFile("../../../inout/" + hash + ".png")
634 if err != nil {
commit-bot@chromium.org90041922014-04-22 21:13:45 +0000635 reportTryError(w, r, err, "Failed to open the generated PNG.", hash)
commit-bot@chromium.org6d036c22014-04-09 18:59:44 +0000636 return
637 }
638
639 m := response{
640 Message: message,
commit-bot@chromium.org90041922014-04-22 21:13:45 +0000641 StdOut: execMessage,
commit-bot@chromium.org6d036c22014-04-09 18:59:44 +0000642 Img: base64.StdEncoding.EncodeToString([]byte(png)),
commit-bot@chromium.orgc81d1c42014-04-14 18:53:10 +0000643 Hash: hash,
commit-bot@chromium.org6d036c22014-04-09 18:59:44 +0000644 }
645 resp, err := json.Marshal(m)
646 if err != nil {
commit-bot@chromium.org90041922014-04-22 21:13:45 +0000647 reportTryError(w, r, err, "Failed to serialize a response.", hash)
commit-bot@chromium.org6d036c22014-04-09 18:59:44 +0000648 return
649 }
650 w.Write(resp)
651 }
652}
653
654func main() {
655 flag.Parse()
commit-bot@chromium.org06aca012014-04-14 20:12:08 +0000656 http.HandleFunc("/i/", imageHandler)
commit-bot@chromium.orgd04e1dd2014-04-19 13:55:50 +0000657 http.HandleFunc("/w/", workspaceHandler)
commit-bot@chromium.org06aca012014-04-14 20:12:08 +0000658 http.HandleFunc("/recent/", recentHandler)
commit-bot@chromium.org2dceeda2014-04-19 14:50:23 +0000659 http.HandleFunc("/iframe/", iframeHandler)
commit-bot@chromium.org35ffc442014-04-22 19:32:06 +0000660 http.HandleFunc("/json/", tryInfoHandler)
commit-bot@chromium.org06aca012014-04-14 20:12:08 +0000661 http.HandleFunc("/css/", cssHandler)
commit-bot@chromium.orgd04e1dd2014-04-19 13:55:50 +0000662 http.HandleFunc("/js/", jsHandler)
commit-bot@chromium.org35ffc442014-04-22 19:32:06 +0000663 // TODO Break out /c/ as it's own handler.
commit-bot@chromium.org6d036c22014-04-09 18:59:44 +0000664 http.HandleFunc("/", mainHandler)
commit-bot@chromium.org282333f2014-04-14 14:54:07 +0000665 log.Fatal(http.ListenAndServe(*port, nil))
commit-bot@chromium.org6d036c22014-04-09 18:59:44 +0000666}