aboutsummaryrefslogtreecommitdiff
path: root/cgi/servers.go
blob: 8538920054444e4025c0f6f2c77a86efcbea9a8b (plain)
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
package cgi

import (
	"context"
	"encoding/json"
	"fmt"
	"io"
	"io/ioutil"
	"net"
	"net/http"
	"net/http/cgi"
	"net/url"
	"os"
	"strings"
	"sync"
	"time"

	"git.capotej.com/capotej/communique/config"
	"git.capotej.com/capotej/communique/delivery"
	"git.capotej.com/capotej/communique/models"
	"git.capotej.com/capotej/communique/urls"
	"git.capotej.com/capotej/communique/views"
	"github.com/microcosm-cc/bluemonday"
	"github.com/mmcdole/gofeed"
	"go.uber.org/zap"
)

type Servers struct {
	log       *zap.SugaredLogger
	persister *models.Persister
	cfg       config.Config
	policy    *bluemonday.Policy
}

func NewServers(log *zap.SugaredLogger, persister *models.Persister, cfg config.Config, policy *bluemonday.Policy) *Servers {
	return &Servers{log: log, persister: persister, cfg: cfg, policy: policy}
}

// Start iterates over all Handlers and starts an internal CGI server for each one
// along with ticker for the configured handler interval then blocks indefinitely
func (s *Servers) Start() {
	var wg sync.WaitGroup
	logger := s.log.With("type", "cgi")

	signed, err := delivery.NewSigned(s.persister)
	if err != nil {
		logger.Error(err)
		return
	}

	for _, handler := range s.cfg.Handlers {
		handlerLogger := logger.With("handler", handler.Name)
		wg.Add(3)
		// Internal CGI server
		go func(aHandler config.Handler) {
			defer wg.Done()
			startCGIServer(aHandler, handlerLogger)
		}(handler)
		// Ticker
		go func(aHandler config.Handler) {
			defer wg.Done()
			startTicker(aHandler, s.persister, handlerLogger, s.cfg, signed, s.policy)
		}(handler)
		// Execute a handler tick on start since Go's ticker waits until $interval to trigger first tick
		go func(aHandler config.Handler) {
			defer wg.Done()
			time.Sleep(1 * time.Second)
			output := tick(aHandler, handlerLogger)
			err := processTick(aHandler, output, s.persister, handlerLogger, s.cfg, signed, s.policy)
			if err != nil {
				s.log.Error(err)
			}
		}(handler)

	}
	wg.Wait()
	return nil
}

func startCGIServer(h config.Handler, log *zap.SugaredLogger) {
	cgiHandler := cgi.Handler{Path: h.Exec}

	server := http.Server{
		Handler: &cgiHandler,
	}

	sock := fmt.Sprintf("%s.sock", h.Name)
	log.Debugf("starting cgi server at %s", sock)
	os.Remove(sock)
	unixListener, err := net.Listen("unix", sock)
	if err != nil {
		panic(err)
	}
	server.Serve(unixListener)
}

func startTicker(h config.Handler, persister *models.Persister, log *zap.SugaredLogger, cfg config.Config, signed *delivery.Signed, policy *bluemonday.Policy) {
	ticker := time.NewTicker(h.Interval) // TODO add some random jitter here so handlers dont run at the same exact intervals
	done := make(chan bool)
	func() {
		for {
			select {
			case <-done:
				return
			case _ = <-ticker.C:
				output := tick(h, log)
				err := processTick(h, output, persister, log, cfg, signed, policy)
				if err != nil {
					log.Error(err)
				}
			}
		}
	}()
}

func processTick(h config.Handler, output []byte, persister *models.Persister, log *zap.SugaredLogger, cfg config.Config, signed *delivery.Signed, policy *bluemonday.Policy) error {
	fp := gofeed.NewParser()
	fp.ParseString(string(output))
	feed, err := fp.ParseString(string(output))
	if err != nil {
		return err
	}

	for _, v := range feed.Items {
		var extractedContent string
		// if there is no content, use descrption
		if len(v.Content) != 0 {
			extractedContent = v.Content
		} else if len(v.Description) != 0 {
			extractedContent = v.Description
		}

		if len(extractedContent) != 0 {
			extractedContent := policy.Sanitize(extractedContent)
			log.Debugf("extracted and sanitized content '%s'", extractedContent)
			outboxItem := models.CreateOutboxItem(h, []byte(extractedContent))
			err = persister.StoreWithCallback(outboxItem, func() {
				logger := log.With("handler", h.Name).With("type", "subscription")
				// go through handler subscriptions and deliver signed outbox items
				logger.Debug("callback for save")
				sub := models.NewSubscription(h)
				keys, err := persister.CollectKeys(sub)
				if err != nil {
					logger.Error(err)
					return
				}
				jsonData, err := views.RenderActivity(h.Name, cfg.Domain, *outboxItem)
				if err != nil {
					logger.Error(err)
					return
				}
				payload, err := json.Marshal(jsonData)
				if err != nil {
					logger.Error(err)
					return
				}
				for _, v := range keys {
					parts := strings.Split(string(v), ":")
					joinedUrl := strings.Join(parts[2:], ":")
					logger.With("payload", jsonData).With("inboxUrl", joinedUrl).Debugf("delivering activity")

					actorKeyUrl, err := urls.UrlProfileKey(h.Name, cfg.Domain)
					if err != nil {
						logger.Error(err)
						continue
					}
					parsedUrl, err := url.Parse(joinedUrl)
					if err != nil {
						logger.Error(err)
						continue
					}
					request, err := signed.SignedRequest(h, []byte(payload), parsedUrl, actorKeyUrl)
					if err != nil {
						logger.Error(err)
						continue
					}

					client := &http.Client{}
					response, err := client.Do(request)
					if err != nil {
						logger.Errorf("could not send activity request: %w", err)
						continue
					}
					responseBody, err := io.ReadAll(response.Body)
					defer response.Body.Close()
					logger.With("response", responseBody).With("status", response.Status).Debugf("remote inbox response received")
				}
			})
			if err != nil {
				return err
			}
		}
	}
	return nil
}

func tick(h config.Handler, log *zap.SugaredLogger) []byte {
	sock := fmt.Sprintf("%s.sock", h.Name)
	httpc := http.Client{
		Transport: &http.Transport{
			DialContext: func(_ context.Context, _, _ string) (net.Conn, error) {
				return net.Dial("unix", sock)
			},
		},
	}
	var response *http.Response
	var err error
	log.Debugf("executing cgi handler at %s", sock)
	response, err = httpc.Get("http://unix/" + sock)
	if err != nil {
		log.Errorf("received error from cgi handler %s", err)
	}

	body, err := ioutil.ReadAll(response.Body)
	response.Body.Close()
	return body
}