-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmce-io.c
2259 lines (1856 loc) · 54.2 KB
/
mce-io.c
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
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/**
* @file mce-io.c
* Generic I/O functionality for the Mode Control Entity
* <p>
* Copyright © 2006-2011 Nokia Corporation and/or its subsidiary(-ies).
* Copyright (C) 2012-2019 Jolla Ltd.
* <p>
* @author David Weinehall <[email protected]>
* @author Santtu Lakkala <[email protected]>
* @author Jukka Turunen <[email protected]>
* @author Simo Piiroinen <[email protected]>
*
* mce is free software; you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License
* version 2.1 as published by the Free Software Foundation.
*
* mce 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
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with mce. If not, see <http://www.gnu.org/licenses/>.
*/
#include "mce-io.h"
#include "mce.h"
#include "mce-log.h"
#include "mce-lib.h"
#include "mce-wakelock.h"
#ifdef ENABLE_WAKELOCKS
# include "libwakelock.h"
#endif
#include <sys/timerfd.h>
#include <unistd.h>
#include <inttypes.h>
#include <string.h>
#include <errno.h>
#include <fcntl.h>
#include <glib/gstdio.h>
#ifndef TFD_TIMER_CANCELON_SET
# define TFD_TIMER_CANCELON_SET (1<<1)
#endif
/* ========================================================================= *
* CONSTANTS
* ========================================================================= */
/** Suffix used for temporary files */
#define TMP_SUFFIX ".tmp"
/* ========================================================================= *
* TYPES
* ========================================================================= */
/** I/O monitor type */
typedef enum {
IOMON_UNSET = -1, /**< I/O monitor type unset */
IOMON_STRING = 0, /**< String I/O monitor */
IOMON_CHUNK = 1, /**< Chunk I/O monitor */
} iomon_type;
/** I/O monitor structure */
struct mce_io_mon_t {
gchar *path; /**< Monitored file */
iomon_type type; /**< Monitor type */
gulong chunk_size; /**< Read-chunk size */
gboolean seekable; /**< is the I/O channel seekable */
gboolean suspended; /**< Is the I/O monitor suspended? */
GIOChannel *iochan; /**< I/O channel */
guint iowatch_id; /**< GSource ID for input */
mce_io_mon_notify_cb nofity_cb; /**< Input handling callback */
mce_io_mon_delete_cb delete_cb; /**< Iomon delete callback */
error_policy_t error_policy; /**< Error policy */
gboolean rewind_policy; /**< Rewind policy */
void *user_data; /**< Attached user data block */
mce_io_mon_free_cb user_free_cb;/**< Callback for freeing user_data */
};
/* ========================================================================= *
* STATE_DATA
* ========================================================================= */
/** List of all file monitors */
static GSList *file_monitors = NULL;
/* ========================================================================= *
* PROTOTYPES
* ========================================================================= */
// SUSPEND_DETECTION
static void io_detect_resume (void);
static gboolean mce_io_resume_timer_cb (GIOChannel *chn, GIOCondition cnd, gpointer aptr);
static bool mce_io_prime_resume_timer (void);
void mce_io_init_resume_timer (void);
void mce_io_quit_resume_timer (void);
// GLIB_IO_HELPERS
const char *mce_io_condition_repr (GIOCondition cond);
const char *mce_io_status_name (GIOStatus io_status);
// IO_MONITOR
static mce_io_mon_t *mce_io_mon_create (const char *path, mce_io_mon_delete_cb delete_cb);
static void mce_io_mon_delete (mce_io_mon_t *self);
static void mce_io_mon_probe_seekable (mce_io_mon_t *self);
static gboolean mce_io_mon_read_chunks (GIOChannel *source, GIOCondition condition, gpointer data);
static gboolean mce_io_mon_read_string (GIOChannel *source, GIOCondition condition, gpointer data);
static gboolean mce_io_mon_input_cb (GIOChannel *source, GIOCondition condition, gpointer data);
static mce_io_mon_t *mce_io_mon_register (gint fd, const gchar *path, error_policy_t error_policy, gboolean rewind_policy, mce_io_mon_notify_cb callback, mce_io_mon_delete_cb delete_cb);
mce_io_mon_t *mce_io_mon_register_string (const gint fd, const gchar *const file, error_policy_t error_policy, gboolean rewind_policy, mce_io_mon_notify_cb callback, mce_io_mon_delete_cb delete_cb);
mce_io_mon_t *mce_io_mon_register_chunk (const gint fd, const gchar *const file, error_policy_t error_policy, gboolean rewind_policy, mce_io_mon_notify_cb callback, mce_io_mon_delete_cb delete_cb, gulong chunk_size);
void mce_io_mon_unregister (mce_io_mon_t *iomon);
void mce_io_mon_unregister_list (GSList *list);
void mce_io_mon_unregister_at_path (const char *path);
void mce_io_mon_suspend (mce_io_mon_t *iomon);
void mce_io_mon_resume (mce_io_mon_t *iomon);
const gchar *mce_io_mon_get_path (const mce_io_mon_t *iomon);
int mce_io_mon_get_fd (const mce_io_mon_t *iomon);
// MISC_UTILS
guint mce_io_add_watch (int fd, bool close_on_unref, GIOCondition cnd, GIOFunc io_cb, gpointer aptr);
gboolean mce_close_file (const gchar *const file, FILE **fp);
gboolean mce_read_chunk_from_file (const gchar *const file, void **data, gssize *len, int flags);
gboolean mce_read_string_from_file (const gchar *const file, gchar **string);
gboolean mce_read_number_string_from_file (const gchar *const file, gulong *number, FILE **fp, gboolean rewind_file, gboolean close_on_exit);
gboolean mce_write_string_to_file (const gchar *const file, const gchar *const string);
void mce_close_output (output_state_t *output);
gboolean mce_write_number_string_to_file (output_state_t *output, const gulong number);
gboolean mce_write_number_string_to_file_atomic (const gchar *const file, const gulong number);
gboolean mce_are_settings_locked (void);
gboolean mce_unlock_settings (void);
static gboolean mce_io_read_all (int fd, void *buff, size_t size, size_t *pdone);
static gboolean mce_io_write_all (int fd, const void *buff, size_t size, size_t *pdone);
void *mce_io_load_file (const char *path, size_t *psize);
void *mce_io_load_file_until_eof (const char *path, size_t *psize);
gboolean mce_io_save_file (const char *path, const void *data, size_t size, mode_t mode);
gboolean mce_io_save_to_existing_file (const char *path, const void *data, size_t size);
gboolean mce_io_save_file_atomic (const char *path, const void *data, size_t size, mode_t mode, gboolean keep_backup);
gboolean mce_io_update_file_atomic (const char *path, const void *data, size_t size, mode_t mode, gboolean keep_backup);
/* ========================================================================= *
* SUSPEND_DETECTION
* ========================================================================= */
/** Detect suspend/resume cycle from CLOCK_MONOTONIC vs CLOCK_BOOTTIME
*/
static void io_detect_resume(void)
{
static int64_t prev = 0;
int64_t boot = mce_lib_get_boot_tick();
int64_t mono = mce_lib_get_mono_tick();
int64_t diff = boot - mono;
int64_t skip = diff - prev;
// small jitter can be due to scheduling too
if( skip < 100 )
goto EXIT;
prev = diff;
// no logging from the 1st time skip
if( prev == skip )
goto EXIT;
mce_log(LL_DEVEL, "time skip: assume %"PRId64".%03"PRId64"s suspend",
skip / 1000, skip % 1000);
// notify in case some timers need re-evaluating
datapipe_exec_full(&resume_detected_event_pipe, &prev);
EXIT:
return;
}
/** Timerfd we use for detecting resume
*/
static int mce_io_resume_timer_fd = -1;
/** Glib io watch for mce_io_resume_timer_fd
*/
static guint mce_io_resume_timer_id = 0;
/** Virtual wakelock used for protecting resume timer wakeups
*/
static const char mce_io_resume_timer_wakelock[] = "mce_io_resume_timer";
/** Glib io callback for mce_io_resume_timer_fd
*/
static gboolean
mce_io_resume_timer_cb(GIOChannel *chn, GIOCondition cnd, gpointer aptr)
{
(void)chn;
(void)aptr;
/* Deny suspending while handling timer wakeup */
mce_wakelock_obtain(mce_io_resume_timer_wakelock, -1);
gboolean result = G_SOURCE_REMOVE;
if( mce_io_resume_timer_fd == -1 || mce_io_resume_timer_id == 0 ) {
mce_log(LL_WARN, "stray resume timer wakeup");
goto EXIT;
}
if( cnd & ~G_IO_IN ) {
mce_log(LL_CRIT, "unexpected resume timer wakeup: %s",
mce_io_condition_repr(cnd));
goto EXIT;
}
/* Read trigger count. Expected result is ECANCELED */
uint64_t cnt = 0;
int res = read(mce_io_resume_timer_fd, &cnt, sizeof cnt);
if( res == -1 ) {
if( errno == EAGAIN || errno == EINTR ) {
/* Silentry ignore temporary errors */
}
else if( errno == ECANCELED ) {
/* The expected error */
mce_log(LL_DEBUG, "resume timer wakeup");
io_detect_resume();
if( !mce_io_prime_resume_timer() )
goto EXIT;
}
else {
/* Some unexpected error */
mce_log(LL_CRIT, "can't read resume timer: %m");
goto EXIT;
}
}
else {
/* Silentry ignore timer actually triggering */
if( !mce_io_prime_resume_timer() )
goto EXIT;
}
result = G_SOURCE_CONTINUE;
EXIT:
if( result != G_SOURCE_CONTINUE && mce_io_resume_timer_id ) {
mce_log(LL_CRIT, "disabling resume timer");
mce_io_resume_timer_id = 0;
mce_io_quit_resume_timer();
}
mce_wakelock_release(mce_io_resume_timer_wakelock);
return result;
}
/** Program resume timer fd
*/
static bool
mce_io_prime_resume_timer(void)
{
bool ack = false;
if( mce_io_resume_timer_fd == -1 )
goto EXIT;
/* Use dummy interval as we are basically only interested in
* getting ECANCELED when CLOCK_REALTIME is adjusted due to
* device resuming from suspend.
*/
struct itimerspec its = { };
int flags = TFD_TIMER_ABSTIME | TFD_TIMER_CANCELON_SET;
if( timerfd_settime(mce_io_resume_timer_fd, flags, &its, 0) == -1 ) {
mce_log(LL_WARN, "can't program resume timer: %m");
goto EXIT;
}
ack = true;
EXIT:
return ack;
}
/** Create resume timer fd
*/
void
mce_io_init_resume_timer(void)
{
bool ack = false;
/* Create realtime clock timerfd */
int clockid = CLOCK_REALTIME;
int flags = O_NONBLOCK | O_CLOEXEC;
mce_io_resume_timer_fd = timerfd_create(clockid, flags);
if( mce_io_resume_timer_fd == -1 ) {
mce_log(LL_WARN, "timerfd_create: %m");
goto EXIT;
}
/* Program dummy wakeup time */
if( !mce_io_prime_resume_timer() )
goto EXIT;
/* Add io watch for the timerfd */
mce_io_resume_timer_id = mce_io_add_watch(mce_io_resume_timer_fd,
false,
G_IO_IN,
mce_io_resume_timer_cb,
0);
if( !mce_io_resume_timer_id )
goto EXIT;
ack = true;
EXIT:
if( !ack ) {
mce_io_quit_resume_timer();
mce_log(LL_WARN, "detect resume via timerfd not in use");
}
}
/** Delete resume timer fd
*/
void
mce_io_quit_resume_timer(void)
{
if( mce_io_resume_timer_id ) {
g_source_remove(mce_io_resume_timer_id),
mce_io_resume_timer_id = 0;
}
if( mce_io_resume_timer_fd != -1 ) {
close(mce_io_resume_timer_fd),
mce_io_resume_timer_fd = -1;
}
}
/* ========================================================================= *
* GLIB_IO_HELPERS
* ========================================================================= */
/**
* Get glib io condition as human readable string
*
* @param cond Bitmap of glib io conditions
*
* @return Names of bits set, separated with " | "
*/
const char *mce_io_condition_repr(GIOCondition cond)
{
static const struct
{
GIOCondition bit;
const char *name;
} lut[] =
{
{ .bit = G_IO_IN, .name = "IN" },
{ .bit = G_IO_OUT, .name = "OUT" },
{ .bit = G_IO_PRI, .name = "PRI" },
{ .bit = G_IO_ERR, .name = "ERR" },
{ .bit = G_IO_HUP, .name = "HUP" },
{ .bit = G_IO_NVAL, .name = "NVAL" },
// sentinel
{ .bit = 0, .name = 0 }
};
static char buf[64];
char *end = buf + sizeof buf - 1;
char *pos = buf;
auto void add(const char *s);
auto void add(const char *s)
{
while( pos < end && *s ) *pos++ = *s++;
}
for( size_t i = 0; lut[i].bit; ++i ) {
if( cond & lut[i].bit ) {
cond ^= lut[i].bit;
if( pos > buf ) add("|");
add(lut[i].name);
}
}
*pos = 0;
if( cond ) {
if( pos > buf ) add("|");
snprintf(pos, end - pos, "0x%x", cond);
}
return buf;
}
/**
* Get glib io status as human readable string
*
* @param io_status as returned from g_io_channel_read_chars()
*
* @return Name of the status enum, without the common prefix
*/
const char *mce_io_status_name(GIOStatus io_status)
{
const char *status_name = "UNKNOWN";
switch (io_status) {
case G_IO_STATUS_NORMAL: status_name = "NORMAL"; break;
case G_IO_STATUS_ERROR: status_name = "ERROR"; break;
case G_IO_STATUS_EOF: status_name = "EOF"; break;
case G_IO_STATUS_AGAIN: status_name = "AGAIN"; break;
default: break; // ... just to keep static analysis happy
}
return status_name;
}
/* ========================================================================= *
* IO_MONITOR
* ========================================================================= */
/** Create I/O monitor object
*
* Allocates I/O monitor object and does all initialization that
* does not need monitoring type information.
*
* Specifically the io watch is not activated from within this
* function, it needs to be done separately.
*
* @param path File path
* @param delete_cb I/O monitor object delete notification callback
*
* @return I/O monitor object
*/
static mce_io_mon_t *mce_io_mon_create(const char *path, mce_io_mon_delete_cb delete_cb)
{
mce_io_mon_t *self = 0;
if( !path ) {
mce_log(LL_ERR, "path == NULL!");
goto EXIT;
}
if( !delete_cb ) {
mce_log(LL_ERR, "delete_cb == NULL!");
goto EXIT;
}
if( !(self = g_slice_new(mce_io_mon_t)) )
goto EXIT;
memset(self, 0, sizeof *self);
/* Fill in sane default values */
self->path = g_strdup(path);
self->type = IOMON_UNSET;
self->chunk_size = 0;
self->seekable = FALSE;
self->suspended = TRUE;
self->iochan = 0;
self->iowatch_id = 0;
self->nofity_cb = 0;
self->delete_cb = delete_cb;
self->error_policy = MCE_IO_ERROR_POLICY_WARN;
self->rewind_policy = FALSE;
self->user_data = 0;
self->user_free_cb = 0;
mce_log(LL_DEBUG, "adding monitor for: %s", self->path);
EXIT:
return self;
}
/** Delete I/O monitor object
*
* Calls delete notification callback to allow upper level
* logic to perform cleanup.
*
* Then removes io watch, closes io channel and releases
* all dynamic resources associated with the I/O monitor object.
*
* @param self I/O monitor object
*/
static void mce_io_mon_delete(mce_io_mon_t *self)
{
if( !self )
goto EXIT;
mce_log(LL_NOTICE, "removing monitor for: %s", self->path);
/* Call the about to delete callback */
if( self->delete_cb ) {
self->delete_cb(self);
}
/* Free attached user data */
if( self->user_data && self->user_free_cb )
self->user_free_cb(self->user_data);
/* Unlink from monitor list */
if( !g_slist_find(file_monitors, self) ) {
mce_log(LL_WARN, "Trying to unregister non-registered"
" file monitor");
}
else {
file_monitors = g_slist_remove(file_monitors, self);
}
/* Remove I/O watch */
mce_io_mon_suspend(self);
/* Close the I/O channel */
if( self->iochan ) {
GError *error = NULL;
GIOStatus iostatus = g_io_channel_shutdown(self->iochan,
TRUE, &error);
if( iostatus != G_IO_STATUS_NORMAL ) {
loglevel_t loglevel = LL_ERR;
/* If we get ENODEV, only log a debug message,
* since this happens for hotpluggable
* /dev/input files
*/
if( (error->code == G_IO_CHANNEL_ERROR_FAILED) &&
(errno == ENODEV) )
loglevel = LL_DEBUG;
mce_log(loglevel, "Cannot close `%s'; %s",
self->path, error->message);
}
g_clear_error(&error);
g_io_channel_unref(self->iochan);
self->iochan = 0;
}
/* Forget file path */
g_free(self->path), self->path = 0;
/* Reset to something that is likely to generate segfaults
* if it ends up used after freeing ... */
memset(self, 0xff, sizeof *self);
g_slice_free(mce_io_mon_t, self);
EXIT:
return;
}
/**
* Check if the monitored io channel is truly seekable
*
* Glib seems to be making guesses based on file type and
* gets it massively wrong for the files MCE needs to read.
*/
static void mce_io_mon_probe_seekable(mce_io_mon_t *self)
{
gboolean glib = FALSE, kernel = FALSE;
/* glib assumes ... */
if (g_io_channel_get_flags(self->iochan) & G_IO_FLAG_IS_SEEKABLE) {
glib = TRUE;
}
/* ... kernel knows */
if (lseek64(g_io_channel_unix_get_fd(self->iochan), 0, SEEK_CUR) != -1) {
kernel = TRUE;
}
/* report the difference */
if (kernel != glib) {
mce_log(LL_DEBUG, "%s: is %sseekable, while glib thinks it is %sseekable",
self->path, kernel ? "" : "NOT ", glib ? "" : "NOT ");
}
self->seekable = kernel;
}
/** Process input for chunked io monitor
*
* For use from mce_io_mon_input_cb() only.
*
* @param source The source of the activity
* @param condition The I/O condition
* @param data The iomon structure
*
* @return TRUE on success, FALSE on failure
*/
static gboolean mce_io_mon_read_chunks(GIOChannel *source,
GIOCondition condition,
gpointer data)
{
gboolean status = FALSE;
mce_io_mon_t *iomon = data;
gchar *buffer = NULL;
gsize bytes_want = 4096;
gsize bytes_have = 0;
gsize chunks_have = 0;
gsize chunks_done = 0;
GError *error = NULL;
GIOStatus io_status = G_IO_STATUS_NORMAL;
#ifdef ENABLE_WAKELOCKS
/* Since the locks on kernel side are released once all
* events are read, we must obtain the userspace lock
* before reading the available data */
wakelock_lock("mce_input_handler", -1);
#endif
/* We get input from evdev nodes at resume, handle that 1st */
io_detect_resume();
// paranoia mode: upper levels should take care of these
if( !(condition & G_IO_IN) )
goto EXIT;
if( !iomon )
goto EXIT;
/* Seek to the beginning of the file before reading if needed */
if( iomon->rewind_policy ) {
g_io_channel_seek_position(source, 0, G_SEEK_SET, &error);
if( error ) {
mce_log(LL_ERR, "%s: seek error: %s",
iomon->path, error->message);
g_clear_error(&error);
}
}
/* Adjust read size to multiples of small sized chunks,
* or size of one larger chunk */
if( iomon->chunk_size < bytes_want )
bytes_want -= bytes_want % iomon->chunk_size;
else
bytes_want = iomon->chunk_size;
/* Allocate read buffer */
buffer = g_malloc(bytes_want);
io_status = g_io_channel_read_chars(source, buffer,
bytes_want, &bytes_have, &error);
/* If the read was interrupted, ignore */
if( io_status == G_IO_STATUS_AGAIN ) {
status = TRUE;
goto EXIT;
}
if( error ) {
mce_log(LL_ERR, "Error when reading from %s: %s",
iomon->path, error->message);
g_clear_error(&error);
goto EXIT;
}
if( bytes_have % iomon->chunk_size ) {
mce_log(LL_WARN, "Incomplete chunks read from: %s",
iomon->path);
}
/* Process the data, and optionally ignore some of it */
chunks_have = bytes_have / iomon->chunk_size;
if( !chunks_have ) {
mce_log(LL_ERR, "Empty read from %s", iomon->path);
}
else {
gchar *chunk = buffer;
for( ; chunks_done < chunks_have ; chunk += iomon->chunk_size ) {
++chunks_done;
if( !iomon->nofity_cb(iomon, chunk, iomon->chunk_size) ) {
continue;
}
/* Ignore rest of the data already read */
if( !iomon->seekable )
break;
/* Try to seek to end of the file */
g_io_channel_seek_position(iomon->iochan, 0,
G_SEEK_END, &error);
if( error ) {
mce_log(LL_ERR, "Error when reading from %s: %s",
iomon->path, error->message);
g_clear_error(&error);
}
break;
}
}
mce_log(LL_INFO, "%s: status=%s, data=%ld/%ld=%ld+%ld, skipped=%ld",
iomon->path, mce_io_status_name(io_status),
(long)bytes_have, (long)iomon->chunk_size, (long)chunks_have,
(long)(bytes_have % iomon->chunk_size), (long)(chunks_have - chunks_done));
status = TRUE;
EXIT:
g_clear_error(&error);
g_free(buffer);
#ifdef ENABLE_WAKELOCKS
/* Release the lock after we're done with processing it */
wakelock_unlock("mce_input_handler");
#endif
return status;
}
/** Process input for string io monitor
*
* For use from mce_io_mon_input_cb() only.
*
* @param source The source of the activity
* @param condition The I/O condition
* @param data The iomon structure
*
* @return TRUE on success, FALSE on failure
*/
static gboolean mce_io_mon_read_string(GIOChannel *source,
GIOCondition condition,
gpointer data)
{
gboolean status = FALSE;
mce_io_mon_t *iomon = data;
gchar *str = NULL;
gsize bytes_read = 0;
GError *error = NULL;
// paranoia mode: upper levels should take care of these
if( !(condition & G_IO_IN) )
goto EXIT;
if( !iomon )
goto EXIT;
/* Seek to the beginning of the file before reading if needed */
if( iomon->rewind_policy ) {
g_io_channel_seek_position(source, 0, G_SEEK_SET, &error);
if( error ) {
mce_log(LL_ERR, "%s: seek error: %s",
iomon->path, error->message);
g_clear_error(&error);
}
}
g_io_channel_read_line(source, &str, &bytes_read, NULL, &error);
if( error ) {
mce_log(LL_ERR, "Error when reading from %s: %s",
iomon->path, error->message);
goto EXIT;
}
if( !bytes_read || !str || !*str )
mce_log(LL_ERR, "Empty read from %s",iomon->path);
else
iomon->nofity_cb(iomon, str, bytes_read);
status = TRUE;
EXIT:
g_free(str);
g_clear_error(&error);
return status;
}
/** Callback for I/O watch
*
* Handles error conditions first; then does input monitor
* type specific input processing.
*
* The I/O monitor will be disabled and deleted on errors.
* Additionally the whole process can be terminated if
* error policy requires it.
*
* @param source Unused
* @param condition The GIOCondition for the error
* @param data The iomon structure
*
* @return TRUE to keep iomon active, FALSE to disable it;
* may also exit depending on error policy for iomon
*/
static gboolean mce_io_mon_input_cb(GIOChannel *source,
GIOCondition condition,
gpointer data)
{
(void)source; // unused
mce_io_mon_t *iomon = data;
gboolean keep_going = TRUE;
gboolean terminate = FALSE;
loglevel_t loglevel = LL_DEBUG;
// sanity checks
if( !iomon ) {
mce_log(LL_ERR, "iomon == NULL!");
keep_going = FALSE;
goto EXIT;
}
// error conditions
if( condition & (G_IO_ERR | G_IO_HUP | G_IO_NVAL) ) {
mce_log(LL_ERR, "iomon '%s' got %s", iomon->path,
mce_io_condition_repr(condition));
keep_going = FALSE;
goto EXIT;
}
// input processing
if( condition & G_IO_IN ) {
switch (iomon->type) {
case IOMON_STRING:
if( !mce_io_mon_read_string(source, condition, data) ) {
mce_log(LL_WARN, "mce_io_mon_read_string failed");
}
break;
case IOMON_CHUNK:
if( !mce_io_mon_read_chunks(source, condition, data) ) {
mce_log(LL_WARN, "mce_io_mon_read_chunks failed");
}
break;
default:
case IOMON_UNSET:
mce_log(LL_WARN, "unknown iomon type");
keep_going = FALSE;
break;
}
}
EXIT:
// cancel io monitor
if( !keep_going && iomon ) {
/* Mark error watch as removed */
iomon->iowatch_id = 0;
/* Adjust actions based on error policy */
switch (iomon->error_policy) {
case MCE_IO_ERROR_POLICY_EXIT:
terminate = TRUE;
loglevel = LL_CRIT;
break;
case MCE_IO_ERROR_POLICY_WARN:
loglevel = LL_WARN;
break;
default:
case MCE_IO_ERROR_POLICY_IGNORE:
loglevel = LL_DEBUG;
break;
}
/* Write log */
mce_log(loglevel, "disabling io monitor for: %s", iomon->path);
/* Remove IO monitor */
mce_io_mon_unregister(iomon);
}
// terminate process
if( terminate ) {
mce_log(LL_CRIT, "terminating due to error policy");
mce_quit_mainloop();
}
return keep_going;
}
/* ========================================================================= *
* I/O MONITOR API
* ========================================================================= */
/**
* Register an I/O monitor; reads and returns data
*
* @param fd File Descriptor; this takes priority over file; -1 if not used
* @param file Path to the file
* @param error_policy MCE_IO_ERROR_POLICY_EXIT to exit on error,
* MCE_IO_ERROR_POLICY_WARN to warn about errors
* but ignore them,
* MCE_IO_ERROR_POLICY_IGNORE to silently ignore errors
* @param callback Function to call with result
* @return An I/O monitor pointer on success, NULL on failure
*/
static mce_io_mon_t *mce_io_mon_register(gint fd,
const gchar *path,
error_policy_t error_policy,
gboolean rewind_policy,
mce_io_mon_notify_cb callback,
mce_io_mon_delete_cb delete_cb)
{
bool success = false;
mce_io_mon_t *iomon = 0;
GError *error = NULL;
/* Sanity checks */
if( !path ) {
mce_log(LL_ERR, "path == NULL!");
goto EXIT;
}
if( !callback ) {
mce_log(LL_ERR, "callback == NULL!");
goto EXIT;
}
/* Silently ignore non-existing files */
if( fd == -1 && access(path, F_OK) == -1 )
goto EXIT;
/* Allocate monitor object */
if( !(iomon = mce_io_mon_create(path, delete_cb)) )
goto EXIT;
/* Add to monitor list */
file_monitors = g_slist_prepend(file_monitors, iomon);
/* Set custom props */
iomon->nofity_cb = callback;
iomon->error_policy = error_policy;
/* Set up io channel */
if( fd != -1 )
iomon->iochan = g_io_channel_unix_new(fd);
else
iomon->iochan = g_io_channel_new_file(path, "r", &error);
if( !iomon->iochan ) {
mce_log(LL_ERR, "Failed to open `%s'; %s", path,
error ? error->message : "unknown error");
goto EXIT;
}
/* Transfer fd ownership to io channel */
g_io_channel_set_close_on_unref(iomon->iochan, TRUE), fd = -1;
/* Glib seekability is broken, probe via syscall */
mce_io_mon_probe_seekable(iomon);
/* Set rewind policy */
if( iomon->seekable ) {
iomon->rewind_policy = rewind_policy;
} else if( rewind_policy ) {
mce_log(LL_ERR, "Attempting to set rewind policy to TRUE "
"on non-seekable I/O channel `%s'", path);
}
success = true;
EXIT:
if( fd != -1 )
close(fd);
if( !success )
mce_io_mon_delete(iomon), iomon = 0;
g_clear_error(&error);
return iomon;
}
/** Unregister an I/O monitor
*
* @param io_monitor A pointer to the I/O monitor to unregister
*/
void mce_io_mon_unregister(mce_io_mon_t *iomon)
{
mce_io_mon_delete(iomon);
}