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