5cd4d57ea2a3786c97a137be8e49066ba3220961
[citadel.git] / citadel / techdoc / hack.txt
1             ------------------------------------------------------
2              The totally incomplete guide to Citadel/UX internals
3             ------------------------------------------------------
4
5  Citadel has evolved quite a bit since its early days, and the data structures
6 have evolved with it.  This document provides a rough overview of how the
7 system works internally.  For details you're going to have to dig through the
8 code, but this'll get you started. 
9
10
11                             Database tables
12  
13
14  As you probably already know by now, Citadel uses a group of tables stored
15 with a record manager (usually Berkeley DB).  Since we're using a record
16 manager rather than a relational database, all record structures are managed
17 by Citadel.  Here are some of the tables we keep on disk:
18
19
20  USERSUPP
21  --------
22  
23  This table contains all user records.  It's called 'usersupp' because it was
24 once a supplementary file (at one point in ancient history, we created a user
25 record on the underlying operating system for each user).  It's indexed by
26 user name (translated to lower case for indexing purposes).  The records in
27 this file look something like this:
28
29 struct usersupp {                       /* User record                      */
30         int version;                    /* Cit vers. which created this rec */
31         uid_t uid;                      /* Associate with a unix account?   */
32         char password[32];              /* password (for BBS-only users)    */
33         unsigned flags;                 /* See US_ flags below              */
34         long timescalled;               /* Total number of logins           */
35         long posted;                    /* Number of messages posted (ever) */
36         CIT_UBYTE axlevel;              /* Access level                     */
37         long usernum;                   /* User number (never recycled)     */
38         time_t lastcall;                /* Last time the user called        */
39         int USuserpurge;                /* Purge time (in days) for user    */
40         char fullname[64];              /* Name for Citadel messages & mail */
41         CIT_UBYTE USscreenwidth;        /* Screen width (for textmode users)*/
42         CIT_UBYTE USscreenheight;       /* Screen height(for textmode users)*/
43 };
44  
45  Most fields here should be fairly self-explanatory.  The ones that might
46 deserve some attention are:
47  
48  uid -- if uid is not the same as the uid Citadel is running as, then the
49 account is assumed to belong to the user on the underlying Unix system with
50 that uid.  This allows us to require the user's OS password instead of having
51 a separate Citadel password.
52  
53  usernum -- these are assigned sequentially, and NEVER REUSED.  This is
54 important because it allows us to use this number in other data structures
55 without having to worry about users being added/removed later on, as you'll
56 see later in this document.
57  
58  The screenwidth and screenheight fields are almost never used anymore.  Back
59 when people were calling into dialup systems we had no way of knowing the
60 user's screen dimensions, but modern networks almost always transmit this
61 information so we set it up dynamically.
62  
63  
64  QUICKROOM
65  ---------
66  
67  These are room records.  One per room.  It's called 'quickroom' because at
68 one time it was a quick index hash type of thing (there was a pair called
69 quickroom and fullroom).  There is a quickroom record for every room on the
70 system, public or private or mailbox.  It's indexed by room name (also in
71 lower case for easy indexing) and it contains records which look like this:
72
73 struct quickroom {
74         char QRname[ROOMNAMELEN];       /* Name of room                     */
75         char QRpasswd[10];              /* Only valid if it's a private rm  */
76         long QRroomaide;                /* User number of room aide         */
77         long QRhighest;                 /* Highest message NUMBER in room   */
78         time_t QRgen;                   /* Generation number of room        */
79         unsigned QRflags;               /* See flag values below            */
80         char QRdirname[15];             /* Directory name, if applicable    */
81         long QRinfo;                    /* Info file update relative to msgs*/
82         char QRfloor;                   /* Which floor this room is on      */
83         time_t QRmtime;                 /* Date/time of last post           */
84         struct ExpirePolicy QRep;       /* Message expiration policy        */
85         long QRnumber;                  /* Globally unique room number      */
86         char QRorder;                   /* Sort key for room listing order  */
87         unsigned QRflags2;              /* Additional flags                 */
88         int QRdefaultview;              /* How to display the contents      */
89 };
90
91  Again, mostly self-explanatory.  Here are the interesting ones:
92  
93  QRnumber is a globally unique room ID, while QRgen is the "generation number"
94 of the room (it's actually a timestamp).  The two combined produce a unique
95 value which identifies the room.  The reason for two separate fields will be
96 explained below when we discuss the visit table.  For now just remember that
97 QRnumber remains the same for the duration of the room's existence, and QRgen
98 is timestamped once during room creation but may be restamped later on when
99 certain circumstances exist.
100
101   
102
103  FLOORTAB
104  --------
105  
106  Floors.  This is so simplistic it's not worth going into detail about, except
107 to note that we keep a reference count of the number of rooms on each floor.
108  
109  
110  
111  MSGLISTS
112  --------
113  Each record in this table consists of a bunch of message  numbers
114 which represent the contents of a room.  A message can exist in more than one
115 room (for example, a mail message with multiple recipients -- 'single instance
116 store').  This table is never, ever traversed in its entirety.  When you do
117 any type of read operation, it fetches the msglist for the room you're in
118 (using the room's ID as the index key) and then you can go ahead and read
119 those messages one by one.
120
121  Each room is basically just a list of message numbers.  Each time
122 we enter a new message in a room, its message number is appended to the end
123 of the list.  If an old message is to be expired, we must delete it from the
124 message base.  Reading a room is just a matter of looking up the messages
125 one by one and sending them to the client for display, printing, or whatever.
126  
127
128  VISIT
129  -----
130  
131  This is the tough one.  Put on your thinking cap and grab a fresh cup of
132 coffee before attempting to grok the visit table.
133  
134  This table contains records which establish the relationship between users
135 and rooms.  Its index is a hash of the user and room combination in question.
136 When looking for such a relationship, the record in this table can tell the
137 server things like "this user has zapped this room," "this user has access to
138 this private room," etc.  It's also where we keep track of which messages
139 the user has marked as "old" and which are "new" (which are not necessarily
140 contiguous; contrast with older Citadel implementations which simply kept a
141 "last read" pointer).
142  
143  Here's what the records look like:
144  
145 struct visit {
146         long v_roomnum;
147         long v_roomgen;
148         long v_usernum;
149         long v_lastseen;
150         unsigned int v_flags;
151         char v_seen[SIZ];
152         int v_view;
153 };
154
155 #define V_FORGET        1       /* User has zapped this room        */
156 #define V_LOCKOUT       2       /* User is locked out of this room  */
157 #define V_ACCESS        4       /* Access is granted to this room   */
158  
159  This table is indexed by a concatenation of the first three fields.  Whenever
160 we want to learn the relationship between a user and a room, we feed that
161 data to a function which looks up the corresponding record.  The record is
162 designed in such a way that an "all zeroes" record (which is what you get if
163 the record isn't found) represents the default relationship.
164  
165  With this data, we now know which private rooms we're allowed to visit: if
166 the V_ACCESS bit is set, the room is one which the user knows, and it may
167 appear in his/her known rooms list.  Conversely, we also know which rooms the
168 user has zapped: if the V_FORGET flag is set, we relegate the room to the
169 zapped list and don't bring it up during new message searches.  It's also
170 worth noting that the V_LOCKOUT flag works in a similar way to administratively
171 lock users out of rooms.
172  
173  Implementing the "cause all users to forget room" command, then, becomes very
174 simple: we simply change the generation number of the room by putting a new
175 timestamp in the QRgen field.  This causes all relevant visit records to
176 become irrelevant, because they appear to point to a different room.  At the
177 same time, we don't lose the messages in the room, because the msglists table
178 is indexed by the room number (QRnumber), which never changes.
179  
180  v_seen contains a string which represents the set of messages in this room
181 which the user has read (marked as 'seen' or 'old').  It follows the same
182 syntax used by IMAP and NNTP.  When we search for new messages, we simply
183 return any messages that are in the room that are *not* represented by this
184 set.  Naturally, when we do want to mark more messages as seen (or unmark
185 them), we change this string.  Citadel BBS client implementations are naive
186 and think linearly in terms of "everything is old up to this point," but IMAP
187 clients want to have more granularity.
188
189
190  DIRECTORY
191  ---------
192   
193  This table simply maps Internet e-mail addresses to Citadel network addresses
194 for quick lookup.  It is generated from data in the Global Address Book room.
195
196
197  USETABLE
198  --------
199  This table keeps track of message ID's of messages arriving over a network,
200 to prevent duplicates from being posted if someone misconfigures the network
201 and a loop is created.  This table goes unused on a non-networked Citadel.
202
203  MSGMAIN
204  -------
205  
206  This is where all message text is stored.  It's indexed by message number:
207 give it a number, get back a message.  Messages are numbered sequentially, and
208 the message numbers are never reused.
209  
210  We also keep a "metadata" record for each message.  This record is also stored
211 in the msgmain table, using the index (0 - msgnum).  We keep in the metadata
212 record, among other things, a reference count for each message.  Since a
213 message may exist in more than one room, it's important to keep this reference
214 count up to date, and to delete the message from disk when the reference count
215 reaches zero.
216  
217  Here's the format for the message itself:
218
219    Each message begins with an 0xFF 'start of message' byte.
220  
221    The next byte denotes whether this is an anonymous message.  The codes
222 available are MES_NORMAL, MES_ANON, or MES_AN2 (defined in citadel.h).
223  
224    The third byte is a "message type" code.  The following codes are defined:
225  0 - "Traditional" Citadel format.  Message is to be displayed "formatted."
226  1 - Plain pre-formatted ASCII text (otherwise known as text/plain)
227  4 - MIME formatted message.  The text of the message which follows is
228      expected to begin with a "Content-type:" header.
229  
230    After these three opening bytes, the remainder of
231 the message consists of a sequence of character strings.  Each string
232 begins with a type byte indicating the meaning of the string and is
233 ended with a null.  All strings are printable ASCII: in particular,
234 all numbers are in ASCII rather than binary.  This is for simplicity,
235 both in implementing the system and in implementing other code to
236 work with the system.  For instance, a database driven off Citadel archives
237 can do wildcard matching without worrying about unpacking binary data such
238 as message ID's first.  To provide later downward compatability
239 all software should be written to IGNORE fields not currently defined.
240
241                   The type bytes currently defined are:         
242
243 BYTE    Mnemonic        Comments
244
245 A       Author          Name of originator of message.
246 D       Destination     Contains name of the system this message should
247                         be sent to, for mail routing (private mail only).
248 E       Extended ID     A persistent alphanumeric Message ID used for
249                         network replication.  When a message arrives that
250                         contains an Extended ID, any existing messages which
251                         contain the same Extended ID and are *older* than this
252                         message should be deleted.  If there exist any messages
253                         with the same Extended ID that are *newer*, then this
254                         message should be dropped.
255 F       rFc822 address  For Internet mail, this is the delivery address of the
256                         message author.
257 H       HumanNodeName   Human-readable name of system message originated on.
258 I       Original ID     A 32-bit integer containing the message ID on the
259                         system the message *originated* on.
260 M       Message Text    Normal ASCII, newlines seperated by CR's or LF's,
261                         null terminated as always.
262 N       Nodename        Contains node name of system message originated on.
263 O       Room            Room of origin.
264 P       Path            Complete path of message, as in the UseNet news
265                         standard.  A user should be able to send Internet mail
266                         to this path. (Note that your system name will not be
267                         tacked onto this until you're sending the message to
268                         someone else)
269 R       Recipient       Only present in Mail messages.
270 S       Special field   Only meaningful for messages being spooled over a
271                         network.  Usually means that the message isn't really
272                         a message, but rather some other network function:
273                         -> "S" followed by "FILE" (followed by a null, of
274                            course) means that the message text is actually an
275                            IGnet/Open file transfer.
276                         -> "S" followed by "CANCEL" means that this message
277                            should be deleted from the local message base once
278                            it has been replicated to all network systems.
279 T       Date/Time       A 32-bit integer containing the date and time of
280                         the message in standard UNIX format (the number
281                         of seconds since January 1, 1970 GMT).
282 U       Subject         Optional.  Developers may choose whether they wish to
283                         generate or display subject fields.  Citadel/UX does
284                         not generate them, but it does print them when found.
285 0       Error           This field is typically never found in a message on
286                         disk or in transit.  Message scanning modules are
287                         expected to fill in this field when rejecting a message
288                         with an explanation as to what happened (virus found,
289                         message looks like spam, etc.)
290   
291                         EXAMPLE
292
293 Let <FF> be a 0xFF byte, and <0> be a null (0x00) byte.  Then a message
294 which prints as...
295
296 Apr 12, 1988 23:16 From Test User In Network Test> @lifesys (Life BBS)
297 Have a nice day!
298
299  might be stored as...
300 <FF><40><0>I12345<0>Pneighbor!lifesys!test_user<0>T576918988<0>    (continued)
301 -----------|Mesg ID#|--Message Path---------------|--Date------
302
303 AThe Test User<0>ONetwork Test<0>Nlifesys<0>HLife BBS<0>MHave a nice day!<0>
304 |-----Author-----|-Room name-----|-nodename-|Human Name-|--Message text-----
305
306  Weird things can happen if fields are missing, especially if you use the
307 networker.  But basically, the date, author, room, and nodename may be in any
308 order.  But the leading fields and the message text must remain in the same
309 place.  The H field looks better when it is placed immediately after the N
310 field.
311
312
313
314
315
316                             Networking
317
318 Citadel nodes network by sharing one or more rooms. Any Citadel node
319 can choose to share messages with any other Citadel node, through the sending
320 of spool files.  The sending system takes all messages it hasn't sent yet, and
321 spools them to the recieving system, which posts them in the rooms.
322
323 Complexities arise primarily from the possibility of densely connected
324 networks: one does not wish to accumulate multiple copies of a given
325 message, which can easily happen.  Nor does one want to see old messages
326 percolating indefinitely through the system.
327
328 This problem is handled by keeping track of the path a message has taken over
329 the network, like the UseNet news system does.  When a system sends out a
330 message, it adds its own name to the bang-path in the <P> field of the
331 message.  If no path field is present, it generates one.  
332    
333 With the path present, all the networker has to do to assure that it doesn't
334 send another system a message it's already received is check the <P>ath field
335 for that system's name somewhere in the bang path.  If it's present, the system
336 has already seen the message, so we don't send it.  (Note that the current
337 implementation does not allow for "loops" in the network -- if you build your
338 net this way you will see lots of duplicate messages.)
339
340 The above discussion should make the function of the fields reasonably clear:
341
342  o  Travelling messages need to carry original message-id, system of origin,
343     date of origin, author, and path with them, to keep reproduction and
344     cycling under control.
345
346 (Uncoincidentally) the format used to transmit messages for networking
347 purposes is precisely that used on disk, serialized.  The current
348 distribution includes serv_network.c, which is basically a database replicator;
349 please see network.txt on its operation and functionality (if any).
350
351
352
353                         Portability issues
354  
355  Citadel/UX is 64-bit clean, architecture-independent, and Year 2000
356 compliant.  The software should compile on any POSIX compliant system with
357 a full pthreads implementation and TCP/IP support.  In the future we may
358 try to port it to non-POSIX systems as well.
359  
360  On the client side, it's also POSIX compliant.  The client even seems to
361 build ok on non-POSIX systems with porting libraries (such as Cygwin).
362   
363
364
365  
366
367                      SUPPORTING PRIVATE MAIL
368
369    Can one have an elegant kludge?  This must come pretty close.
370  
371    Private mail is sent and recieved in the Mail> room, which otherwise
372 behaves pretty much as any other room.  To make this work, we have a
373 separate Mail> room for each user behind the scenes.  The actual room name
374 in the database looks like "0000001234.Mail" (where '1234' is the user
375 number) and it's flagged with the QR_MAILBOX flag.  The user number is
376 stripped off by the server before the name is presented to the client.  This
377 provides the ability to give each user a separate namespace for mailboxes
378 and personal rooms.
379
380    This requires a little fiddling to get things just right.  For example,
381 make_message() has to be kludged to ask for the name of the recipient
382 of the message whenever a message is entered in Mail>.  But basically
383 it works pretty well, keeping the code and user interface simple and
384 regular.
385
386
387
388                    PASSWORDS AND NAME VALIDATION
389  
390   This has changed a couple of times over the course of Citadel's history.  At
391 this point it's very simple, again due to the fact that record managers are
392 used for everything.    The user file (usersupp) is indexed using the user's
393 name, converted to all lower-case.  Searching for a user, then, is easy.  We
394 just lowercase the name we're looking for and query the database.  If no
395 match is found, it is assumed that the user does not exist.
396    
397   This makes it difficult to forge messages from an existing user.  (Fine
398 point: nonprinting characters are converted to printing characters, and
399 leading, trailing, and double blanks are deleted.)