Initial revision
[crypto.git] / doc / CodingStyle
1 Coding Style in SILC source tree
2 ================================
3
4 This documents describes the coding style and coding conventions used
5 in the SILC source tree.  The purpose of the document is to describe the
6 common way to program for SILC and thus should be learned when programming
7 new code.  The document describes various conventions regarding variable
8 naming, function naming, indentation, overall appearance of a piece of
9 code and how some of the technical issues has been done in the SILC and
10 should be done in the future.
11
12
13 Naming
14 ======
15
16 Generic naming
17
18 All identifiers, whether they defines, functions or something else, with
19 execption of variables, has a common naming convention.  Usually all 
20 identifiers use `silc' prefix to indicate that the identifier is part of
21 SILC distribution.  For example, silc_server_init(), SILC_PACKET_TYPE_ERROR, 
22 etc.  As mentioned however, variables, local or global, does not use this
23 naming convention.
24
25 Lower lever routines, usually some library routines, may use their
26 own naming convention if generic API is defined over them.  The API uses
27 the common naming convention while the lower level routines uses what
28 ever they want.  For example, ciphers are implemented currently in this
29 way.  They define common SILC Cipher API but the actual implementation
30 of algorithms uses their own naming convention.  Another example is
31 the GMP math library that uses its own function naming but we have our
32 own SILC MP API over it that has been defined using common SILC naming
33 convention.
34
35
36 Variables
37
38 Variable names are always in lowercase and any mixed-case or totally
39 uppercase variable names should be avoided.  Variable names may include
40 underscore if it is necessary.  For example, `unsigned char *id_string;'.
41
42 The same name convention is used in structure field names.  All fields
43 in structures should be in lowercase.  Global variables should have some
44 sort of prefix to indicate that the variable is global.  Although, global
45 variables should be avoided if possible.
46
47 Local variable names should be as short as possible without losing
48 meaning of the name.  For example there is no reason to call loop
49 counter as `loop_counter' when `i' is commonly used instead.  Using
50 variable name `tmp' is also ok and should be used when some temporary
51 value is used.
52
53
54 #define's and Macros
55
56 All #define's should always be in uppercase to indicate that it is
57 a define, for example, `#define SILC_PACKET_TYPE_NONE 0'.  As mentioned
58 previously #define's and macros always use the `SILC' prefix.  The
59 names also uses always underscores.
60
61 Names of #define's and macros should be self explanatory.  This may
62 lead to long names but it is better than having some `#define SILC_KE1_SX'
63 which does not tell you anything.
64
65
66 Type definitions
67
68 Type definitions (typedefs) uses some what different naming convention
69 from variables and macros.  Typedefs has mixed-case names and they
70 never use underscores.  For example, `SilcSomeStruct', `SilcServerObject'.
71 Like in any other case the names should be self explanatory which may
72 lead to long names but that is not a problem.
73
74 The names should tell what the typedef is about.  If it is a typedef
75 of a structure it should tell what the structure is for in the first
76 place.  For example `SilcClientStruct', `SilcCipherObject', 
77 `SilcConfigSection´, etc.
78
79
80 Structures
81
82 Same naming convention used in typedefs applies to names of structures as
83 well.  Same as with typedef, structure names should be self explanatory
84 and should tell what the structure is made for.
85
86 Structures are used a lot in SILC.  They are used as simple structures
87 and as objects as well.  When normal structures are needed they are
88 defined as follows,
89
90         struct SilcDummyStruct {
91           unsigned char *dummy;
92         };
93
94 And used as `struct SilcDummyStruct *dummy'.  However, this is quite
95 rarely used in the SILC, instead structures are typedef'd as following
96 later.  When structure is used as object they are defined as follows,
97
98         typedef struct SilcDummyStruct {
99           unsigned char *dummy;
100           unsigned int flags;
101           void (*callback)(void *, unsigned int);
102         } SilcDummyObject;
103
104 If the SilcDummyStruct is not needed it may be omitted (which is very
105 common in SILC code), leaving,
106
107         typedef struct {
108           unsigned char *dummy;
109           unsigned int flags;
110           void (*callback)(void *, unsigned int);
111         } SilcDummyObject;
112
113 Finally, it is common that structures are typedef'd pointers as they
114 are very flexible to use,
115
116         typedef SilcDummyObject *SilcDummy;
117
118 It is common in SILC to typedef structures instead of defining name
119 for the structure.  In this case the structure may be used without
120 defining `struct' to the code, For example,
121
122         SilcDummyObject dummy_obj;
123         SilcDummyObject *dummy;
124
125 If the structure has a pointer typedef then they are defined as normal
126 variables but for real they are pointers, For example,
127
128         SilcDummy dummy;
129         dummy = silc_calloc(1, sizeof(*dummy));
130         dummy->flags = 0;
131
132 This convention is very common in SILC code and has been used consistently
133 throughout the code.  The pattern here is that all structures are named
134 as `SilcXxxStruct', all objects are named as `SilcXxxObject' and when
135 they are typedef'd pointers they are named as `SilcXxx'.
136
137
138 Functions
139
140 Function naming uses the common naming convention used in the SILC.  All
141 functions are always lowercase and they use underscores.  The name of
142 the function always starts with prefix `silc_'.  The name of the function
143 should be self explanatory which may lead to long names.  The name of
144 a function is constructed from following parts,
145
146         silc_<application>_<module>_<function>
147
148 The <application> is for example <client> or <server>, however, it is
149 always omitted (and must be omitted) when programming library code.
150
151 The <module> is the module you are programming currently.  You should
152 have a pretty good idea what you are programming and what the module
153 does.  For example, <cipher>, <config>, <command>, <packet>, etc.
154
155 The <function> is the describtion of the functionality of the function
156 you are writing.  Naturally it should be self explanatory and weird
157 short names should be avoided.  It is better to have long function
158 names than some odd name that does not tell what it is about.  Function
159 naming could be for example, <read>, <new_id>, <register>, <find_by_name>,
160 etc.
161
162 So, it is common in SILC to have function names, such as,
163
164         silc_server_packet_send
165         silc_server_packet_send_to_channel
166         silc_client_packet_process
167         silc_idcache_del_by_id
168         silc_task_unregister_by_fd
169         silc_protocol_excute_final
170         silc_buffer_alloc
171
172 When function registers something the name of the function should
173 generally be `silc_function_register' and unregistering should happen
174 with `silc_function_unregister'.  When function allocates something it
175 should be called `silc_function_alloc' and when freeing it should be
176 called `silc_function_free'.  Respectively, with init/uninit functions.
177
178 When this naming convention is used consistently it is easy to remember
179 what the name of the function is.  For example, if you need buffer it
180 is easy to figure out that the routines are most likely called 
181 `silc_buffer_*',  and if you need to allocate buffer it is most likely 
182 called `silc_buffer_alloc'.  This sort of naming makes the programming,
183 in the long run, much cleaner, simpler and faster.
184
185
186 Inline functions
187
188 SILC uses quite a bit inline functions to optimize the code.  The
189 naming of inline functions must follow same convention as any normal
190 function.  All inline functions in SILC are defined and written into
191 header files.  Inline functions must be defined in following manner
192 in the header file,
193
194 extern inline void silc_dummy_inline(unsigned int flags)
195 {
196   doing_little_dummy_things;
197 }
198
199 Because the function is defined as extern they can be included into
200 public header files.  Do not forget to define inline function as extern.
201 There are no any explicit prototype definitions for inline functions.
202
203
204 Indentation
205 ===========
206
207 SILC has been coded with Emacs so standard indentation of Emacs is used
208 in the SILC code.  The indentation is always 2 characters, not a 
209 tabulator.  If you use Emacs then this should not be a problem.  So,
210 if you code for SILC be sure to format the code to the standard way
211 used in the SILC before submitting the code.
212
213 A tip for those who think that these long function names etc are just
214 too long to type, consider using dynamic abbreviation found in Emacs.
215 With this cool feature you only have type some part of the string and
216 then use the dabbrev to find the rest of the string.  I guess, by 
217 default it is M-/ in Emacs but I have binded it into Shift-TAB so it
218 is fast to use when typing.
219
220
221 Placing Braces
222 ==============
223
224 The common fight about how the braces should be placed in the C code
225 is probably going on in the SILC code as well.  However, SILC code
226 is consistent about this.  The placing uses K&R style thus the opening
227 of the brace is put to the last on the line and the closing brace is
228 on first on its own line,
229
230         if (condition) {
231           silc_something();
232           silc_something_more();
233         }
234
235 The function's braces are as follows,
236
237         int silc_client_function()
238         {
239           return 0;
240         }
241
242 More examples,
243
244         if (condition) {
245           something;
246           silc_something_more();
247         } else {
248           something_else;
249         }
250
251         if (condition) {
252           something;
253           silc_something_more();
254         } else if (other_condition) {
255           something;
256           silc_something_more();
257         } else {
258           something_else;
259         }
260
261
262 Commenting
263 ==========
264
265 SILC code is usually pretty well commented and this should be the way
266 in the future as well.  However, the comments should not tell how the
267 code works, it should be apparent by looking at the code.  Instead the
268 commenting should tell what the function does.  All functions should
269 be commented.  If nothing more a line of comment telling what the function
270 is about helps a lot when you go back to it after six months.  Static
271 functions should be commented as well.
272
273 The commenting of functions in SILC has been made into the source files,
274 and not in the header files where the function prototypes reside.  Header
275 files usually includes structure comments, macro comments and perhaps
276 some other relevant commenting but usually not function comments.
277 It is also Ok to comment the code inside function when it is needed.
278
279 Comments should use normal C-language comments /* */ and not C++ comments.
280
281
282 General Appearance
283 ==================
284
285 The code should be clean and good to eye, although the function of it
286 must always superseed the appearance.  However, it is nice to read code
287 that looks good.  Here are some issues on general appearance.
288
289         o Use empty lines when appropriate but not too much.  There
290           should not be excess empty lines at the end of file.  However,
291           using some empty lines in the code makes the code better 
292           looking.
293
294         o The line is 79 characters long and not one character longer.
295           Longer lines must be cut in two, or three, or ...
296
297         o Use spaces very much.  Do not write things like `if(!k)',
298           instead write `if (!k)'.  Same with `for', `while', etc.
299           Spaces should be put around all binary operators like `*', 
300           `==', `+', etc.  Also, when setting a value to variable be
301           sure to set spaces around `='.  When writing argument list 
302           to a function, space should follow each of the comma in the
303           list.  However, do not use spaces with parenthesis, for 
304           example, `if ( !k )' is not accepted.
305
306         o If you are not sure about how something should be done or
307           the code you've done is not finished, it should be commented
308           with XXX plus explanation what is going on.
309
310
311 Source Files
312
313 All source files starts with header that includes the name of the author,
314 copyright notice and the copyright policy, usually part of GNU GPL licence.
315 Now, if this really isn't that important but some sort of header should
316 be in all source files.
317
318 In the start of the source files should include the #include's that are
319 needed.  All library source files must include `silcincludes.h', this is
320 a must.  Client source file must include at least `clientincludes.h' and
321 server source file must include `serverincludes.h'.  Additional include's
322 may be added as well, however, system specific includes should not be
323 added directly (unless it is really a special case).  Go see any source
324 file as an example.
325
326
327 Header Files
328
329 As with source files, header files should include same file header at
330 the start of the file.
331
332 Header files are usually divided in three parts in SILC.  At the start
333 of header files should include all definitions, typedefs, structure
334 definitions etc.  After definitions should include macros and inline
335 functions if any of those exist.  After macros should include the
336 public prototypes of the functions.  Go see any header file as an example.
337
338
339 Debug Messages
340 ==============
341
342 When writing new code it is recommended that the code produces some sort
343 of debug messages.  SILC has own debug logging system that must be used
344 in the generic SILC code.  Few macros exist,
345
346         SILC_LOG_DEBUG
347         SILC_LOG_HEXDUMP
348         SILC_LOG_INFO
349         SILC_LOG_WARNING
350         SILC_LOG_ERROR
351         SILC_LOG_FATAL
352
353 When doing debugging the most used macros are SILC_LOG_DEBUG and 
354 SILC_LOG_HEXDUMP.  With first macro you can print out any sort of debug
355 messages with variable argument list, for example,
356
357         SILC_LOG_DEBUG(("Start"));
358         SILC_LOG_DEBUG(("Packet length %d", packet_len));
359
360 Note the extra parenthesis that are required for the macro so that the
361 variable argument list formatting would work correctly.
362
363 When you need to dump some data into screen you should use SILC_LOG_HEXDUMP
364 macro.  For example,
365
366         SILC_LOG_HEXDUMP(("Packet"), packet->data, packet->len);
367         SILC_LOG_HEXDUMP(("Packet, size %d", size), packet->data, packet->len);
368
369 In SILC_LOG_HEXDUMP the data to be dumped are set between the second last
370 and last parenthesis in order that the data is first and the length of the
371 data is next.  If arguments are used they are used the same way as in
372 SILC_LOG_DEBUG and the data to be dumped are set after the argument list
373 is closed with the parenthesis.
374
375
376 Memory Allocation
377 =================
378
379 Naturally, memory allocation is a big part of SILC.  However, there are
380 few things that must be noted on the issue.  SILC has defined its own
381 memory allocation functions that must be used.  System specific functions
382 must not be used directly.  There are functions like,
383
384         silc_malloc
385         silc_calloc
386         silc_realloc
387         silc_free
388
389 You should always use silc_calloc instead of silc_malloc because
390 silc_calloc automatically zeroes the allocated memory area.  This is
391 imporant especially with structures because generally we want that all
392 fields, by default, are zero.
393
394 So, instead of doing
395
396         SilcStruct *ptr;
397
398         ptr = silc_malloc(sizeof(*ptr));
399
400 You should do
401
402         SilcStruct *ptr
403
404         ptr = silc_calloc(1, sizeof(*ptr));
405
406
407 When freeing memory it should be zero'ed when appropriate.  All memory
408 allocations that handle sensitive data such as keys should be zero'ed
409 by memset() before freeing the memory.  Common way to do is,
410
411         memset(ptr, 'F', sizeof(*ptr));
412         silc_free(ptr);
413
414 Where 'F' indicates free'd memory if you ever check it with debugger.
415 Other choice is to use 0 instead of 'F'.  The pointer after freeing 
416 should be set to NULL if appropriate, ptr = NULL.
417
418 Note that some functions in the SILC library handles the zeroing of
419 the memory area automatically, like for example, silc_buffer_free.
420
421
422 Callback Programming
423 ====================
424
425 SILC uses pretty much programming convention called callback programming.
426 This is a programming style that extensively uses function pointers
427 which are usually called inside some other function.
428
429 Typical scenario is this;  You are performing some task that most likely
430 is asynchronous.  You need to be able get some structure context when
431 the operation finishes.  Most common way in this case is to pass the
432 structure context to the operation function with a callback function
433 that is called when the operation has finished.  Following code explains
434 probaly better.
435
436
437 /* Prototypes */
438 static silc_callback(void *context);
439 void silc_start();
440 void silc_async_operation_register(int fd, SilcAsyncCb callback, 
441                                    void *context);
442 void silc_async_operation(int fd, SilcAsyncCb callback, void *context);
443
444 /* Type definition of the callback function */
445 typedef (*SilcAsyncCb)(void *context);
446
447 /* Registers async operation and passes callback function and context
448    to it as arguments. */
449
450 void silc_start()
451 {
452   SilcDummyStruct *ctx;
453
454   ctx = silc_calloc(1, sizeof(*ctx));
455   ctx->fd = 30;
456
457   silc_async_operation_register(30, silc_callback, (void *)ctx);
458 }
459
460 /* The callblack function that is called from the operation function */
461
462 static void silc_callback(void *context)
463 {
464   SilcDummyStruct *ctx = (SilcDummyStruct *)context;
465
466   ctx->fd = 10;
467 }
468
469 /* Register async operation */
470
471 void silc_async_operation_register(int fd, SilcAsyncCb callback, 
472                                    void *context)
473 {
474   /* Register and return immediately */
475   silc_register_async_operation_internal(fd, callback, context);
476 }
477
478 /* Operation function that will call the callback function after it
479    has finished. */
480
481 void silc_async_operation(int fd, SilcAsyncCb callback, void *context)
482 {
483   here_this_function_does_what_ever_it_wants;
484
485   here_something_more;
486
487   /* We are finished, call the callback */
488   if (callback)
489     (*callback)(context);
490 }
491         
492
493 Now, after the registeration of the async operation in this dumb example
494 the silc_start returns immediately.  Lets say, 10 seconds later the
495 async operation is executed (it would have been better to call it just
496 timeout) by calling silc_async_operation which on the other hand will
497 call the callback function after it has finished.  The context that
498 was passed to the registeration function is now passed back to the
499 callback function.  Thus, you will get the context you wanted.  This is
500 the typical scenario where callback functions come in very handy.  This 
501 is also the best way to pass context's that are needed later without
502 making them global context's.  And as long as the context's are defined
503 as void * they can be what ever contexts making the functions, that
504 takes in the context, generic.  Like in above example, you could pass
505 what ever context to the registeration function if you'd want to.
506
507 Callback programming is also used when making generic API's of some
508 operation.  For example, if you want generic hooks to the API so that
509 something could be done while doing the operation (maybe to collect
510 statistics or something else) just get the functions accept a callback
511 function and context and call them when appropriate, then continue
512 as normally.
513
514 Callback functions has been used a lot in SILC code.  The scheduler
515 and task system implemented in core library uses extensively callback
516 functions.  Timeout's uses callbacks as well.  SILC Key Exchange protocol
517 uses callback functions too.  The callback function in SKE provides
518 packet sending without defining into the SKE code how the packets
519 should be sent thus making it generic for both client and server 
520 (and actually to any application for that matter).
521
522 There are some technical issues on callback programming that are
523 common in SILC code.
524
525         o Callback functions are usually defined as void functions
526           as the routine that calls them usually don't care about
527           what the callback function does.  Many times it doesn't
528           actually know what it does nor would it be interested to
529           know that.  It doesn't care about return values.
530
531         o Many times the callback functions are static functions
532           because they are not wanted to be called in anyway else
533           than as callback functions.
534
535         o Callback function names usually have the `_cb' or `_callback'
536           at the end of function name, eg. silc_client_cb.
537
538         o Type of callback functions should be typedef'd instead of
539           defining them directly to the function.  See above example.
540           This makes the code much cleaner.
541
542         o Callback function types has usually the suffix `Cb' or
543           ´Callback' in the type name, eg. SilcAsyncCallback.
544
545         o You must explicitly cast the void * context's to correct
546           type in the callback function.  Of course you must be careful
547           to cast them to the correct type as they are void * they 
548           could be anything.  Many times this causes problems when you
549           forget what was the type you passed to it.  Callback 
550           programming may get very complex.
551
552         o You cannot use inline functions as callback functions,
553           naturally.
554
555 Callback programming may be hard to understand from first standing if
556 you haven't done these before, and debugging them may be pain in the
557 ass sometimes.  But after the grand idea behind callback functions 
558 becomes clear they are a wonderful tool.
559
560
561 Copyrights of the Code
562 ======================
563
564 The original code in SILC is GPL licensed.  GMP is GPL licensed as well
565 and zlib is with free license as well.  New code will be accepted to
566 the official SILC source tree if it is coded in GPL or similiar free
567 license as GPL is, and of course if it is public domain.  Code with
568 restricting licenses will not be accepted to the SILC source tree.
569 SILC is free software, open source, what ever, project and will remain
570 as such.
571
572 Also, about authoring; If you write code to SILC don't forget to add
573 yourself as author at the start of the file.  The reason for this is
574 of course that everybody should get the credits they deserve but also 
575 if problems occur we know who to blame. :)