databaselayout.md: added code blocks
[citadel.git] / citadel / docs / databaselayout.md
1 The totally incomplete guide to Citadel internals
2 -----------------------------------------------------
3
4 Citadel has evolved quite a bit since its early days, and the data structures
5 have evolved with it.  This document provides a rough overview of how the
6 system works internally.  For details you're going to have to dig through the
7 code, but this'll get you started. 
8
9
10 DATABASE TABLES
11 ---------------
12 As you probably already know by now, Citadel uses a group of tables stored
13 with a record manager (usually Berkeley DB).  Since we're using a record
14 manager rather than a relational database, all record structures are managed
15 by Citadel.  Here are some of the tables we keep on disk:
16
17
18 USER RECORDS
19 ------------
20 This table contains all user records.  It's indexed by
21 user name (translated to lower case for indexing purposes).  The records in
22 this file look something like this:
23
24 ```
25     struct ctdluser {                   // User record
26         int version;                    // Citadel version. which created this record
27         uid_t uid;                      // Associate with a unix account?
28         char password[32];              // Account password (unless using external authentication)
29         unsigned flags;                 // See US_ flags below
30         CIT_UBYTE axlevel;              // Access level
31         long usernum;                   // User number (never recycled)
32         time_t lastcall;                // Last time the user called
33         int USuserpurge;                // Purge time (in days) for user
34         char fullname[64];              // Name for Citadel messages & mail
35     };
36 ```
37  
38  Most fields here should be fairly self-explanatory.  The ones that might
39 deserve some attention are:
40
41  - `uid` -- if uid is not the same as the *unix uid* Citadel is running as, then the
42    account is assumed to belong to the user on the underlying Unix system with
43    that uid.  This allows us to require the user's OS password instead of having
44    a separate Citadel password.
45  
46  - `usernum` -- these are assigned sequentially, and **NEVER REUSED**. This is
47   important because it allows us to use this number in other data structures
48   without having to worry about users being added/removed later on, as you'll
49   see later in this document.
50  
51  
52 ROOM RECORDS
53 ------------
54 These are room records.  There is a room record for every room on the
55 system, public or private or mailbox.  It's indexed by room name (also in
56 lower case for easy indexing) and it contains records which look like this:
57
58 ```
59     struct ctdlroom {
60         char QRname[ROOMNAMELEN];       /* Name of room                     */
61         char QRpasswd[10];              /* Only valid if it's a private rm  */
62         long QRroomaide;                /* User number of room aide         */
63         long QRhighest;                 /* Highest message NUMBER in room   */
64         time_t QRgen;                   /* Generation number of room        */
65         unsigned QRflags;               /* See flag values below            */
66         char QRdirname[15];             /* Directory name, if applicable    */
67         long QRinfo;                    /* Info file update relative to msgs*/
68         char QRfloor;                   /* Which floor this room is on      */
69         time_t QRmtime;                 /* Date/time of last post           */
70         struct ExpirePolicy QRep;       /* Message expiration policy        */
71         long QRnumber;                  /* Globally unique room number      */
72         char QRorder;                   /* Sort key for room listing order  */
73         unsigned QRflags2;              /* Additional flags                 */
74         int QRdefaultview;              /* How to display the contents      */
75     };
76 ```
77
78 Again, mostly self-explanatory.  Here are the interesting ones:
79  
80 `QRnumber` is a globally unique room ID, while `QRgen` is the "generation number"
81 of the room (it's actually a timestamp).  The two combined produce a unique
82 value which identifies the room.  The reason for two separate fields will be
83 explained below when we discuss the visit table.  For now just remember that
84 `QRnumber` remains the same for the duration of the room's existence, and `QRgen`
85 is timestamped once during room creation but may be restamped later on when
86 certain circumstances exist.
87
88 FLOORTAB
89 --------
90 Floors.  This is so simplistic it's not worth going into detail about, except
91 to note that we keep a reference count of the number of rooms on each floor.
92  
93 MSGLISTS
94 --------
95 Each record in this table consists of a bunch of message numbers
96 which represent the contents of a room.  A message can exist in more than one
97 room (for example, a mail message with multiple recipients -- 'single instance
98 store').  This table is never, ever traversed in its entirety.  When you do
99 any type of read operation, it fetches the msglist for the room you're in
100 (using the room's ID as the index key) and then you can go ahead and read
101 those messages one by one.
102
103 Each room is basically just a list of message numbers.  Each time
104 we enter a new message in a room, its message number is appended to the end
105 of the list.  If an old message is to be expired, we must delete it from the
106 message base.  Reading a room is just a matter of looking up the messages
107 one by one and sending them to the client for display, printing, or whatever.
108  
109
110 VISIT
111 -----
112 This is the tough one.  Put on your thinking cap and grab a fresh cup of
113 coffee before attempting to grok the visit table.
114  
115 This table contains records which establish the relationship between users
116 and rooms.  Its index is a hash of the user and room combination in question.
117 When looking for such a relationship, the record in this table can tell the
118 server things like "this user has zapped this room," "this user has access to
119 this private room," etc.  It's also where we keep track of which messages
120 the user has marked as "old" and which are "new" (which are not necessarily
121 contiguous; contrast with older Citadel implementations which simply kept a
122 "last read" pointer).
123  
124
125 Here's what the records look like:
126  
127 ```
128     struct visit {
129         long v_roomnum;
130         long v_roomgen;
131         long v_usernum;
132         long v_lastseen;
133         unsigned int v_flags;
134         char v_seen[SIZ];
135         int v_view;
136     };
137
138     #define V_FORGET        1       /* User has zapped this room        */
139     #define V_LOCKOUT       2       /* User is locked out of this room  */
140     #define V_ACCESS        4       /* Access is granted to this room   */
141 ```
142  
143 This table is indexed by a concatenation of the first three fields.  Whenever
144 we want to learn the relationship between a user and a room, we feed that
145 data to a function which looks up the corresponding record.  The record is
146 designed in such a way that an "all zeroes" record (which is what you get if
147 the record isn't found) represents the default relationship.
148  
149 With this data, we now know which private rooms we're allowed to visit: if
150 the `V_ACCESS` bit is set, the room is one which the user knows, and it may
151 appear in his/her known rooms list.  Conversely, we also know which rooms the
152 user has zapped: if the `V_FORGET` flag is set, we relegate the room to the
153 zapped list and don't bring it up during new message searches.  It's also
154 worth noting that the `V_LOCKOUT` flag works in a similar way to administratively
155 lock users out of rooms.
156  
157 Implementing the "cause all users to forget room" command, then, becomes very
158 simple: we simply change the generation number of the room by putting a new
159 timestamp in the `QRgen` field.  This causes all relevant visit records to
160 become irrelevant, because they appear to point to a different room.  At the
161 same time, we don't lose the messages in the room, because the msglists table
162 is indexed by the room number (`QRnumber`), which never changes.
163  
164 `v_seen` contains a string which represents the set of messages in this room
165 which the user has read (marked as 'seen' or 'old').  It follows the same
166 syntax used by IMAP and NNTP.  When we search for new messages, we simply
167 return any messages that are in the room that are **not** represented by this
168 set.  Naturally, when we do want to mark more messages as seen (or unmark
169 them), we change this string.  Citadel BBS client implementations are naive
170 and think linearly in terms of "everything is old up to this point," but IMAP
171 clients want to have more granularity.
172
173
174 DIRECTORY
175 ---------
176 This table simply maps Internet e-mail addresses to Citadel network addresses
177 for quick lookup.  It is generated from data in the Global Address Book room.
178
179 USETABLE
180 --------
181 This table keeps track of message ID's of messages arriving over a network,
182 to prevent duplicates from being posted if someone misconfigures the network
183 and a loop is created.  This table goes unused on a non-networked Citadel.
184
185 THE MESSAGE STORE
186 -----------------
187 This is where all message text is stored.  It's indexed by message number:
188 give it a number, get back a message.  Messages are numbered sequentially, and
189 the message numbers are never reused.
190  
191 We also keep a "metadata" record for each message.  This record is also stored
192 in the msgmain table, using the index (0 - msgnum).  We keep in the metadata
193 record, among other things, a reference count for each message.  Since a
194 message may exist in more than one room, it's important to keep this reference
195 count up to date, and to delete the message from disk when the reference count
196 reaches zero.
197
198 NoSQL pros might recognize the message store as a "document database".  Each
199 record is an arbitrary collection of keys and values, some of which may
200 appear all the time, and some which might appear infrequently.
201  
202 # Here's the format for the message itself:
203
204  - Each message begins with an 0xFF 'start of message' byte.
205  
206  - The next byte denotes whether this is an anonymous message.  The codes
207    available are `MES_NORMAL`, `MES_ANON`, or `MES_AN2` (defined in `citadel.h`).
208  
209  - The third byte is a "message type" code.  The following codes are defined:
210   - 0 - "Traditional" Citadel format.  Message is to be displayed "formatted."
211   - 1 - Plain pre-formatted ASCII text (otherwise known as text/plain)
212   - 4 - MIME formatted message.  The text of the message which follows is
213         expected to begin with a "Content-type:" header.
214  
215  - After these three opening bytes, the remainder of
216    the message consists of a sequence of character strings.  Each string
217    begins with a type byte indicating the meaning of the string and is
218    ended with a null.  All strings are printable ASCII: in particular,
219    all numbers are in ASCII rather than binary.  This is for simplicity,
220    both in implementing the system and in implementing other code to
221    work with the system.  For instance, a database driven off Citadel archives
222    can do wildcard matching without worrying about unpacking binary data such
223    as message ID's first.  To provide later downward compatability
224    all software should be written to IGNORE fields not currently defined.
225
226
227 # The type bytes currently defined are:
228
229
230     | BYTE  |       Enum        | NW   | Mnemonic       |  Enum / Comments
231     |-------|-------------------|------|----------------|---------------------------------------------------------
232     | A     |    eAuthor        | from | Author         |  The display name of the Author of the message.
233     | B     |    eBig_message   |      | Big message    |  This is a flag which indicates that the message is
234     |       |                   |      |                |  big, and Citadel is storing the body in a separate
235     |       |                   |      |                |  record.  You will never see this field because the
236     |       |                   |      |                |  internal API handles it.
237     | E     |    eExclusiveID   | exti | Exclusive ID   |  A persistent alphanumeric Message ID used for
238     |       |                   |      |                |  replication control.  When a message arrives that
239     |       |                   |      |                |  contains an Exclusive ID, any existing messages which
240     |       |                   |      |                |  contain the same Exclusive ID and are *older* than this
241     |       |                   |      |                |  message should be deleted.  If there exist any messages
242     |       |                   |      |                |  with the same Exclusive ID that are *newer*, then this
243     |       |                   |      |                |  message should be dropped.
244     | F     |    erFc822Addr    | rfca | rFc822 address |  email address or user principal name of the message
245     |       |                   |      |                |  author.
246     | I     |    emessageId     | msgn | Message ID     |  An RFC822-compatible message ID for this message.
247     |       |                   |      |                |  
248     | J     |    eJournal       | jrnl | Journal        |  The presence of this field indicates that the message
249     |       |                   |      |                |  is disqualified from being journaled, perhaps because
250     |       |                   |      |                |  it is itself a journalized message and we wish to
251     |       |                   |      |                |  avoid double journaling.
252     | K     |    eReplyTo       | rep2 | Reply-To       |  the Reply-To header for mailinglist outbound messages
253     | L     |    eListID        | list | List-ID        |  Mailing list identification, as per RFC 2919
254     | M     |    eMesageText    | text | Message Text   |  Normal ASCII, newlines seperated by CR's or LF's,
255     |       |                   |      |                |  null terminated as always.
256     | O     |    eOriginalRoom  | room | Room           |  Room of origin.
257     | P     |    eMessagePath   | path | Path           |  Complete path of message, as in the UseNet news
258     |       |                   |      |                |  standard.  A user should be able to send Internet mail
259     |       |                   |      |                |  to this path. (Note that your system name will not be
260     |       |                   |      |                |  tacked onto this until you're sending the message to
261     |       |                   |      |                |  someone else)
262     | R     |    eRecipient     | rcpt | Recipient      |  Only present in Mail messages.
263     | T     |    eTimestamp     | time | date/Time      |  Unix timestamp containing the creation date/time of
264     |       |                   |      |                |  the message.
265     | U     |    eMsgSubject    | subj | sUbject        |  Message subject.  Optional.
266     |       |                   |      |                |  Developers may choose whether they wish to
267     |       |                   |      |                |  generate or display subject fields.
268     | V     |    eenVelopeTo    | nvto | enVelope-to    |  The recipient specified in incoming SMTP messages.
269     | W     |    eWeferences    | wefw | Wefewences     |  Previous message ID's for conversation threading.  When
270     |       |                   |      |                |  converting from RFC822 we use References: if present, or
271     |       |                   |      |                |  In-Reply-To: otherwise.
272     |       |                   |      |                |  (Who in extnotify spool messages which don't need to know
273     |       |                   |      |                |  other message ids)
274     | Y     |    eCarbonCopY    | cccc | carbon copY    |  Carbon copy (CC) recipients.
275     |       |                   |      |                |  Optional, and only in Mail messages.
276     | %     |    eHeaderOnly    | nhdr | oNlyHeader     |  we will just be sending headers. for the Wire protocol only.
277     | %     |    eFormatType    | type | type           |  type of citadel message: (Wire protocol only)
278     |       |                   |      |                |     FMT_CITADEL     0   Citadel vari-format (proprietary) 
279     |       |                   |      |                |     FMT_FIXED       1   Fixed format (proprietary)
280     |       |                   |      |                |     FMT_RFC822      4   Standard (headers are in M field)
281     | %     |    eMessagePart   | part | emessagePart   |  eMessagePart is the id of this part in the mime hierachy
282     | %     |    eSubFolder     | suff | eSubFolder     |  descend into a mime sub container
283     | %     |    ePevious       | pref | ePevious       |  exit a mime sub container
284     | 0     |    eErrorMsg      |      | Error          |  This field is typically never found in a message on
285     |       |                   |      |                |  disk or in transit.  Message scanning modules are
286     |       |                   |      |                |  expected to fill in this field when rejecting a message
287     |       |                   |      |                |  with an explanation as to what happened (virus found,
288     |       |                   |      |                |  message looks like spam, etc.)
289     | 1     |    eSuppressIdx   |      | suppress index |  The presence of this field indicates that the message is
290     |       |                   |      |                |  disqualified from being added to the full text index.
291     | 2     |    eExtnotify     |      | extnotify      |  Used internally by the serv_extnotify module.
292     | 3     |    eVltMsgNum     |      | msgnum         |  Used internally to pass the local message number in the
293     |       |                   |      |                |  database to after-save hooks.  Discarded afterwards.
294     |       |                   | locl |                |  The presence of this field indicates that the message
295     |       |                   |      |                |  is believed to have originated on the local Citadel node,
296     |       |                   |      |                |  not as an inbound email or some other outside source.
297
298 EXAMPLE
299 -------
300 Let `<FF>` be a `0xFF` byte, and `<0>` be a null `(0x00)` byte.  Then a message
301 which prints as...
302
303 ```
304     Apr 12, 1988 23:16 From Test User In Network Test> @lifesys (Life Central)
305     Have a nice day!
306 ```
307
308 might be stored as...
309
310 ```
311     <FF><40><0>I12345<0>Pneighbor!lifesys!test_user<0>T576918988<0>    (continued)
312     -----------|Mesg ID#|--Message Path---------------|--Date------
313     
314     AThe Test User<0>ONetwork Test<0>Nlifesys<0>HLife Central<0>MHave a nice day!<0>
315     |-----Author-----|-Room name-----|-nodename-|Human Name-|--Message text-----
316 ```
317
318 Weird things can happen if fields are missing, especially if you use the
319 networker.  But basically, the date, author, room, and nodename may be in any
320 order.  But the leading fields and the message text must remain in the same
321 place.  The H field looks better when it is placed immediately after the N
322 field.
323
324
325 EUID (EXCLUSIVE MESSAGE ID'S)
326 -----------------------------
327 This is where the groupware magic happens.  Any message in any room may have
328 a field called the Exclusive message *ID*, or *EUID*.  We keep an index in the
329 table `CDB_EUIDINDEX` which knows the message number of any item that has an
330 *EUID*.  This allows us to do two things:
331  
332  - If a subsequent message arrives with the same *EUID*, it automatically
333    *deletes* the existing one, because the new one is considered a replacement
334    for the existing one.
335  - If we know the *EUID* of the item we're looking for, we can fetch it by *EUID*
336    and get the most up-to-date version, even if it's been updated several times.
337
338 This functionality is made more useful by server-side hooks.  For example,
339 when we save a vCard to an address book room, or an iCalendar item to a
340 calendar room, our server modules detect this condition, and automatically set
341 the *EUID* of the message to the *UUID* of the *vCard* or *iCalendar* item.
342 Therefore when you save an updated version of an address book entry or
343 a calendar item, the old one is automatically deleted.
344
345 PORTABILITY ISSUES
346 ------------------
347 Citadel is 32/64 bit clean and architecture-independent.  The software is
348 developed and primarily run on the Linux operating system (which uses the
349 Linux kernel) but it should compile and run on any reasonably POSIX
350 compliant system.
351
352 On the client side, it's also POSIX compliant.  The client even seems to
353 build ok on non-POSIX systems with porting libraries (such as Cygwin and
354 WSL).
355
356 SUPPORTING PRIVATE MAIL
357 -----------------------
358 Can one have an elegant kludge?  This must come pretty close.
359
360 Private mail is sent and recieved in the `Mail>` room, which otherwise
361 behaves pretty much as any other room.        To make this work, we have a
362 separate Mail> room for each user behind the scenes.  The actual room name
363 in the database looks like `0000001234.Mail` (where `1234` is the user
364 number) and it's flagged with the `QR_MAILBOX` flag.  The user number is
365 stripped off by the server before the name is presented to the client.  This
366 provides the ability to give each user a separate namespace for mailboxes
367 and personal rooms.
368
369 This requires a little fiddling to get things just right. For example,
370 `make_message()` has to be kludged to ask for the name of the recipient
371 of the message whenever a message is entered in `Mail>`. But basically
372 it works pretty well, keeping the code and user interface simple and
373 regular.
374
375 PASSWORDS AND NAME VALIDATION
376 -----------------------------
377 This has changed a couple of times over the course of Citadel's history.  At
378 this point it's very simple, again due to the fact that record managers are
379 used for everything.    The user file (user) is indexed using the user's
380 name, converted to all lower-case.  Searching for a user, then, is easy.  We
381 just lowercase the name we're looking for and query the database.  If no
382 match is found, it is assumed that the user does not exist.
383
384 This makes it difficult to forge messages from an existing user.  (Fine
385 point: nonprinting characters are converted to printing characters, and
386 leading, trailing, and double blanks are deleted.)