about summary refs log tree commit diff stats
path: root/103kernel-string-equal.subx
blob: 7e1b9d6f6834aa5b4b32a14b625bc5989ea43ee9 (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
# Checking null-terminated strings.
#
# By default we create strings as arrays of bytes, and all arrays have a 4-byte
# size prefix.
#
# However, we sometimes need to deal with null-terminated strings when
# interacting with the Linux kernel. This layer implements a function for
# comparing a null-terminated 'kernel string' with a size-prefixed 'SubX
# string'.
#
# To run (from the subx directory):
#   $ ./bootstrap translate 05[0-2]*.subx -o /tmp/tmp52
#   $ ./bootstrap run /tmp/tmp52  # runs a series of tests
#   ......  # all tests pass
#
# (We can't yet run the tests when given a "test" commandline argument,
# because checking for it would require the function being tested! Breakage
# would cause tests to not run, rather than to fail as we'd like.)

== code
#   instruction                     effective address                                                   register    displacement    immediate
# . op          subop               mod             rm32          base        index         scale       r32
# . 1-3 bytes   3 bits              2 bits          3 bits        3 bits      3 bits        2 bits      2 bits      0/1/2/4 bytes   0/1/2/4 bytes

Entry:  # run all tests
    e8/call  run-tests/disp32  # 'run-tests' is a function created automatically by SubX. It calls all functions that start with 'test-'.
    # syscall(exit, Num-test-failures)
    8b/copy                         0/mod/indirect  5/rm32/.disp32            .             .           3/r32/ebx   Num-test-failures/disp32          # copy *Num-test-failures to ebx
    e8/call  syscall_exit/disp32

kernel-string-equal?:  # s: (addr kernel-string), benchmark: (addr array byte) -> result/eax: boolean
    # pseudocode:
    #   n = benchmark->size
    #   s1 = s
    #   s2 = benchmark->data
    #   i = 0
    #   while (i < n)
    #     c1 = *s1
    #     c2 = *s2
    #     if (c1 == 0) return false
    #     if (c1 != c2) return false
    #     ++s1, ++s2, ++i
    #   return *s1 == 0
    #
    # registers:
    #   i: ecx
    #   n: edx
    #   s1: edi
    #   s2: esi
    #   c1: eax
    #   c2: ebx
    #
    # . prologue
    55/push-ebp
    89/copy                         3/mod/direct    5/rm32/ebp    .           .             .           4/r32/esp   .               .                 # copy esp to ebp
    # . save registers
    51/push-ecx
    52/push-edx
    53/push-ebx
    56/push-esi
    57/push-edi
    # var s1/edi: (addr byte) = s
    8b/copy                         1/mod/*+disp8   5/rm32/ebp    .           .             .           7/r32/edi   8/disp8         .                 # copy *(ebp+8) to edi
    # var n/edx: int = benchmark->size
    8b/copy                         1/mod/*+disp8   5/rm32/ebp    .           .             .           2/r32/edx   0xc/disp8       .                 # copy *(ebp+12) to edx
    8b/copy                         0/mod/indirect  2/rm32/edx    .           .             .           2/r32/edx   .               .                 # copy *edx to edx
    # var s2/esi: (addr byte) = benchmark->data
    8b/copy                         1/mod/*+disp8   5/rm32/ebp    .           .             .           6/r32/esi   0xc/disp8       .                 # copy *(ebp+12) to esi
    81          0/subop/add         3/mod/direct    6/rm32/esi    .           .             .           .           .               4/imm32           # add to esi
    # var i/ecx: int = 0
    b9/copy-to-ecx  0/imm32/exit
    # var c1/eax: byte = 0
    b8/copy-to-eax  0/imm32
    # var c2/ebx: byte = 0
    bb/copy-to-ebx  0/imm32
$kernel-string-equal?:loop:
    # if (i >= n) break
    39/compare                      3/mod/direct    1/rm32/ecx    .           .             .           2/r32/edx   .               .                 # compare ecx with edx
    7d/jump-if->=  $kernel-string-equal?:break/disp8
    # c1 = *s1
    8a/copy-byte                    0/mod/indirect  7/rm32/edi    .           .             .           0/r32/AL    .               .                 # copy byte at *edi to AL
    # c2 = *s2
    8a/copy-byte                    0/mod/indirect  6/rm32/esi    .           .             .           3/r32/BL    .               .                 # copy byte at *esi to BL
    # if (c1 == 0) return false
    3d/compare-eax-and  0/imm32/null
    74/jump-if-=  $kernel-string-equal?:false/disp8
    # if (c1 != c2) return false
    39/compare                      3/mod/direct    0/rm32/eax    .           .             .           3/r32/ebx   .               .                 # compare eax and ebx
    75/jump-if-!=  $kernel-string-equal?:false/disp8
    # ++i
    41/increment-ecx
    # ++s1
    47/increment-edi
    # ++s2
    46/increment-esi
    eb/jump  $kernel-string-equal?:loop/disp8
$kernel-string-equal?:break:
    # return *s1 == 0
    8a/copy-byte                    0/mod/indirect  7/rm32/edi    .           .             .           0/r32/AL    .               .                 # copy byte at *edi to AL
    3d/compare-eax-and  0/imm32/null
    75/jump-if-!=  $kernel-string-equal?:false/disp8
$kernel-string-equal?:true:
    b8/copy-to-eax  1/imm32
    eb/jump  $kernel-string-equal?:end/disp8
$kernel-string-equal?:false:
    b8/copy-to-eax  0/imm32
$kernel-string-equal?:end:
    # . restore registers
    5f/pop-to-edi
    5e/pop-to-esi
    5b/pop-to-ebx
    5a/pop-to-edx
    59/pop-to-ecx
    # . epilogue
    89/copy                         3/mod/direct    4/rm32/esp    .           .             .           5/r32/ebp   .               .                 # copy ebp to esp
    5d/pop-to-ebp
    c3/return

# - tests

test-compare-null-kernel-string-with-empty-array:
    # eax = kernel-string-equal?(Null-kernel-string, "")
    # . . push args
    68/push  ""/imm32
    68/push  Null-kernel-string/imm32
    # . . call
    e8/call  kernel-string-equal?/disp32
    # . . discard args
    81          0/subop/add         3/mod/direct    4/rm32/esp    .           .             .           .           .               8/imm32           # add to esp
    # check-ints-equal(eax, 1, msg)
    # . . push args
    68/push  "F - test-compare-null-kernel-string-with-empty-array"/imm32
    68/push  1/imm32/true
    50/push-eax
    # . . call
    e8/call  check-ints-equal/disp32
    # . . discard args
    81          0/subop/add         3/mod/direct    4/rm32/esp    .           .             .           .           .               0xc/imm32         # add to esp
    c3/return

test-compare-null-kernel-string-with-non-empty-array:
    # eax = kernel-string-equal?(Null-kernel-string, "Abc")
    # . . push args
    68/push  "Abc"/imm32
    68/push  Null-kernel-string/imm32
    # . . call
    e8/call  kernel-string-equal?/disp32
    # . . discard args
    81          0/subop/add         3/mod/direct    4/rm32/esp    .           .             .           .           .               8/imm32           # add to esp
    # check-ints-equal(eax, 0, msg)
    # . . push args
    68/push  "F - test-compare-null-kernel-string-with-non-empty-array"/imm32
    68/push  0/imm32/false
    50/push-eax
    # . . call
    e8/call  check-ints-equal/disp32
    # . . discard args
    81          0/subop/add         3/mod/direct    4/rm32/esp    .           .             .           .           .               0xc/imm32         # add to esp
    c3/return

test-compare-kernel-string-with-equal-array:
    # eax = kernel-string-equal?(_test-Abc-kernel-string, "Abc")
    # . . push args
    68/push  "Abc"/imm32
    68/push  _test-Abc-kernel-string/imm32
    # . . call
    e8/call  kernel-string-equal?/disp32
    # . . discard args
    81          0/subop/add         3/mod/direct    4/rm32/esp    .           .             .           .           .               8/imm32           # add to esp
    # check-ints-equal(eax, 1, msg)
    # . . push args
    68/push  "F - test-compare-kernel-string-with-equal-array"/imm32
    68/push  1/imm32/true
    50/push-eax
    # . . call
    e8/call  check-ints-equal/disp32
    # . . discard args
    81          0/subop/add         3/mod/direct    4/rm32/esp    .           .             .           .           .               0xc/imm32         # add to esp
    c3/return

test-compare-kernel-string-with-inequal-array:
    # eax = kernel-string-equal?(_test-Abc-kernel-string, "Adc")
    # . . push args
    68/push  "Adc"/imm32
    68/push  _test-Abc-kernel-string/imm32
    # . . call
    e8/call  kernel-string-equal?/disp32
    # . . discard args
    81          0/subop/add         3/mod/direct    4/rm32/esp    .           .             .           .           .               8/imm32           # add to esp
    # check-ints-equal(eax, 0, msg)
    # . . push args
    68/push  "F - test-compare-kernel-string-with-equal-array"/imm32
    68/push  0/imm32/false
    50/push-eax
    # . . call
    e8/call  check-ints-equal/disp32
    # . . discard args
    81          0/subop/add         3/mod/direct    4/rm32/esp    .           .             .           .           .               0xc/imm32         # add to esp
    c3/return

test-compare-kernel-string-with-empty-array:
    # eax = kernel-string-equal?(_test-Abc-kernel-string, "")
    # . . push args
    68/push  ""/imm32
    68/push  _test-Abc-kernel-string/imm32
    # . . call
    e8/call  kernel-string-equal?/disp32
    # . . discard args
    81          0/subop/add         3/mod/direct    4/rm32/esp    .           .             .           .           .               8/imm32           # add to esp
    # check-ints-equal(eax, 0, msg)
    # . . push args
    68/push  "F - test-compare-kernel-string-with-equal-array"/imm32
    68/push  0/imm32/false
    50/push-eax
    # . . call
    e8/call  check-ints-equal/disp32
    # . . discard args
    81          0/subop/add         3/mod/direct    4/rm32/esp    .           .             .           .           .               0xc/imm32         # add to esp
    c3/return

test-compare-kernel-string-with-shorter-array:
    # eax = kernel-string-equal?(_test-Abc-kernel-string, "Ab")
    # . . push args
    68/push  "Ab"/imm32
    68/push  _test-Abc-kernel-string/imm32
    # . . call
    e8/call  kernel-string-equal?/disp32
    # . . discard args
    81          0/subop/add         3/mod/direct    4/rm32/esp    .           .             .           .           .               8/imm32           # add to esp
    # check-ints-equal(eax, 0, msg)
    # . . push args
    68/push  "F - test-compare-kernel-string-with-shorter-array"/imm32
    68/push  0/imm32/false
    50/push-eax
    # . . call
    e8/call  check-ints-equal/disp32
    # . . discard args
    81          0/subop/add         3/mod/direct    4/rm32/esp    .           .             .           .           .               0xc/imm32         # add to esp
    c3/return

test-compare-kernel-string-with-longer-array:
    # eax = kernel-string-equal?(_test-Abc-kernel-string, "Abcd")
    # . . push args
    68/push  "Abcd"/imm32
    68/push  _test-Abc-kernel-string/imm32
    # . . call
    e8/call  kernel-string-equal?/disp32
    # . . discard args
    81          0/subop/add         3/mod/direct    4/rm32/esp    .           .             .           .           .               8/imm32           # add to esp
    # check-ints-equal(eax, 0, msg)
    # . . push args
    68/push  "F - test-compare-kernel-string-with-longer-array"/imm32
    68/push  0/imm32/false
    50/push-eax
    # . . call
    e8/call  check-ints-equal/disp32
    # . . discard args
    81          0/subop/add         3/mod/direct    4/rm32/esp    .           .             .           .           .               0xc/imm32         # add to esp
    c3/return

== data

Null-kernel-string:  # (addr kernel-string)
    00/null

_test-Abc-kernel-string:  # (addr kernel-string)
    41/A 62/b 63/c 00/null

# . . vim:nowrap:textwidth=0
'>
03b90cf5 ^
72d96a92 ^
4d190a9c ^

3a8229bf ^
279737ba ^
4d190a9c ^
3a8229bf ^
72d96a92 ^
2bbac1c8 ^
1d44a8a3 ^
3a8229bf ^










7dfea94c ^
4d190a9c ^

279737ba ^

4d190a9c ^
72d96a92 ^
3a8229bf ^

72d96a92 ^
4d190a9c ^

279737ba ^

4d190a9c ^
366eecc1 ^
e7270cca ^

366eecc1 ^
41daf094 ^




4d190a9c ^
72d96a92 ^
4d190a9c ^

8c24a7c4 ^
4d190a9c ^
72d96a92 ^
4d190a9c ^

72d96a92 ^
e7270cca ^
41daf094 ^
4d190a9c ^


72d96a92 ^
4d190a9c ^
e7270cca ^


4d190a9c ^
0c024607 ^
279737ba ^

f5013914 ^


72d96a92 ^
f5013914 ^



72d96a92 ^
f5013914 ^




72d96a92 ^
f5013914 ^


279737ba ^

f5eab875 ^

fadf841d ^





2fe5d3e9 ^
fadf841d ^


2fe5d3e9 ^











fadf841d ^





70310bb5 ^












fadf841d ^

f5eab875 ^

ee8407f4 ^











6900d52d ^







279737ba ^
ee8407f4 ^
ae84c92d ^
0c024607 ^
3970a4d7 ^
a7c77687 ^


8b1653f7 ^






9f00ef14 ^
8b1653f7 ^
a7c77687 ^

0c024607 ^
a7c77687 ^
0c024607 ^
8b1653f7 ^
3970a4d7 ^


0c024607 ^
3970a4d7 ^
0c024607 ^
9f00ef14 ^
0c024607 ^



279737ba ^
ee8407f4 ^
ae84c92d ^

0c024607 ^



9e5b8996 ^
310d712d ^
66ae3d2b ^
0c024607 ^
ee8407f4 ^

f5013914 ^
b512f3b8 ^
0c024607 ^




4e23031c ^
72d96a92 ^
9ccb5846 ^
65022b3c ^
3a8229bf ^



3a8229bf ^

3a8229bf ^


310d712d ^
3a8229bf ^




9805b2b2 ^
310d712d generated by cgit-pink 1.4.1-2-gfad0 (git 2.36.2.497.gbbea4dcf42) at 2024-08-23 11:33:43 +0000
ping when connected' href='/danisanti/profani-tty/commit/jabber.c?id=c447e050811f41af28c60683e2fef674c8184bda'>c447e050 ^
b512f3b8 ^
c447e050 ^
b512f3b8 ^
c447e050 ^




b512f3b8 ^


02ba1daf ^
279737ba ^
ee8407f4 ^
02ba1daf ^

bcef3b1a ^




02ba1daf ^
509888c4 ^
02ba1daf ^

ecf5640f ^
02ba1daf ^
ecf5640f ^











bcef3b1a ^
02224ea7 ^



bcef3b1a ^
bcef3b1a ^
09602a6f ^
02ba1daf ^

ee8407f4 ^


















































1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488





















                                                                       
                   
                   
 
                    
 
                   

                   
                        
                      
 

                                         



                              
                                     
                               

                     
 





                                                               
 

                                                          

                                                                     
                                                      
                                                         

                                                         
                                                       
                                                         

                                                                                

                                  
 
                                  
                                             
                                            


                                           
                    
                                        
                              
 
                                       
                      
 
                                              

                                                          
 

                                                 
 

                                                
 
                                                                        
                                              
 
                            
                                                    
          
                                                      
 
                                   

 
        
                       
 
                                                          
                                                      
                                       
                                          










                                                                
     

 

                           
 
                                                    

                                                               
                                           

 

                                                                 
 
                                                     

                                                            
 




                                                                        
 
                                             

                                           
                                                      
 
                                            

                                       
                                            
                                           
                                         


                                       
                                       
                               


                     
 
 

                           


                              
                                          



                                     
                                             




                                              
                                    


                            

                                                                        

                                  





                                            
                                    


                                                               











                                                 





                                          












                                                                 

                                      

 











                                               







                                            
          
                                           
                                                        
 
                                                                        


                                          






                                                                                    
                                         
             

         
                 
     
 
                            


                                                           
 
                                               
                                                           
                                                



             
           
                                              

                                                                    



                                             
                                                  
                                           
 
                            

                                                                               
                                                                  
                                                                              




                                               
 
                                                   
                                               
                                



                                                                      

                                                          


                                                                 
                                              




                                                          
                
                                       


                                                          
         

     
 

                                          
                                                        

                                
                                              

                                   
                                         

                                                               
                              
                                               
        
                              

                                                                       
 
                                                                             
 

                                           
                    
                                   
             
                                     
 

                                                   
         

                                   



             
 

                                                                    
 



                                                      
 



                                        
 

                                           
 
                                                  
 




                                        


             
 
          
                                            

                                                        




                                                          
                                                           
                                         

                                                           
                                
   











                                                                            
                                            



                                                                          
         
     
 

             


















































                                                                      
/* 
 * jabber.c
 *
 * Copyright (C) 2012 James Booth <boothj5@gmail.com>
 * 
 * This file is part of Profanity.
 *
 * Profanity is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 *
 * Profanity is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with Profanity.  If not, see <http://www.gnu.org/licenses/>.
 *
 */

#include <string.h>
#include <stdlib.h>

#include <strophe.h>

#include "common.h"
#include "jabber.h"
#include "log.h"
#include "preferences.h"
#include "profanity.h"

#define PING_INTERVAL 120000 // 2 minutes

static struct _jabber_conn_t {
    xmpp_log_t *log;
    xmpp_ctx_t *ctx;
    xmpp_conn_t *conn;
    jabber_conn_status_t conn_status;
    jabber_presence_t presence;
    int tls_disabled;
} jabber_conn;

static log_level_t _get_log_level(xmpp_log_level_t xmpp_level);
static xmpp_log_level_t _get_xmpp_log_level();
static void _xmpp_file_logger(void * const userdata, 
    const xmpp_log_level_t level, const char * const area, 
    const char * const msg);
static xmpp_log_t * _xmpp_get_file_logger();

// XMPP event handlers
static void _connection_handler(xmpp_conn_t * const conn, 
    const xmpp_conn_event_t status, const int error, 
    xmpp_stream_error_t * const stream_error, void * const userdata);
static int _message_handler(xmpp_conn_t * const conn, 
    xmpp_stanza_t * const stanza, void * const userdata);
static int _roster_handler(xmpp_conn_t * const conn, 
    xmpp_stanza_t * const stanza, void * const userdata);
static int _presence_handler(xmpp_conn_t * const conn, 
    xmpp_stanza_t * const stanza, void * const userdata);
static int _ping_timed_handler(xmpp_conn_t * const conn, void * const userdata);

void
jabber_init(const int disable_tls)
{
    log_info("Initialising XMPP");
    jabber_conn.conn_status = JABBER_STARTED;
    jabber_conn.presence = PRESENCE_OFFLINE;
    jabber_conn.tls_disabled = disable_tls;
}

jabber_conn_status_t
jabber_connect(const char * const user, 
    const char * const passwd)
{
    log_info("Connecting as %s", user);
    xmpp_initialize();

    jabber_conn.log = _xmpp_get_file_logger();
    jabber_conn.ctx = xmpp_ctx_new(NULL, jabber_conn.log);
    jabber_conn.conn = xmpp_conn_new(jabber_conn.ctx);

    xmpp_conn_set_jid(jabber_conn.conn, user);
    xmpp_conn_set_pass(jabber_conn.conn, passwd);

    if (jabber_conn.tls_disabled)
        xmpp_conn_disable_tls(jabber_conn.conn);

    int connect_status = xmpp_connect_client(jabber_conn.conn, NULL, 0, 
        _connection_handler, jabber_conn.ctx);

    if (connect_status == 0)
        jabber_conn.conn_status = JABBER_CONNECTING;
    else  
        jabber_conn.conn_status = JABBER_DISCONNECTED;

    return jabber_conn.conn_status;
}

gboolean
jabber_disconnect(void)
{
    // if connected, send end stream and wait for response
    if (jabber_conn.conn_status == JABBER_CONNECTED) {
        log_info("Closing connection");
        xmpp_disconnect(jabber_conn.conn);
        jabber_conn.conn_status = JABBER_DISCONNECTING;
        return TRUE;

    // if disconnected dont wait just shutdown
    } else if (jabber_conn.conn_status == JABBER_DISCONNECTED) {
        log_info("No connection open");
        return FALSE;

    // any other states, just shutdown
    } else {
        return FALSE;
    }
}

void
jabber_process_events(void)
{
    if (jabber_conn.conn_status == JABBER_CONNECTED 
            || jabber_conn.conn_status == JABBER_CONNECTING
            || jabber_conn.conn_status == JABBER_DISCONNECTING)
        xmpp_run_once(jabber_conn.ctx, 10);
}

void
jabber_send(const char * const msg, const char * const recipient)
{
    char *coded_msg = str_replace(msg, "&", "&amp;");
    char *coded_msg2 = str_replace(coded_msg, "<", "&lt;");
    char *coded_msg3 = str_replace(coded_msg2, ">", "&gt;");

    xmpp_stanza_t *reply, *body, *text, *active;
    
    active = xmpp_stanza_new(jabber_conn.ctx);
    xmpp_stanza_set_name(active, "active");
    xmpp_stanza_set_ns(active, "http://jabber.org/protocol/chatstates");

    reply = xmpp_stanza_new(jabber_conn.ctx);
    xmpp_stanza_set_name(reply, "message");
    xmpp_stanza_set_type(reply, "chat");
    xmpp_stanza_set_attribute(reply, "to", recipient);

    body = xmpp_stanza_new(jabber_conn.ctx);
    xmpp_stanza_set_name(body, "body");

    text = xmpp_stanza_new(jabber_conn.ctx);
    xmpp_stanza_set_text(text, coded_msg3);
    xmpp_stanza_add_child(reply, active);
    xmpp_stanza_add_child(body, text);
    xmpp_stanza_add_child(reply, body);

    xmpp_send(jabber_conn.conn, reply);
    xmpp_stanza_release(reply);
    free(coded_msg);
    free(coded_msg2);
    free(coded_msg3);
}

void
jabber_roster_request(void)
{
    xmpp_stanza_t *iq, *query;

    iq = xmpp_stanza_new(jabber_conn.ctx);
    xmpp_stanza_set_name(iq, "iq");
    xmpp_stanza_set_type(iq, "get");
    xmpp_stanza_set_id(iq, "roster");

    query = xmpp_stanza_new(jabber_conn.ctx);
    xmpp_stanza_set_name(query, "query");
    xmpp_stanza_set_ns(query, XMPP_NS_ROSTER);

    xmpp_stanza_add_child(iq, query);
    xmpp_stanza_release(query);
    xmpp_send(jabber_conn.conn, iq);
    xmpp_stanza_release(iq);
}

void
jabber_update_presence(jabber_presence_t status, const char * const msg)
{
    jabber_conn.presence = status;

    xmpp_stanza_t *pres, *show;

    pres = xmpp_stanza_new(jabber_conn.ctx);
    xmpp_stanza_set_name(pres, "presence");
    
    if (status != PRESENCE_ONLINE) {
        show = xmpp_stanza_new(jabber_conn.ctx);
        xmpp_stanza_set_name(show, "show");
        xmpp_stanza_t *text = xmpp_stanza_new(jabber_conn.ctx);

        if (status == PRESENCE_AWAY)
            xmpp_stanza_set_text(text, "away");
        else if (status == PRESENCE_DND)
            xmpp_stanza_set_text(text, "dnd");
        else if (status == PRESENCE_CHAT)
            xmpp_stanza_set_text(text, "chat");
        else if (status == PRESENCE_XA)
            xmpp_stanza_set_text(text, "xa");
        else 
            xmpp_stanza_set_text(text, "online");

        xmpp_stanza_add_child(show, text);
        xmpp_stanza_add_child(pres, show);
        xmpp_stanza_release(text);
        xmpp_stanza_release(show);
    }

    if (msg != NULL) {
        xmpp_stanza_t *status = xmpp_stanza_new(jabber_conn.ctx);
        xmpp_stanza_set_name(status, "status");
        xmpp_stanza_t *text = xmpp_stanza_new(jabber_conn.ctx);

        xmpp_stanza_set_text(text, msg);

        xmpp_stanza_add_child(status, text);
        xmpp_stanza_add_child(pres, status);
        xmpp_stanza_release(text);
        xmpp_stanza_release(status);
    }

    xmpp_send(jabber_conn.conn, pres);
    xmpp_stanza_release(pres);
}

jabber_conn_status_t
jabber_get_connection_status(void)
{
    return (jabber_conn.conn_status);
}

const char *
jabber_get_jid(void)
{
    return xmpp_conn_get_jid(jabber_conn.conn);
}

void
jabber_free_resources(void)
{
	xmpp_conn_release(jabber_conn.conn);
	xmpp_ctx_free(jabber_conn.ctx);
	xmpp_shutdown();
}

static int
_message_handler(xmpp_conn_t * const conn, 
    xmpp_stanza_t * const stanza, void * const userdata)
{
    xmpp_stanza_t *body = xmpp_stanza_get_child_by_name(stanza, "body");

    // if no message, check for chatstates
    if (body == NULL) {

        if (prefs_get_typing()) {
            if (xmpp_stanza_get_child_by_name(stanza, "active") != NULL) {
                // active
            } else if (xmpp_stanza_get_child_by_name(stanza, "composing") != NULL) {
                // composing
                char *from = xmpp_stanza_get_attribute(stanza, "from");
                prof_handle_typing(from);
            }
        }
        
        return 1;
    }

    // message body recieved
    char *type = xmpp_stanza_get_attribute(stanza, "type");
    if(strcmp(type, "error") == 0)
        return 1;

    char *message = xmpp_stanza_get_text(body);
    char *from = xmpp_stanza_get_attribute(stanza, "from");
    prof_handle_incoming_message(from, message);

    return 1;
}

static void
_connection_handler(xmpp_conn_t * const conn, 
    const xmpp_conn_event_t status, const int error, 
    xmpp_stream_error_t * const stream_error, void * const userdata)
{
    xmpp_ctx_t *ctx = (xmpp_ctx_t *)userdata;

    if (status == XMPP_CONN_CONNECT) {
        const char *jid = xmpp_conn_get_jid(conn);
        prof_handle_login_success(jid);    

        xmpp_stanza_t* pres;
        xmpp_handler_add(conn, _message_handler, NULL, "message", NULL, ctx);
        xmpp_handler_add(conn, _presence_handler, NULL, "presence", NULL, ctx);
        xmpp_id_handler_add(conn, _roster_handler, "roster", ctx);
        xmpp_timed_handler_add(conn, _ping_timed_handler, PING_INTERVAL, ctx);

        pres = xmpp_stanza_new(ctx);
        xmpp_stanza_set_name(pres, "presence");
        xmpp_send(conn, pres);
        xmpp_stanza_release(pres);

        jabber_conn.conn_status = JABBER_CONNECTED;
        jabber_conn.presence = PRESENCE_ONLINE;
        jabber_roster_request();
    } else {
    
        // received close stream response from server after disconnect
        if (jabber_conn.conn_status == JABBER_DISCONNECTING) {
            jabber_conn.conn_status = JABBER_DISCONNECTED;
            jabber_conn.presence = PRESENCE_OFFLINE;
            
        // lost connection for unkown reason
        } else if (jabber_conn.conn_status == JABBER_CONNECTED) {
            prof_handle_lost_connection();    
            xmpp_stop(ctx);
            jabber_conn.conn_status = JABBER_DISCONNECTED;
            jabber_conn.presence = PRESENCE_OFFLINE;

        // login attempt failed
        } else {
            prof_handle_failed_login();
            xmpp_stop(ctx);
            jabber_conn.conn_status = JABBER_DISCONNECTED;
            jabber_conn.presence = PRESENCE_OFFLINE;
        }
    }
}

static int
_roster_handler(xmpp_conn_t * const conn, 
    xmpp_stanza_t * const stanza, void * const userdata)
{
    xmpp_stanza_t *query, *item;
    char *type = xmpp_stanza_get_type(stanza);
    
    if (strcmp(type, "error") == 0)
        log_error("Roster query failed");
    else {
        query = xmpp_stanza_get_child_by_name(stanza, "query");
        GSList *roster = NULL;
        item = xmpp_stanza_get_children(query);
        
        while (item != NULL) {
            const char *name = xmpp_stanza_get_attribute(item, "name");
            const char *jid = xmpp_stanza_get_attribute(item, "jid");

            jabber_roster_entry *entry = malloc(sizeof(jabber_roster_entry));

            if (name != NULL) {
                entry->name = strdup(name);
            } else {
                entry->name = NULL;
            }
            entry->jid = strdup(jid);

            roster = g_slist_append(roster, entry);
            item = xmpp_stanza_get_next(item);
        }

        prof_handle_roster(roster);
    }
    
    return 1;
}

static int
_ping_timed_handler(xmpp_conn_t * const conn, void * const userdata)
{
    if (jabber_conn.conn_status == JABBER_CONNECTED) {
        xmpp_ctx_t *ctx = (xmpp_ctx_t *)userdata;
        
        xmpp_stanza_t *iq, *ping;

        iq = xmpp_stanza_new(ctx);
        xmpp_stanza_set_name(iq, "iq");
        xmpp_stanza_set_type(iq, "get");
        xmpp_stanza_set_id(iq, "c2s1");

        ping = xmpp_stanza_new(ctx);
        xmpp_stanza_set_name(ping, "ping");

        xmpp_stanza_set_ns(ping, "urn:xmpp:ping");

        xmpp_stanza_add_child(iq, ping);
        xmpp_stanza_release(ping);
        xmpp_send(conn, iq);
        xmpp_stanza_release(iq);
    }

    return 1;
}

static int
_presence_handler(xmpp_conn_t * const conn, 
    xmpp_stanza_t * const stanza, void * const userdata)
{
    const char *jid = xmpp_conn_get_jid(jabber_conn.conn);
    char jid_cpy[strlen(jid) + 1];
    strcpy(jid_cpy, jid);
    char *short_jid = strtok(jid_cpy, "/");
    
    char *from = xmpp_stanza_get_attribute(stanza, "from");
    char *short_from = strtok(from, "/");
    char *type = xmpp_stanza_get_attribute(stanza, "type");

    char *show_str, *status_str;
   
    xmpp_stanza_t *show = xmpp_stanza_get_child_by_name(stanza, "show");
    if (show != NULL)
        show_str = xmpp_stanza_get_text(show);
    else
        show_str = NULL;

    xmpp_stanza_t *status = xmpp_stanza_get_child_by_name(stanza, "status");
    if (status != NULL)    
        status_str = xmpp_stanza_get_text(status);
    else 
        status_str = NULL;

    if (strcmp(short_jid, short_from) !=0) {
        if (type == NULL) {
            prof_handle_contact_online(short_from, show_str, status_str);
        } else {
            prof_handle_contact_offline(short_from, show_str, status_str);
        }
    }

    return 1;
}

static log_level_t
_get_log_level(xmpp_log_level_t xmpp_level)
{
    if (xmpp_level == XMPP_LEVEL_DEBUG) {
        return PROF_LEVEL_DEBUG;
    } else if (xmpp_level == XMPP_LEVEL_INFO) {
        return PROF_LEVEL_INFO;
    } else if (xmpp_level == XMPP_LEVEL_WARN) {
        return PROF_LEVEL_WARN;
    } else {
        return PROF_LEVEL_ERROR;
    }
}

static xmpp_log_level_t
_get_xmpp_log_level()
{
    log_level_t prof_level = log_get_filter();

    if (prof_level == PROF_LEVEL_DEBUG) {
        return XMPP_LEVEL_DEBUG;
    } else if (prof_level == PROF_LEVEL_INFO) {
        return XMPP_LEVEL_INFO;
    } else if (prof_level == PROF_LEVEL_WARN) {
        return XMPP_LEVEL_WARN;
    } else {
        return XMPP_LEVEL_ERROR;
    }
}

static void
_xmpp_file_logger(void * const userdata, const xmpp_log_level_t level,
    const char * const area, const char * const msg)
{
    log_level_t prof_level = _get_log_level(level);
    log_msg(prof_level, area, msg);
}

static xmpp_log_t *
_xmpp_get_file_logger()
{
    xmpp_log_level_t level = _get_xmpp_log_level();
    xmpp_log_t *file_log = malloc(sizeof(xmpp_log_t));

    file_log->handler = _xmpp_file_logger;
    file_log->userdata = &level;

    return file_log;
}