updates
[silc.git] / doc / CodingStyle
1 Coding Style in SILC source tree
2 ================================
3
4 This document 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 MPI 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 description 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 When writing a new header it is preferred that the header file is 
274 immediately written in the ROBOdoc documentation format.  This is 
275 important when you are doing library code under lib/.  There are plenty
276 of examples of this format.  The ROBOdoc is used automatically generate
277 the Toolkit documentation.
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 supersede 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.  For example,
309           /* XXX hmm... how is this flushed? */
310
311
312 Source Files
313
314 All source files starts with header that includes the name of the author,
315 copyright notice and the copyright policy, usually part of GNU GPL licence.
316 Now, this really isn't that important but some sort of header should be in
317 all source files.
318
319 In the start of the source files should include the #include's that are
320 needed.  All library source files must include `silcincludes.h', this is
321 a must.  Client source file must include at least `clientincludes.h' and
322 server source file must include `serverincludes.h'.  Additional include's
323 may be added as well, however, system specific includes should not be
324 added directly (unless it is really a special case).  Go see any source
325 file as an example.
326
327
328 Header Files
329
330 As with source files, header files should include same file header at
331 the start of the file.
332
333 Header files are usually divided in three parts in SILC.  At the start
334 of header files should include all definitions, typedefs, structure
335 definitions etc.  After definitions should include macros and inline
336 functions if any of those exist.  After macros should include the
337 public prototypes of the functions.  Go see any header file as an example.
338
339
340 Using gotos
341 ===========
342
343 Gotos are used in the SILC code quite often.  If you know how to use
344 goto's properly then it is ok to use them for example to optimize the
345 code.  If you use goto's then use them only to make forward jumps, try
346 to avoid backward jumps at all cost.  If you don't know how to use goto's 
347 do not use them.
348
349
350 Debug Messages
351 ==============
352
353 When writing new code it is recommended that the code produces some sort
354 of debug messages.  SILC has own debug logging system that must be used
355 in the generic SILC code.  Few macros exist,
356
357         SILC_LOG_DEBUG
358         SILC_LOG_HEXDUMP
359         SILC_LOG_INFO
360         SILC_LOG_WARNING
361         SILC_LOG_ERROR
362         SILC_LOG_FATAL
363
364 When doing debugging the most used macros are SILC_LOG_DEBUG and 
365 SILC_LOG_HEXDUMP.  With first macro you can print out any sort of debug
366 messages with variable argument list, for example,
367
368         SILC_LOG_DEBUG(("Start"));
369         SILC_LOG_DEBUG(("Packet length %d", packet_len));
370
371 Note the extra parenthesis that are required for the macro so that the
372 variable argument list formatting would work correctly.
373
374 When you need to dump some data into screen you should use SILC_LOG_HEXDUMP
375 macro.  For example,
376
377         SILC_LOG_HEXDUMP(("Packet"), packet->data, packet->len);
378         SILC_LOG_HEXDUMP(("Packet, size %d", size), packet->data, packet->len);
379
380 In SILC_LOG_HEXDUMP the data to be dumped are set between the second last
381 and last parenthesis in order that the data is first and the length of the
382 data is next.  If arguments are used they are used the same way as in
383 SILC_LOG_DEBUG and the data to be dumped are set after the argument list
384 is closed with the parenthesis.
385
386
387 Memory Allocation
388 =================
389
390 Naturally, memory allocation is a big part of SILC.  However, there are
391 few things that must be noted on the issue.  SILC has defined its own
392 memory allocation functions that must be used.  System specific functions
393 must not be used directly.  There are functions like,
394
395         silc_malloc
396         silc_calloc
397         silc_realloc
398         silc_free
399
400 You should always use silc_calloc instead of silc_malloc because
401 silc_calloc automatically zeroes the allocated memory area.  This is
402 important especially with structures because generally we want that all
403 fields, by default, are zero.
404
405 So, instead of doing
406
407         SilcStruct *ptr;
408
409         ptr = silc_malloc(sizeof(*ptr));
410
411 You should do
412
413         SilcStruct *ptr
414
415         ptr = silc_calloc(1, sizeof(*ptr));
416
417
418 When freeing memory it should be zero'ed when appropriate.  All memory
419 allocations that handle sensitive data such as keys should be zero'ed
420 by memset() before freeing the memory.  Common way to do is,
421
422         memset(ptr, 'F', sizeof(*ptr));
423         silc_free(ptr);
424
425 Where 'F' indicates free'd memory if you'd ever check it with debugger.
426 Other choice is to use 0 instead of 'F'.  The pointer after freeing 
427 should be set to NULL if appropriate, ptr = NULL.
428
429 Note that some functions in the SILC library handles the zeroing of
430 the memory area automatically, like for example, silc_buffer_free.
431
432 Also note that all allocation routines assert()'s if the memory allocation
433 fails, ie. system does not have free memory.
434
435
436 Callback Programming
437 ====================
438
439 SILC uses pretty much programming convention called callback programming.
440 This is a programming style that extensively uses function pointers
441 which are usually called inside some other function.
442
443 Typical scenario is this;  You are performing some task that most likely
444 is asynchronous.  You need to be able get some structure context when
445 the operation finishes.  Most common way in this case is to pass the
446 structure context to the operation function with a callback function
447 that is called when the operation has finished.  Following code explains
448 probaly better.
449
450
451 /* Prototypes */
452 static silc_callback(void *context);
453 void silc_start();
454 void silc_async_operation_register(int fd, SilcAsyncCb callback, 
455                                    void *context);
456 void silc_async_operation(int fd, SilcAsyncCb callback, void *context);
457
458 /* Type definition of the callback function */
459 typedef (*SilcAsyncCb)(void *context);
460
461 /* Registers async operation and passes callback function and context
462    to it as arguments. */
463
464 void silc_start()
465 {
466   SilcDummyStruct *ctx;
467
468   ctx = silc_calloc(1, sizeof(*ctx));
469   ctx->fd = 30;
470
471   silc_async_operation_register(30, silc_callback, (void *)ctx);
472 }
473
474 /* The callblack function that is called from the operation function */
475
476 static void silc_callback(void *context)
477 {
478   SilcDummyStruct *ctx = (SilcDummyStruct *)context;
479
480   ctx->fd = 10;
481 }
482
483 /* Register async operation */
484
485 void silc_async_operation_register(int fd, SilcAsyncCb callback, 
486                                    void *context)
487 {
488   /* Register and return immediately */
489   silc_register_async_operation_internal(fd, callback, context);
490 }
491
492 /* Operation function that will call the callback function after it
493    has finished. */
494
495 void silc_async_operation(int fd, SilcAsyncCb callback, void *context)
496 {
497   here_this_function_does_what_ever_it_wants;
498
499   here_something_more;
500
501   /* We are finished, call the callback */
502   if (callback)
503     (*callback)(context);
504 }
505         
506
507 Now, after the registeration of the async operation in this dumb example
508 the silc_start returns immediately.  Lets say, 10 seconds later the
509 async operation is executed (it would have been better to call it just
510 timeout) by calling silc_async_operation which on the other hand will
511 call the callback function after it has finished.  The context that
512 was passed to the registeration function is now passed back to the
513 callback function.  Thus, you will get the context you wanted.  This is
514 the typical scenario where callback functions come in very handy.  This 
515 is also the best way to pass context's that are needed later without
516 making them global context's.  And as long as the context's are defined
517 as void * they can be what ever contexts making the functions, that
518 takes in the context, generic.  Like in above example, you could pass
519 what ever context to the registeration function if you'd want to.
520
521 Callback programming is also used when making generic API's of some
522 operation.  For example, if you want generic hooks to the API so that
523 something could be done while doing the operation (maybe to collect
524 statistics or something else) just get the functions accept a callback
525 function and context and call them when appropriate, then continue
526 as normally.
527
528 Callback functions has been used a lot in SILC code.  The scheduler
529 and task system implemented in core library uses extensively callback
530 functions.  Timeout's uses callbacks as well.  SILC Key Exchange protocol
531 uses callback functions too.  The callback function in SKE provides
532 packet sending without defining into the SKE code how the packets
533 should be sent thus making it generic for both client and server 
534 (and actually to any application for that matter).
535
536 There are some technical issues on callback programming that are
537 common in SILC code.
538
539         o Callback functions are usually defined as void functions
540           as the routine that calls them usually don't care about
541           what the callback function does.  Many times it doesn't
542           actually know what it does nor would it be interested to
543           know that.  It doesn't care about return values.
544
545         o Many times the callback functions are static functions
546           because they are not wanted to be called in anyway else
547           than as callback functions.
548
549         o Callback function names usually have the `_cb' or `_callback'
550           at the end of function name, eg. silc_client_cb.
551
552         o Type of callback functions should be typedef'd instead of
553           defining them directly to the function.  See above example.
554           This makes the code much cleaner.
555
556         o Callback function types has usually the suffix `Cb' or
557           ´Callback' in the type name, eg. SilcAsyncCallback.
558
559         o You must explicitly cast the void * context's to correct
560           type in the callback function.  Of course you must be careful
561           to cast them to the correct type as they are void * they 
562           could be anything.  Many times this causes problems when you
563           forget what was the type you passed to it.  Callback 
564           programming may get very complex.
565
566         o You cannot use inline functions as callback functions,
567           naturally.
568
569 Callback programming may be hard to understand from first standing if
570 you haven't done these before, and debugging them may be pain in the
571 ass sometimes.  But after the grand idea behind callback functions 
572 becomes clear they are a wonderful tool.
573
574
575 Lists
576 =====
577
578 SILC has two different list API's.  The List API and the Dynamic List API.
579 For definitions of List API see lib/silcutil/silclist.h and for Dynamic 
580 List API see lib/silcutil/silcdlist.h.  Following short example of the 
581 List API.
582
583 List API
584
585 typedef struct SilcDummyStruct {
586   int dummy;
587   void *context;
588   struct SilcDummyStruct *next;
589 } SilcDummy;
590
591 int main()
592 {
593   SilcList list;
594   SilcDummy *dummy;
595   SilcDummy *entry;
596
597   /* Initialize the list */
598   silc_list_init(list, struct SilcDummyStruct, next);
599
600   /* Allocate one list entry */ 
601   dummy = silc_calloc(1, sizeof(*dummy));
602   dummy->dummy = 100;
603   dummy->context = NULL;
604
605   /* Add the entry to the list */
606   silc_list_add(list, dummy);
607
608   /* Allocate second list entry */      
609   dummy = silc_calloc(1, sizeof(*dummy));
610   dummy->dummy = 3000;
611   dummy->context = NULL;
612
613   /* Add the entry to the list */
614   silc_list_add(list, dummy);
615         
616   /* Then traverse the list, print the values, remove from list and free
617      memory */
618   silc_list_start(list);
619   while ((entry = silc_list_get(list)) != SILC_LIST_END) {
620     fprintf(stderr, "%d\n", entry->dummy);
621
622     /* Remove from list and free memory */
623     silc_list_del(list, entry);  
624     silc_free(entry);
625   }
626
627   return 0;
628 }
629
630
631 Copyrights of the Code
632 ======================
633
634 The original code in SILC is GPL licensed.  MPI is GPL licensed as well
635 and zlib is with free license as well.  New code will be accepted to
636 the official SILC source tree if it is coded in GPL or similiar free
637 license as GPL is, and of course if it is public domain.  Code with
638 restricting licenses will not be accepted to the SILC source tree.
639 SILC is free software, open source, what ever, project and will remain
640 as such.
641
642 Also, about authoring; If you write code to SILC don't forget to add
643 yourself as author at the start of the file.  The reason for this is
644 of course that everybody should get the credits they deserve but also 
645 if problems occur we know who to blame. :)