File: handledtgroupchangemessage.cc

package info (click to toggle)
signalbackup-tools 20250313.1-1
  • links: PTS, VCS
  • area: main
  • in suites: sid, trixie
  • size: 3,752 kB
  • sloc: cpp: 47,042; sh: 477; ansic: 399; ruby: 19; makefile: 3
file content (377 lines) | stat: -rw-r--r-- 16,235 bytes parent folder | download
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
/*
  Copyright (C) 2022-2025  Selwin van Dijk

  This file is part of signalbackup-tools.

  signalbackup-tools is free software: you can redistribute it and/or modify
  it under the terms of the GNU General Public License as published by
  the Free Software Foundation, either version 3 of the License, or
  (at your option) any later version.

  signalbackup-tools 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 General Public License for more details.

  You should have received a copy of the GNU General Public License
  along with signalbackup-tools.  If not, see <https://www.gnu.org/licenses/>.
*/

#include "signalbackup.ih"

/*
  It seems the desktop message does not contain most of the info of the phone message. For example the creation message:

  ("type":"group-v2-change","groupV2Change":{"from":"0d70b7f4-fe4a-41af-9fd5-e74268d13f6e","details":[{"type":"create"}]}"

  has no group title, no group memberlist (uuids, profilekeys, roles, accesscontrol...)

  Also, the same rules for sms/mms database apply for incoming/outgoing messages (since these are all group messages), but
  the desktop database does not say if the messages are incoming or outgoing. Only the source uuid ('from'), but we don't
  know without scanning other messages (and possibly cant know if unlucky), which uuid is self and which are others.

*/

