-
-
Notifications
You must be signed in to change notification settings - Fork 149
/
main.go
executable file
·559 lines (497 loc) · 19.5 KB
/
main.go
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
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
// Copyright 2022 Arduino SA
//
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU Affero General Public License as published
// by the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU Affero General Public License for more details.
//
// You should have received a copy of the GNU Affero General Public License
// along with this program. If not, see <https://www.gnu.org/licenses/>.
// Version 1.82
// Supports Windows, Linux, Mac, and Raspberry Pi, Beagle Bone Black
package main
import (
_ "embed"
"encoding/json"
"flag"
"html/template"
"io"
"os"
"regexp"
"runtime"
"runtime/debug"
"strconv"
"strings"
"time"
cert "github.com/arduino/arduino-create-agent/certificates"
"github.com/arduino/arduino-create-agent/config"
"github.com/arduino/arduino-create-agent/globals"
"github.com/arduino/arduino-create-agent/index"
"github.com/arduino/arduino-create-agent/systray"
"github.com/arduino/arduino-create-agent/tools"
"github.com/arduino/arduino-create-agent/updater"
"github.com/arduino/arduino-create-agent/utilities"
v2 "github.com/arduino/arduino-create-agent/v2"
paths "github.com/arduino/go-paths-helper"
cors "github.com/gin-contrib/cors"
"github.com/gin-gonic/gin"
"github.com/go-ini/ini"
log "github.com/sirupsen/logrus"
//"github.com/sanbornm/go-selfupdate/selfupdate" #included in update.go to change heavily
)
var (
version = "x.x.x-dev" //don't modify it, Jenkins will take care
commit = "xxxxxxxx" //don't modify it, Jenkins will take care
port string
portSSL string
)
// regular flags
var (
hibernate = flag.Bool("hibernate", false, "start hibernated")
genCert = flag.Bool("generateCert", false, "")
additionalConfig = flag.String("additional-config", "config.ini", "config file path")
isLaunchSelf = flag.Bool("ls", false, "launch self 5 seconds later")
// Ignored flags for compatibility
_ = flag.String("gc", "std", "Deprecated. Use the config.ini file")
_ = flag.String("regex", "usb|acm|com", "Deprecated. Use the config.ini file")
)
// iniflags
var (
address = iniConf.String("address", "127.0.0.1", "The address where to listen. Defaults to localhost")
appName = iniConf.String("appName", "", "")
gcType = iniConf.String("gc", "std", "Type of garbage collection. std = Normal garbage collection allowing system to decide (this has been known to cause a stop the world in the middle of a CNC job which can cause lost responses from the CNC controller and thus stalled jobs. use max instead to solve.), off = let memory grow unbounded (you have to send in the gc command manually to garbage collect or you will run out of RAM eventually), max = Force garbage collection on each recv or send on a serial port (this minimizes stop the world events and thus lost serial responses, but increases CPU usage)")
hostname = iniConf.String("hostname", "unknown-hostname", "Override the hostname we get from the OS")
httpProxy = iniConf.String("httpProxy", "", "Proxy server for HTTP requests")
httpsProxy = iniConf.String("httpsProxy", "", "Proxy server for HTTPS requests")
indexURL = iniConf.String("indexURL", "https://downloads.arduino.cc/packages/package_index.json", "The address from where to download the index json containing the location of upload tools")
iniConf = flag.NewFlagSet("ini", flag.ContinueOnError)
logDump = iniConf.String("log", "off", "off = (default)")
origins = iniConf.String("origins", "", "Allowed origin list for CORS")
portsFilterRegexp = iniConf.String("regex", "usb|acm|com", "Regular expression to filter serial port list")
signatureKey = iniConf.String("signatureKey", globals.SignatureKey, "Pem-encoded public key to verify signed commandlines")
updateURL = iniConf.String("updateUrl", "", "")
verbose = iniConf.Bool("v", true, "show debug logging")
crashreport = iniConf.Bool("crashreport", false, "enable crashreport logging")
autostartMacOS = iniConf.Bool("autostartMacOS", true, "the Arduino Create Agent is able to start automatically after login on macOS (launchd agent)")
installCerts = iniConf.Bool("installCerts", false, "install the HTTPS certificate for Safari and keep it updated")
)
// the ports filter provided by the user via the -regex flag, if any
var portsFilter *regexp.Regexp
var homeTemplate = template.Must(template.New("home").Parse(homeTemplateHTML))
// If you navigate to this server's homepage, you'll get this HTML
// so you can directly interact with the serial port server
//
//go:embed home.html
var homeTemplateHTML string
// global clients
var (
Tools *tools.Tools
Systray systray.Systray
Index *index.Resource
)
type logWriter struct{}
func (u *logWriter) Write(p []byte) (n int, err error) {
h.broadcastSys <- p
return len(p), nil
}
var loggerWs logWriter
func homeHandler(c *gin.Context) {
homeTemplate.Execute(c.Writer, c.Request.Host)
}
func launchSelfLater() {
log.Println("Going to launch myself 2 seconds later.")
time.Sleep(2 * 1000 * time.Millisecond)
log.Println("Done waiting 2 secs. Now launching...")
}
func main() {
// prevents bad errors in OSX, such as '[NS...] is only safe to invoke on the main thread'.
runtime.LockOSThread()
// Parse regular flags
flag.Parse()
// Generate certificates
if *genCert {
cert.GenerateCertificates(config.GetCertificatesDir())
os.Exit(0)
}
// Check if certificates made with Agent <=1.2.7 needs to be moved over the new location
cert.MigrateCertificatesGeneratedWithOldAgentVersions(config.GetCertificatesDir())
// Launch main loop in a goroutine
go loop()
// SetupSystray is the main thread
configDir := config.GetDefaultConfigDir()
Systray = systray.Systray{
Hibernate: *hibernate,
Version: version + "-" + commit,
DebugURL: func() string {
return "http://" + *address + port
},
AdditionalConfig: *additionalConfig,
ConfigDir: configDir,
}
if src, err := os.Executable(); err != nil {
panic(err)
} else if restartPath := updater.Start(src); restartPath != "" {
Systray.RestartWith(restartPath)
} else {
Systray.Start()
}
}
func loop() {
if *hibernate {
return
}
log.SetLevel(log.InfoLevel)
log.SetOutput(os.Stdout)
// We used to install the agent in $HOME/Applications before versions <= 1.2.7-ventura
// With version > 1.3.0 we changed the install path of the agent in /Applications.
// If we are updating manually from 1.2.7 to 1.3.0 we have to uninstall the old agent manually first.
// This check will inform the user if he needs to run the uninstall first
if runtime.GOOS == "darwin" && oldInstallExists() {
utilities.UserPrompt("Old agent installation of the Arduino Create Agent found, please uninstall it before launching the new one", "\"OK\"", "OK", "OK", "Error")
os.Exit(0)
}
logger := func(msg string) {
mapD := map[string]string{"DownloadStatus": "Pending", "Msg": msg}
mapB, _ := json.Marshal(mapD)
h.broadcastSys <- mapB
}
// Let's handle the config
configDir := config.GetDefaultConfigDir()
var configPath *paths.Path
// see if the env var is defined, if it is take the config from there, this will override the default path
if envConfig := os.Getenv("ARDUINO_CREATE_AGENT_CONFIG"); envConfig != "" {
configPath = paths.New(envConfig)
if configPath.NotExist() {
log.Panicf("config from env var %s does not exists", envConfig)
}
log.Infof("using config from env variable: %s", configPath)
} else if defaultConfigPath := configDir.Join("config.ini"); defaultConfigPath.Exist() {
// by default take the config from the ~/.arduino-create/config.ini file
configPath = defaultConfigPath
log.Infof("using config from default: %s", configPath)
} else {
// Fall back to the old config.ini location
src, _ := os.Executable()
oldConfigPath := paths.New(src).Parent().Join("config.ini")
if oldConfigPath.Exist() {
err := oldConfigPath.CopyTo(defaultConfigPath)
if err != nil {
log.Errorf("cannot copy old %s, to %s, generating new config", oldConfigPath, configPath)
} else {
configPath = defaultConfigPath
log.Infof("copied old %s, to %s", oldConfigPath, configPath)
}
}
}
if configPath == nil {
configPath = config.GenerateConfig(configDir)
}
// if the default browser is Safari, prompt the user to install HTTPS certificates
// and eventually install them
if runtime.GOOS == "darwin" {
if exist, err := installCertsKeyExists(configPath.String()); err != nil {
log.Panicf("config.ini cannot be parsed: %s", err)
} else if !exist {
if cert.CertInKeychain() || config.CertsExist() {
err = config.SetInstallCertsIni(configPath.String(), "true")
if err != nil {
log.Panicf("config.ini cannot be parsed: %s", err)
}
} else if cert.GetDefaultBrowserName() == "Safari" {
if promptInstallCertsSafari() {
err = config.SetInstallCertsIni(configPath.String(), "true")
if err != nil {
log.Panicf("config.ini cannot be parsed: %s", err)
}
cert.GenerateAndInstallCertificates(config.GetCertificatesDir())
} else {
err = config.SetInstallCertsIni(configPath.String(), "false")
if err != nil {
log.Panicf("config.ini cannot be parsed: %s", err)
}
}
}
}
}
// Parse the config.ini
args, err := parseIni(configPath.String())
if err != nil {
log.Panicf("config.ini cannot be parsed: %s", err)
}
err = iniConf.Parse(args)
if err != nil {
log.Panicf("cannot parse arguments: %s", err)
}
Systray.SetCurrentConfigFile(configPath)
// Parse additional ini config if defined
if len(*additionalConfig) > 0 {
additionalConfigPath := paths.New(*additionalConfig)
if additionalConfigPath.NotExist() {
log.Infof("additional config file not found in %s", additionalConfigPath.String())
} else {
args, err = parseIni(additionalConfigPath.String())
if err != nil {
log.Panicf("additional config cannot be parsed: %s", err)
}
err = iniConf.Parse(args)
if err != nil {
log.Panicf("cannot parse arguments: %s", err)
}
log.Infof("using additional config from %s", additionalConfigPath.String())
}
}
// Instantiate Index and Tools
Index = index.Init(*indexURL, config.GetDataDir())
Tools = tools.New(config.GetDataDir(), Index, logger)
// see if we are supposed to wait 5 seconds
if *isLaunchSelf {
launchSelfLater()
}
log.Println("Version:" + version)
// hostname
hn, _ := os.Hostname()
if *hostname == "unknown-hostname" {
*hostname = hn
}
log.Println("Hostname:", *hostname)
// turn off garbage collection
// this is dangerous, as u could overflow memory
//if *isGC {
if *gcType == "std" {
log.Println("Garbage collection is on using Standard mode, meaning we just let Golang determine when to garbage collect.")
} else if *gcType == "max" {
log.Println("Garbage collection is on for MAXIMUM real-time collecting on each send/recv from serial port. Higher CPU, but less stopping of the world to garbage collect since it is being done on a constant basis.")
} else {
log.Println("Garbage collection is off. Memory use will grow unbounded. You WILL RUN OUT OF RAM unless you send in the gc command to manually force garbage collection. Lower CPU, but progressive memory footprint.")
debug.SetGCPercent(-1)
}
// If the httpProxy setting is set, use its value to override the
// HTTP_PROXY environment variable. Setting this environment
// variable ensures that all HTTP requests using net/http use this
// proxy server.
if *httpProxy != "" {
log.Printf("Setting HTTP_PROXY variable to %v", *httpProxy)
err := os.Setenv("HTTP_PROXY", *httpProxy)
if err != nil {
// The os.Setenv documentation doesn't specify how it can
// fail, so I don't know how to handle this error
// appropriately.
panic(err)
}
}
if *httpsProxy != "" {
log.Printf("Setting HTTPS_PROXY variable to %v", *httpProxy)
err := os.Setenv("HTTPS_PROXY", *httpProxy)
if err != nil {
// The os.Setenv documentation doesn't specify how it can
// fail, so I don't know how to handle this error
// appropriately.
panic(err)
}
}
// see if they provided a regex filter
if len(*portsFilterRegexp) > 0 {
log.Printf("You specified a serial port regular expression filter: %v\n", *portsFilterRegexp)
if filter, err := regexp.Compile("(?i)" + *portsFilterRegexp); err != nil {
log.Panicf("Error compiling the regex filter: %v\n", err)
} else {
portsFilter = filter
}
}
if !*verbose {
log.Println("You can enter verbose mode to see all logging by setting the v key in the configuration file to true.")
log.SetOutput(io.Discard)
}
// save crashreport to file
if *crashreport {
logFilename := "crashreport_" + time.Now().Format("20060102150405") + ".log"
// handle logs directory creation
logsDir := config.GetLogsDir()
logFile, err := os.OpenFile(logsDir.Join(logFilename).String(), os.O_WRONLY|os.O_CREATE|os.O_SYNC|os.O_APPEND, 0644)
if err != nil {
log.Print("Cannot create file used for crash-report")
} else {
redirectStderr(logFile)
}
}
// macos agent launchd autostart
if runtime.GOOS == "darwin" {
if *autostartMacOS {
config.InstallPlistFile()
} else {
config.UninstallPlistFile()
}
}
// check if the HTTPS certificates are expired or expiring and prompt the user to update them on macOS
if runtime.GOOS == "darwin" && *installCerts {
if cert.CertInKeychain() || config.CertsExist() {
certDir := config.GetCertificatesDir()
if expired, err := cert.IsExpired(); err != nil {
log.Errorf("cannot check if certificates are expired something went wrong: %s", err)
} else if expired {
buttonPressed := utilities.UserPrompt("The Arduino Agent needs a local HTTPS certificate to work correctly with Safari.\nYour certificate is expired or close to expiration. Do you want to update it?", "{\"Do not update\", \"Update the certificate for Safari\"}", "Update the certificate for Safari", "Update the certificate for Safari", "Arduino Agent: Update certificate")
if buttonPressed {
err := cert.UninstallCertificates()
if err != nil {
log.Errorf("cannot uninstall certificates something went wrong: %s", err)
} else {
cert.DeleteCertificates(certDir)
cert.GenerateAndInstallCertificates(certDir)
}
} else {
err = config.SetInstallCertsIni(configPath.String(), "false")
if err != nil {
log.Panicf("config.ini cannot be parsed: %s", err)
}
}
}
} else if promptInstallCertsSafari() {
// installing the certificates from scratch at this point should only happen if
// something went wrong during previous installation attempts
cert.GenerateAndInstallCertificates(config.GetCertificatesDir())
} else {
err = config.SetInstallCertsIni(configPath.String(), "false")
if err != nil {
log.Panicf("config.ini cannot be parsed: %s", err)
}
}
}
// launch the discoveries for the running system
go serialPorts.Run()
// launch the hub routine which is the singleton for the websocket server
go h.run()
// launch our dummy data routine
//go d.run()
r := gin.New()
socketHandler := wsHandler().ServeHTTP
extraOrigins := []string{
"https://create.arduino.cc",
"https://cloud.arduino.cc",
"https://app.arduino.cc",
"https://board-registration.arduino.cc",
"https://*.app.arduino.cc",
}
for i := 8990; i < 9001; i++ {
port := strconv.Itoa(i)
extraOrigins = append(extraOrigins, "http://localhost:"+port)
extraOrigins = append(extraOrigins, "https://localhost:"+port)
extraOrigins = append(extraOrigins, "http://127.0.0.1:"+port)
extraOrigins = append(extraOrigins, "https://127.0.0.1:"+port)
}
allowOrigins := strings.Split(*origins, ",")
// We need to trim possible spaces from the origins, otherwise the CORS middleware
// validation might not work as expected
for i := range allowOrigins {
allowOrigins[i] = strings.TrimSpace(allowOrigins[i])
}
allowOrigins = append(allowOrigins, extraOrigins...)
r.Use(cors.New(cors.Config{
AllowWildcard: true,
AllowOrigins: allowOrigins,
AllowMethods: []string{"PUT", "GET", "POST", "DELETE"},
AllowHeaders: []string{"Origin", "Authorization", "Content-Type"},
ExposeHeaders: []string{},
AllowCredentials: true,
MaxAge: 50 * time.Second,
AllowPrivateNetwork: true,
}))
r.LoadHTMLFiles("templates/nofirefox.html")
r.GET("/", homeHandler)
r.POST("/upload", uploadHandler)
r.GET("/socket.io/", socketHandler)
r.POST("/socket.io/", socketHandler)
r.Handle("WS", "/socket.io/", socketHandler)
r.Handle("WSS", "/socket.io/", socketHandler)
r.GET("/info", infoHandler)
r.POST("/pause", pauseHandler)
r.POST("/update", updateHandler)
// Mount goa handlers
goa := v2.Server(config.GetDataDir().String(), Index)
r.Any("/v2/*path", gin.WrapH(goa))
go func() {
// check if certificates exist; if not, use plain http
certsDir := config.GetCertificatesDir()
if certsDir.Join("cert.pem").NotExist() {
log.Error("Could not find HTTPS certificate. Using plain HTTP only.")
return
}
start := 8990
end := 9000
i := start
for i < end {
i = i + 1
portSSL = ":" + strconv.Itoa(i)
if err := r.RunTLS(*address+portSSL, certsDir.Join("cert.pem").String(), certsDir.Join("key.pem").String()); err != nil {
log.Printf("Error trying to bind to port: %v, so exiting...", err)
continue
} else {
log.Print("Starting server and websocket (SSL) on " + *address + "" + port)
break
}
}
}()
go func() {
start := 8990
end := 9000
i := start
for i < end {
i = i + 1
port = ":" + strconv.Itoa(i)
if err := r.Run(*address + port); err != nil {
log.Printf("Error trying to bind to port: %v, so exiting...", err)
continue
} else {
log.Print("Starting server and websocket on " + *address + "" + port)
break
}
}
}()
}
// oldInstallExists will return true if an old installation of the agent exists (on macos) and is not the process running
func oldInstallExists() bool {
oldAgentPath := config.GetDefaultHomeDir().Join("Applications", "ArduinoCreateAgent")
currentBinary, _ := os.Executable()
// if the current running binary is the old one we don't need to do anything
binIsOld, _ := paths.New(currentBinary).IsInsideDir(oldAgentPath)
if binIsOld {
return false
}
return oldAgentPath.Join("ArduinoCreateAgent.app").Exist()
}
func parseIni(filename string) (args []string, err error) {
cfg, err := ini.LoadSources(ini.LoadOptions{IgnoreInlineComment: false, AllowPythonMultilineValues: true}, filename)
if err != nil {
return nil, err
}
for _, section := range cfg.Sections() {
for key, val := range section.KeysHash() {
// Ignore launchself
if key == "ls" {
continue
} // Ignore configUpdateInterval
if key == "configUpdateInterval" {
continue
} // Ignore name
if key == "name" {
continue
}
args = append(args, "-"+key+"="+val)
}
}
return args, nil
}
func installCertsKeyExists(filename string) (bool, error) {
cfg, err := ini.LoadSources(ini.LoadOptions{IgnoreInlineComment: false, AllowPythonMultilineValues: true}, filename)
if err != nil {
return false, err
}
return cfg.Section("").HasKey("installCerts"), nil
}
func promptInstallCertsSafari() bool {
return utilities.UserPrompt("The Arduino Agent needs a local HTTPS certificate to work correctly with Safari.\nIf you use Safari, you need to install it.", "{\"Do not install\", \"Install the certificate for Safari\"}", "Install the certificate for Safari", "Install the certificate for Safari", "Arduino Agent: Install certificate")
}