stats: Avoid double-frees on a failed mapping
[framework/connectivity/connman.git] / src / stats.c
1 /*
2  *
3  *  Connection Manager
4  *
5  *  Copyright (C) 2010  BMW Car IT GmbH. All rights reserved.
6  *
7  *  This program is free software; you can redistribute it and/or modify
8  *  it under the terms of the GNU General Public License version 2 as
9  *  published by the Free Software Foundation.
10  *
11  *  This program is distributed in the hope that it will be useful,
12  *  but WITHOUT ANY WARRANTY; without even the implied warranty of
13  *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
14  *  GNU General Public License for more details.
15  *
16  *  You should have received a copy of the GNU General Public License
17  *  along with this program; if not, write to the Free Software
18  *  Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA  02110-1301  USA
19  *
20  */
21
22 #ifdef HAVE_CONFIG_H
23 #include <config.h>
24 #endif
25
26 #define _GNU_SOURCE
27 #include <sys/mman.h>
28 #include <sys/types.h>
29 #include <sys/stat.h>
30 #include <sys/time.h>
31 #include <fcntl.h>
32 #include <unistd.h>
33 #include <string.h>
34 #include <limits.h>
35
36 #include "connman.h"
37
38 #ifdef TEMP_FAILURE_RETRY
39 #define TFR TEMP_FAILURE_RETRY
40 #else
41 #define TFR
42 #endif
43
44 #define MAGIC 0xFA00B916
45
46 /*
47  * Statistics counters are stored into a ring buffer which is stored
48  * into a file
49  *
50  * File properties:
51  *   The ring buffer is mmap to a file
52  *   Initialy only the smallest possible amount of disk space is allocated
53  *   The files grow to the configured maximal size
54  *   The grows by _SC_PAGESIZE step size
55  *   For each service a file is created
56  *   Each file has a header where the indexes are stored
57  *
58  * Entries properties:
59  *   Each entry has a timestamp
60  *   A flag to mark if the entry is either home (0) or roaming (1) entry
61  *   The entries are fixed sized (stats_record)
62  *
63  * Ring buffer properties:
64  *   There are to indexes 'begin', 'end', 'home' and 'roaming'
65  *   'begin' points to the oldest entry
66  *   'end' points to the newest/current entry
67  *   'home' points to the current home entry
68  *   'roaming' points to the current roaming entry
69  *   If 'begin' == 'end' then the buffer is empty
70  *   If 'end' + 1 == 'begin then it's full
71  *   The ring buffer is valid in the range (begin, end]
72  *   If 'home' has the value UINT_MAX', 'home' is invalid
73  *   if 'roaming' has the value UINT_MAX', 'roaming' is invalid
74  *   'first' points to the first entry in the ring buffer
75  *   'last' points to the last entry in the ring buffer
76  *
77  * History file:
78  *   Same format as the ring buffer file
79  *   For a period of at least 2 months dayly records are keept
80  *   If older, then only a monthly record is keept
81  */
82
83
84 struct stats_file_header {
85         unsigned int magic;
86         unsigned int begin;
87         unsigned int end;
88         unsigned int home;
89         unsigned int roaming;
90 };
91
92 struct stats_record {
93         time_t ts;
94         unsigned int roaming;
95         struct connman_stats_data data;
96 };
97
98 struct stats_file {
99         int fd;
100         char *name;
101         char *addr;
102         size_t len;
103         size_t max_len;
104
105         /* cached values */
106         struct stats_record *first;
107         struct stats_record *last;
108         struct stats_record *home;
109         struct stats_record *roaming;
110
111         /* history */
112         char *history_name;
113         int account_period_offset;
114 };
115
116 struct stats_iter {
117         struct stats_file *file;
118         struct stats_record *begin;
119         struct stats_record *end;
120         struct stats_record *it;
121 };
122
123 GHashTable *stats_hash = NULL;
124
125 static struct stats_file_header *get_hdr(struct stats_file *file)
126 {
127         return (struct stats_file_header *)file->addr;
128 }
129
130 static struct stats_record *get_begin(struct stats_file *file)
131 {
132         unsigned int off = get_hdr(file)->begin;
133
134         return (struct stats_record *)(file->addr + off);
135 }
136
137 static struct stats_record *get_end(struct stats_file *file)
138 {
139         unsigned int off = get_hdr(file)->end;
140
141         return (struct stats_record *)(file->addr + off);
142 }
143
144 static struct stats_record *get_home(struct stats_file *file)
145 {
146         struct stats_file_header *hdr;
147
148         hdr = get_hdr(file);
149
150         if (hdr->home == UINT_MAX)
151                 return NULL;
152
153         return (struct stats_record *)(file->addr + hdr->home);
154 }
155
156 static struct stats_record *get_roaming(struct stats_file *file)
157 {
158         struct stats_file_header *hdr;
159
160         hdr = get_hdr(file);
161
162         if (hdr->roaming == UINT_MAX)
163                 return NULL;
164
165         return (struct stats_record *)(file->addr + hdr->roaming);
166 }
167
168 static void set_end(struct stats_file *file, struct stats_record *end)
169 {
170         struct stats_file_header *hdr;
171
172         hdr = get_hdr(file);
173         hdr->end = (char *)end - file->addr;
174 }
175
176 static void set_home(struct stats_file *file, struct stats_record *home)
177 {
178         struct stats_file_header *hdr;
179
180         hdr = get_hdr(file);
181         hdr->home = (char *)home - file->addr;
182 }
183
184 static void set_roaming(struct stats_file *file, struct stats_record *roaming)
185 {
186         struct stats_file_header *hdr;
187
188         hdr = get_hdr(file);
189         hdr->roaming = (char *)roaming - file->addr;
190 }
191
192 static struct stats_record *get_next(struct stats_file *file,
193                                         struct stats_record *cur)
194 {
195         cur++;
196
197         if (cur > file->last)
198                 cur = file->first;
199
200         return cur;
201 }
202
203 static struct stats_record *get_iterator_begin(struct stats_file *file)
204 {
205         return get_next(file, get_begin(file));
206 }
207
208 static struct stats_record *get_iterator_end(struct stats_file *file)
209 {
210         return get_next(file, get_end(file));
211 }
212
213 static void stats_free(gpointer user_data)
214 {
215         struct stats_file *file = user_data;
216
217         if (file == NULL)
218                 return;
219
220         msync(file->addr, file->len, MS_SYNC);
221
222         munmap(file->addr, file->len);
223         file->addr = NULL;
224
225         TFR(close(file->fd));
226         file->fd = -1;
227
228         if (file->history_name != NULL) {
229                 g_free(file->history_name);
230                 file->history_name = NULL;
231         }
232
233         if (file->name != NULL) {
234                 g_free(file->name);
235                 file->name = NULL;
236         }
237
238         g_free(file);
239 }
240
241 static void update_first(struct stats_file *file)
242 {
243         file->first = (struct stats_record *)
244                         (file->addr + sizeof(struct stats_file_header));
245 }
246
247 static void update_last(struct stats_file *file)
248 {
249         unsigned int max_entries;
250
251         max_entries = (file->len - sizeof(struct stats_file_header)) /
252                         sizeof(struct stats_record);
253         file->last = file->first + max_entries - 1;
254 }
255
256 static void update_home(struct stats_file *file)
257 {
258         file->home = get_home(file);
259 }
260
261 static void update_roaming(struct stats_file *file)
262 {
263         file->roaming = get_roaming(file);
264 }
265
266 static void stats_file_update_cache(struct stats_file *file)
267 {
268         update_first(file);
269         update_last(file);
270         update_home(file);
271         update_roaming(file);
272 }
273
274 static int stats_file_remap(struct stats_file *file, size_t size)
275 {
276         size_t page_size, new_size;
277         void *addr;
278         int err;
279
280         DBG("file %p size %u addr %p len %u", file, size, file->addr,
281                 file->len);
282
283         page_size = sysconf(_SC_PAGESIZE);
284         new_size = (size + page_size - 1) & ~(page_size - 1);
285
286         err = ftruncate(file->fd, new_size);
287         if (err < 0) {
288                 connman_error("ftrunctate error %s for %s",
289                                 strerror(errno), file->name);
290                 return -errno;
291         }
292
293         if (file->addr == NULL) {
294                 /*
295                  * Though the buffer is not shared between processes, we still
296                  * have to take MAP_SHARED because MAP_PRIVATE does not guarantee
297                  * that writes will hit the file eventually. For more details
298                  * please read the mmap man pages.
299                  */
300                 addr = mmap(NULL, new_size, PROT_READ | PROT_WRITE,
301                                 MAP_SHARED, file->fd, 0);
302         } else {
303                 addr = mremap(file->addr, file->len, new_size, MREMAP_MAYMOVE);
304         }
305
306         if (addr == MAP_FAILED) {
307                 connman_error("mmap error %s for %s",
308                                 strerror(errno), file->name);
309                 return -errno;
310         }
311
312         file->addr = addr;
313         file->len = new_size;
314
315         stats_file_update_cache(file);
316
317         return 0;
318 }
319
320 static int stats_open(struct stats_file *file,
321                         const char *name)
322 {
323         DBG("file %p name %s", file, name);
324
325         file->name = g_strdup(name);
326
327         file->fd = TFR(open(file->name, O_RDWR | O_CREAT, 0644));
328         if (file->fd < 0) {
329                 connman_error("open error %s for %s",
330                                 strerror(errno), file->name);
331                 g_free(file->name);
332                 file->name = NULL;
333                 return -errno;
334         }
335
336         return 0;
337 }
338
339 static int stats_open_temp(struct stats_file *file)
340 {
341         file->name = g_strdup_printf("%s/stats/stats.XXXXXX.tmp",
342                                         STORAGEDIR);
343         file->fd = g_mkstemp_full(file->name, O_RDWR | O_CREAT, 0644);
344         if (file->fd < 0) {
345                 connman_error("create tempory file error %s for %s",
346                                 strerror(errno), file->name);
347                 g_free(file->name);
348                 file->name = NULL;
349                 return -errno;
350         }
351
352         return 0;
353 }
354
355 static int stats_file_setup(struct stats_file *file)
356 {
357         struct stats_file_header *hdr;
358         struct stat st;
359         size_t size = 0;
360         int err;
361
362         DBG("file %p fd %d name %s", file, file->fd, file->name);
363
364         err = fstat(file->fd, &st);
365         if (err < 0) {
366                 connman_error("fstat error %s for %s\n",
367                         strerror(errno), file->name);
368
369                 TFR(close(file->fd));
370                 g_free(file->name);
371                 file->name = NULL;
372
373                 return -errno;
374         }
375
376         size = (size_t)st.st_size;
377         file->max_len = STATS_MAX_FILE_SIZE;
378
379         if (size < (size_t)sysconf(_SC_PAGESIZE))
380                 size = sysconf(_SC_PAGESIZE);
381
382         err = stats_file_remap(file, size);
383         if (err < 0) {
384                 TFR(close(file->fd));
385                 g_free(file->name);
386                 file->name = NULL;
387
388                 return err;
389         }
390
391         hdr = get_hdr(file);
392
393         if (hdr->magic != MAGIC ||
394                         hdr->begin < sizeof(struct stats_file_header) ||
395                         hdr->end < sizeof(struct stats_file_header) ||
396                         hdr->home < sizeof(struct stats_file_header) ||
397                         hdr->roaming < sizeof(struct stats_file_header) ||
398                         hdr->begin > file->len ||
399                         hdr->end > file->len) {
400                 hdr->magic = MAGIC;
401                 hdr->begin = sizeof(struct stats_file_header);
402                 hdr->end = sizeof(struct stats_file_header);
403                 hdr->home = UINT_MAX;
404                 hdr->roaming = UINT_MAX;
405
406                 stats_file_update_cache(file);
407         }
408
409         return 0;
410 }
411
412
413 static struct stats_record *get_next_record(struct stats_iter *iter)
414 {
415         if (iter->it != iter->end) {
416                 struct stats_record *tmp;
417
418                 tmp = iter->it;
419                 iter->it = get_next(iter->file, iter->it);
420
421                 return tmp;
422         }
423
424         return NULL;
425 }
426
427 static int append_record(struct stats_file *file,
428                                 struct stats_record *rec)
429 {
430         struct stats_record *cur, *next;
431         int err;
432
433         if (file->last == get_end(file)) {
434                 err = stats_file_remap(file, file->len +
435                                         sysconf(_SC_PAGESIZE));
436                 if (err < 0)
437                         return err;
438
439                 stats_file_update_cache(file);
440         }
441
442         cur = get_end(file);
443         next = get_next(file, cur);
444
445         memcpy(next, rec, sizeof(struct stats_record));
446
447         set_end(file, next);
448
449         return 0;
450 }
451
452 static struct stats_record *process_file(struct stats_iter *iter,
453                                         struct stats_file *temp_file,
454                                         struct stats_record *cur,
455                                         GDate *date_change_step_size,
456                                         int account_period_offset)
457 {
458         struct stats_record *home, *roaming;
459         struct stats_record *next;
460
461         home = NULL;
462         roaming = NULL;
463
464         if (cur == NULL)
465                 cur = get_next_record(iter);
466         next = get_next_record(iter);
467
468         while (next != NULL) {
469                 GDate date_cur;
470                 GDate date_next;
471                 int append;
472
473                 append = FALSE;
474
475                 if (cur->roaming == TRUE)
476                         roaming = cur;
477                 else
478                         home = cur;
479
480                 g_date_set_time_t(&date_cur, cur->ts);
481                 g_date_set_time_t(&date_next, next->ts);
482
483                 if (g_date_compare(&date_cur, date_change_step_size) < 0) {
484                         /* month period size */
485                         GDateDay day_cur, day_next;
486                         GDateMonth month_cur, month_next;
487
488                         month_cur = g_date_get_month(&date_cur);
489                         month_next = g_date_get_month(&date_next);
490
491                         day_cur = g_date_get_day(&date_cur);
492                         day_next = g_date_get_day(&date_next);
493
494                         if (day_cur == day_next && month_cur != month_next) {
495                                 append = TRUE;
496                         } else if (day_cur < account_period_offset &&
497                                         day_next >= account_period_offset) {
498                                 append = TRUE;
499                         }
500                 } else {
501                         /* day period size */
502                         if (g_date_days_between(&date_cur, &date_next) > 0)
503                                 append = TRUE;
504                 }
505
506                 if (append == TRUE) {
507                         if (home != NULL) {
508                                 append_record(temp_file, home);
509                                 home = NULL;
510                         }
511
512                         if (roaming != NULL) {
513                                 append_record(temp_file, roaming);
514                                 roaming = NULL;
515                         }
516                 }
517
518                 cur = next;
519                 next = get_next_record(iter);
520         }
521
522         return cur;
523 }
524
525 static int summarize(struct stats_file *data_file,
526                         struct stats_file *history_file,
527                         struct stats_file *temp_file)
528 {
529         struct stats_iter data_iter;
530         struct stats_iter history_iter;
531         struct stats_record *cur, *next;
532
533         GDate today, date_change_step_size;
534
535         /*
536          * First calculate the date when switch from monthly
537          * accounting period size to daily size
538          */
539         g_date_set_time_t(&today, time(NULL));
540
541         date_change_step_size = today;
542         if (g_date_get_day(&today) - data_file->account_period_offset >= 0)
543                 g_date_subtract_months(&date_change_step_size, 2);
544         else
545                 g_date_subtract_months(&date_change_step_size, 3);
546
547         g_date_set_day(&date_change_step_size,
548                         data_file->account_period_offset);
549
550
551         /* Now process history file */
552         cur = NULL;
553
554         if (history_file != NULL) {
555                 history_iter.file = history_file;
556                 history_iter.begin = get_iterator_begin(history_iter.file);
557                 history_iter.end = get_iterator_end(history_iter.file);
558                 history_iter.it = history_iter.begin;
559
560                 cur = process_file(&history_iter, temp_file, NULL,
561                                         &date_change_step_size,
562                                         data_file->account_period_offset);
563         }
564
565         data_iter.file = data_file;
566         data_iter.begin = get_iterator_begin(data_iter.file);
567         data_iter.end = get_iterator_end(data_iter.file);
568         data_iter.it = data_iter.begin;
569
570         /*
571          * Ensure date_file records are newer than the history_file
572          * record
573          */
574         if (cur != NULL) {
575                 next = get_next_record(&data_iter);
576                 while (next != NULL && cur->ts > next->ts)
577                         next = get_next_record(&data_iter);
578         }
579
580         /* And finally process the new data records */
581         cur = process_file(&data_iter, temp_file, cur,
582                                 &date_change_step_size,
583                                 data_file->account_period_offset);
584
585         if (cur != NULL)
586                 append_record(temp_file, cur);
587
588         return 0;
589 }
590
591 static void stats_file_unmap(struct stats_file *file)
592 {
593         msync(file->addr, file->len, MS_SYNC);
594         munmap(file->addr, file->len);
595         file->addr = NULL;
596 }
597
598 static void stats_file_cleanup(struct stats_file *file)
599 {
600         file->fd = -1;
601         g_free(file->name);
602         file->name = NULL;
603 }
604
605 static int stats_file_close_swap(struct stats_file *history_file,
606                                         struct stats_file *temp_file)
607 {
608         int err;
609
610         stats_file_unmap(history_file);
611         stats_file_unmap(temp_file);
612
613         TFR(close(temp_file->fd));
614
615         unlink(history_file->name);
616
617         err = link(temp_file->name, history_file->name);
618
619         unlink(temp_file->name);
620
621         TFR(close(history_file->fd));
622
623         stats_file_cleanup(history_file);
624         stats_file_cleanup(temp_file);
625
626         return err;
627 }
628
629 static int stats_file_history_update(struct stats_file *data_file)
630 {
631         struct stats_file _history_file, *history_file;
632         struct stats_file _temp_file, *temp_file;
633         int err;
634
635         history_file = &_history_file;
636         temp_file = &_temp_file;
637
638         bzero(history_file, sizeof(struct stats_file));
639         bzero(temp_file, sizeof(struct stats_file));
640
641         err = stats_open(history_file, data_file->history_name);
642         if (err < 0)
643                 return err;
644         stats_file_setup(history_file);
645
646         err = stats_open_temp(temp_file);
647         if (err < 0) {
648                 stats_free(history_file);
649                 return err;
650         }
651         stats_file_setup(temp_file);
652
653         summarize(data_file, history_file, temp_file);
654
655         err = stats_file_close_swap(history_file, temp_file);
656
657         return err;
658 }
659
660 int __connman_stats_service_register(struct connman_service *service)
661 {
662         struct stats_file *file;
663         char *name;
664         int err;
665
666         DBG("service %p", service);
667
668         file = g_hash_table_lookup(stats_hash, service);
669         if (file == NULL) {
670                 file = g_try_new0(struct stats_file, 1);
671                 if (file == NULL)
672                         return -ENOMEM;
673
674                 g_hash_table_insert(stats_hash, service, file);
675         } else {
676                 return -EALREADY;
677         }
678
679         name = g_strdup_printf("%s/stats/%s.data", STORAGEDIR,
680                                 __connman_service_get_ident(service));
681         file->history_name = g_strdup_printf("%s/stats/%s.history", STORAGEDIR,
682                                 __connman_service_get_ident(service));
683
684         /* TODO: Use a global config file instead of hard coded value. */
685         file->account_period_offset = 1;
686
687         err = stats_open(file, name);
688         g_free(name);
689         if (err < 0)
690                 goto err;
691
692         err = stats_file_setup(file);
693         if (err < 0)
694                 goto err;
695
696         return 0;
697
698 err:
699         g_hash_table_remove(stats_hash, service);
700
701         return err;
702 }
703
704 void __connman_stats_service_unregister(struct connman_service *service)
705 {
706         DBG("service %p", service);
707
708         g_hash_table_remove(stats_hash, service);
709 }
710
711 int  __connman_stats_update(struct connman_service *service,
712                                 connman_bool_t roaming,
713                                 struct connman_stats_data *data)
714 {
715         struct stats_file *file;
716         struct stats_record *next;
717         int err;
718
719         file = g_hash_table_lookup(stats_hash, service);
720         if (file == NULL)
721                 return -EEXIST;
722
723         if (file->len < file->max_len &&
724                         file->last == get_end(file)) {
725                 DBG("grow file %s", file->name);
726
727                 err = stats_file_remap(file, file->len + sysconf(_SC_PAGESIZE));
728                 if (err < 0)
729                         return err;
730         }
731
732         next = get_next(file, get_end(file));
733
734         if (next == get_begin(file)) {
735                 DBG("ring buffer is full, update history file");
736
737                 if (stats_file_history_update(file) < 0) {
738                         connman_warn("history file update failed %s",
739                                         file->history_name);
740                 }
741         }
742
743         next->ts = time(NULL);
744         next->roaming = roaming;
745         memcpy(&next->data, data, sizeof(struct connman_stats_data));
746
747         if (roaming != TRUE)
748                 set_home(file, next);
749         else
750                 set_roaming(file, next);
751
752         set_end(file, next);
753
754         return 0;
755 }
756
757 int __connman_stats_get(struct connman_service *service,
758                                 connman_bool_t roaming,
759                                 struct connman_stats_data *data)
760 {
761         struct stats_file *file;
762         struct stats_record *rec;
763
764         file = g_hash_table_lookup(stats_hash, service);
765         if (file == NULL)
766                 return -EEXIST;
767
768         if (roaming != TRUE)
769                 rec = file->home;
770         else
771                 rec = file->roaming;
772
773         if (rec != NULL) {
774                 memcpy(data, &rec->data,
775                         sizeof(struct connman_stats_data));
776         }
777
778         return 0;
779 }
780
781 int __connman_stats_init(void)
782 {
783         DBG("");
784
785         stats_hash = g_hash_table_new_full(g_direct_hash, g_direct_equal,
786                                                         NULL, stats_free);
787
788         return 0;
789 }
790
791 void __connman_stats_cleanup(void)
792 {
793         DBG("");
794
795         g_hash_table_destroy(stats_hash);
796         stats_hash = NULL;
797 }