conf.go 8.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401
  1. // conf.go - Functions for pacman.conf parsing.
  2. //
  3. // Copyright (c) 2013 The go-alpm Authors
  4. //
  5. // MIT Licensed. See LICENSE for details.
  6. package alpm
  7. import (
  8. "bufio"
  9. "bytes"
  10. "fmt"
  11. "io"
  12. "os"
  13. "reflect"
  14. "strconv"
  15. "strings"
  16. "syscall"
  17. )
  18. type PacmanOption uint
  19. const (
  20. ConfUseSyslog PacmanOption = 1 << iota
  21. ConfColor
  22. ConfTotalDownload
  23. ConfCheckSpace
  24. ConfVerbosePkgLists
  25. ConfILoveCandy
  26. )
  27. var optionsMap = map[string]PacmanOption{
  28. "UseSyslog": ConfUseSyslog,
  29. "Color": ConfColor,
  30. "TotalDownload": ConfTotalDownload,
  31. "CheckSpace": ConfCheckSpace,
  32. "VerbosePkgLists": ConfVerbosePkgLists,
  33. "ILoveCandy": ConfILoveCandy,
  34. }
  35. // PacmanConfig is a type for holding pacman options parsed from pacman
  36. // configuration data passed to ParseConfig.
  37. type PacmanConfig struct {
  38. RootDir string
  39. DBPath string
  40. CacheDir []string
  41. HookDir []string
  42. GPGDir string
  43. LogFile string
  44. HoldPkg []string
  45. IgnorePkg []string
  46. IgnoreGroup []string
  47. Include []string
  48. Architecture string
  49. XferCommand string
  50. NoUpgrade []string
  51. NoExtract []string
  52. CleanMethod []string
  53. SigLevel SigLevel
  54. LocalFileSigLevel SigLevel
  55. RemoteFileSigLevel SigLevel
  56. UseDelta float64
  57. Options PacmanOption
  58. Repos []RepoConfig
  59. }
  60. // RepoConfig is a type that stores the signature level of a repository
  61. // specified in the pacman config file.
  62. type RepoConfig struct {
  63. Name string
  64. SigLevel SigLevel
  65. Servers []string
  66. }
  67. // Constants for pacman configuration parsing
  68. const (
  69. tokenSection = iota
  70. tokenKey
  71. tokenComment
  72. )
  73. type iniToken struct {
  74. Type uint
  75. Name string
  76. Values []string
  77. }
  78. type confReader struct {
  79. *bufio.Reader
  80. Lineno uint
  81. }
  82. // newConfReader reads from the io.Reader if it is buffered and returns a
  83. // confReader containing the number of bytes read and 0 for the first line. If
  84. // r is not a buffered reader, a new buffered reader is created using r as its
  85. // input and returned.
  86. func newConfReader(r io.Reader) confReader {
  87. if buf, ok := r.(*bufio.Reader); ok {
  88. return confReader{buf, 0}
  89. }
  90. buf := bufio.NewReader(r)
  91. return confReader{buf, 0}
  92. }
  93. func (rdr *confReader) ParseLine() (tok iniToken, err error) {
  94. line, overflow, err := rdr.ReadLine()
  95. switch {
  96. case err != nil:
  97. return
  98. case overflow:
  99. err = fmt.Errorf("line %d too long", rdr.Lineno)
  100. return
  101. }
  102. rdr.Lineno++
  103. line = bytes.TrimSpace(line)
  104. if len(line) == 0 {
  105. tok.Type = tokenComment
  106. return
  107. }
  108. switch line[0] {
  109. case '#':
  110. tok.Type = tokenComment
  111. return
  112. case '[':
  113. closing := bytes.IndexByte(line, ']')
  114. if closing < 0 {
  115. err = fmt.Errorf("missing ']' is section name at line %d", rdr.Lineno)
  116. return
  117. }
  118. tok.Name = string(line[1:closing])
  119. if closing+1 < len(line) {
  120. err = fmt.Errorf("trailing characters %q after section name %s",
  121. line[closing+1:], tok.Name)
  122. return
  123. }
  124. return
  125. default:
  126. tok.Type = tokenKey
  127. if idx := bytes.IndexByte(line, '='); idx >= 0 {
  128. optname := bytes.TrimSpace(line[:idx])
  129. values := bytes.Split(line[idx+1:], []byte{' '})
  130. tok.Name = string(optname)
  131. tok.Values = make([]string, 0, len(values))
  132. for _, word := range values {
  133. word = bytes.TrimSpace(word)
  134. if len(word) > 0 {
  135. tok.Values = append(tok.Values, string(word))
  136. }
  137. }
  138. } else {
  139. // boolean option
  140. tok.Name = string(line)
  141. tok.Values = nil
  142. }
  143. return
  144. }
  145. }
  146. func ParseConfig(r io.Reader) (conf PacmanConfig, err error) {
  147. rdr := newConfReader(r)
  148. rdrStack := []confReader{rdr}
  149. conf.SetDefaults()
  150. confReflect := reflect.ValueOf(&conf).Elem()
  151. var currentSection string
  152. var curRepo *RepoConfig
  153. lineloop:
  154. for {
  155. line, err := rdr.ParseLine()
  156. // fmt.Printf("%+v\n", line)
  157. switch err {
  158. case io.EOF:
  159. // pop reader stack.
  160. l := len(rdrStack)
  161. if l == 1 {
  162. break lineloop
  163. }
  164. rdr = rdrStack[l-2]
  165. rdrStack = rdrStack[:l-1]
  166. default:
  167. break lineloop
  168. case nil:
  169. // Ok.
  170. }
  171. switch line.Type {
  172. case tokenComment:
  173. case tokenSection:
  174. currentSection = line.Name
  175. if currentSection != "options" {
  176. conf.Repos = append(conf.Repos, RepoConfig{})
  177. curRepo = &conf.Repos[len(conf.Repos)-1]
  178. curRepo.Name = line.Name
  179. }
  180. case tokenKey:
  181. switch line.Name {
  182. case "SigLevel":
  183. // TODO: implement SigLevel parsing.
  184. continue lineloop
  185. case "Server":
  186. curRepo.Servers = append(curRepo.Servers, line.Values...)
  187. continue lineloop
  188. case "Include":
  189. conf.Include = append(conf.Include, line.Values[0])
  190. f, err := os.Open(line.Values[0])
  191. if err != nil {
  192. err = fmt.Errorf("error while processing Include directive at line %d: %s",
  193. rdr.Lineno, err)
  194. break lineloop
  195. }
  196. rdr = newConfReader(f)
  197. rdrStack = append(rdrStack, rdr)
  198. continue lineloop
  199. case "UseDelta":
  200. if len(line.Values) > 0 {
  201. deltaRatio, err := strconv.ParseFloat(line.Values[0], 64)
  202. if err != nil {
  203. break lineloop
  204. }
  205. conf.UseDelta = deltaRatio
  206. }
  207. continue lineloop
  208. }
  209. if currentSection != "options" {
  210. err = fmt.Errorf("option %s outside of [options] section, at line %d",
  211. line.Name, rdr.Lineno)
  212. break lineloop
  213. }
  214. // main options.
  215. if opt, ok := optionsMap[line.Name]; ok {
  216. // boolean option.
  217. conf.Options |= opt
  218. } else {
  219. // key-value option.
  220. fld := confReflect.FieldByName(line.Name)
  221. if !fld.IsValid() || !fld.CanAddr() {
  222. _ = fmt.Errorf("unknown option at line %d: %s", rdr.Lineno, line.Name)
  223. continue
  224. }
  225. switch fieldP := fld.Addr().Interface().(type) {
  226. case *string:
  227. // single valued option.
  228. *fieldP = strings.Join(line.Values, " ")
  229. case *[]string:
  230. //many valued option.
  231. *fieldP = append(*fieldP, line.Values...)
  232. }
  233. }
  234. }
  235. }
  236. if len(conf.CleanMethod) == 0 {
  237. conf.CleanMethod = []string{"KeepInstalled"}
  238. }
  239. if len(conf.CacheDir) == 0 {
  240. conf.CacheDir = []string{"/var/cache/pacman/pkg/"} //should only be set if the config does not specify this
  241. }
  242. return conf, err
  243. }
  244. func (conf *PacmanConfig) SetDefaults() {
  245. conf.RootDir = "/"
  246. conf.DBPath = "/var/lib/pacman"
  247. conf.DBPath = "/var/lib/pacman/"
  248. conf.HookDir = []string{"/etc/pacman.d/hooks/"} //should be added to whatever the config states
  249. conf.GPGDir = "/etc/pacman.d/gnupg/"
  250. conf.LogFile = "/var/log/pacman.log"
  251. conf.UseDelta = 0.7
  252. conf.SigLevel = SigPackage | SigPackageOptional | SigDatabase | SigDatabaseOptional
  253. conf.LocalFileSigLevel = SigUseDefault
  254. conf.RemoteFileSigLevel = SigUseDefault
  255. }
  256. func getArch() (string, error) {
  257. var uname syscall.Utsname
  258. err := syscall.Uname(&uname)
  259. if err != nil {
  260. return "", err
  261. }
  262. var arch [65]byte
  263. for i, c := range uname.Machine {
  264. if c == 0 {
  265. return string(arch[:i]), nil
  266. }
  267. arch[i] = byte(c)
  268. }
  269. return string(arch[:]), nil
  270. }
  271. func (conf *PacmanConfig) CreateHandle() (*Handle, error) {
  272. h, err := Init(conf.RootDir, conf.DBPath)
  273. if err != nil {
  274. return nil, err
  275. }
  276. if conf.Architecture == "auto" {
  277. conf.Architecture, err = getArch()
  278. if err != nil {
  279. return nil, fmt.Errorf("architecture is 'auto' but couldn't uname()")
  280. }
  281. }
  282. for _, repoconf := range conf.Repos {
  283. // TODO: set SigLevel
  284. db, err := h.RegisterSyncDb(repoconf.Name, 0)
  285. if err == nil {
  286. for i, addr := range repoconf.Servers {
  287. addr = strings.Replace(addr, "$repo", repoconf.Name, -1)
  288. addr = strings.Replace(addr, "$arch", conf.Architecture, -1)
  289. repoconf.Servers[i] = addr
  290. }
  291. db.SetServers(repoconf.Servers)
  292. }
  293. }
  294. err = h.SetCacheDirs(conf.CacheDir...)
  295. if err != nil {
  296. return nil, err
  297. }
  298. // add hook directories 1-by-1 to avoid overwriting the system directory
  299. for _, dir := range conf.HookDir {
  300. err = h.AddHookDir(dir)
  301. if err != nil {
  302. return nil, err
  303. }
  304. }
  305. err = h.SetGPGDir(conf.GPGDir)
  306. if err != nil {
  307. return nil, err
  308. }
  309. err = h.SetLogFile(conf.LogFile)
  310. if err != nil {
  311. return nil, err
  312. }
  313. err = h.SetIgnorePkgs(conf.IgnorePkg...)
  314. if err != nil {
  315. return nil, err
  316. }
  317. err = h.SetIgnoreGroups(conf.IgnoreGroup...)
  318. if err != nil {
  319. return nil, err
  320. }
  321. err = h.SetArch(conf.Architecture)
  322. if err != nil {
  323. return nil, err
  324. }
  325. h.SetNoUpgrades(conf.NoUpgrade...)
  326. if err != nil {
  327. return nil, err
  328. }
  329. h.SetNoExtracts(conf.NoExtract...)
  330. if err != nil {
  331. return nil, err
  332. }
  333. err = h.SetDefaultSigLevel(conf.SigLevel)
  334. if err != nil {
  335. return nil, err
  336. }
  337. err = h.SetLocalFileSigLevel(conf.LocalFileSigLevel)
  338. if err != nil {
  339. return nil, err
  340. }
  341. err = h.SetRemoteFileSigLevel(conf.RemoteFileSigLevel)
  342. if err != nil {
  343. return nil, err
  344. }
  345. err = h.SetDeltaRatio(conf.UseDelta)
  346. if err != nil {
  347. return nil, err
  348. }
  349. err = h.SetUseSyslog(conf.Options&ConfUseSyslog > 0)
  350. if err != nil {
  351. return nil, err
  352. }
  353. err = h.SetCheckSpace(conf.Options&ConfCheckSpace > 0)
  354. if err != nil {
  355. return nil, err
  356. }
  357. return h, nil
  358. }