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
|
package state
import (
"context"
"fmt"
"runtime"
"strconv"
"strings"
"sync/atomic"
"github.com/ProtonMail/gluon/async"
"github.com/ProtonMail/gluon/db"
"github.com/ProtonMail/gluon/imap"
"github.com/ProtonMail/gluon/imap/command"
"github.com/ProtonMail/gluon/internal/contexts"
"github.com/ProtonMail/gluon/internal/response"
"github.com/ProtonMail/gluon/rfc822"
"github.com/bradenaw/juniper/parallel"
"github.com/bradenaw/juniper/xslices"
)
var totalActiveFetchRequest int32
func (m *Mailbox) Fetch(ctx context.Context, cmd *command.Fetch, ch chan response.Response) error {
snapMessages, err := m.snap.getMessagesInRange(ctx, cmd.SeqSet)
if err != nil {
return err
}
operations := make([]func(snapMsgWithSeq, *db.Message, []byte) (response.Item, error), 0, len(cmd.Attributes))
var (
needsLiteral bool
wantUID bool
setSeen bool
)
for _, attribute := range cmd.Attributes {
switch attribute := attribute.(type) {
case *command.FetchAttributeAll:
// Macro equivalent to: (FLAGS INTERNALDATE RFC822.SIZE ENVELOPE).
operations = append(operations, fetchFlags, fetchInternalDate, fetchRFC822Size, fetchEnvelope)
case *command.FetchAttributeFast:
// Macro equivalent to: (FLAGS INTERNALDATE RFC822.SIZE).
operations = append(operations, fetchFlags, fetchInternalDate, fetchRFC822Size)
case *command.FetchAttributeFull:
// Macro equivalent to: (FLAGS INTERNALDATE RFC822.SIZE ENVELOPE BODY).
operations = append(operations, fetchFlags, fetchInternalDate, fetchRFC822Size, fetchEnvelope, fetchBody)
case *command.FetchAttributeUID:
wantUID = true
operations = append(operations, fetchUID)
case *command.FetchAttributeRFC822:
setSeen = true
needsLiteral = true
operations = append(operations, fetchRFC822)
case *command.FetchAttributeRFC822Text:
setSeen = true
needsLiteral = true
operations = append(operations, fetchRFC822Text)
case *command.FetchAttributeRFC822Header:
needsLiteral = true
operations = append(operations, fetchRFC822Header)
case *command.FetchAttributeRFC822Size:
operations = append(operations, fetchRFC822Size)
case *command.FetchAttributeFlags:
operations = append(operations, fetchFlags)
case *command.FetchAttributeEnvelope:
operations = append(operations, fetchEnvelope)
case *command.FetchAttributeInternalDate:
operations = append(operations, fetchInternalDate)
case *command.FetchAttributeBody:
operations = append(operations, fetchBody)
case *command.FetchAttributeBodyStructure:
operations = append(operations, fetchBodyStructure)
case *command.FetchAttributeBodySection:
needsLiteral = true
if !attribute.Peek {
setSeen = true
}
op := func(_ snapMsgWithSeq, _ *db.Message, literal []byte) (response.Item, error) {
return fetchAttributeBodySection(attribute, literal)
}
operations = append(operations, op)
}
}
const minCountForParallelism = 4
var parallelism int
activeFetchRequests := atomic.AddInt32(&totalActiveFetchRequest, 1)
defer atomic.AddInt32(&totalActiveFetchRequest, -1)
// Only run in parallel if we have to fetch more than minCountForParallelism messages or if we have more than one
// message and we need to access the literal.
if !contexts.IsParallelismDisabledCtx(ctx) && (len(snapMessages) > minCountForParallelism || (len(snapMessages) > 1 && needsLiteral)) {
// If multiple fetch request are happening in parallel, reduce the number of goroutines in proportion to that
// to avoid overloading the user's machine.
parallelism = runtime.NumCPU() / int(activeFetchRequests)
// make sure that if division hits 0, we run single threaded rather than use MAXGOPROCS
if parallelism < 1 {
parallelism = 1
}
} else {
parallelism = 1
}
if err := parallel.DoContext(ctx, parallelism, len(snapMessages), func(ctx context.Context, i int) error {
defer async.HandlePanic(m.state.panicHandler)
msg := snapMessages[i]
message, err := stateDBReadResult(ctx, m.state, func(ctx context.Context, client db.ReadOnly) (*db.Message, error) {
return client.GetMessageNoEdges(ctx, msg.ID.InternalID)
})
if err != nil {
return err
}
var literal []byte
if needsLiteral {
l, err := m.state.getLiteral(ctx, msg.ID)
if err != nil {
return err
}
literal = l
}
items := make([]response.Item, 0, len(operations))
for _, op := range operations {
item, err := op(msg, message, literal)
if err != nil {
return err
}
items = append(items, item)
}
if contexts.IsUID(ctx) && !wantUID {
items = append(items, response.ItemUID(msg.UID))
}
if setSeen {
if !msg.flags.ContainsUnchecked(imap.FlagSeenLowerCase) {
msg.flags.AddToSelf(imap.FlagSeen)
items = append(items, response.ItemFlags(msg.flags))
}
} else {
// remove message from the list to avoid being processed for seen flag changes later.
snapMessages[i].snapMsg = nil
}
ch <- response.Fetch(msg.Seq).WithItems(items...)
return nil
}); err != nil {
return err
}
msgsToBeMarkedSeen := xslices.Filter(snapMessages, func(s snapMsgWithSeq) bool {
return s.snapMsg != nil
})
if len(msgsToBeMarkedSeen) != 0 {
if err := stateDBWrite(ctx, m.state, func(ctx context.Context, tx db.Transaction) ([]Update, error) {
return m.state.actionAddMessageFlags(ctx, tx, msgsToBeMarkedSeen, imap.NewFlagSet(imap.FlagSeen))
}); err != nil {
return err
}
}
return nil
}
func fetchEnvelope(_ snapMsgWithSeq, message *db.Message, _ []byte) (response.Item, error) {
return response.ItemEnvelope(message.Envelope), nil
}
func fetchFlags(msg snapMsgWithSeq, message *db.Message, _ []byte) (response.Item, error) {
return response.ItemFlags(msg.flags), nil
}
func fetchInternalDate(_ snapMsgWithSeq, message *db.Message, _ []byte) (response.Item, error) {
return response.ItemInternalDate(message.Date), nil
}
func fetchRFC822(_ snapMsgWithSeq, _ *db.Message, literal []byte) (response.Item, error) {
return response.ItemRFC822Literal(literal), nil
}
func fetchRFC822Header(_ snapMsgWithSeq, _ *db.Message, literal []byte) (response.Item, error) {
section := rfc822.Parse(literal)
return response.ItemRFC822Header(section.Header()), nil
}
func fetchRFC822Size(_ snapMsgWithSeq, message *db.Message, _ []byte) (response.Item, error) {
return response.ItemRFC822Size(message.Size), nil
}
func fetchRFC822Text(_ snapMsgWithSeq, _ *db.Message, literal []byte) (response.Item, error) {
section := rfc822.Parse(literal)
return response.ItemRFC822Text(section.Body()), nil
}
func fetchBody(_ snapMsgWithSeq, message *db.Message, _ []byte) (response.Item, error) {
return response.ItemBody(message.Body), nil
}
func fetchBodyStructure(_ snapMsgWithSeq, message *db.Message, _ []byte) (response.Item, error) {
return response.ItemBodyStructure(message.BodyStructure), nil
}
func fetchUID(msg snapMsgWithSeq, _ *db.Message, _ []byte) (response.Item, error) {
return response.ItemUID(msg.UID), nil
}
func fetchAttributeBodySection(attribute *command.FetchAttributeBodySection, literal []byte) (response.Item, error) {
b, section, err := fetchBodyLiteral(attribute.Section, literal)
if err != nil {
return nil, err
}
item := response.ItemBodyLiteral(section, b)
if attribute.Partial != nil {
item.WithPartial(int(attribute.Partial.Offset), int(attribute.Partial.Count))
}
return item, nil
}
func fetchBodyLiteral(section command.BodySection, literal []byte) ([]byte, string, error) {
if section == nil {
return literal, "", nil
}
b, err := fetchBodySection(section, literal)
if err != nil {
return nil, "", err
}
renderedSection, err := renderSection(section)
if err != nil {
return nil, "", err
}
return b, renderedSection, nil
}
func fetchBodySection(section command.BodySection, literal []byte) ([]byte, error) {
root := rfc822.Parse(literal)
switch v := section.(type) {
case *command.BodySectionPart:
if len(v.Part) > 0 {
p, err := root.Part(v.Part...)
if err != nil {
return nil, err
}
root = p
section = v.Section
}
default:
}
if root == nil {
return nil, fmt.Errorf("invalid section part")
}
// HEADER and TEXT keywords should handle embedded message/rfc822 parts!
handleEmbeddedParts := func(root *rfc822.Section) (*rfc822.Section, error) {
contentType, _, err := root.ContentType()
if err != nil {
return nil, err
}
if rfc822.MIMEType(contentType) == rfc822.MessageRFC822 {
root = rfc822.Parse(root.Body())
}
return root, nil
}
if section == nil {
return root.Body(), nil
}
switch section := section.(type) {
case *command.BodySectionMIME:
return root.Header(), nil
case *command.BodySectionHeader:
r, err := handleEmbeddedParts(root)
if err != nil {
return nil, err
}
return r.Header(), nil
case *command.BodySectionText:
r, err := handleEmbeddedParts(root)
if err != nil {
return nil, err
}
return r.Body(), nil
case *command.BodySectionHeaderFields:
r, err := handleEmbeddedParts(root)
if err != nil {
return nil, err
}
header, err := r.ParseHeader()
if err != nil {
return nil, err
}
if section.Negate {
return header.FieldsNot(section.Fields), nil
}
return header.Fields(section.Fields), nil
default:
return nil, fmt.Errorf("unknown section")
}
}
func renderSection(section command.BodySection) (string, error) {
var res []string
switch v := section.(type) {
case *command.BodySectionPart:
res = append(res, renderParts(v.Part))
section = v.Section
default:
}
if section != nil {
switch section := section.(type) {
case *command.BodySectionMIME:
res = append(res, "MIME")
case *command.BodySectionHeader:
res = append(res, "HEADER")
case *command.BodySectionText:
res = append(res, "TEXT")
case *command.BodySectionHeaderFields:
if section.Negate {
res = append(res, fmt.Sprintf("HEADER.FIELDS.NOT (%v)", strings.Join(section.Fields, " ")))
} else {
res = append(res, fmt.Sprintf("HEADER.FIELDS (%v)", strings.Join(section.Fields, " ")))
}
default:
return "", fmt.Errorf("bad body section keyword")
}
}
return strings.ToUpper(strings.Join(res, ".")), nil
}
func renderParts(sectionParts []int) string {
return strings.Join(xslices.Map(sectionParts, func(part int) string { return strconv.Itoa(part) }), ".")
}
|