/
frontend_http.go
1577 lines (1430 loc) · 40.4 KB
/
frontend_http.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
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
//
// frontend_http.go
//
// srnd http frontend implementation
//
package srnd
import (
"bytes"
"encoding/json"
"errors"
"fmt"
"github.com/dchest/captcha"
"github.com/gorilla/csrf"
"github.com/gorilla/mux"
"github.com/gorilla/sessions"
"github.com/gorilla/websocket"
"io"
"log"
"mime"
"net/http"
"strings"
"time"
)
type bannedFunc func()
type errorFunc func(error)
type successFunc func(NNTPMessage)
// an attachment in a post
type postAttachment struct {
DeleteFile func()
NNTP NNTPAttachment
Filename string `json:"name"`
Filedata string `json:"data"`
Filetype string `json:"type"`
}
// an api post request
type postRequest struct {
Reference string `json:"reference"`
Name string `json:"name"`
Email string `json:"email"`
Subject string `json:"subject"`
Frontend string `json:"frontend"`
Attachments []postAttachment `json:"files"`
Group string `json:"newsgroup"`
IpAddress string `json:"ip"`
Destination string `json:"i2p"`
Dubs bool `json:"dubs"`
Message string `json:"message"`
ExtraHeaders map[string]string `json:"headers"`
}
// regenerate a newsgroup page
type groupRegenRequest struct {
// which newsgroup
group string
// page number
page int
}
// livechan captcha solution
type liveCaptcha struct {
ID string
Solution string
}
// inbound livechan command
type liveCommand struct {
Type string
Captcha *liveCaptcha
Post *postRequest
}
type liveChan struct {
// channel for recv-ing posts for sub'd newsgroup
postchnl chan PostModel
// channel for sending control messages
datachnl chan []byte
// unique session id
uuid string
// for recv-ing self
resultchnl chan *liveChan
// subbed newsgroup
newsgroup string
// have we solved captcha?
captcha bool
// our ip address
IP string
}
// inform this livechan that we got a new post
func (lc *liveChan) Inform(post PostModel) {
if lc.postchnl != nil {
if lc.newsgroup == "" || lc.newsgroup == post.Board() {
lc.postchnl <- post
}
}
}
func (lc *liveChan) SendError(err error) {
msg, _ := json.Marshal(map[string]string{
"Type": "error",
"Error": err.Error(),
})
if lc.datachnl != nil {
lc.datachnl <- msg
}
}
func (lc *liveChan) PostSuccess(nntp NNTPMessage) {
// inform ui that a post was made
msg, _ := json.Marshal(map[string]interface{}{
"Type": "posted",
"Msgid": nntp.MessageID(),
"OP": nntp.OP(),
})
if lc.datachnl != nil {
lc.datachnl <- msg
}
}
func (lc *liveChan) SendBanned() {
msg, _ := json.Marshal(map[string]string{
"Type": "ban",
// TODO: real ban message
"Reason": "your an fagt, your IP was: " + lc.IP,
})
if lc.datachnl != nil {
lc.datachnl <- msg
}
}
// handle message from a websocket session
func (lc *liveChan) handleMessage(front *httpFrontend, cmd *liveCommand) {
if cmd.Captcha != nil {
lc.captcha = captcha.VerifyString(cmd.Captcha.ID, cmd.Captcha.Solution)
// send captcha result
msg, _ := json.Marshal(map[string]interface{}{
"Type": "captcha",
"Success": lc.captcha,
})
if lc.datachnl != nil {
lc.datachnl <- msg
}
}
if lc.captcha && cmd.Post != nil {
cmd.Post.Frontend = front.name
cmd.Post.IpAddress = lc.IP
if lc.newsgroup != "" {
cmd.Post.Group = lc.newsgroup
}
cmd.Post.ExtraHeaders = map[string]string{"X-Livechan": "1"}
front.handle_postRequest(cmd.Post, lc.SendBanned, lc.SendError, lc.PostSuccess, false)
} else if cmd.Captcha == nil {
// resend captcha challenge
msg, _ := json.Marshal(map[string]string{
"Type": "captcha",
})
if lc.datachnl != nil {
lc.datachnl <- msg
}
}
}
type httpFrontend struct {
modui ModUI
httpmux *mux.Router
daemon *NNTPDaemon
cache CacheInterface
bindaddr string
name string
secret string
webroot_dir string
template_dir string
static_dir string
regen_threads int
regen_on_start bool
attachments bool
prefix string
store *sessions.CookieStore
upgrader websocket.Upgrader
jsonUsername string
jsonPassword string
enableJson bool
enableBoardCreation bool
attachmentLimit int
liveui_chnl chan PostModel
liveui_register chan *liveChan
liveui_deregister chan *liveChan
end_liveui chan bool
// all liveui users
// maps uuid -> liveChan
liveui_chans map[string]*liveChan
liveui_usercount int
// this is a very important thing by the way
requireCaptcha bool
// are we in archive mode?
archive bool
}
// do we allow this newsgroup?
func (self httpFrontend) AllowNewsgroup(group string) bool {
return newsgroupValidFormat(group) || group == "ctl" && !strings.HasSuffix(group, ".")
}
func (self *httpFrontend) Regen(msg ArticleEntry) {
self.cache.Regen(msg)
}
func (self *httpFrontend) RegenerateBoard(board string) {
self.cache.RegenerateBoard(board)
}
func (self *httpFrontend) RegenFrontPage() {
pages, _ := self.daemon.database.GetUkkoPageCount(10)
self.cache.RegenFrontPage(int(pages))
}
func (self httpFrontend) regenAll() {
self.cache.RegenAll()
}
func (self httpFrontend) deleteThreadMarkup(root_post_id string) {
self.cache.DeleteThreadMarkup(root_post_id)
}
func (self httpFrontend) deleteBoardMarkup(group string) {
self.cache.DeleteBoardMarkup(group)
}
func (self *httpFrontend) ArchiveMode() {
self.archive = true
}
// load post model and inform live ui
func (self *httpFrontend) informLiveUI(msgid, ref, group string) {
// root post
if ref == "" {
ref = msgid
}
model := self.daemon.database.GetPostModel(self.prefix, msgid)
// inform liveui
if model != nil && self.liveui_chnl != nil {
self.liveui_chnl <- model
log.Println("liveui", msgid, ref, group)
} else {
log.Println("liveui failed to get model")
}
}
// poll live ui events
func (self *httpFrontend) poll_liveui() {
for {
select {
case live, ok := <-self.liveui_deregister:
// deregister existing user event
if ok {
if self.liveui_chans != nil {
delete(self.liveui_chans, live.uuid)
self.liveui_usercount--
}
close(live.postchnl)
live.postchnl = nil
close(live.datachnl)
live.datachnl = nil
}
case live, ok := <-self.liveui_register:
// register new user event
if ok {
if self.liveui_chans != nil {
live.uuid = randStr(10)
live.postchnl = make(chan PostModel, 8)
self.liveui_chans[live.uuid] = live
self.liveui_usercount++
}
if live.resultchnl != nil {
live.resultchnl <- live
// get scrollback
go func() {
var threads []ThreadModel
group := live.newsgroup
if group == "" {
// for ukko
ents := self.daemon.database.GetLastBumpedThreads("", 5)
if ents != nil {
for _, e := range ents {
g := e[1]
page := self.daemon.database.GetGroupForPage(self.prefix, self.name, g, 0, 10)
for _, t := range page.Threads() {
if t.OP().MessageID() == e[0] {
threads = append(threads, t)
break
}
}
}
}
} else {
// for board
board := self.daemon.database.GetGroupForPage(self.prefix, self.name, live.newsgroup, 0, 5)
if board != nil {
threads = board.Threads()
}
}
if threads != nil {
c := len(threads)
for idx := range threads {
th := threads[c-idx-1]
th.Update(self.daemon.database)
// send root post
live.Inform(th.OP())
// send replies
for _, post := range th.Replies() {
live.Inform(post)
}
}
}
}()
}
}
case model, ok := <-self.liveui_chnl:
// TODO: should we do board specific filtering?
if ok {
for _, livechan := range self.liveui_chans {
go livechan.Inform(model)
}
}
case <-self.end_liveui:
livechnl := self.liveui_chnl
self.liveui_chnl = nil
close(livechnl)
chnl := self.liveui_register
self.liveui_register = nil
close(chnl)
chnl = self.liveui_deregister
self.liveui_deregister = nil
close(chnl)
// remove all
for _, livechan := range self.liveui_chans {
if livechan.postchnl != nil {
close(livechan.postchnl)
livechan.postchnl = nil
}
}
self.liveui_chans = nil
return
}
}
}
func (self *httpFrontend) poll() {
// regenerate front page
self.RegenFrontPage()
// trigger regen
if self.regen_on_start {
self.cache.RegenAll()
}
modChnl := self.modui.MessageChan()
for {
select {
case nntp := <-modChnl:
storeMessage(self.daemon, nntp.MIMEHeader(), nntp.BodyReader())
}
}
}
func (self *httpFrontend) HandleNewPost(nntp frontendPost) {
msgid := nntp.MessageID()
group := nntp.Newsgroup()
ref := nntp.Reference()
go self.informLiveUI(msgid, ref, group)
if len(ref) > 0 {
msgid = ref
}
entry := ArticleEntry{msgid, group}
// regnerate thread
self.Regen(entry)
// regenerate all board pages if not archiving
if !self.archive {
self.RegenerateBoard(group)
}
// regen front page
self.RegenFrontPage()
}
// create a new captcha, return as json object
func (self *httpFrontend) new_captcha_json(wr http.ResponseWriter, r *http.Request) {
s, err := self.store.Get(r, self.name)
if err != nil {
http.Error(wr, err.Error(), 500)
return
}
captcha_id := captcha.New()
resp := make(map[string]string)
// the captcha id
resp["id"] = captcha_id
s.Values["captcha_id"] = captcha_id
s.Save(r, wr)
// url of the image
resp["url"] = fmt.Sprintf("%scaptcha/%s.png", self.prefix, captcha_id)
wr.Header().Set("Content-Type", "text/json; encoding=UTF-8")
enc := json.NewEncoder(wr)
enc.Encode(&resp)
}
// handle newboard page
func (self *httpFrontend) handle_newboard(wr http.ResponseWriter, r *http.Request) {
param := make(map[string]interface{})
param["prefix"] = self.prefix
io.WriteString(wr, template.renderTemplate("newboard", param, self.cache.GetHandler().GetI18N(r)))
}
// handle new post via http request for a board
func (self *httpFrontend) handle_postform(wr http.ResponseWriter, r *http.Request, board string, sendJson, checkCaptcha bool) {
// the post we will turn into an nntp article
pr := new(postRequest)
pr.ExtraHeaders = make(map[string]string)
if sendJson {
wr.Header().Add("Content-Type", "text/json; encoding=UTF-8")
}
// close request body when done
defer r.Body.Close()
mp_reader, err := r.MultipartReader()
if err != nil {
wr.WriteHeader(500)
if sendJson {
json.NewEncoder(wr).Encode(map[string]interface{}{"error": err.Error()})
} else {
io.WriteString(wr, err.Error())
}
return
}
pr.Group = board
// encrypt IP Addresses
// when a post is recv'd from a frontend, the remote address is given its own symetric key that the local srnd uses to encrypt the address with, for privacy
// when a mod event is fired, it includes the encrypted IP address and the symetric key that frontend used to encrypt it, thus allowing others to determine the IP address
// each node will optionally comply with the mod event, banning the address from being able to post from that frontend
// get the "real" ip address from the request
pr.IpAddress, err = extractRealIP(r)
pr.Destination = r.Header.Get("X-I2P-DestHash")
pr.Frontend = self.name
var captcha_retry bool
var captcha_solution, captcha_id string
url := self.generateBoardURL(board, 0)
var part_buff bytes.Buffer
for {
part, err := mp_reader.NextPart()
if err == nil {
defer part.Close()
// get the name of the part
partname := part.FormName()
// read part for attachment
if strings.HasPrefix(partname, "attachment_") && self.attachments {
if len(pr.Attachments) < self.attachmentLimit {
att := readAttachmentFromMimePartAndStore(part, self.daemon.store)
if att != nil && att.Filename() != "" {
log.Println("attaching file", att.Filename())
pa := postAttachment{
Filename: att.Filename(),
Filetype: att.Mime(),
NNTP: att,
DeleteFile: func() {
f := att.Filepath()
DelFile(self.daemon.store.AttachmentFilepath(f))
DelFile(self.daemon.store.ThumbnailFilepath(f))
},
}
pr.Attachments = append(pr.Attachments, pa)
}
}
continue
}
io.Copy(&part_buff, part)
// check for values we want
if partname == "subject" {
pr.Subject = part_buff.String()
} else if partname == "name" {
pr.Name = part_buff.String()
} else if partname == "message" {
pr.Message = strings.Trim(part_buff.String(), "\r")
} else if partname == "reference" {
pr.Reference = part_buff.String()
if len(pr.Reference) != 0 {
url = self.generateThreadURL(pr.Reference)
}
} else if partname == "captcha_id" {
captcha_id = part_buff.String()
} else if partname == "captcha" {
captcha_solution = part_buff.String()
} else if partname == "dubs" {
pr.Dubs = part_buff.String() == "on"
} else if partname == "uri" {
str := part_buff.String()
if len(str) > 0 {
pr.ExtraHeaders["X-References-Uri"] = safeHeader(str)
}
}
// we done
// reset buffer for reading parts
part_buff.Reset()
} else {
if err != io.EOF {
for _, att := range pr.Attachments {
if att.DeleteFile != nil {
att.DeleteFile()
}
}
// TODO: we need to delete uploaded files somehow since they are unregistered at this point
errmsg := fmt.Sprintf("httpfrontend post handler error reading multipart: %s", err)
log.Println(errmsg)
wr.WriteHeader(500)
if sendJson {
json.NewEncoder(wr).Encode(map[string]interface{}{"error": errmsg})
} else {
io.WriteString(wr, errmsg)
}
return
}
break
}
}
sess, err := self.store.Get(r, self.name)
if err != nil {
errmsg := fmt.Sprintf("session store error: %s", err.Error())
if sendJson {
json.NewEncoder(wr).Encode(map[string]interface{}{"error": errmsg})
} else {
io.WriteString(wr, errmsg)
}
return
}
if checkCaptcha && len(captcha_id) == 0 {
cid, ok := sess.Values["captcha_id"]
if ok {
captcha_id = cid.(string)
} else {
log.Println("no captcha id in session?")
}
sess.Values["captcha_id"] = ""
}
log.Println("captcha", captcha_id, "try '", captcha_solution, "'")
if checkCaptcha && !captcha.VerifyString(captcha_id, captcha_solution) {
// captcha is not valid
captcha_retry = true
} else {
// valid captcha
// increment post count
var posts int
val, ok := sess.Values["posts"]
if ok {
posts = val.(int)
} else {
posts = 0
}
posts++
sess.Values["posts"] = posts
}
sess.Save(r, wr)
// make error template param
resp_map := make(map[string]interface{})
resp_map["prefix"] = self.prefix
// set redirect url
if len(url) > 0 {
// if we explicitly know the url use that
resp_map["redirect_url"] = url
} else {
// if our referer is saying we are from /new/ page use that
// otherwise use prefix
if strings.HasSuffix(r.Referer(), self.prefix+"new/") {
resp_map["redirect_url"] = self.prefix + "new/"
} else {
resp_map["redirect_url"] = self.prefix
}
}
if captcha_retry {
for _, att := range pr.Attachments {
if att.DeleteFile != nil {
att.DeleteFile()
}
}
if sendJson {
json.NewEncoder(wr).Encode(map[string]interface{}{"error": "bad captcha"})
} else {
// retry the post with a new captcha
resp_map = make(map[string]interface{})
resp_map["prefix"] = self.prefix
resp_map["redirect_url"] = url
resp_map["reason"] = "captcha incorrect"
io.WriteString(wr, template.renderTemplate("post_fail", resp_map, self.cache.GetHandler().GetI18N(r)))
}
return
}
b := func() {
for _, att := range pr.Attachments {
if att.DeleteFile != nil {
att.DeleteFile()
}
}
if sendJson {
wr.WriteHeader(403)
json.NewEncoder(wr).Encode(map[string]interface{}{"error": "banned"})
} else {
wr.WriteHeader(403)
io.WriteString(wr, "banned")
}
}
e := func(err error) {
for _, att := range pr.Attachments {
if att.DeleteFile != nil {
att.DeleteFile()
}
}
log.Println("frontend error:", err)
wr.WriteHeader(200)
if sendJson {
json.NewEncoder(wr).Encode(map[string]interface{}{"error": err.Error()})
} else {
resp_map["reason"] = err.Error()
resp_map["prefix"] = self.prefix
resp_map["redirect_url"] = url
io.WriteString(wr, template.renderTemplate("post_fail", resp_map, self.cache.GetHandler().GetI18N(r)))
}
}
s := func(nntp NNTPMessage) {
// send success reply
wr.WriteHeader(201)
// determine the root post so we can redirect to the thread for it
msg_id := nntp.Headers().Get("References", nntp.MessageID())
// render response as success
url := self.generateThreadURL(msg_id)
if sendJson {
json.NewEncoder(wr).Encode(map[string]interface{}{"message_id": nntp.MessageID(), "url": url, "error": nil})
} else {
template.writeTemplate("post_success", map[string]interface{}{"prefix": self.prefix, "message_id": nntp.MessageID(), "redirect_url": url}, wr, self.cache.GetHandler().GetI18N(r))
}
}
self.handle_postRequest(pr, b, e, s, self.enableBoardCreation)
}
func (self *httpFrontend) generateThreadURL(msgid string) (url string) {
url = fmt.Sprintf("%st/%s/", self.prefix, HashMessageID(msgid))
return
}
func (self *httpFrontend) generateBoardURL(newsgroup string, pageno int) (url string) {
if pageno > 0 {
url = fmt.Sprintf("%sb/%s/%d/", self.prefix, newsgroup, pageno)
} else {
url = fmt.Sprintf("%sb/%s/", self.prefix, newsgroup)
}
return
}
// turn a post request into an nntp article write it to temp dir and tell daemon
func (self *httpFrontend) handle_postRequest(pr *postRequest, b bannedFunc, e errorFunc, s successFunc, createGroup bool) {
var err error
if len(pr.Attachments) > self.attachmentLimit {
err = errors.New("too many attachments")
e(err)
return
}
pr.Message = strings.Trim(pr.Message, "\r")
m := strings.Trim(pr.Message, "\n")
m = strings.Trim(m, " ")
if len(pr.Attachments) == 0 && len(m) == 0 {
err = errors.New("no post message")
e(err)
return
}
nntp := new(nntpArticle)
defer nntp.Reset()
var banned bool
nntp.headers = make(ArticleHeaders)
address := pr.IpAddress
// check for banned
if len(address) > 0 {
banned, err = self.daemon.database.CheckIPBanned(address)
if err == nil {
if banned {
b()
return
}
} else {
e(err)
return
}
}
if len(address) == 0 {
address = "Tor"
}
if !strings.HasPrefix(address, "127.") {
// set the ip address of the poster to be put into article headers
// if we cannot determine it, i.e. we are on Tor/i2p, this value is not set
if address == "Tor" {
nntp.headers.Set("X-Tor-Poster", "1")
} else {
address, err = self.daemon.database.GetEncAddress(address)
if err == nil {
nntp.headers.Set("X-Encrypted-IP", address)
} else {
e(err)
return
}
// TODO: add x-tor-poster header for tor exits
}
}
board := pr.Group
// post fail message
banned, err = self.daemon.database.NewsgroupBanned(board)
if banned {
e(errors.New("newsgroup banned "))
return
}
if err != nil {
e(err)
}
if !createGroup && !self.daemon.database.HasNewsgroup(board) {
e(errors.New("we don't have this newsgroup " + board))
return
}
// if we don't have an address for the poster try checking for i2p httpd headers
if len(pr.Destination) == i2pDestHashLen() {
nntp.headers.Set("X-I2P-DestHash", pr.Destination)
}
ref := pr.Reference
if ref != "" {
if ValidMessageID(ref) {
if self.daemon.database.HasArticleLocal(ref) {
nntp.headers.Set("References", ref)
} else {
e(errors.New("article referenced not locally available"))
return
}
} else {
e(errors.New("invalid reference"))
return
}
}
// set newsgroup
nntp.headers.Set("Newsgroups", pr.Group)
// check message size
if len(pr.Attachments) == 0 && len(pr.Message) == 0 {
e(errors.New("no message"))
return
}
// TODO: make configurable
if len(pr.Message) > 1024*1024 {
e(errors.New("your message is too big"))
return
}
if !self.daemon.CheckText(pr.Message) {
e(errors.New("spam"))
return
}
if len(pr.Frontend) == 0 {
// :-DDD
pr.Frontend = "mongo.db.is.web.scale"
} else if len(pr.Frontend) > 128 {
e(errors.New("frontend name is too long"))
return
}
subject := strings.TrimSpace(pr.Subject)
// set subject
if subject == "" {
subject = "None"
} else if len(subject) > 256 {
// subject too big
e(errors.New("Subject is too long"))
return
}
nntp.headers.Set("Subject", safeHeader(subject))
if isSage(subject) && ref != "" {
nntp.headers.Set("X-Sage", "1")
}
name := strings.TrimSpace(pr.Name)
var tripcode_privkey []byte
// tripcode
if idx := strings.IndexByte(name, '#'); idx >= 0 {
tripcode_privkey = parseTripcodeSecret(name[idx+1:])
name = strings.TrimSpace(name[:idx])
}
if name == "" {
name = "Anonymous"
}
if len(name) > 128 {
// name too long
e(errors.New("name too long"))
return
}
msgid := genMessageID(pr.Frontend)
// roll until dubs if desired
for pr.Dubs && !MessageIDWillDoDubs(msgid) {
msgid = genMessageID(pr.Frontend)
}
nntp.headers.Set("From", formatAddress(safeHeader(name), "poster@"+pr.Frontend))
nntp.headers.Set("Message-ID", msgid)
// set message
nntp.message = nntpSanitize(pr.Message)
cites, err := self.daemon.database.FindCitesInText(pr.Message)
if err != nil {
e(err)
return
}
if len(cites) > 0 {
if ref == "" && len(cites) == 1 {
/*
this is workaround for:
{RFC 5322}
If the parent message does not contain
a "References:" field but does have an "In-Reply-To:" field
containing a single message identifier, then the "References:" field
will contain the contents of the parent's "In-Reply-To:" field
followed by the contents of the parent's "Message-ID:" field (if
any).
*/
cites = append(cites, "<0>")
}
nntp.headers.Set("In-Reply-To", strings.Join(cites, " "))
}
// set date
nntp.headers.Set("Date", timeNowStr())
// append path from frontend
nntp.AppendPath(pr.Frontend)
// add extra headers if needed
if pr.ExtraHeaders != nil {
for name, val := range pr.ExtraHeaders {
// don't overwrite existing headers
if nntp.headers.Get(name, "") == "" {
nntp.headers.Set(name, val)
}
}
}
if self.attachments {
var delfiles []string
for _, att := range pr.Attachments {
// add attachment
if len(att.Filedata) > 0 {
a := createAttachment(att.Filetype, att.Filetype, strings.NewReader(att.Filedata))
nntp.Attach(a)
err = a.Save(self.daemon.store.AttachmentDir())
if err == nil {
delfiles = append(delfiles, a.Filepath())
// check if we need to thumbnail it
if !CheckFile(self.daemon.store.ThumbnailFilepath(a.Filepath())) {
_, err = self.daemon.store.GenerateThumbnail(a.Filepath())
}
if err == nil {
delfiles = append(delfiles, self.daemon.store.ThumbnailFilepath(a.Filepath()))
}
}
if err != nil {
break
}
} else {
nntp.Attach(att.NNTP)
}
}
if err != nil {
// nuke files
for _, fname := range delfiles {
DelFile(fname)
}
for _, att := range pr.Attachments {
if att.DeleteFile != nil {
att.DeleteFile()
}
}
e(err)
return
}
}
// pack it before sending so that the article is well formed
// sign if needed
if len(tripcode_privkey) == 32 {
pk, _ := naclSeedToKeyPair(tripcode_privkey)
nntp.headers.Set("X-PubKey-Ed25519", hexify(pk))
nntp.Pack()
if err != nil {
e(err)
return
}
nntp, err = signArticle(nntp, tripcode_privkey)
if err != nil {
// error signing
e(err)
return
}
} else {
nntp.Pack()
}
// have daemon sign message-id
self.daemon.WrapSign(nntp)
err = storeMessage(self.daemon, nntp.MIMEHeader(), nntp.BodyReader())
if err != nil {
// clean up
self.daemon.expire.ExpirePost(nntp.MessageID())
e(err)
} else {
s(nntp)
}
}
// handle posting / postform
func (self httpFrontend) handle_poster(wr http.ResponseWriter, r *http.Request) {
path := r.URL.Path
sendJSON := false
if strings.HasSuffix(path, "/json") || strings.HasSuffix(path, "/json/") {
sendJSON = true
}
var board string
// extract board
parts := strings.Count(path, "/")
if parts > 1 {
board = strings.Split(path, "/")[2]
}
// this is a POST request
if r.Method == "POST" && self.AllowNewsgroup(board) && newsgroupValidFormat(board) {
self.handle_postform(wr, r, board, sendJSON, self.requireCaptcha)
} else {
wr.WriteHeader(403)
io.WriteString(wr, "Nope")
}
}
func (self *httpFrontend) serve_captcha(wr http.ResponseWriter, r *http.Request) {
s, err := self.store.Get(r, self.name)
if err == nil {
captcha_id := captcha.New()
s.Values["captcha_id"] = captcha_id
log.Println("captcha_id", captcha_id)
s.Save(r, wr)
redirect_url := fmt.Sprintf("%scaptcha/%s.png", self.prefix, captcha_id)
// redirect to the image
http.Redirect(wr, r, redirect_url, 302)
} else {
// handle session error
// TODO: clear cookies?