bool SignalBackup::handleDTGroupChangeMessage(SqliteDB const &ddb, long long int rowid,
                                              long long int thread_id, long long int address, long long int date,
                                              std::map<long long int, long long int> *adjusted_timestamps,
                                              std::map<std::string, long long int> *savedmap,
                                              std::string const &databasedir, bool istimermessage, bool createcontacts,
                                              bool createvalidcontacts, bool *warn)
{
  if (date == -1)
  {
    // print wrn
    return false;
  }

  if (istimermessage)
  {

    SqliteDB::QueryResults timer_results;
    if (!ddb.exec("SELECT "
                  "type, "
                  "conversationId, "
                  "IFNULL(json_extract(json,'$.expirationTimerUpdate.fromGroupUpdate'), false) AS fromgroupupdate, "
                  "IFNULL(json_extract(json,'$.expirationTimerUpdate.fromSync'), false) AS fromsync, "
                  "IFNULL(json_extract(json,'$.expirationTimerUpdate.expireTimer'), 0) AS expiretimer, "
                  "json_extract(json,'$.expirationTimerUpdate.source') AS source, "
                  "COALESCE(json_extract(json,'$.expirationTimerUpdate.sourceServiceId'), json_extract(json,'$.expirationTimerUpdate.sourceUuid')) AS sourceuuid "
                  "FROM messages WHERE rowid = ?", rowid, &timer_results))
    {
      Logger::error("Querying database");
      return false;
    }
    bool incoming = bepaald::toLower(timer_results("sourceuuid")) != d_selfuuid;
    long long int timer = timer_results.getValueAs<long long int>(0, "expiretimer");
    long long int groupv2type = Types::SECURE_MESSAGE_BIT | Types::PUSH_MESSAGE_BIT | Types::GROUP_V2_BIT |
      Types::GROUP_UPDATE_BIT | (incoming ? Types::BASE_INBOX_TYPE : Types::BASE_SENDING_TYPE);
    // at this point address is the group_recipient. This is good for outgoing messages,
    // but incoming should have individual_recipient
    if (timer_results("sourceuuid").empty())
      return false;
    if (incoming)
    {
      address = getRecipientIdFromUuidMapped(timer_results("sourceuuid"), savedmap);

      if (address == -1)
      {
        if (createcontacts)
        {
          if ((address = dtCreateRecipient(ddb, timer_results("sourceuuid"), std::string(), std::string(), databasedir, savedmap, createvalidcontacts, warn)) == -1)
          {
            Logger::error("Failed to create group-v2-expiration-timer contact (1), skipping");
            return false;
          }
        }
        else
        {
          Logger::error("Failed to create group-v2-expiration-timer contact (2), skipping");
          return false;
        }
      }
    }
    //std::cout << "Got timer message: " << timer << std::endl;

    DecryptedTimer dt;
    dt.addField<1>(timer);
    DecryptedGroupChange groupchange;
    groupchange.addField<12>(dt);
    DecryptedGroupV2Context groupv2ctx;
    groupv2ctx.addField<2>(groupchange);
    std::pair<unsigned char *, size_t> groupchange_data(groupv2ctx.data(), groupv2ctx.size());
    std::string groupchange_data_b64 = Base64::bytesToBase64String(groupchange_data);
    // add message to database
    // if (d_database.containsTable("sms"))
    //   not going through the trouble
    // else
    // {
    if (!d_database.tableContainsColumn(d_mms_table, "to_recipient_id"))
    {
      if (!insertRow(d_mms_table, {{"thread_id", thread_id},
                                   {d_mms_date_sent, date},
                                   {"date_received", date},
                                   {"body", groupchange_data_b64},
                                   {d_mms_type, groupv2type},
                                   {d_mms_recipient_id, address},
                                   {"m_type", incoming ? 132 : 128},
                                   {"read", 1}}))              // hardcoded to 1 in Signal Android
      {
        Logger::error("Inserting verified-change into mms");
        return false;
      }
    }
    else
    {
      //newer tables have a unique constraint on date_sent/thread_id/from_recipient_id, so
      //we try to get the first free date_sent
      long long int freedate = getFreeDateForMessage(date, thread_id, Types::isOutgoing(groupv2type) ? d_selfid : address);
      if (freedate == -1)
      {
        Logger::error("Getting free date for inserting verified-change message into mms");
        return false;
      }
      if (date != freedate)
        (*adjusted_timestamps)[date] = freedate;

      std::any newmms_id;
      if (!insertRow(d_mms_table, {{"thread_id", thread_id},
                                   {d_mms_date_sent, freedate},
                                   {"date_received", freedate},
                                   {"body", groupchange_data_b64},
                                   {d_mms_type, groupv2type},
                                   {d_mms_recipient_id, incoming ? address : d_selfid},
                                   {"to_recipient_id", incoming ? d_selfid : address},
                                   {"m_type", incoming ? 132 : 128},
                                   {"read", 1}}, "_id", &newmms_id))              // hardcoded to 1 in Signal Android
      {
        Logger::error("Inserting verified-change into mms");
        return false;
      }
    }
    return true;
  }

  // !istimermessage

  SqliteDB::QueryResults res;
  if (!ddb.exec("SELECT "
                "LOWER(json_extract(json, '$.groupV2Change.from')) AS source,"
                "IFNULL(json_array_length(json, '$.groupV2Change.details'), 0) AS numchanges"
                " FROM messages WHERE rowid = ?", rowid, &res))
    return false;

  //res.prettyPrint();
  long long int numchanges = res.getValueAs<long long int>(0, "numchanges");
  if (numchanges == 0)
    return false;

  std::string source_uuid = res("source");
  if (STRING_STARTS_WITH(source_uuid, "pni")) // get real uuid if source was a "PNI:" type id...?
  {
    std::string realuuid = ddb.getSingleResultAs<std::string>("SELECT " + d_dt_c_uuid + " FROM conversations WHERE LOWER(json_extract(json, '$.pni')) IS ?", source_uuid, std::string());
    if (!realuuid.empty())
      source_uuid = std::move(realuuid);
  }
  bool incoming = source_uuid != d_selfuuid;
  long long int groupv2type = Types::SECURE_MESSAGE_BIT | Types::PUSH_MESSAGE_BIT | Types::GROUP_V2_BIT |
    Types::GROUP_UPDATE_BIT | (incoming ? Types::BASE_INBOX_TYPE : Types::BASE_SENDING_TYPE);
  if (incoming)
  {
    address = getRecipientIdFromUuidMapped(source_uuid, savedmap);
    if (address == -1)
    {
      if (createcontacts)
      {
        if ((address = dtCreateRecipient(ddb, source_uuid, std::string(), std::string(), databasedir, savedmap, createvalidcontacts, warn)) == -1)
        {
          Logger::error("Failed to create group-v2-update contact (1), skipping");
          return false;
        }
      }
      else
      {
        Logger::error("Failed to create group-v2-update contact (2), skipping");
        return false;
      }
    }
  }

  DecryptedGroupV2Context groupv2ctx;
  DecryptedGroupChange groupchange;
  bool addchange = false;

  // add each group change...
  for (unsigned int i = 0; i < numchanges; ++i)
  {
    if (!ddb.exec("SELECT "
                  "json_extract(json, '$.groupV2Change.details[' || ? || '].type') AS type,"
                  "COALESCE(json_extract(json, '$.groupV2Change.details[' || ? || '].aci'), json_extract(json, '$.groupV2Change.details[' || ? || '].uuid')) AS uuid,"
                  "json_extract(json, '$.groupV2Change.details[' || ? || '].newTitle') AS title,"
                  "json_extract(json, '$.groupV2Change.details[' || ? || '].description') AS description,"
                  "json_extract(json, '$.groupV2Change.details[' || ? || '].avatar') AS avatar,"
                  "json_extract(json, '$.groupV2Change.details[' || ? || '].removed') AS removed"
                  " FROM messages WHERE rowid = ?", {i, i, i, i, i, i, i, rowid}, &res))
      continue;

    std::string changetype = res("type");

    if (changetype == "title")
    {
      DecryptedString newtitle;
      newtitle.addField<1>(res("title"));
      groupchange.addField<10>(newtitle);
      addchange = true;
      //Logger::message("new title '", title, "'");
    }
    else if (changetype == "description")
    {
      //bool removed [[maybe_unused]] = res.valueAsInt(0, "removed");
      DecryptedString newdescription;
      newdescription.addField<1>(res("description"));
      groupchange.addField<20>(newdescription);
      addchange = true;
      //Logger::message("new description: '", description, "' (", removed, ")");
    }
    else if (changetype == "avatar")
    {
      //bool removed [[maybe_unused]] = res.valueAsInt(0, "removed");
      DecryptedString newavatar;
      newavatar.addField<1>("new_avatar");
      groupchange.addField<11>(newavatar);
      addchange = true;
      //Logger::message("new avatar (", removed, ")");
    }
    else if (changetype == "member-add")
    {
      std::string uuid = res("uuid");
      if (static_cast<int>(uuid.size()) != STRLEN("xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx") ||
          static_cast<int>(source_uuid.size()) != STRLEN("xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx"))
        continue;

      unsigned int uuid_bytes_size = (STRLEN("xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx") - STRLEN("----")) / 2;
      std::unique_ptr<unsigned char[]> uuid_bytes(new unsigned char[uuid_bytes_size]);
      bepaald::hexStringToBytes(source_uuid, uuid_bytes.get(), uuid_bytes_size);
      groupchange.addField<1>(std::make_pair<unsigned char *, int>(uuid_bytes.get(), uuid_bytes_size));

      DecryptedMember newmember;
      uuid_bytes.reset(new unsigned char[uuid_bytes_size]);
      bepaald::hexStringToBytes(uuid, uuid_bytes.get(), uuid_bytes_size);
      newmember.addField<1>(std::make_pair<unsigned char *, int>(uuid_bytes.get(), uuid_bytes_size));
      groupchange.addField<3>(newmember);

      addchange = true;

      //Logger::message("member add: ", uuid);
    }
    else if (changetype == "member-remove")
    {
      std::string uuid = res("uuid");

      if (uuid == source_uuid) // xxx left the group
        groupv2type |= Types::GROUP_QUIT_BIT;
      //else // xxx removed yyy

      if (static_cast<int>(uuid.size()) != STRLEN("xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx"))
        continue;

      unsigned int uuid_bytes_size = (STRLEN("xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx") - STRLEN("----")) / 2;
      std::unique_ptr<unsigned char[]> uuid_bytes(new unsigned char[uuid_bytes_size]);
      bepaald::hexStringToBytes(uuid, uuid_bytes.get(), uuid_bytes_size);
      groupchange.addField<4>(std::make_pair<unsigned char *, int>(uuid_bytes.get(), uuid_bytes_size));

      addchange = true;
      //Logger::message("member remove: ", uuid);
    }
    else if (changetype == "create")
    {
      if (static_cast<int>(source_uuid.size()) != STRLEN("xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx"))
        continue;

      // set source = source_uuid
      unsigned int uuid_bytes_size = (STRLEN("xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx") - STRLEN("----")) / 2;
      std::unique_ptr<unsigned char[]> uuid_bytes(new unsigned char[uuid_bytes_size]);
      bepaald::hexStringToBytes(source_uuid, uuid_bytes.get(), uuid_bytes_size);
      groupchange.addField<1>(std::make_pair<unsigned char *, int>(uuid_bytes.get(), uuid_bytes_size));

      // set new member = also source_uuid
      DecryptedMember newmember;
      newmember.addField<1>(std::make_pair<unsigned char *, int>(uuid_bytes.get(), uuid_bytes_size));
      groupchange.addField<3>(newmember);

      // explicitly set revision 0
      GroupContextV2 groupctx;
      groupctx.addField<2>(0);
      groupv2ctx.addField<1>(groupctx);

      addchange = true;
      //Logger::message("member add: ", uuid);
    }
    else
    {
      Logger::warnOnce("Unsupported message type 'group-v2-change:" + changetype + "'. Skipping... (this warning will be shown only once)");
      continue;
    }

    //res.prettyPrint(d_truncate);

  }

  if (addchange)
  {
    groupv2ctx.addField<2>(groupchange);
    std::pair<unsigned char *, size_t> groupchange_data(groupv2ctx.data(), groupv2ctx.size());
    std::string groupchange_data_b64 = Base64::bytesToBase64String(groupchange_data);
    // add message to database
    // if (d_database.containsTable("sms"))
    //   not going through the trouble
    // else
    // {
    if (!d_database.tableContainsColumn(d_mms_table, "to_recipient_id"))
    {
      if (!insertRow(d_mms_table, {{"thread_id", thread_id},
                                   {d_mms_date_sent, date},
                                   {"date_received", date},
                                   {"body", groupchange_data_b64},
                                   {d_mms_type, groupv2type},
                                   {d_mms_recipient_id, address},
                                   {"m_type", incoming ? 132 : 128},
                                   {"read", 1}}))              // hardcoded to 1 in Signal Android
      {
        Logger::error("Inserting verified-change into mms");
        return false;
      }
    }
    else
    {
      //newer tables have a unique constraint on date_sent/thread_id/from_recipient_id, so
      //we try to get the first free date_sent
      long long int freedate = getFreeDateForMessage(date, thread_id, Types::isOutgoing(groupv2type) ? d_selfid : address);
      if (freedate == -1)
      {
        Logger::error("Getting free date for inserting verified-change message into mms");
        return false;
      }
      if (date != freedate)
        (*adjusted_timestamps)[date] = freedate;

      //std::cout << "ADDING NEW GROUPV2 MESSAGE AT DATE: " << bepaald::toDateString(freedate / 1000, "%Y-%m-%d %H:%M:%S") << std::endl;

      std::any newmms_id;
      if (!insertRow(d_mms_table, {{"thread_id", thread_id},
                                   {d_mms_date_sent, freedate},
                                   {"date_received", freedate},
                                   {"body", groupchange_data_b64},
                                   {d_mms_type, groupv2type},
                                   {d_mms_recipient_id, incoming ? address : d_selfid},
                                   {"to_recipient_id", incoming ? d_selfid : address},
                                   {"m_type", incoming ? 132 : 128},
                                   {"read", 1}}, "_id", &newmms_id))              // hardcoded to 1 in Signal Android
      {
        Logger::error("Inserting verified-change into mms");
        return false;
      }
    }
  }
  return true;
}